aoptx86.pas 575 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1, hp2 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1418. asml.InsertAfter(hp1, p);
  1419. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1420. RemoveCurrentP(p, hp1);
  1421. Result := True;
  1422. end
  1423. else if ((taicpu(p).ops <= 2) or
  1424. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1425. not(cs_opt_size in current_settings.optimizerswitches) and
  1426. (not(GetNextInstruction(p, hp1)) or
  1427. not((tai(hp1).typ = ait_instruction) and
  1428. ((taicpu(hp1).opcode=A_Jcc) and
  1429. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1430. begin
  1431. {
  1432. imul X, reg1, reg2 to
  1433. lea (reg1,reg1,Y), reg2
  1434. shl ZZ,reg2
  1435. imul XX, reg1 to
  1436. lea (reg1,reg1,YY), reg1
  1437. shl ZZ,reg2
  1438. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1439. it does not exist as a separate optimization target in FPC though.
  1440. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1441. at most two zeros
  1442. }
  1443. reference_reset(tmpref,1,[]);
  1444. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1445. begin
  1446. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1447. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1448. TmpRef.base := taicpu(p).oper[1]^.reg;
  1449. TmpRef.index := taicpu(p).oper[1]^.reg;
  1450. if not(BaseValue in [3,5,9]) then
  1451. Internalerror(2018110101);
  1452. TmpRef.ScaleFactor := BaseValue-1;
  1453. if (taicpu(p).ops = 2) then
  1454. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1455. else
  1456. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1457. AsmL.InsertAfter(hp1,p);
  1458. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1459. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1460. RemoveCurrentP(p, hp1);
  1461. if ShiftValue>0 then
  1462. begin
  1463. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1464. AsmL.InsertAfter(hp2,hp1);
  1465. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1466. end;
  1467. Result := True;
  1468. end;
  1469. end;
  1470. end;
  1471. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1472. begin
  1473. Result := False;
  1474. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1475. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1476. begin
  1477. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1478. taicpu(p).opcode := A_MOV;
  1479. Result := True;
  1480. end;
  1481. end;
  1482. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1483. var
  1484. p: taicpu absolute hp; { Implicit typecast }
  1485. i: Integer;
  1486. begin
  1487. Result := False;
  1488. if not assigned(hp) or
  1489. (hp.typ <> ait_instruction) then
  1490. Exit;
  1491. Prefetch(insprop[p.opcode]);
  1492. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1493. with insprop[p.opcode] do
  1494. begin
  1495. case getsubreg(reg) of
  1496. R_SUBW,R_SUBD,R_SUBQ:
  1497. Result:=
  1498. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1499. uncommon flags are checked first }
  1500. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1501. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1502. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1503. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1504. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1505. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1506. R_SUBFLAGCARRY:
  1507. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGPARITY:
  1509. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGAUXILIARY:
  1511. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGZERO:
  1513. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGSIGN:
  1515. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1516. R_SUBFLAGOVERFLOW:
  1517. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1518. R_SUBFLAGINTERRUPT:
  1519. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1520. R_SUBFLAGDIRECTION:
  1521. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1522. else
  1523. internalerror(2017050501);
  1524. end;
  1525. exit;
  1526. end;
  1527. { Handle special cases first }
  1528. case p.opcode of
  1529. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1530. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1531. begin
  1532. Result :=
  1533. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1534. (p.oper[1]^.typ = top_reg) and
  1535. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1536. (
  1537. (p.oper[0]^.typ = top_const) or
  1538. (
  1539. (p.oper[0]^.typ = top_reg) and
  1540. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1541. ) or (
  1542. (p.oper[0]^.typ = top_ref) and
  1543. not RegInRef(reg,p.oper[0]^.ref^)
  1544. )
  1545. );
  1546. end;
  1547. A_MUL, A_IMUL:
  1548. Result :=
  1549. (
  1550. (p.ops=3) and { IMUL only }
  1551. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1552. (
  1553. (
  1554. (p.oper[1]^.typ=top_reg) and
  1555. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1556. ) or (
  1557. (p.oper[1]^.typ=top_ref) and
  1558. not RegInRef(reg,p.oper[1]^.ref^)
  1559. )
  1560. )
  1561. ) or (
  1562. (
  1563. (p.ops=1) and
  1564. (
  1565. (
  1566. (
  1567. (p.oper[0]^.typ=top_reg) and
  1568. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1569. )
  1570. ) or (
  1571. (p.oper[0]^.typ=top_ref) and
  1572. not RegInRef(reg,p.oper[0]^.ref^)
  1573. )
  1574. ) and (
  1575. (
  1576. (p.opsize=S_B) and
  1577. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1578. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1579. ) or (
  1580. (p.opsize=S_W) and
  1581. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1582. ) or (
  1583. (p.opsize=S_L) and
  1584. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1585. {$ifdef x86_64}
  1586. ) or (
  1587. (p.opsize=S_Q) and
  1588. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1589. {$endif x86_64}
  1590. )
  1591. )
  1592. )
  1593. );
  1594. A_CBW:
  1595. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1596. {$ifndef x86_64}
  1597. A_LDS:
  1598. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1599. A_LES:
  1600. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1601. {$endif not x86_64}
  1602. A_LFS:
  1603. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1604. A_LGS:
  1605. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1606. A_LSS:
  1607. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1608. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1609. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1610. A_LODSB:
  1611. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1612. A_LODSW:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1614. {$ifdef x86_64}
  1615. A_LODSQ:
  1616. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1617. {$endif x86_64}
  1618. A_LODSD:
  1619. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1620. A_FSTSW, A_FNSTSW:
  1621. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1622. else
  1623. begin
  1624. with insprop[p.opcode] do
  1625. begin
  1626. if (
  1627. { xor %reg,%reg etc. is classed as a new value }
  1628. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1629. MatchOpType(p, top_reg, top_reg) and
  1630. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1631. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1632. ) then
  1633. begin
  1634. Result := True;
  1635. Exit;
  1636. end;
  1637. { Make sure the entire register is overwritten }
  1638. if (getregtype(reg) = R_INTREGISTER) then
  1639. begin
  1640. if (p.ops > 0) then
  1641. begin
  1642. if RegInOp(reg, p.oper[0]^) then
  1643. begin
  1644. if (p.oper[0]^.typ = top_ref) then
  1645. begin
  1646. if RegInRef(reg, p.oper[0]^.ref^) then
  1647. begin
  1648. Result := False;
  1649. Exit;
  1650. end;
  1651. end
  1652. else if (p.oper[0]^.typ = top_reg) then
  1653. begin
  1654. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1655. begin
  1656. Result := False;
  1657. Exit;
  1658. end
  1659. else if ([Ch_WOp1]*Ch<>[]) then
  1660. begin
  1661. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1662. Result := True
  1663. else
  1664. begin
  1665. Result := False;
  1666. Exit;
  1667. end;
  1668. end;
  1669. end;
  1670. end;
  1671. if (p.ops > 1) then
  1672. begin
  1673. if RegInOp(reg, p.oper[1]^) then
  1674. begin
  1675. if (p.oper[1]^.typ = top_ref) then
  1676. begin
  1677. if RegInRef(reg, p.oper[1]^.ref^) then
  1678. begin
  1679. Result := False;
  1680. Exit;
  1681. end;
  1682. end
  1683. else if (p.oper[1]^.typ = top_reg) then
  1684. begin
  1685. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1686. begin
  1687. Result := False;
  1688. Exit;
  1689. end
  1690. else if ([Ch_WOp2]*Ch<>[]) then
  1691. begin
  1692. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1693. Result := True
  1694. else
  1695. begin
  1696. Result := False;
  1697. Exit;
  1698. end;
  1699. end;
  1700. end;
  1701. end;
  1702. if (p.ops > 2) then
  1703. begin
  1704. if RegInOp(reg, p.oper[2]^) then
  1705. begin
  1706. if (p.oper[2]^.typ = top_ref) then
  1707. begin
  1708. if RegInRef(reg, p.oper[2]^.ref^) then
  1709. begin
  1710. Result := False;
  1711. Exit;
  1712. end;
  1713. end
  1714. else if (p.oper[2]^.typ = top_reg) then
  1715. begin
  1716. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1717. begin
  1718. Result := False;
  1719. Exit;
  1720. end
  1721. else if ([Ch_WOp3]*Ch<>[]) then
  1722. begin
  1723. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1724. Result := True
  1725. else
  1726. begin
  1727. Result := False;
  1728. Exit;
  1729. end;
  1730. end;
  1731. end;
  1732. end;
  1733. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1734. begin
  1735. if (p.oper[3]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[3]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[3]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp4]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. end;
  1763. end;
  1764. end;
  1765. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1766. case getsupreg(reg) of
  1767. RS_EAX:
  1768. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_ECX:
  1774. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EDX:
  1780. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_EBX:
  1786. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_ESP:
  1792. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_EBP:
  1798. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_ESI:
  1804. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. RS_EDI:
  1810. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1811. begin
  1812. Result := True;
  1813. Exit;
  1814. end;
  1815. else
  1816. ;
  1817. end;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1824. var
  1825. hp2,hp3 : tai;
  1826. begin
  1827. { some x86-64 issue a NOP before the real exit code }
  1828. if MatchInstruction(p,A_NOP,[]) then
  1829. GetNextInstruction(p,p);
  1830. result:=assigned(p) and (p.typ=ait_instruction) and
  1831. ((taicpu(p).opcode = A_RET) or
  1832. ((taicpu(p).opcode=A_LEAVE) and
  1833. GetNextInstruction(p,hp2) and
  1834. MatchInstruction(hp2,A_RET,[S_NO])
  1835. ) or
  1836. (((taicpu(p).opcode=A_LEA) and
  1837. MatchOpType(taicpu(p),top_ref,top_reg) and
  1838. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1839. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1840. ) and
  1841. GetNextInstruction(p,hp2) and
  1842. MatchInstruction(hp2,A_RET,[S_NO])
  1843. ) or
  1844. ((((taicpu(p).opcode=A_MOV) and
  1845. MatchOpType(taicpu(p),top_reg,top_reg) and
  1846. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1847. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1848. ((taicpu(p).opcode=A_LEA) and
  1849. MatchOpType(taicpu(p),top_ref,top_reg) and
  1850. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1851. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1852. )
  1853. ) and
  1854. GetNextInstruction(p,hp2) and
  1855. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1856. MatchOpType(taicpu(hp2),top_reg) and
  1857. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1858. GetNextInstruction(hp2,hp3) and
  1859. MatchInstruction(hp3,A_RET,[S_NO])
  1860. )
  1861. );
  1862. end;
  1863. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1864. begin
  1865. isFoldableArithOp := False;
  1866. case hp1.opcode of
  1867. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1868. isFoldableArithOp :=
  1869. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1870. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1872. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1873. (taicpu(hp1).oper[1]^.reg = reg);
  1874. A_INC,A_DEC,A_NEG,A_NOT:
  1875. isFoldableArithOp :=
  1876. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1877. (taicpu(hp1).oper[0]^.reg = reg);
  1878. else
  1879. ;
  1880. end;
  1881. end;
  1882. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1883. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1884. var
  1885. hp2: tai;
  1886. begin
  1887. hp2 := p;
  1888. repeat
  1889. hp2 := tai(hp2.previous);
  1890. if assigned(hp2) and
  1891. (hp2.typ = ait_regalloc) and
  1892. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1893. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1894. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1895. begin
  1896. RemoveInstruction(hp2);
  1897. break;
  1898. end;
  1899. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1900. end;
  1901. begin
  1902. case current_procinfo.procdef.returndef.typ of
  1903. arraydef,recorddef,pointerdef,
  1904. stringdef,enumdef,procdef,objectdef,errordef,
  1905. filedef,setdef,procvardef,
  1906. classrefdef,forwarddef:
  1907. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1908. orddef:
  1909. if current_procinfo.procdef.returndef.size <> 0 then
  1910. begin
  1911. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1912. { for int64/qword }
  1913. if current_procinfo.procdef.returndef.size = 8 then
  1914. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1921. var
  1922. hp1,hp2 : tai;
  1923. begin
  1924. result:=false;
  1925. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1926. begin
  1927. { vmova* reg1,reg1
  1928. =>
  1929. <nop> }
  1930. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1931. begin
  1932. RemoveCurrentP(p);
  1933. result:=true;
  1934. exit;
  1935. end
  1936. else if GetNextInstruction(p,hp1) then
  1937. begin
  1938. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1940. begin
  1941. { vmova* reg1,reg2
  1942. vmova* reg2,reg3
  1943. dealloc reg2
  1944. =>
  1945. vmova* reg1,reg3 }
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1949. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1950. begin
  1951. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1952. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1953. RemoveInstruction(hp1);
  1954. result:=true;
  1955. exit;
  1956. end
  1957. { special case:
  1958. vmova* reg1,<op>
  1959. vmova* <op>,reg1
  1960. =>
  1961. vmova* reg1,<op> }
  1962. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1963. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1964. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1965. ) then
  1966. begin
  1967. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1968. RemoveInstruction(hp1);
  1969. result:=true;
  1970. exit;
  1971. end
  1972. end
  1973. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1974. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1975. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1976. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1977. ) and
  1978. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1979. begin
  1980. { vmova* reg1,reg2
  1981. vmovs* reg2,<op>
  1982. dealloc reg2
  1983. =>
  1984. vmovs* reg1,reg3 }
  1985. TransferUsedRegs(TmpUsedRegs);
  1986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1987. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1988. begin
  1989. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1990. taicpu(p).opcode:=taicpu(hp1).opcode;
  1991. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1992. RemoveInstruction(hp1);
  1993. result:=true;
  1994. exit;
  1995. end
  1996. end;
  1997. end;
  1998. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1999. begin
  2000. if MatchInstruction(hp1,[A_VFMADDPD,
  2001. A_VFMADD132PD,
  2002. A_VFMADD132PS,
  2003. A_VFMADD132SD,
  2004. A_VFMADD132SS,
  2005. A_VFMADD213PD,
  2006. A_VFMADD213PS,
  2007. A_VFMADD213SD,
  2008. A_VFMADD213SS,
  2009. A_VFMADD231PD,
  2010. A_VFMADD231PS,
  2011. A_VFMADD231SD,
  2012. A_VFMADD231SS,
  2013. A_VFMADDSUB132PD,
  2014. A_VFMADDSUB132PS,
  2015. A_VFMADDSUB213PD,
  2016. A_VFMADDSUB213PS,
  2017. A_VFMADDSUB231PD,
  2018. A_VFMADDSUB231PS,
  2019. A_VFMSUB132PD,
  2020. A_VFMSUB132PS,
  2021. A_VFMSUB132SD,
  2022. A_VFMSUB132SS,
  2023. A_VFMSUB213PD,
  2024. A_VFMSUB213PS,
  2025. A_VFMSUB213SD,
  2026. A_VFMSUB213SS,
  2027. A_VFMSUB231PD,
  2028. A_VFMSUB231PS,
  2029. A_VFMSUB231SD,
  2030. A_VFMSUB231SS,
  2031. A_VFMSUBADD132PD,
  2032. A_VFMSUBADD132PS,
  2033. A_VFMSUBADD213PD,
  2034. A_VFMSUBADD213PS,
  2035. A_VFMSUBADD231PD,
  2036. A_VFMSUBADD231PS,
  2037. A_VFNMADD132PD,
  2038. A_VFNMADD132PS,
  2039. A_VFNMADD132SD,
  2040. A_VFNMADD132SS,
  2041. A_VFNMADD213PD,
  2042. A_VFNMADD213PS,
  2043. A_VFNMADD213SD,
  2044. A_VFNMADD213SS,
  2045. A_VFNMADD231PD,
  2046. A_VFNMADD231PS,
  2047. A_VFNMADD231SD,
  2048. A_VFNMADD231SS,
  2049. A_VFNMSUB132PD,
  2050. A_VFNMSUB132PS,
  2051. A_VFNMSUB132SD,
  2052. A_VFNMSUB132SS,
  2053. A_VFNMSUB213PD,
  2054. A_VFNMSUB213PS,
  2055. A_VFNMSUB213SD,
  2056. A_VFNMSUB213SS,
  2057. A_VFNMSUB231PD,
  2058. A_VFNMSUB231PS,
  2059. A_VFNMSUB231SD,
  2060. A_VFNMSUB231SS],[S_NO]) and
  2061. { we mix single and double opperations here because we assume that the compiler
  2062. generates vmovapd only after double operations and vmovaps only after single operations }
  2063. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2064. GetNextInstruction(hp1,hp2) and
  2065. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2066. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2067. begin
  2068. TransferUsedRegs(TmpUsedRegs);
  2069. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2070. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2071. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2072. begin
  2073. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2074. RemoveCurrentP(p);
  2075. RemoveInstruction(hp2);
  2076. end;
  2077. end
  2078. else if (hp1.typ = ait_instruction) and
  2079. GetNextInstruction(hp1, hp2) and
  2080. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2081. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2082. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2083. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2084. (((taicpu(p).opcode=A_MOVAPS) and
  2085. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2086. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2087. ((taicpu(p).opcode=A_MOVAPD) and
  2088. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2089. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2090. ) then
  2091. { change
  2092. movapX reg,reg2
  2093. addsX/subsX/... reg3, reg2
  2094. movapX reg2,reg
  2095. to
  2096. addsX/subsX/... reg3,reg
  2097. }
  2098. begin
  2099. TransferUsedRegs(TmpUsedRegs);
  2100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2101. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2102. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2105. debug_op2str(taicpu(p).opcode)+' '+
  2106. debug_op2str(taicpu(hp1).opcode)+' '+
  2107. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2108. { we cannot eliminate the first move if
  2109. the operations uses the same register for source and dest }
  2110. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2111. { Remember that hp1 is not necessarily the immediate
  2112. next instruction }
  2113. RemoveCurrentP(p);
  2114. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2115. RemoveInstruction(hp2);
  2116. result:=true;
  2117. end;
  2118. end
  2119. else if (hp1.typ = ait_instruction) and
  2120. (((taicpu(p).opcode=A_VMOVAPD) and
  2121. (taicpu(hp1).opcode=A_VCOMISD)) or
  2122. ((taicpu(p).opcode=A_VMOVAPS) and
  2123. ((taicpu(hp1).opcode=A_VCOMISS))
  2124. )
  2125. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2126. { change
  2127. movapX reg,reg1
  2128. vcomisX reg1,reg1
  2129. to
  2130. vcomisX reg,reg
  2131. }
  2132. begin
  2133. TransferUsedRegs(TmpUsedRegs);
  2134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2135. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2136. begin
  2137. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2138. debug_op2str(taicpu(p).opcode)+' '+
  2139. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2140. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2141. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2142. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2143. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2144. RemoveCurrentP(p);
  2145. result:=true;
  2146. exit;
  2147. end;
  2148. end
  2149. end;
  2150. end;
  2151. end;
  2152. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2153. var
  2154. hp1 : tai;
  2155. begin
  2156. result:=false;
  2157. { replace
  2158. V<Op>X %mreg1,%mreg2,%mreg3
  2159. VMovX %mreg3,%mreg4
  2160. dealloc %mreg3
  2161. by
  2162. V<Op>X %mreg1,%mreg2,%mreg4
  2163. ?
  2164. }
  2165. if GetNextInstruction(p,hp1) and
  2166. { we mix single and double operations here because we assume that the compiler
  2167. generates vmovapd only after double operations and vmovaps only after single operations }
  2168. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2169. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2170. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2171. begin
  2172. TransferUsedRegs(TmpUsedRegs);
  2173. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2174. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2175. begin
  2176. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2177. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2178. RemoveInstruction(hp1);
  2179. result:=true;
  2180. end;
  2181. end;
  2182. end;
  2183. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2184. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2185. begin
  2186. Result := False;
  2187. { For safety reasons, only check for exact register matches }
  2188. { Check base register }
  2189. if (ref.base = AOldReg) then
  2190. begin
  2191. ref.base := ANewReg;
  2192. Result := True;
  2193. end;
  2194. { Check index register }
  2195. if (ref.index = AOldReg) then
  2196. begin
  2197. ref.index := ANewReg;
  2198. Result := True;
  2199. end;
  2200. end;
  2201. { Replaces all references to AOldReg in an operand to ANewReg }
  2202. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2203. var
  2204. OldSupReg, NewSupReg: TSuperRegister;
  2205. OldSubReg, NewSubReg: TSubRegister;
  2206. OldRegType: TRegisterType;
  2207. ThisOper: POper;
  2208. begin
  2209. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2210. Result := False;
  2211. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2212. InternalError(2020011801);
  2213. OldSupReg := getsupreg(AOldReg);
  2214. OldSubReg := getsubreg(AOldReg);
  2215. OldRegType := getregtype(AOldReg);
  2216. NewSupReg := getsupreg(ANewReg);
  2217. NewSubReg := getsubreg(ANewReg);
  2218. if OldRegType <> getregtype(ANewReg) then
  2219. InternalError(2020011802);
  2220. if OldSubReg <> NewSubReg then
  2221. InternalError(2020011803);
  2222. case ThisOper^.typ of
  2223. top_reg:
  2224. if (
  2225. (ThisOper^.reg = AOldReg) or
  2226. (
  2227. (OldRegType = R_INTREGISTER) and
  2228. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2229. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2230. (
  2231. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2232. {$ifndef x86_64}
  2233. and (
  2234. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2235. don't have an 8-bit representation }
  2236. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2237. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2238. )
  2239. {$endif x86_64}
  2240. )
  2241. )
  2242. ) then
  2243. begin
  2244. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2245. Result := True;
  2246. end;
  2247. top_ref:
  2248. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2249. Result := True;
  2250. else
  2251. ;
  2252. end;
  2253. end;
  2254. { Replaces all references to AOldReg in an instruction to ANewReg }
  2255. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2256. const
  2257. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2258. var
  2259. OperIdx: Integer;
  2260. begin
  2261. Result := False;
  2262. for OperIdx := 0 to p.ops - 1 do
  2263. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2264. begin
  2265. { The shift and rotate instructions can only use CL }
  2266. if not (
  2267. (OperIdx = 0) and
  2268. { This second condition just helps to avoid unnecessarily
  2269. calling MatchInstruction for 10 different opcodes }
  2270. (p.oper[0]^.reg = NR_CL) and
  2271. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2272. ) then
  2273. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2274. end
  2275. else if p.oper[OperIdx]^.typ = top_ref then
  2276. { It's okay to replace registers in references that get written to }
  2277. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2278. end;
  2279. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2280. begin
  2281. with ref^ do
  2282. Result :=
  2283. (index = NR_NO) and
  2284. (
  2285. {$ifdef x86_64}
  2286. (
  2287. (base = NR_RIP) and
  2288. (refaddr in [addr_pic, addr_pic_no_got])
  2289. ) or
  2290. {$endif x86_64}
  2291. (base = NR_STACK_POINTER_REG) or
  2292. (base = current_procinfo.framepointer)
  2293. );
  2294. end;
  2295. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2296. var
  2297. l: asizeint;
  2298. begin
  2299. Result := False;
  2300. { Should have been checked previously }
  2301. if p.opcode <> A_LEA then
  2302. InternalError(2020072501);
  2303. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2304. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2305. not(cs_opt_size in current_settings.optimizerswitches) then
  2306. exit;
  2307. with p.oper[0]^.ref^ do
  2308. begin
  2309. if (base <> p.oper[1]^.reg) or
  2310. (index <> NR_NO) or
  2311. assigned(symbol) then
  2312. exit;
  2313. l:=offset;
  2314. if (l=1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_INC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2320. end
  2321. else if (l=-1) and UseIncDec then
  2322. begin
  2323. p.opcode:=A_DEC;
  2324. p.loadreg(0,p.oper[1]^.reg);
  2325. p.ops:=1;
  2326. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2327. end
  2328. else
  2329. begin
  2330. if (l<0) and (l<>-2147483648) then
  2331. begin
  2332. p.opcode:=A_SUB;
  2333. p.loadConst(0,-l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2335. end
  2336. else
  2337. begin
  2338. p.opcode:=A_ADD;
  2339. p.loadConst(0,l);
  2340. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2341. end;
  2342. end;
  2343. end;
  2344. Result := True;
  2345. end;
  2346. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2347. var
  2348. CurrentReg, ReplaceReg: TRegister;
  2349. begin
  2350. Result := False;
  2351. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2352. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2353. case hp.opcode of
  2354. A_FSTSW, A_FNSTSW,
  2355. A_IN, A_INS, A_OUT, A_OUTS,
  2356. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2357. { These routines have explicit operands, but they are restricted in
  2358. what they can be (e.g. IN and OUT can only read from AL, AX or
  2359. EAX. }
  2360. Exit;
  2361. A_IMUL:
  2362. begin
  2363. { The 1-operand version writes to implicit registers
  2364. The 2-operand version reads from the first operator, and reads
  2365. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2366. the 3-operand version reads from a register that it doesn't write to
  2367. }
  2368. case hp.ops of
  2369. 1:
  2370. if (
  2371. (
  2372. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2373. ) or
  2374. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2375. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2376. begin
  2377. Result := True;
  2378. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2379. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2380. end;
  2381. 2:
  2382. { Only modify the first parameter }
  2383. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2384. begin
  2385. Result := True;
  2386. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2387. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2388. end;
  2389. 3:
  2390. { Only modify the second parameter }
  2391. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2392. begin
  2393. Result := True;
  2394. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2395. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2396. end;
  2397. else
  2398. InternalError(2020012901);
  2399. end;
  2400. end;
  2401. else
  2402. if (hp.ops > 0) and
  2403. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2404. begin
  2405. Result := True;
  2406. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2407. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2408. end;
  2409. end;
  2410. end;
  2411. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2412. var
  2413. hp1, hp2, hp3: tai;
  2414. DoOptimisation, TempBool: Boolean;
  2415. {$ifdef x86_64}
  2416. NewConst: TCGInt;
  2417. {$endif x86_64}
  2418. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2419. begin
  2420. if taicpu(hp1).opcode = signed_movop then
  2421. begin
  2422. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2423. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2424. end
  2425. else
  2426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2427. end;
  2428. function TryConstMerge(var p1, p2: tai): Boolean;
  2429. var
  2430. ThisRef: TReference;
  2431. begin
  2432. Result := False;
  2433. ThisRef := taicpu(p2).oper[1]^.ref^;
  2434. { Only permit writes to the stack, since we can guarantee alignment with that }
  2435. if (ThisRef.index = NR_NO) and
  2436. (
  2437. (ThisRef.base = NR_STACK_POINTER_REG) or
  2438. (ThisRef.base = current_procinfo.framepointer)
  2439. ) then
  2440. begin
  2441. case taicpu(p).opsize of
  2442. S_B:
  2443. begin
  2444. { Word writes must be on a 2-byte boundary }
  2445. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2446. begin
  2447. { Reduce offset of second reference to see if it is sequential with the first }
  2448. Dec(ThisRef.offset, 1);
  2449. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2450. begin
  2451. { Make sure the constants aren't represented as a
  2452. negative number, as these won't merge properly }
  2453. taicpu(p1).opsize := S_W;
  2454. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2455. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2456. RemoveInstruction(p2);
  2457. Result := True;
  2458. end;
  2459. end;
  2460. end;
  2461. S_W:
  2462. begin
  2463. { Longword writes must be on a 4-byte boundary }
  2464. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2465. begin
  2466. { Reduce offset of second reference to see if it is sequential with the first }
  2467. Dec(ThisRef.offset, 2);
  2468. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2469. begin
  2470. { Make sure the constants aren't represented as a
  2471. negative number, as these won't merge properly }
  2472. taicpu(p1).opsize := S_L;
  2473. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2474. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2475. RemoveInstruction(p2);
  2476. Result := True;
  2477. end;
  2478. end;
  2479. end;
  2480. {$ifdef x86_64}
  2481. S_L:
  2482. begin
  2483. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2484. see if the constants can be encoded this way. }
  2485. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2486. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2487. { Quadword writes must be on an 8-byte boundary }
  2488. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2489. begin
  2490. { Reduce offset of second reference to see if it is sequential with the first }
  2491. Dec(ThisRef.offset, 4);
  2492. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2493. begin
  2494. { Make sure the constants aren't represented as a
  2495. negative number, as these won't merge properly }
  2496. taicpu(p1).opsize := S_Q;
  2497. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2498. taicpu(p1).oper[0]^.val := NewConst;
  2499. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$endif x86_64}
  2506. else
  2507. ;
  2508. end;
  2509. end;
  2510. end;
  2511. var
  2512. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2513. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2514. NewSize: topsize;
  2515. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2516. SourceRef, TargetRef: TReference;
  2517. MovAligned, MovUnaligned: TAsmOp;
  2518. ThisRef: TReference;
  2519. JumpTracking: TLinkedList;
  2520. begin
  2521. Result:=false;
  2522. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2523. { remove mov reg1,reg1? }
  2524. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2525. then
  2526. begin
  2527. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2528. { take care of the register (de)allocs following p }
  2529. RemoveCurrentP(p, hp1);
  2530. Result:=true;
  2531. exit;
  2532. end;
  2533. { All the next optimisations require a next instruction }
  2534. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2535. Exit;
  2536. { Prevent compiler warnings }
  2537. p_TargetReg := NR_NO;
  2538. if taicpu(p).oper[1]^.typ = top_reg then
  2539. begin
  2540. { Saves on a large number of dereferences }
  2541. p_TargetReg := taicpu(p).oper[1]^.reg;
  2542. { Look for:
  2543. mov %reg1,%reg2
  2544. ??? %reg2,r/m
  2545. Change to:
  2546. mov %reg1,%reg2
  2547. ??? %reg1,r/m
  2548. }
  2549. if taicpu(p).oper[0]^.typ = top_reg then
  2550. begin
  2551. if RegReadByInstruction(p_TargetReg, hp1) and
  2552. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2553. begin
  2554. { A change has occurred, just not in p }
  2555. Result := True;
  2556. TransferUsedRegs(TmpUsedRegs);
  2557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2559. { Just in case something didn't get modified (e.g. an
  2560. implicit register) }
  2561. not RegReadByInstruction(p_TargetReg, hp1) then
  2562. begin
  2563. { We can remove the original MOV }
  2564. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2565. RemoveCurrentp(p, hp1);
  2566. { UsedRegs got updated by RemoveCurrentp }
  2567. Result := True;
  2568. Exit;
  2569. end;
  2570. { If we know a MOV instruction has become a null operation, we might as well
  2571. get rid of it now to save time. }
  2572. if (taicpu(hp1).opcode = A_MOV) and
  2573. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2574. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2575. { Just being a register is enough to confirm it's a null operation }
  2576. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2577. begin
  2578. Result := True;
  2579. { Speed-up to reduce a pipeline stall... if we had something like...
  2580. movl %eax,%edx
  2581. movw %dx,%ax
  2582. ... the second instruction would change to movw %ax,%ax, but
  2583. given that it is now %ax that's active rather than %eax,
  2584. penalties might occur due to a partial register write, so instead,
  2585. change it to a MOVZX instruction when optimising for speed.
  2586. }
  2587. if not (cs_opt_size in current_settings.optimizerswitches) and
  2588. IsMOVZXAcceptable and
  2589. (taicpu(hp1).opsize < taicpu(p).opsize)
  2590. {$ifdef x86_64}
  2591. { operations already implicitly set the upper 64 bits to zero }
  2592. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2593. {$endif x86_64}
  2594. then
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2597. case taicpu(p).opsize of
  2598. S_W:
  2599. if taicpu(hp1).opsize = S_B then
  2600. taicpu(hp1).opsize := S_BL
  2601. else
  2602. InternalError(2020012911);
  2603. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2604. case taicpu(hp1).opsize of
  2605. S_B:
  2606. taicpu(hp1).opsize := S_BL;
  2607. S_W:
  2608. taicpu(hp1).opsize := S_WL;
  2609. else
  2610. InternalError(2020012912);
  2611. end;
  2612. else
  2613. InternalError(2020012910);
  2614. end;
  2615. taicpu(hp1).opcode := A_MOVZX;
  2616. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2617. end
  2618. else
  2619. begin
  2620. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2621. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2622. RemoveInstruction(hp1);
  2623. { The instruction after what was hp1 is now the immediate next instruction,
  2624. so we can continue to make optimisations if it's present }
  2625. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2626. Exit;
  2627. hp1 := hp2;
  2628. end;
  2629. end;
  2630. end;
  2631. end;
  2632. end;
  2633. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2634. overwrites the original destination register. e.g.
  2635. movl ###,%reg2d
  2636. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2637. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2638. }
  2639. if (taicpu(p).oper[1]^.typ = top_reg) and
  2640. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2641. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2642. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2643. begin
  2644. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2645. begin
  2646. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2647. case taicpu(p).oper[0]^.typ of
  2648. top_const:
  2649. { We have something like:
  2650. movb $x, %regb
  2651. movzbl %regb,%regd
  2652. Change to:
  2653. movl $x, %regd
  2654. }
  2655. begin
  2656. case taicpu(hp1).opsize of
  2657. S_BW:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2661. taicpu(p).opsize := S_W;
  2662. end;
  2663. S_BL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. S_WL:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FFFF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2673. taicpu(p).opsize := S_L;
  2674. end;
  2675. {$ifdef x86_64}
  2676. S_BQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_WQ:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FFFF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. S_LQ:
  2689. begin
  2690. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2692. taicpu(p).opsize := S_Q;
  2693. end;
  2694. {$endif x86_64}
  2695. else
  2696. { If hp1 was a MOV instruction, it should have been
  2697. optimised already }
  2698. InternalError(2020021001);
  2699. end;
  2700. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2701. RemoveInstruction(hp1);
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. top_ref:
  2706. begin
  2707. { We have something like:
  2708. movb mem, %regb
  2709. movzbl %regb,%regd
  2710. Change to:
  2711. movzbl mem, %regd
  2712. }
  2713. ThisRef := taicpu(p).oper[0]^.ref^;
  2714. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2715. begin
  2716. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2717. taicpu(hp1).loadref(0, ThisRef);
  2718. { Make sure any registers in the references are properly tracked }
  2719. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2720. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2721. if (ThisRef.index <> NR_NO) then
  2722. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2723. RemoveCurrentP(p, hp1);
  2724. Result := True;
  2725. Exit;
  2726. end;
  2727. end;
  2728. else
  2729. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2730. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2731. Exit;
  2732. end;
  2733. end
  2734. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2735. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2736. optimised }
  2737. else
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2740. RemoveCurrentP(p, hp1);
  2741. Result := True;
  2742. Exit;
  2743. end;
  2744. end;
  2745. if (taicpu(hp1).opcode = A_AND) and
  2746. (taicpu(p).oper[1]^.typ = top_reg) and
  2747. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2748. begin
  2749. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2750. begin
  2751. case taicpu(p).opsize of
  2752. S_L:
  2753. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2754. begin
  2755. { Optimize out:
  2756. mov x, %reg
  2757. and ffffffffh, %reg
  2758. }
  2759. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2760. RemoveInstruction(hp1);
  2761. Result:=true;
  2762. exit;
  2763. end;
  2764. S_Q: { TODO: Confirm if this is even possible }
  2765. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2766. begin
  2767. { Optimize out:
  2768. mov x, %reg
  2769. and ffffffffffffffffh, %reg
  2770. }
  2771. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2772. RemoveInstruction(hp1);
  2773. Result:=true;
  2774. exit;
  2775. end;
  2776. else
  2777. ;
  2778. end;
  2779. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2780. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2781. GetNextInstruction(hp1,hp2) and
  2782. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2783. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2784. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2785. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2786. GetNextInstruction(hp2,hp3) and
  2787. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2788. (taicpu(hp3).condition in [C_E,C_NE]) then
  2789. begin
  2790. TransferUsedRegs(TmpUsedRegs);
  2791. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2792. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2793. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2794. begin
  2795. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2796. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2797. taicpu(hp1).opcode:=A_TEST;
  2798. RemoveInstruction(hp2);
  2799. RemoveCurrentP(p, hp1);
  2800. Result:=true;
  2801. exit;
  2802. end;
  2803. end;
  2804. end
  2805. else if IsMOVZXAcceptable and
  2806. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2807. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2808. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2809. then
  2810. begin
  2811. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2812. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2813. case taicpu(p).opsize of
  2814. S_B:
  2815. if (taicpu(hp1).oper[0]^.val = $ff) then
  2816. begin
  2817. { Convert:
  2818. movb x, %regl movb x, %regl
  2819. andw ffh, %regw andl ffh, %regd
  2820. To:
  2821. movzbw x, %regd movzbl x, %regd
  2822. (Identical registers, just different sizes)
  2823. }
  2824. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2825. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2826. case taicpu(hp1).opsize of
  2827. S_W: NewSize := S_BW;
  2828. S_L: NewSize := S_BL;
  2829. {$ifdef x86_64}
  2830. S_Q: NewSize := S_BQ;
  2831. {$endif x86_64}
  2832. else
  2833. InternalError(2018011510);
  2834. end;
  2835. end
  2836. else
  2837. NewSize := S_NO;
  2838. S_W:
  2839. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2840. begin
  2841. { Convert:
  2842. movw x, %regw
  2843. andl ffffh, %regd
  2844. To:
  2845. movzwl x, %regd
  2846. (Identical registers, just different sizes)
  2847. }
  2848. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2849. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2850. case taicpu(hp1).opsize of
  2851. S_L: NewSize := S_WL;
  2852. {$ifdef x86_64}
  2853. S_Q: NewSize := S_WQ;
  2854. {$endif x86_64}
  2855. else
  2856. InternalError(2018011511);
  2857. end;
  2858. end
  2859. else
  2860. NewSize := S_NO;
  2861. else
  2862. NewSize := S_NO;
  2863. end;
  2864. if NewSize <> S_NO then
  2865. begin
  2866. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2867. { The actual optimization }
  2868. taicpu(p).opcode := A_MOVZX;
  2869. taicpu(p).changeopsize(NewSize);
  2870. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2871. { Safeguard if "and" is followed by a conditional command }
  2872. TransferUsedRegs(TmpUsedRegs);
  2873. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2874. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2875. begin
  2876. { At this point, the "and" command is effectively equivalent to
  2877. "test %reg,%reg". This will be handled separately by the
  2878. Peephole Optimizer. [Kit] }
  2879. DebugMsg(SPeepholeOptimization + PreMessage +
  2880. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2881. end
  2882. else
  2883. begin
  2884. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2885. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2886. RemoveInstruction(hp1);
  2887. end;
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. end;
  2892. end;
  2893. if (taicpu(hp1).opcode = A_OR) and
  2894. (taicpu(p).oper[1]^.typ = top_reg) and
  2895. MatchOperand(taicpu(p).oper[0]^, 0) and
  2896. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2897. begin
  2898. { mov 0, %reg
  2899. or ###,%reg
  2900. Change to (only if the flags are not used):
  2901. mov ###,%reg
  2902. }
  2903. TransferUsedRegs(TmpUsedRegs);
  2904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2905. DoOptimisation := True;
  2906. { Even if the flags are used, we might be able to do the optimisation
  2907. if the conditions are predictable }
  2908. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2909. begin
  2910. { Only perform if ### = %reg (the same register) or equal to 0,
  2911. so %reg is guaranteed to still have a value of zero }
  2912. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2913. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2914. begin
  2915. hp2 := hp1;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2917. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2918. GetNextInstruction(hp2, hp3) do
  2919. begin
  2920. { Don't continue modifying if the flags state is getting changed }
  2921. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2922. Break;
  2923. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2924. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2925. begin
  2926. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2927. begin
  2928. { Condition is always true }
  2929. case taicpu(hp3).opcode of
  2930. A_Jcc:
  2931. begin
  2932. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2933. { Check for jump shortcuts before we destroy the condition }
  2934. DoJumpOptimizations(hp3, TempBool);
  2935. MakeUnconditional(taicpu(hp3));
  2936. Result := True;
  2937. end;
  2938. A_CMOVcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2941. taicpu(hp3).opcode := A_MOV;
  2942. taicpu(hp3).condition := C_None;
  2943. Result := True;
  2944. end;
  2945. A_SETcc:
  2946. begin
  2947. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2948. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2949. taicpu(hp3).opcode := A_MOV;
  2950. taicpu(hp3).ops := 2;
  2951. taicpu(hp3).condition := C_None;
  2952. taicpu(hp3).opsize := S_B;
  2953. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2954. taicpu(hp3).loadconst(0, 1);
  2955. Result := True;
  2956. end;
  2957. else
  2958. InternalError(2021090701);
  2959. end;
  2960. end
  2961. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  2962. begin
  2963. { Condition is always false }
  2964. case taicpu(hp3).opcode of
  2965. A_Jcc:
  2966. begin
  2967. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2968. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2969. RemoveInstruction(hp3);
  2970. Result := True;
  2971. { Since hp3 was deleted, hp2 must not be updated }
  2972. Continue;
  2973. end;
  2974. A_CMOVcc:
  2975. begin
  2976. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2977. RemoveInstruction(hp3);
  2978. Result := True;
  2979. { Since hp3 was deleted, hp2 must not be updated }
  2980. Continue;
  2981. end;
  2982. A_SETcc:
  2983. begin
  2984. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2985. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2986. taicpu(hp3).opcode := A_MOV;
  2987. taicpu(hp3).ops := 2;
  2988. taicpu(hp3).condition := C_None;
  2989. taicpu(hp3).opsize := S_B;
  2990. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2991. taicpu(hp3).loadconst(0, 0);
  2992. Result := True;
  2993. end;
  2994. else
  2995. InternalError(2021090702);
  2996. end;
  2997. end
  2998. else
  2999. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3000. DoOptimisation := False;
  3001. end;
  3002. hp2 := hp3;
  3003. end;
  3004. { Flags are still in use - don't optimise }
  3005. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3006. DoOptimisation := False;
  3007. end
  3008. else
  3009. DoOptimisation := False;
  3010. end;
  3011. if DoOptimisation then
  3012. begin
  3013. {$ifdef x86_64}
  3014. { OR only supports 32-bit sign-extended constants for 64-bit
  3015. instructions, so compensate for this if the constant is
  3016. encoded as a value greater than or equal to 2^31 }
  3017. if (taicpu(hp1).opsize = S_Q) and
  3018. (taicpu(hp1).oper[0]^.typ = top_const) and
  3019. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3020. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3021. {$endif x86_64}
  3022. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3023. taicpu(hp1).opcode := A_MOV;
  3024. RemoveCurrentP(p, hp1);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. { Next instruction is also a MOV ? }
  3030. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3031. begin
  3032. if MatchOpType(taicpu(p), top_const, top_ref) and
  3033. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3034. TryConstMerge(p, hp1) then
  3035. begin
  3036. Result := True;
  3037. { In case we have four byte writes in a row, check for 2 more
  3038. right now so we don't have to wait for another iteration of
  3039. pass 1
  3040. }
  3041. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3042. case taicpu(p).opsize of
  3043. S_W:
  3044. begin
  3045. if GetNextInstruction(p, hp1) and
  3046. MatchInstruction(hp1, A_MOV, [S_B]) and
  3047. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3048. GetNextInstruction(hp1, hp2) and
  3049. MatchInstruction(hp2, A_MOV, [S_B]) and
  3050. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3051. { Try to merge the two bytes }
  3052. TryConstMerge(hp1, hp2) then
  3053. { Now try to merge the two words (hp2 will get deleted) }
  3054. TryConstMerge(p, hp1);
  3055. end;
  3056. S_L:
  3057. begin
  3058. { Though this only really benefits x86_64 and not i386, it
  3059. gets a potential optimisation done faster and hence
  3060. reduces the number of times OptPass1MOV is entered }
  3061. if GetNextInstruction(p, hp1) and
  3062. MatchInstruction(hp1, A_MOV, [S_W]) and
  3063. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3064. GetNextInstruction(hp1, hp2) and
  3065. MatchInstruction(hp2, A_MOV, [S_W]) and
  3066. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3067. { Try to merge the two words }
  3068. TryConstMerge(hp1, hp2) then
  3069. { This will always fail on i386, so don't bother
  3070. calling it unless we're doing x86_64 }
  3071. {$ifdef x86_64}
  3072. { Now try to merge the two longwords (hp2 will get deleted) }
  3073. TryConstMerge(p, hp1)
  3074. {$endif x86_64}
  3075. ;
  3076. end;
  3077. else
  3078. ;
  3079. end;
  3080. Exit;
  3081. end;
  3082. if (taicpu(p).oper[1]^.typ = top_reg) and
  3083. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3084. begin
  3085. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3086. TransferUsedRegs(TmpUsedRegs);
  3087. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3088. { we have
  3089. mov x, %treg
  3090. mov %treg, y
  3091. }
  3092. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3093. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3094. { we've got
  3095. mov x, %treg
  3096. mov %treg, y
  3097. with %treg is not used after }
  3098. case taicpu(p).oper[0]^.typ Of
  3099. { top_reg is covered by DeepMOVOpt }
  3100. top_const:
  3101. begin
  3102. { change
  3103. mov const, %treg
  3104. mov %treg, y
  3105. to
  3106. mov const, y
  3107. }
  3108. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3109. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3110. begin
  3111. if taicpu(hp1).oper[1]^.typ=top_reg then
  3112. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3113. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3114. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3115. RemoveInstruction(hp1);
  3116. Result:=true;
  3117. Exit;
  3118. end;
  3119. end;
  3120. top_ref:
  3121. case taicpu(hp1).oper[1]^.typ of
  3122. top_reg:
  3123. begin
  3124. { change
  3125. mov mem, %treg
  3126. mov %treg, %reg
  3127. to
  3128. mov mem, %reg"
  3129. }
  3130. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3131. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3132. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3133. RemoveInstruction(hp1);
  3134. Result:=true;
  3135. Exit;
  3136. end;
  3137. top_ref:
  3138. begin
  3139. {$ifdef x86_64}
  3140. { Look for the following to simplify:
  3141. mov x(mem1), %reg
  3142. mov %reg, y(mem2)
  3143. mov x+8(mem1), %reg
  3144. mov %reg, y+8(mem2)
  3145. Change to:
  3146. movdqu x(mem1), %xmmreg
  3147. movdqu %xmmreg, y(mem2)
  3148. ...but only as long as the memory blocks don't overlap
  3149. }
  3150. SourceRef := taicpu(p).oper[0]^.ref^;
  3151. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3152. if (taicpu(p).opsize = S_Q) and
  3153. GetNextInstruction(hp1, hp2) and
  3154. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3155. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3156. begin
  3157. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3158. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3159. Inc(SourceRef.offset, 8);
  3160. if UseAVX then
  3161. begin
  3162. MovAligned := A_VMOVDQA;
  3163. MovUnaligned := A_VMOVDQU;
  3164. end
  3165. else
  3166. begin
  3167. MovAligned := A_MOVDQA;
  3168. MovUnaligned := A_MOVDQU;
  3169. end;
  3170. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3171. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3172. begin
  3173. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3174. Inc(TargetRef.offset, 8);
  3175. if GetNextInstruction(hp2, hp3) and
  3176. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3177. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3178. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3179. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3180. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3181. begin
  3182. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3183. if NewMMReg <> NR_NO then
  3184. begin
  3185. { Remember that the offsets are 8 ahead }
  3186. if ((SourceRef.offset mod 16) = 8) and
  3187. (
  3188. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3189. (SourceRef.base = current_procinfo.framepointer) or
  3190. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3191. ) then
  3192. taicpu(p).opcode := MovAligned
  3193. else
  3194. taicpu(p).opcode := MovUnaligned;
  3195. taicpu(p).opsize := S_XMM;
  3196. taicpu(p).oper[1]^.reg := NewMMReg;
  3197. if ((TargetRef.offset mod 16) = 8) and
  3198. (
  3199. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3200. (TargetRef.base = current_procinfo.framepointer) or
  3201. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3202. ) then
  3203. taicpu(hp1).opcode := MovAligned
  3204. else
  3205. taicpu(hp1).opcode := MovUnaligned;
  3206. taicpu(hp1).opsize := S_XMM;
  3207. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3208. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3209. RemoveInstruction(hp2);
  3210. RemoveInstruction(hp3);
  3211. Result := True;
  3212. Exit;
  3213. end;
  3214. end;
  3215. end
  3216. else
  3217. begin
  3218. { See if the next references are 8 less rather than 8 greater }
  3219. Dec(SourceRef.offset, 16); { -8 the other way }
  3220. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3221. begin
  3222. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3223. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3224. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3225. GetNextInstruction(hp2, hp3) and
  3226. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3227. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3228. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3229. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3230. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3231. begin
  3232. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3233. if NewMMReg <> NR_NO then
  3234. begin
  3235. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3236. if ((SourceRef.offset mod 16) = 0) and
  3237. (
  3238. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3239. (SourceRef.base = current_procinfo.framepointer) or
  3240. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3241. ) then
  3242. taicpu(hp2).opcode := MovAligned
  3243. else
  3244. taicpu(hp2).opcode := MovUnaligned;
  3245. taicpu(hp2).opsize := S_XMM;
  3246. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3247. if ((TargetRef.offset mod 16) = 0) and
  3248. (
  3249. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3250. (TargetRef.base = current_procinfo.framepointer) or
  3251. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3252. ) then
  3253. taicpu(hp3).opcode := MovAligned
  3254. else
  3255. taicpu(hp3).opcode := MovUnaligned;
  3256. taicpu(hp3).opsize := S_XMM;
  3257. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3258. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3259. RemoveInstruction(hp1);
  3260. RemoveCurrentP(p, hp2);
  3261. Result := True;
  3262. Exit;
  3263. end;
  3264. end;
  3265. end;
  3266. end;
  3267. end;
  3268. {$endif x86_64}
  3269. end;
  3270. else
  3271. { The write target should be a reg or a ref }
  3272. InternalError(2021091601);
  3273. end;
  3274. else
  3275. ;
  3276. end
  3277. else
  3278. { %treg is used afterwards, but all eventualities
  3279. other than the first MOV instruction being a constant
  3280. are covered by DeepMOVOpt, so only check for that }
  3281. if (taicpu(p).oper[0]^.typ = top_const) and
  3282. (
  3283. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3284. not (cs_opt_size in current_settings.optimizerswitches) or
  3285. (taicpu(hp1).opsize = S_B)
  3286. ) and
  3287. (
  3288. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3289. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3290. ) then
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3293. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3297. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3298. { mov reg1, mem1 or mov mem1, reg1
  3299. mov mem2, reg2 mov reg2, mem2}
  3300. begin
  3301. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3302. { mov reg1, mem1 or mov mem1, reg1
  3303. mov mem2, reg1 mov reg2, mem1}
  3304. begin
  3305. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3306. { Removes the second statement from
  3307. mov reg1, mem1/reg2
  3308. mov mem1/reg2, reg1 }
  3309. begin
  3310. if taicpu(p).oper[0]^.typ=top_reg then
  3311. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3312. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3313. RemoveInstruction(hp1);
  3314. Result:=true;
  3315. exit;
  3316. end
  3317. else
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3321. if (taicpu(p).oper[1]^.typ = top_ref) and
  3322. { mov reg1, mem1
  3323. mov mem2, reg1 }
  3324. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3325. GetNextInstruction(hp1, hp2) and
  3326. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3327. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3328. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3329. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3330. { change to
  3331. mov reg1, mem1 mov reg1, mem1
  3332. mov mem2, reg1 cmp reg1, mem2
  3333. cmp mem1, reg1
  3334. }
  3335. begin
  3336. RemoveInstruction(hp2);
  3337. taicpu(hp1).opcode := A_CMP;
  3338. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3339. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3340. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3341. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3342. end;
  3343. end;
  3344. end
  3345. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3346. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3347. begin
  3348. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3349. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3350. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3351. end
  3352. else
  3353. begin
  3354. TransferUsedRegs(TmpUsedRegs);
  3355. if GetNextInstruction(hp1, hp2) and
  3356. MatchOpType(taicpu(p),top_ref,top_reg) and
  3357. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3358. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3359. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3360. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3361. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3362. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3363. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3364. { mov mem1, %reg1
  3365. mov %reg1, mem2
  3366. mov mem2, reg2
  3367. to:
  3368. mov mem1, reg2
  3369. mov reg2, mem2}
  3370. begin
  3371. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3372. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3373. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3374. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3375. RemoveInstruction(hp2);
  3376. Result := True;
  3377. end
  3378. {$ifdef i386}
  3379. { this is enabled for i386 only, as the rules to create the reg sets below
  3380. are too complicated for x86-64, so this makes this code too error prone
  3381. on x86-64
  3382. }
  3383. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3384. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3385. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3386. { mov mem1, reg1 mov mem1, reg1
  3387. mov reg1, mem2 mov reg1, mem2
  3388. mov mem2, reg2 mov mem2, reg1
  3389. to: to:
  3390. mov mem1, reg1 mov mem1, reg1
  3391. mov mem1, reg2 mov reg1, mem2
  3392. mov reg1, mem2
  3393. or (if mem1 depends on reg1
  3394. and/or if mem2 depends on reg2)
  3395. to:
  3396. mov mem1, reg1
  3397. mov reg1, mem2
  3398. mov reg1, reg2
  3399. }
  3400. begin
  3401. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3402. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3403. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3404. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3405. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3406. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3407. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3408. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3409. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3410. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3411. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3412. end
  3413. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3414. begin
  3415. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3416. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3417. end
  3418. else
  3419. begin
  3420. RemoveInstruction(hp2);
  3421. end
  3422. {$endif i386}
  3423. ;
  3424. end;
  3425. end
  3426. { movl [mem1],reg1
  3427. movl [mem1],reg2
  3428. to
  3429. movl [mem1],reg1
  3430. movl reg1,reg2
  3431. }
  3432. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3433. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3434. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3435. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3436. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3437. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3438. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3439. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3440. begin
  3441. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3442. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3443. end;
  3444. { movl const1,[mem1]
  3445. movl [mem1],reg1
  3446. to
  3447. movl const1,reg1
  3448. movl reg1,[mem1]
  3449. }
  3450. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3451. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3452. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3453. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3454. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3455. begin
  3456. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3457. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3458. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3459. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3460. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3461. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3462. Result:=true;
  3463. exit;
  3464. end;
  3465. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3466. { Change:
  3467. movl %reg1,%reg2
  3468. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3469. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3470. To:
  3471. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3472. movl x(%reg1),%reg1
  3473. movl %reg1,%regX
  3474. }
  3475. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3476. begin
  3477. p_SourceReg := taicpu(p).oper[0]^.reg;
  3478. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3479. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3480. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3481. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3482. GetNextInstruction(hp1, hp2) and
  3483. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3484. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3485. begin
  3486. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3487. if RegInRef(p_TargetReg, SourceRef) and
  3488. { If %reg1 also appears in the second reference, then it will
  3489. not refer to the same memory block as the first reference }
  3490. not RegInRef(p_SourceReg, SourceRef) then
  3491. begin
  3492. { Check to see if the references match if %reg2 is changed to %reg1 }
  3493. if SourceRef.base = p_TargetReg then
  3494. SourceRef.base := p_SourceReg;
  3495. if SourceRef.index = p_TargetReg then
  3496. SourceRef.index := p_SourceReg;
  3497. { RefsEqual also checks to ensure both references are non-volatile }
  3498. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3499. begin
  3500. taicpu(hp2).loadreg(0, p_SourceReg);
  3501. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3502. Result := True;
  3503. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3504. begin
  3505. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3506. RemoveCurrentP(p, hp1);
  3507. Exit;
  3508. end
  3509. else
  3510. begin
  3511. { Check to see if %reg2 is no longer in use }
  3512. TransferUsedRegs(TmpUsedRegs);
  3513. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3514. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3515. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3516. begin
  3517. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3518. RemoveCurrentP(p, hp1);
  3519. Exit;
  3520. end;
  3521. end;
  3522. { If we reach this point, p and hp1 weren't actually modified,
  3523. so we can do a bit more work on this pass }
  3524. end;
  3525. end;
  3526. end;
  3527. end;
  3528. end;
  3529. { search further than the next instruction for a mov (as long as it's not a jump) }
  3530. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3531. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3532. (taicpu(p).oper[1]^.typ = top_reg) and
  3533. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3534. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3535. begin
  3536. { we work with hp2 here, so hp1 can be still used later on when
  3537. checking for GetNextInstruction_p }
  3538. hp3 := hp1;
  3539. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3540. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3541. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3542. TransferUsedRegs(TmpUsedRegs);
  3543. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3544. if NotFirstIteration then
  3545. JumpTracking := TLinkedList.Create
  3546. else
  3547. JumpTracking := nil;
  3548. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3549. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3550. (hp2.typ=ait_instruction) do
  3551. begin
  3552. case taicpu(hp2).opcode of
  3553. A_POP:
  3554. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3555. begin
  3556. if not CrossJump and
  3557. not RegUsedBetween(p_TargetReg, p, hp2) then
  3558. begin
  3559. { We can remove the original MOV since the register
  3560. wasn't used between it and its popping from the stack }
  3561. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3562. RemoveCurrentp(p, hp1);
  3563. Result := True;
  3564. JumpTracking.Free;
  3565. Exit;
  3566. end;
  3567. { Can't go any further }
  3568. Break;
  3569. end;
  3570. A_MOV:
  3571. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3572. ((taicpu(p).oper[0]^.typ=top_const) or
  3573. ((taicpu(p).oper[0]^.typ=top_reg) and
  3574. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3575. )
  3576. ) then
  3577. begin
  3578. { we have
  3579. mov x, %treg
  3580. mov %treg, y
  3581. }
  3582. { We don't need to call UpdateUsedRegs for every instruction between
  3583. p and hp2 because the register we're concerned about will not
  3584. become deallocated (otherwise GetNextInstructionUsingReg would
  3585. have stopped at an earlier instruction). [Kit] }
  3586. TempRegUsed :=
  3587. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3588. RegReadByInstruction(p_TargetReg, hp3) or
  3589. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3590. case taicpu(p).oper[0]^.typ Of
  3591. top_reg:
  3592. begin
  3593. { change
  3594. mov %reg, %treg
  3595. mov %treg, y
  3596. to
  3597. mov %reg, y
  3598. }
  3599. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3600. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3601. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3602. begin
  3603. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3604. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3605. if TempRegUsed then
  3606. begin
  3607. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3608. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3609. { Set the start of the next GetNextInstructionUsingRegCond search
  3610. to start at the entry right before hp2 (which is about to be removed) }
  3611. hp3 := tai(hp2.Previous);
  3612. RemoveInstruction(hp2);
  3613. { See if there's more we can optimise }
  3614. Continue;
  3615. end
  3616. else
  3617. begin
  3618. RemoveInstruction(hp2);
  3619. { We can remove the original MOV too }
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3621. RemoveCurrentP(p, hp1);
  3622. Result:=true;
  3623. JumpTracking.Free;
  3624. Exit;
  3625. end;
  3626. end
  3627. else
  3628. begin
  3629. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3630. taicpu(hp2).loadReg(0, p_SourceReg);
  3631. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3632. { Check to see if the register also appears in the reference }
  3633. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3634. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3635. { Don't remove the first instruction if the temporary register is in use }
  3636. if not TempRegUsed and
  3637. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3638. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3639. begin
  3640. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3641. RemoveCurrentP(p, hp1);
  3642. Result:=true;
  3643. JumpTracking.Free;
  3644. Exit;
  3645. end;
  3646. { No need to set Result to True here. If there's another instruction later
  3647. on that can be optimised, it will be detected when the main Pass 1 loop
  3648. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3649. end;
  3650. end;
  3651. top_const:
  3652. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3653. begin
  3654. { change
  3655. mov const, %treg
  3656. mov %treg, y
  3657. to
  3658. mov const, y
  3659. }
  3660. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3661. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3662. begin
  3663. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3664. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3665. if TempRegUsed then
  3666. begin
  3667. { Don't remove the first instruction if the temporary register is in use }
  3668. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3669. { No need to set Result to True. If there's another instruction later on
  3670. that can be optimised, it will be detected when the main Pass 1 loop
  3671. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3672. end
  3673. else
  3674. begin
  3675. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3676. RemoveCurrentP(p, hp1);
  3677. Result:=true;
  3678. Exit;
  3679. end;
  3680. end;
  3681. end;
  3682. else
  3683. Internalerror(2019103001);
  3684. end;
  3685. end
  3686. else
  3687. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3688. begin
  3689. if not CrossJump and
  3690. not RegUsedBetween(p_TargetReg, p, hp2) and
  3691. not RegReadByInstruction(p_TargetReg, hp2) then
  3692. begin
  3693. { Register is not used before it is overwritten }
  3694. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3695. RemoveCurrentp(p, hp1);
  3696. Result := True;
  3697. Exit;
  3698. end;
  3699. if (taicpu(p).oper[0]^.typ = top_const) and
  3700. (taicpu(hp2).oper[0]^.typ = top_const) then
  3701. begin
  3702. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3703. begin
  3704. { Same value - register hasn't changed }
  3705. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3706. RemoveInstruction(hp2);
  3707. Result := True;
  3708. { See if there's more we can optimise }
  3709. Continue;
  3710. end;
  3711. end;
  3712. end;
  3713. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3714. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3715. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3716. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3717. begin
  3718. {
  3719. Change from:
  3720. mov ###, %reg
  3721. ...
  3722. movs/z %reg,%reg (Same register, just different sizes)
  3723. To:
  3724. movs/z ###, %reg (Longer version)
  3725. ...
  3726. (remove)
  3727. }
  3728. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3729. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3730. { Keep the first instruction as mov if ### is a constant }
  3731. if taicpu(p).oper[0]^.typ = top_const then
  3732. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3733. else
  3734. begin
  3735. taicpu(p).opcode := taicpu(hp2).opcode;
  3736. taicpu(p).opsize := taicpu(hp2).opsize;
  3737. end;
  3738. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3739. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3740. RemoveInstruction(hp2);
  3741. Result := True;
  3742. JumpTracking.Free;
  3743. Exit;
  3744. end;
  3745. else
  3746. { Move down to the MatchOpType if-block below };
  3747. end;
  3748. { Also catches MOV/S/Z instructions that aren't modified }
  3749. if taicpu(p).oper[0]^.typ = top_reg then
  3750. begin
  3751. p_SourceReg := taicpu(p).oper[0]^.reg;
  3752. if
  3753. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3754. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3755. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3756. begin
  3757. Result := True;
  3758. { Just in case something didn't get modified (e.g. an
  3759. implicit register). Also, if it does read from this
  3760. register, then there's no longer an advantage to
  3761. changing the register on subsequent instructions.}
  3762. if not RegReadByInstruction(p_TargetReg, hp2) then
  3763. begin
  3764. { If a conditional jump was crossed, do not delete
  3765. the original MOV no matter what }
  3766. if not CrossJump and
  3767. { RegEndOfLife returns True if the register is
  3768. deallocated before the next instruction or has
  3769. been loaded with a new value }
  3770. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3771. begin
  3772. { We can remove the original MOV }
  3773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3774. RemoveCurrentp(p, hp1);
  3775. JumpTracking.Free;
  3776. Result := True;
  3777. Exit;
  3778. end;
  3779. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3780. begin
  3781. { See if there's more we can optimise }
  3782. hp3 := hp2;
  3783. Continue;
  3784. end;
  3785. end;
  3786. end;
  3787. end;
  3788. { Break out of the while loop under normal circumstances }
  3789. Break;
  3790. end;
  3791. JumpTracking.Free;
  3792. end;
  3793. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3794. (taicpu(p).oper[1]^.typ = top_reg) and
  3795. (taicpu(p).opsize = S_L) and
  3796. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3797. (hp2.typ = ait_instruction) and
  3798. (taicpu(hp2).opcode = A_AND) and
  3799. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3800. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3801. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3802. ) then
  3803. begin
  3804. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3805. begin
  3806. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3807. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3808. begin
  3809. { Optimize out:
  3810. mov x, %reg
  3811. and ffffffffh, %reg
  3812. }
  3813. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3814. RemoveInstruction(hp2);
  3815. Result:=true;
  3816. exit;
  3817. end;
  3818. end;
  3819. end;
  3820. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3821. x >= RetOffset) as it doesn't do anything (it writes either to a
  3822. parameter or to the temporary storage room for the function
  3823. result)
  3824. }
  3825. if IsExitCode(hp1) and
  3826. (taicpu(p).oper[1]^.typ = top_ref) and
  3827. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3828. (
  3829. (
  3830. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3831. not (
  3832. assigned(current_procinfo.procdef.funcretsym) and
  3833. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3834. )
  3835. ) or
  3836. { Also discard writes to the stack that are below the base pointer,
  3837. as this is temporary storage rather than a function result on the
  3838. stack, say. }
  3839. (
  3840. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3841. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3842. )
  3843. ) then
  3844. begin
  3845. RemoveCurrentp(p, hp1);
  3846. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3847. RemoveLastDeallocForFuncRes(p);
  3848. Result:=true;
  3849. exit;
  3850. end;
  3851. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3852. begin
  3853. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3854. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3855. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3856. begin
  3857. { change
  3858. mov reg1, mem1
  3859. test/cmp x, mem1
  3860. to
  3861. mov reg1, mem1
  3862. test/cmp x, reg1
  3863. }
  3864. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3865. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3866. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3867. Result := True;
  3868. Exit;
  3869. end;
  3870. if DoMovCmpMemOpt(p, hp1, True) then
  3871. begin
  3872. Result := True;
  3873. Exit;
  3874. end;
  3875. end;
  3876. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3877. { If the flags register is in use, don't change the instruction to an
  3878. ADD otherwise this will scramble the flags. [Kit] }
  3879. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3880. begin
  3881. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3882. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3883. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3884. ) or
  3885. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3886. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3887. )
  3888. ) then
  3889. { mov reg1,ref
  3890. lea reg2,[reg1,reg2]
  3891. to
  3892. add reg2,ref}
  3893. begin
  3894. TransferUsedRegs(TmpUsedRegs);
  3895. { reg1 may not be used afterwards }
  3896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3897. begin
  3898. Taicpu(hp1).opcode:=A_ADD;
  3899. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3900. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3901. RemoveCurrentp(p, hp1);
  3902. result:=true;
  3903. exit;
  3904. end;
  3905. end;
  3906. { If the LEA instruction can be converted into an arithmetic instruction,
  3907. it may be possible to then fold it in the next optimisation, otherwise
  3908. there's nothing more that can be optimised here. }
  3909. if not ConvertLEA(taicpu(hp1)) then
  3910. Exit;
  3911. end;
  3912. if (taicpu(p).oper[1]^.typ = top_reg) and
  3913. (hp1.typ = ait_instruction) and
  3914. GetNextInstruction(hp1, hp2) and
  3915. MatchInstruction(hp2,A_MOV,[]) and
  3916. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3917. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3918. (
  3919. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3920. {$ifdef x86_64}
  3921. or
  3922. (
  3923. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3924. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3925. )
  3926. {$endif x86_64}
  3927. ) then
  3928. begin
  3929. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3930. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3931. { change movsX/movzX reg/ref, reg2
  3932. add/sub/or/... reg3/$const, reg2
  3933. mov reg2 reg/ref
  3934. dealloc reg2
  3935. to
  3936. add/sub/or/... reg3/$const, reg/ref }
  3937. begin
  3938. TransferUsedRegs(TmpUsedRegs);
  3939. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3940. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3941. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3942. begin
  3943. { by example:
  3944. movswl %si,%eax movswl %si,%eax p
  3945. decl %eax addl %edx,%eax hp1
  3946. movw %ax,%si movw %ax,%si hp2
  3947. ->
  3948. movswl %si,%eax movswl %si,%eax p
  3949. decw %eax addw %edx,%eax hp1
  3950. movw %ax,%si movw %ax,%si hp2
  3951. }
  3952. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3953. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3954. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3955. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3956. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3957. {
  3958. ->
  3959. movswl %si,%eax movswl %si,%eax p
  3960. decw %si addw %dx,%si hp1
  3961. movw %ax,%si movw %ax,%si hp2
  3962. }
  3963. case taicpu(hp1).ops of
  3964. 1:
  3965. begin
  3966. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3967. if taicpu(hp1).oper[0]^.typ=top_reg then
  3968. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3969. end;
  3970. 2:
  3971. begin
  3972. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3973. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3974. (taicpu(hp1).opcode<>A_SHL) and
  3975. (taicpu(hp1).opcode<>A_SHR) and
  3976. (taicpu(hp1).opcode<>A_SAR) then
  3977. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3978. end;
  3979. else
  3980. internalerror(2008042701);
  3981. end;
  3982. {
  3983. ->
  3984. decw %si addw %dx,%si p
  3985. }
  3986. RemoveInstruction(hp2);
  3987. RemoveCurrentP(p, hp1);
  3988. Result:=True;
  3989. Exit;
  3990. end;
  3991. end;
  3992. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3993. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3994. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3995. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3996. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3997. )
  3998. {$ifdef i386}
  3999. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4000. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4001. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4002. {$endif i386}
  4003. then
  4004. { change movsX/movzX reg/ref, reg2
  4005. add/sub/or/... regX/$const, reg2
  4006. mov reg2, reg3
  4007. dealloc reg2
  4008. to
  4009. movsX/movzX reg/ref, reg3
  4010. add/sub/or/... reg3/$const, reg3
  4011. }
  4012. begin
  4013. TransferUsedRegs(TmpUsedRegs);
  4014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4016. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4017. begin
  4018. { by example:
  4019. movswl %si,%eax movswl %si,%eax p
  4020. decl %eax addl %edx,%eax hp1
  4021. movw %ax,%si movw %ax,%si hp2
  4022. ->
  4023. movswl %si,%eax movswl %si,%eax p
  4024. decw %eax addw %edx,%eax hp1
  4025. movw %ax,%si movw %ax,%si hp2
  4026. }
  4027. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4028. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4029. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4030. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4031. { limit size of constants as well to avoid assembler errors, but
  4032. check opsize to avoid overflow when left shifting the 1 }
  4033. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4034. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4035. {$ifdef x86_64}
  4036. { Be careful of, for example:
  4037. movl %reg1,%reg2
  4038. addl %reg3,%reg2
  4039. movq %reg2,%reg4
  4040. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4041. }
  4042. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4043. begin
  4044. taicpu(hp2).changeopsize(S_L);
  4045. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4046. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4047. end;
  4048. {$endif x86_64}
  4049. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4050. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4051. if taicpu(p).oper[0]^.typ=top_reg then
  4052. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4053. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4054. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4055. {
  4056. ->
  4057. movswl %si,%eax movswl %si,%eax p
  4058. decw %si addw %dx,%si hp1
  4059. movw %ax,%si movw %ax,%si hp2
  4060. }
  4061. case taicpu(hp1).ops of
  4062. 1:
  4063. begin
  4064. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4065. if taicpu(hp1).oper[0]^.typ=top_reg then
  4066. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4067. end;
  4068. 2:
  4069. begin
  4070. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4071. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4072. (taicpu(hp1).opcode<>A_SHL) and
  4073. (taicpu(hp1).opcode<>A_SHR) and
  4074. (taicpu(hp1).opcode<>A_SAR) then
  4075. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4076. end;
  4077. else
  4078. internalerror(2018111801);
  4079. end;
  4080. {
  4081. ->
  4082. decw %si addw %dx,%si p
  4083. }
  4084. RemoveInstruction(hp2);
  4085. end;
  4086. end;
  4087. end;
  4088. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4089. GetNextInstruction(hp1, hp2) and
  4090. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4091. MatchOperand(Taicpu(p).oper[0]^,0) and
  4092. (Taicpu(p).oper[1]^.typ = top_reg) and
  4093. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4094. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4095. { mov reg1,0
  4096. bts reg1,operand1 --> mov reg1,operand2
  4097. or reg1,operand2 bts reg1,operand1}
  4098. begin
  4099. Taicpu(hp2).opcode:=A_MOV;
  4100. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4101. asml.remove(hp1);
  4102. insertllitem(hp2,hp2.next,hp1);
  4103. RemoveCurrentp(p, hp1);
  4104. Result:=true;
  4105. exit;
  4106. end;
  4107. {
  4108. mov ref,reg0
  4109. <op> reg0,reg1
  4110. dealloc reg0
  4111. to
  4112. <op> ref,reg1
  4113. }
  4114. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4115. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4116. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4117. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4118. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4119. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4120. begin
  4121. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4122. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4123. RemoveCurrentp(p, hp1);
  4124. Result:=true;
  4125. exit;
  4126. end;
  4127. {$ifdef x86_64}
  4128. { Convert:
  4129. movq x(ref),%reg64
  4130. shrq y,%reg64
  4131. To:
  4132. movl x+4(ref),%reg32
  4133. shrl y-32,%reg32 (Remove if y = 32)
  4134. }
  4135. if (taicpu(p).opsize = S_Q) and
  4136. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4137. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4138. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4139. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4140. (taicpu(hp1).oper[0]^.val >= 32) and
  4141. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4142. begin
  4143. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4144. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4145. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4146. { Convert to 32-bit }
  4147. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4148. taicpu(p).opsize := S_L;
  4149. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4150. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4151. if (taicpu(hp1).oper[0]^.val = 32) then
  4152. begin
  4153. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4154. RemoveInstruction(hp1);
  4155. end
  4156. else
  4157. begin
  4158. { This will potentially open up more arithmetic operations since
  4159. the peephole optimizer now has a big hint that only the lower
  4160. 32 bits are currently in use (and opcodes are smaller in size) }
  4161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4162. taicpu(hp1).opsize := S_L;
  4163. Dec(taicpu(hp1).oper[0]^.val, 32);
  4164. DebugMsg(SPeepholeOptimization + PreMessage +
  4165. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4166. end;
  4167. Result := True;
  4168. Exit;
  4169. end;
  4170. {$endif x86_64}
  4171. { Backward optimisation. If we have:
  4172. func. %reg1,%reg2
  4173. mov %reg2,%reg3
  4174. (dealloc %reg2)
  4175. Change to:
  4176. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4177. }
  4178. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4179. begin
  4180. p_SourceReg := taicpu(p).oper[0]^.reg;
  4181. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4182. TransferUsedRegs(TmpUsedRegs);
  4183. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4184. GetLastInstruction(p, hp2) and
  4185. (hp2.typ = ait_instruction) and
  4186. { Have to make sure it's an instruction that only reads from
  4187. operand 1 and only writes (not reads or modifies) from operand 2;
  4188. in essence, a one-operand pure function such as BSR or POPCNT }
  4189. (taicpu(hp2).ops = 2) and
  4190. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4191. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4192. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4193. begin
  4194. case taicpu(hp2).opcode of
  4195. A_FSTSW, A_FNSTSW,
  4196. A_IN, A_INS, A_OUT, A_OUTS,
  4197. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4198. { These routines have explicit operands, but they are restricted in
  4199. what they can be (e.g. IN and OUT can only read from AL, AX or
  4200. EAX. }
  4201. ;
  4202. else
  4203. begin
  4204. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4205. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4206. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4207. RemoveCurrentp(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end;
  4211. end;
  4212. end;
  4213. end;
  4214. end;
  4215. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4216. var
  4217. hp1 : tai;
  4218. begin
  4219. Result:=false;
  4220. if taicpu(p).ops <> 2 then
  4221. exit;
  4222. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4223. GetNextInstruction(p,hp1) then
  4224. begin
  4225. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4226. (taicpu(hp1).ops = 2) then
  4227. begin
  4228. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4229. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4230. { movXX reg1, mem1 or movXX mem1, reg1
  4231. movXX mem2, reg2 movXX reg2, mem2}
  4232. begin
  4233. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4234. { movXX reg1, mem1 or movXX mem1, reg1
  4235. movXX mem2, reg1 movXX reg2, mem1}
  4236. begin
  4237. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4238. begin
  4239. { Removes the second statement from
  4240. movXX reg1, mem1/reg2
  4241. movXX mem1/reg2, reg1
  4242. }
  4243. if taicpu(p).oper[0]^.typ=top_reg then
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. { Removes the second statement from
  4246. movXX mem1/reg1, reg2
  4247. movXX reg2, mem1/reg1
  4248. }
  4249. if (taicpu(p).oper[1]^.typ=top_reg) and
  4250. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4251. begin
  4252. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4253. RemoveInstruction(hp1);
  4254. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4255. Result:=true;
  4256. exit;
  4257. end
  4258. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4259. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4260. begin
  4261. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4262. RemoveInstruction(hp1);
  4263. Result:=true;
  4264. exit;
  4265. end;
  4266. end
  4267. end;
  4268. end;
  4269. end;
  4270. end;
  4271. end;
  4272. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4273. var
  4274. hp1 : tai;
  4275. begin
  4276. result:=false;
  4277. { replace
  4278. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4279. MovX %mreg2,%mreg1
  4280. dealloc %mreg2
  4281. by
  4282. <Op>X %mreg2,%mreg1
  4283. ?
  4284. }
  4285. if GetNextInstruction(p,hp1) and
  4286. { we mix single and double opperations here because we assume that the compiler
  4287. generates vmovapd only after double operations and vmovaps only after single operations }
  4288. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4289. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4290. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4291. (taicpu(p).oper[0]^.typ=top_reg) then
  4292. begin
  4293. TransferUsedRegs(TmpUsedRegs);
  4294. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4295. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4296. begin
  4297. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4298. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4299. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4300. RemoveInstruction(hp1);
  4301. result:=true;
  4302. end;
  4303. end;
  4304. end;
  4305. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4306. var
  4307. hp1, p_label, p_dist, hp1_dist: tai;
  4308. JumpLabel, JumpLabel_dist: TAsmLabel;
  4309. FirstValue, SecondValue: TCGInt;
  4310. begin
  4311. Result := False;
  4312. if (taicpu(p).oper[0]^.typ = top_const) and
  4313. (taicpu(p).oper[0]^.val <> -1) then
  4314. begin
  4315. { Convert unsigned maximum constants to -1 to aid optimisation }
  4316. case taicpu(p).opsize of
  4317. S_B:
  4318. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4319. begin
  4320. taicpu(p).oper[0]^.val := -1;
  4321. Result := True;
  4322. Exit;
  4323. end;
  4324. S_W:
  4325. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4326. begin
  4327. taicpu(p).oper[0]^.val := -1;
  4328. Result := True;
  4329. Exit;
  4330. end;
  4331. S_L:
  4332. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4333. begin
  4334. taicpu(p).oper[0]^.val := -1;
  4335. Result := True;
  4336. Exit;
  4337. end;
  4338. {$ifdef x86_64}
  4339. S_Q:
  4340. { Storing anything greater than $7FFFFFFF is not possible so do
  4341. nothing };
  4342. {$endif x86_64}
  4343. else
  4344. InternalError(2021121001);
  4345. end;
  4346. end;
  4347. if GetNextInstruction(p, hp1) and
  4348. TrySwapMovCmp(p, hp1) then
  4349. begin
  4350. Result := True;
  4351. Exit;
  4352. end;
  4353. { Search for:
  4354. test $x,(reg/ref)
  4355. jne @lbl1
  4356. test $y,(reg/ref) (same register or reference)
  4357. jne @lbl1
  4358. Change to:
  4359. test $(x or y),(reg/ref)
  4360. jne @lbl1
  4361. (Note, this doesn't work with je instead of jne)
  4362. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4363. Also search for:
  4364. test $x,(reg/ref)
  4365. je @lbl1
  4366. test $y,(reg/ref)
  4367. je/jne @lbl2
  4368. If (x or y) = x, then the second jump is deterministic
  4369. }
  4370. if (
  4371. (
  4372. (taicpu(p).oper[0]^.typ = top_const) or
  4373. (
  4374. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4375. (taicpu(p).oper[0]^.typ = top_reg) and
  4376. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4377. )
  4378. ) and
  4379. MatchInstruction(hp1, A_JCC, [])
  4380. ) then
  4381. begin
  4382. if (taicpu(p).oper[0]^.typ = top_reg) and
  4383. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4384. FirstValue := -1
  4385. else
  4386. FirstValue := taicpu(p).oper[0]^.val;
  4387. { If we have several test/jne's in a row, it might be the case that
  4388. the second label doesn't go to the same location, but the one
  4389. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4390. so accommodate for this with a while loop.
  4391. }
  4392. hp1_dist := hp1;
  4393. if GetNextInstruction(hp1, p_dist) and
  4394. (p_dist.typ = ait_instruction) and
  4395. (
  4396. (
  4397. (taicpu(p_dist).opcode = A_TEST) and
  4398. (
  4399. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4400. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4401. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4402. )
  4403. ) or
  4404. (
  4405. { cmp 0,%reg = test %reg,%reg }
  4406. (taicpu(p_dist).opcode = A_CMP) and
  4407. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4408. )
  4409. ) and
  4410. { Make sure the destination operands are actually the same }
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4412. GetNextInstruction(p_dist, hp1_dist) and
  4413. MatchInstruction(hp1_dist, A_JCC, []) then
  4414. begin
  4415. if
  4416. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4417. (
  4418. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4419. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4420. ) then
  4421. SecondValue := -1
  4422. else
  4423. SecondValue := taicpu(p_dist).oper[0]^.val;
  4424. { If both of the TEST constants are identical, delete the second
  4425. TEST that is unnecessary. }
  4426. if (FirstValue = SecondValue) then
  4427. begin
  4428. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4429. RemoveInstruction(p_dist);
  4430. { Don't let the flags register become deallocated and reallocated between the jumps }
  4431. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4432. Result := True;
  4433. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4434. begin
  4435. { Since the second jump's condition is a subset of the first, we
  4436. know it will never branch because the first jump dominates it.
  4437. Get it out of the way now rather than wait for the jump
  4438. optimisations for a speed boost. }
  4439. if IsJumpToLabel(taicpu(hp1_dist)) then
  4440. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4441. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4442. RemoveInstruction(hp1_dist);
  4443. end
  4444. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4445. begin
  4446. { If the inverse of the first condition is a subset of the second,
  4447. the second one will definitely branch if the first one doesn't }
  4448. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4449. MakeUnconditional(taicpu(hp1_dist));
  4450. RemoveDeadCodeAfterJump(hp1_dist);
  4451. end;
  4452. Exit;
  4453. end;
  4454. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4455. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4456. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4457. then the second jump will never branch, so it can also be
  4458. removed regardless of where it goes }
  4459. (
  4460. (FirstValue = -1) or
  4461. (SecondValue = -1) or
  4462. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4463. ) then
  4464. begin
  4465. { Same jump location... can be a register since nothing's changed }
  4466. { If any of the entries are equivalent to test %reg,%reg, then the
  4467. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4468. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4469. if IsJumpToLabel(taicpu(hp1_dist)) then
  4470. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4471. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4472. RemoveInstruction(hp1_dist);
  4473. { Only remove the second test if no jumps or other conditional instructions follow }
  4474. TransferUsedRegs(TmpUsedRegs);
  4475. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4477. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4478. RemoveInstruction(p_dist);
  4479. Result := True;
  4480. Exit;
  4481. end;
  4482. end;
  4483. end;
  4484. { Search for:
  4485. test %reg,%reg
  4486. j(c1) @lbl1
  4487. ...
  4488. @lbl:
  4489. test %reg,%reg (same register)
  4490. j(c2) @lbl2
  4491. If c2 is a subset of c1, change to:
  4492. test %reg,%reg
  4493. j(c1) @lbl2
  4494. (@lbl1 may become a dead label as a result)
  4495. }
  4496. if (taicpu(p).oper[1]^.typ = top_reg) and
  4497. (taicpu(p).oper[0]^.typ = top_reg) and
  4498. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4499. MatchInstruction(hp1, A_JCC, []) and
  4500. IsJumpToLabel(taicpu(hp1)) then
  4501. begin
  4502. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4503. p_label := nil;
  4504. if Assigned(JumpLabel) then
  4505. p_label := getlabelwithsym(JumpLabel);
  4506. if Assigned(p_label) and
  4507. GetNextInstruction(p_label, p_dist) and
  4508. MatchInstruction(p_dist, A_TEST, []) and
  4509. { It's fine if the second test uses smaller sub-registers }
  4510. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4511. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4512. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4513. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4514. GetNextInstruction(p_dist, hp1_dist) and
  4515. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4516. begin
  4517. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4518. if JumpLabel = JumpLabel_dist then
  4519. { This is an infinite loop }
  4520. Exit;
  4521. { Best optimisation when the first condition is a subset (or equal) of the second }
  4522. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4523. begin
  4524. { Any registers used here will already be allocated }
  4525. if Assigned(JumpLabel) then
  4526. JumpLabel.DecRefs;
  4527. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4528. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4529. Result := True;
  4530. Exit;
  4531. end;
  4532. end;
  4533. end;
  4534. end;
  4535. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4536. var
  4537. hp1, hp2: tai;
  4538. ActiveReg: TRegister;
  4539. OldOffset: asizeint;
  4540. ThisConst: TCGInt;
  4541. function RegDeallocated: Boolean;
  4542. begin
  4543. TransferUsedRegs(TmpUsedRegs);
  4544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4545. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4546. end;
  4547. begin
  4548. result:=false;
  4549. hp1 := nil;
  4550. { replace
  4551. addX const,%reg1
  4552. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4553. dealloc %reg1
  4554. by
  4555. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4556. }
  4557. if MatchOpType(taicpu(p),top_const,top_reg) then
  4558. begin
  4559. ActiveReg := taicpu(p).oper[1]^.reg;
  4560. { Ensures the entire register was updated }
  4561. if (taicpu(p).opsize >= S_L) and
  4562. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4563. MatchInstruction(hp1,A_LEA,[]) and
  4564. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4565. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4566. (
  4567. { Cover the case where the register in the reference is also the destination register }
  4568. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4569. (
  4570. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4571. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4572. RegDeallocated
  4573. )
  4574. ) then
  4575. begin
  4576. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4577. {$push}
  4578. {$R-}{$Q-}
  4579. { Explicitly disable overflow checking for these offset calculation
  4580. as those do not matter for the final result }
  4581. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4582. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4583. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4584. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4585. {$pop}
  4586. {$ifdef x86_64}
  4587. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4588. begin
  4589. { Overflow; abort }
  4590. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4591. end
  4592. else
  4593. {$endif x86_64}
  4594. begin
  4595. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4596. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4597. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4598. RemoveCurrentP(p, hp1)
  4599. else
  4600. RemoveCurrentP(p);
  4601. result:=true;
  4602. Exit;
  4603. end;
  4604. end;
  4605. if (
  4606. { Save calling GetNextInstructionUsingReg again }
  4607. Assigned(hp1) or
  4608. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4609. ) and
  4610. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4611. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4612. begin
  4613. if taicpu(hp1).oper[0]^.typ = top_const then
  4614. begin
  4615. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4616. if taicpu(hp1).opcode = A_ADD then
  4617. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4618. else
  4619. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4620. Result := True;
  4621. { Handle any overflows }
  4622. case taicpu(p).opsize of
  4623. S_B:
  4624. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4625. S_W:
  4626. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4627. S_L:
  4628. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4629. {$ifdef x86_64}
  4630. S_Q:
  4631. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4632. { Overflow; abort }
  4633. Result := False
  4634. else
  4635. taicpu(p).oper[0]^.val := ThisConst;
  4636. {$endif x86_64}
  4637. else
  4638. InternalError(2021102610);
  4639. end;
  4640. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4641. if Result then
  4642. begin
  4643. if (taicpu(p).oper[0]^.val < 0) and
  4644. (
  4645. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4646. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4647. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4648. ) then
  4649. begin
  4650. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4651. taicpu(p).opcode := A_SUB;
  4652. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4653. end
  4654. else
  4655. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4656. RemoveInstruction(hp1);
  4657. end;
  4658. end
  4659. else
  4660. begin
  4661. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4662. TransferUsedRegs(TmpUsedRegs);
  4663. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4664. hp2 := p;
  4665. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4666. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4667. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4668. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4669. begin
  4670. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4671. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4672. Asml.Remove(p);
  4673. Asml.InsertAfter(p, hp1);
  4674. p := hp1;
  4675. Result := True;
  4676. end;
  4677. end;
  4678. end;
  4679. end;
  4680. end;
  4681. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4682. var
  4683. hp1: tai;
  4684. ref: Integer;
  4685. saveref: treference;
  4686. Multiple: TCGInt;
  4687. Adjacent: Boolean;
  4688. begin
  4689. Result:=false;
  4690. { play save and throw an error if LEA uses a seg register prefix,
  4691. this is most likely an error somewhere else }
  4692. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4693. internalerror(2022022001);
  4694. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4695. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4696. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4697. (
  4698. { do not mess with leas accessing the stack pointer
  4699. unless it's a null operation }
  4700. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4701. (
  4702. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4703. (taicpu(p).oper[0]^.ref^.offset = 0)
  4704. )
  4705. ) and
  4706. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4707. begin
  4708. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4709. begin
  4710. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4711. begin
  4712. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4713. taicpu(p).oper[1]^.reg);
  4714. InsertLLItem(p.previous,p.next, hp1);
  4715. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4716. p.free;
  4717. p:=hp1;
  4718. end
  4719. else
  4720. begin
  4721. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4722. RemoveCurrentP(p);
  4723. end;
  4724. Result:=true;
  4725. exit;
  4726. end
  4727. else if (
  4728. { continue to use lea to adjust the stack pointer,
  4729. it is the recommended way, but only if not optimizing for size }
  4730. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4731. (cs_opt_size in current_settings.optimizerswitches)
  4732. ) and
  4733. { If the flags register is in use, don't change the instruction
  4734. to an ADD otherwise this will scramble the flags. [Kit] }
  4735. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4736. ConvertLEA(taicpu(p)) then
  4737. begin
  4738. Result:=true;
  4739. exit;
  4740. end;
  4741. end;
  4742. { Don't optimise if the stack or frame pointer is the destination register }
  4743. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4744. Exit;
  4745. if GetNextInstruction(p,hp1) and
  4746. (hp1.typ=ait_instruction) then
  4747. begin
  4748. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4749. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4750. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4751. begin
  4752. TransferUsedRegs(TmpUsedRegs);
  4753. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4754. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4755. begin
  4756. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4757. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4758. RemoveInstruction(hp1);
  4759. result:=true;
  4760. exit;
  4761. end;
  4762. end;
  4763. { changes
  4764. lea <ref1>, reg1
  4765. <op> ...,<ref. with reg1>,...
  4766. to
  4767. <op> ...,<ref1>,... }
  4768. { find a reference which uses reg1 }
  4769. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  4770. ref:=0
  4771. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  4772. ref:=1
  4773. else
  4774. ref:=-1;
  4775. if (ref<>-1) and
  4776. { reg1 must be either the base or the index }
  4777. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4778. begin
  4779. { reg1 can be removed from the reference }
  4780. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4781. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4782. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4783. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4784. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4785. else
  4786. Internalerror(2019111201);
  4787. { check if the can insert all data of the lea into the second instruction }
  4788. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4789. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4790. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4791. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4792. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4793. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4794. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4795. {$ifdef x86_64}
  4796. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4797. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4798. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4799. )
  4800. {$endif x86_64}
  4801. then
  4802. begin
  4803. { reg1 might not used by the second instruction after it is remove from the reference }
  4804. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4805. begin
  4806. TransferUsedRegs(TmpUsedRegs);
  4807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4808. { reg1 is not updated so it might not be used afterwards }
  4809. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4810. begin
  4811. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4812. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4813. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4814. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4815. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4816. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4817. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4818. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4819. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4820. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4821. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4822. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4823. RemoveCurrentP(p, hp1);
  4824. result:=true;
  4825. exit;
  4826. end
  4827. end;
  4828. end;
  4829. { recover }
  4830. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4831. end;
  4832. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4833. if Adjacent or
  4834. { Check further ahead (up to 2 instructions ahead for -O2) }
  4835. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4836. begin
  4837. { Check common LEA/LEA conditions }
  4838. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4839. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4840. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4841. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4842. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4843. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4844. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4845. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4846. (
  4847. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4848. calling it (since it calls GetNextInstruction) }
  4849. Adjacent or
  4850. (
  4851. (
  4852. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4853. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4854. ) and (
  4855. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4856. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4857. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4858. )
  4859. )
  4860. ) then
  4861. begin
  4862. { changes
  4863. lea (regX,scale), reg1
  4864. lea offset(reg1,reg1), reg1
  4865. to
  4866. lea offset(regX,scale*2), reg1
  4867. and
  4868. lea (regX,scale1), reg1
  4869. lea offset(reg1,scale2), reg1
  4870. to
  4871. lea offset(regX,scale1*scale2), reg1
  4872. ... so long as the final scale does not exceed 8
  4873. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4874. }
  4875. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4876. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4877. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4878. (
  4879. (
  4880. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4881. ) or (
  4882. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4883. (
  4884. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4885. (
  4886. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4887. Adjacent or
  4888. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4889. )
  4890. )
  4891. )
  4892. ) and (
  4893. (
  4894. { lea (reg1,scale2), reg1 variant }
  4895. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4896. (
  4897. (
  4898. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4899. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4900. ) or (
  4901. { lea (regX,regX), reg1 variant }
  4902. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4904. )
  4905. )
  4906. ) or (
  4907. { lea (reg1,reg1), reg1 variant }
  4908. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4909. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4910. )
  4911. ) then
  4912. begin
  4913. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4914. { Make everything homogeneous to make calculations easier }
  4915. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4916. begin
  4917. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4918. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4919. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4920. else
  4921. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4922. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4923. end;
  4924. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4925. begin
  4926. { Just to prevent miscalculations }
  4927. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4928. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4929. else
  4930. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4931. end
  4932. else
  4933. begin
  4934. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4935. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4936. end;
  4937. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4938. RemoveCurrentP(p);
  4939. result:=true;
  4940. exit;
  4941. end
  4942. { changes
  4943. lea offset1(regX), reg1
  4944. lea offset2(reg1), reg1
  4945. to
  4946. lea offset1+offset2(regX), reg1 }
  4947. else if
  4948. (
  4949. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4950. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4951. ) or (
  4952. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4953. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4954. (
  4955. (
  4956. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4957. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4958. ) or (
  4959. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4960. (
  4961. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4962. (
  4963. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4964. (
  4965. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4966. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4967. )
  4968. )
  4969. )
  4970. )
  4971. )
  4972. ) then
  4973. begin
  4974. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4975. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4976. begin
  4977. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4978. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4979. { if the register is used as index and base, we have to increase for base as well
  4980. and adapt base }
  4981. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4982. begin
  4983. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4984. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4985. end;
  4986. end
  4987. else
  4988. begin
  4989. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4990. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4991. end;
  4992. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4993. begin
  4994. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4995. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4996. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4997. end;
  4998. RemoveCurrentP(p);
  4999. result:=true;
  5000. exit;
  5001. end;
  5002. end;
  5003. { Change:
  5004. leal/q $x(%reg1),%reg2
  5005. ...
  5006. shll/q $y,%reg2
  5007. To:
  5008. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5009. }
  5010. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5011. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5012. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5013. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5014. (taicpu(hp1).oper[0]^.val <= 3) then
  5015. begin
  5016. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5017. TransferUsedRegs(TmpUsedRegs);
  5018. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5019. if
  5020. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5021. (this works even if scalefactor is zero) }
  5022. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5023. { Ensure offset doesn't go out of bounds }
  5024. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5025. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5026. (
  5027. (
  5028. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5029. (
  5030. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5031. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5032. (
  5033. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5034. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5035. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5036. )
  5037. )
  5038. ) or (
  5039. (
  5040. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5041. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5042. ) and
  5043. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5044. )
  5045. ) then
  5046. begin
  5047. repeat
  5048. with taicpu(p).oper[0]^.ref^ do
  5049. begin
  5050. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5051. if index = base then
  5052. begin
  5053. if Multiple > 4 then
  5054. { Optimisation will no longer work because resultant
  5055. scale factor will exceed 8 }
  5056. Break;
  5057. base := NR_NO;
  5058. scalefactor := 2;
  5059. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5060. end
  5061. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5062. begin
  5063. { Scale factor only works on the index register }
  5064. index := base;
  5065. base := NR_NO;
  5066. end;
  5067. { For safety }
  5068. if scalefactor <= 1 then
  5069. begin
  5070. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5071. scalefactor := Multiple;
  5072. end
  5073. else
  5074. begin
  5075. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5076. scalefactor := scalefactor * Multiple;
  5077. end;
  5078. offset := offset * Multiple;
  5079. end;
  5080. RemoveInstruction(hp1);
  5081. Result := True;
  5082. Exit;
  5083. { This repeat..until loop exists for the benefit of Break }
  5084. until True;
  5085. end;
  5086. end;
  5087. end;
  5088. end;
  5089. end;
  5090. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5091. var
  5092. hp1 : tai;
  5093. begin
  5094. DoSubAddOpt := False;
  5095. if taicpu(p).oper[0]^.typ <> top_const then
  5096. { Should have been confirmed before calling }
  5097. InternalError(2021102601);
  5098. if GetLastInstruction(p, hp1) and
  5099. (hp1.typ = ait_instruction) and
  5100. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5101. case taicpu(hp1).opcode Of
  5102. A_DEC:
  5103. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5104. begin
  5105. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5106. RemoveInstruction(hp1);
  5107. end;
  5108. A_SUB:
  5109. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5111. begin
  5112. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5113. RemoveInstruction(hp1);
  5114. end;
  5115. A_ADD:
  5116. begin
  5117. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5118. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5119. begin
  5120. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5121. RemoveInstruction(hp1);
  5122. if (taicpu(p).oper[0]^.val = 0) then
  5123. begin
  5124. hp1 := tai(p.next);
  5125. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5126. if not GetLastInstruction(hp1, p) then
  5127. p := hp1;
  5128. DoSubAddOpt := True;
  5129. end
  5130. end;
  5131. end;
  5132. else
  5133. ;
  5134. end;
  5135. end;
  5136. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5137. begin
  5138. Result := False;
  5139. if UpdateTmpUsedRegs then
  5140. TransferUsedRegs(TmpUsedRegs);
  5141. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5142. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5143. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5144. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5145. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5146. (
  5147. (
  5148. (taicpu(hp1).opcode = A_TEST)
  5149. ) or (
  5150. (taicpu(hp1).opcode = A_CMP) and
  5151. { A sanity check more than anything }
  5152. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5153. )
  5154. ) then
  5155. begin
  5156. { change
  5157. mov mem, %reg
  5158. cmp/test x, %reg / test %reg,%reg
  5159. (reg deallocated)
  5160. to
  5161. cmp/test x, mem / cmp 0, mem
  5162. }
  5163. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5164. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5165. begin
  5166. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5167. if (taicpu(hp1).opcode = A_TEST) and
  5168. (
  5169. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5170. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5171. ) then
  5172. begin
  5173. taicpu(hp1).opcode := A_CMP;
  5174. taicpu(hp1).loadconst(0, 0);
  5175. end;
  5176. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5177. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5178. RemoveCurrentP(p, hp1);
  5179. Result := True;
  5180. Exit;
  5181. end;
  5182. end;
  5183. end;
  5184. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5185. var
  5186. hp2, hp3, hp4, hp5, hp6: tai;
  5187. ThisReg: TRegister;
  5188. JumpLoc: TAsmLabel;
  5189. begin
  5190. Result := False;
  5191. {
  5192. Convert:
  5193. j<c> .L1
  5194. .L2:
  5195. mov 1,reg
  5196. jmp .L3 (or ret, although it might not be a RET yet)
  5197. .L1:
  5198. mov 0,reg
  5199. jmp .L3 (or ret)
  5200. ( As long as .L3 <> .L1 or .L2)
  5201. To:
  5202. mov 0,reg
  5203. set<not(c)> reg
  5204. jmp .L3 (or ret)
  5205. .L2:
  5206. mov 1,reg
  5207. jmp .L3 (or ret)
  5208. .L1:
  5209. mov 0,reg
  5210. jmp .L3 (or ret)
  5211. }
  5212. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5213. Exit;
  5214. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5215. if GetNextInstruction(hp_label, hp2) and
  5216. MatchInstruction(hp2,A_MOV,[]) and
  5217. (taicpu(hp2).oper[0]^.typ = top_const) and
  5218. (
  5219. (
  5220. (taicpu(hp2).oper[1]^.typ = top_reg)
  5221. {$ifdef i386}
  5222. { Under i386, ESI, EDI, EBP and ESP
  5223. don't have an 8-bit representation }
  5224. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5225. {$endif i386}
  5226. ) or (
  5227. {$ifdef i386}
  5228. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5229. {$endif i386}
  5230. (taicpu(hp2).opsize = S_B)
  5231. )
  5232. ) and
  5233. GetNextInstruction(hp2, hp3) and
  5234. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5235. (
  5236. (taicpu(hp3).opcode=A_RET) or
  5237. (
  5238. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5239. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5240. )
  5241. ) and
  5242. GetNextInstruction(hp3, hp4) and
  5243. SkipAligns(hp4, hp4) and
  5244. (hp4.typ=ait_label) and
  5245. (tai_label(hp4).labsym=JumpLoc) and
  5246. (
  5247. not (cs_opt_size in current_settings.optimizerswitches) or
  5248. { If the initial jump is the label's only reference, then it will
  5249. become a dead label if the other conditions are met and hence
  5250. remove at least 2 instructions, including a jump }
  5251. (JumpLoc.getrefs = 1)
  5252. ) and
  5253. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5254. that will be optimised out }
  5255. GetNextInstruction(hp4, hp5) and
  5256. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5257. (taicpu(hp5).oper[0]^.typ = top_const) and
  5258. (
  5259. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5260. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5261. ) and
  5262. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5263. GetNextInstruction(hp5,hp6) and
  5264. (
  5265. (hp6.typ<>ait_label) or
  5266. SkipLabels(hp6, hp6)
  5267. ) and
  5268. (hp6.typ=ait_instruction) then
  5269. begin
  5270. { First, let's look at the two jumps that are hp3 and hp6 }
  5271. if not
  5272. (
  5273. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5274. (
  5275. (taicpu(hp6).opcode=A_RET) or
  5276. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5277. )
  5278. ) then
  5279. { If condition is False, then the JMP/RET instructions matched conventionally }
  5280. begin
  5281. { See if one of the jumps can be instantly converted into a RET }
  5282. if (taicpu(hp3).opcode=A_JMP) then
  5283. begin
  5284. { Reuse hp5 }
  5285. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5286. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5287. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5288. Exit;
  5289. if MatchInstruction(hp5, A_RET, []) then
  5290. begin
  5291. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5292. ConvertJumpToRET(hp3, hp5);
  5293. Result := True;
  5294. end
  5295. else
  5296. Exit;
  5297. end;
  5298. if (taicpu(hp6).opcode=A_JMP) then
  5299. begin
  5300. { Reuse hp5 }
  5301. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5302. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5303. Exit;
  5304. if MatchInstruction(hp5, A_RET, []) then
  5305. begin
  5306. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5307. ConvertJumpToRET(hp6, hp5);
  5308. Result := True;
  5309. end
  5310. else
  5311. Exit;
  5312. end;
  5313. if not
  5314. (
  5315. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5316. (
  5317. (taicpu(hp6).opcode=A_RET) or
  5318. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5319. )
  5320. ) then
  5321. { Still doesn't match }
  5322. Exit;
  5323. end;
  5324. if (taicpu(hp2).oper[0]^.val = 1) then
  5325. begin
  5326. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5327. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5328. end
  5329. else
  5330. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5331. if taicpu(hp2).opsize=S_B then
  5332. begin
  5333. if taicpu(hp2).oper[1]^.typ = top_reg then
  5334. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5335. else
  5336. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5337. hp2 := p;
  5338. end
  5339. else
  5340. begin
  5341. { Will be a register because the size can't be S_B otherwise }
  5342. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5343. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5344. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5345. { Inserting it right before p will guarantee that the flags are also tracked }
  5346. Asml.InsertBefore(hp2, p);
  5347. end;
  5348. taicpu(hp4).condition:=taicpu(p).condition;
  5349. asml.InsertBefore(hp4, hp2);
  5350. JumpLoc.decrefs;
  5351. if taicpu(hp3).opcode = A_JMP then
  5352. begin
  5353. MakeUnconditional(taicpu(p));
  5354. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5355. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5356. end
  5357. else
  5358. begin
  5359. taicpu(p).condition := C_None;
  5360. taicpu(p).opcode := A_RET;
  5361. taicpu(p).clearop(0);
  5362. taicpu(p).ops := 0;
  5363. end;
  5364. if (JumpLoc.getrefs = 0) then
  5365. RemoveDeadCodeAfterJump(hp3);
  5366. Result:=true;
  5367. exit;
  5368. end;
  5369. end;
  5370. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5371. var
  5372. hp1, hp2: tai;
  5373. ActiveReg: TRegister;
  5374. OldOffset: asizeint;
  5375. ThisConst: TCGInt;
  5376. function RegDeallocated: Boolean;
  5377. begin
  5378. TransferUsedRegs(TmpUsedRegs);
  5379. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5380. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5381. end;
  5382. begin
  5383. Result:=false;
  5384. hp1 := nil;
  5385. { replace
  5386. subX const,%reg1
  5387. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5388. dealloc %reg1
  5389. by
  5390. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5391. }
  5392. if MatchOpType(taicpu(p),top_const,top_reg) then
  5393. begin
  5394. ActiveReg := taicpu(p).oper[1]^.reg;
  5395. { Ensures the entire register was updated }
  5396. if (taicpu(p).opsize >= S_L) and
  5397. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5398. MatchInstruction(hp1,A_LEA,[]) and
  5399. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5400. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5401. (
  5402. { Cover the case where the register in the reference is also the destination register }
  5403. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5404. (
  5405. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5406. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5407. RegDeallocated
  5408. )
  5409. ) then
  5410. begin
  5411. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5412. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5413. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5414. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5415. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5416. {$ifdef x86_64}
  5417. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5418. begin
  5419. { Overflow; abort }
  5420. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5421. end
  5422. else
  5423. {$endif x86_64}
  5424. begin
  5425. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5426. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5427. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5428. RemoveCurrentP(p, hp1)
  5429. else
  5430. RemoveCurrentP(p);
  5431. result:=true;
  5432. Exit;
  5433. end;
  5434. end;
  5435. if (
  5436. { Save calling GetNextInstructionUsingReg again }
  5437. Assigned(hp1) or
  5438. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5439. ) and
  5440. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5441. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5442. begin
  5443. if taicpu(hp1).oper[0]^.typ = top_const then
  5444. begin
  5445. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5446. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5447. Result := True;
  5448. { Handle any overflows }
  5449. case taicpu(p).opsize of
  5450. S_B:
  5451. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5452. S_W:
  5453. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5454. S_L:
  5455. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5456. {$ifdef x86_64}
  5457. S_Q:
  5458. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5459. { Overflow; abort }
  5460. Result := False
  5461. else
  5462. taicpu(p).oper[0]^.val := ThisConst;
  5463. {$endif x86_64}
  5464. else
  5465. InternalError(2021102610);
  5466. end;
  5467. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5468. if Result then
  5469. begin
  5470. if (taicpu(p).oper[0]^.val < 0) and
  5471. (
  5472. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5473. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5474. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5475. ) then
  5476. begin
  5477. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5478. taicpu(p).opcode := A_SUB;
  5479. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5480. end
  5481. else
  5482. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5483. RemoveInstruction(hp1);
  5484. end;
  5485. end
  5486. else
  5487. begin
  5488. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5489. TransferUsedRegs(TmpUsedRegs);
  5490. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5491. hp2 := p;
  5492. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5493. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5494. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5495. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5496. begin
  5497. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5498. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5499. Asml.Remove(p);
  5500. Asml.InsertAfter(p, hp1);
  5501. p := hp1;
  5502. Result := True;
  5503. Exit;
  5504. end;
  5505. end;
  5506. end;
  5507. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5508. { * change "sub/add const1, reg" or "dec reg" followed by
  5509. "sub const2, reg" to one "sub ..., reg" }
  5510. {$ifdef i386}
  5511. if (taicpu(p).oper[0]^.val = 2) and
  5512. (ActiveReg = NR_ESP) and
  5513. { Don't do the sub/push optimization if the sub }
  5514. { comes from setting up the stack frame (JM) }
  5515. (not(GetLastInstruction(p,hp1)) or
  5516. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5517. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5518. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5519. begin
  5520. hp1 := tai(p.next);
  5521. while Assigned(hp1) and
  5522. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5523. not RegReadByInstruction(NR_ESP,hp1) and
  5524. not RegModifiedByInstruction(NR_ESP,hp1) do
  5525. hp1 := tai(hp1.next);
  5526. if Assigned(hp1) and
  5527. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5528. begin
  5529. taicpu(hp1).changeopsize(S_L);
  5530. if taicpu(hp1).oper[0]^.typ=top_reg then
  5531. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5532. hp1 := tai(p.next);
  5533. RemoveCurrentp(p, hp1);
  5534. Result:=true;
  5535. exit;
  5536. end;
  5537. end;
  5538. {$endif i386}
  5539. if DoSubAddOpt(p) then
  5540. Result:=true;
  5541. end;
  5542. end;
  5543. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5544. var
  5545. TmpBool1,TmpBool2 : Boolean;
  5546. tmpref : treference;
  5547. hp1,hp2: tai;
  5548. mask: tcgint;
  5549. begin
  5550. Result:=false;
  5551. { All these optimisations work on "shl/sal const,%reg" }
  5552. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5553. Exit;
  5554. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5555. (taicpu(p).oper[0]^.val <= 3) then
  5556. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5557. begin
  5558. { should we check the next instruction? }
  5559. TmpBool1 := True;
  5560. { have we found an add/sub which could be
  5561. integrated in the lea? }
  5562. TmpBool2 := False;
  5563. reference_reset(tmpref,2,[]);
  5564. TmpRef.index := taicpu(p).oper[1]^.reg;
  5565. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5566. while TmpBool1 and
  5567. GetNextInstruction(p, hp1) and
  5568. (tai(hp1).typ = ait_instruction) and
  5569. ((((taicpu(hp1).opcode = A_ADD) or
  5570. (taicpu(hp1).opcode = A_SUB)) and
  5571. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5572. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5573. (((taicpu(hp1).opcode = A_INC) or
  5574. (taicpu(hp1).opcode = A_DEC)) and
  5575. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5576. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5577. ((taicpu(hp1).opcode = A_LEA) and
  5578. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5579. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5580. (not GetNextInstruction(hp1,hp2) or
  5581. not instrReadsFlags(hp2)) Do
  5582. begin
  5583. TmpBool1 := False;
  5584. if taicpu(hp1).opcode=A_LEA then
  5585. begin
  5586. if (TmpRef.base = NR_NO) and
  5587. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5588. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5589. { Segment register isn't a concern here }
  5590. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5591. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5592. begin
  5593. TmpBool1 := True;
  5594. TmpBool2 := True;
  5595. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5596. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5597. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5598. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5599. RemoveInstruction(hp1);
  5600. end
  5601. end
  5602. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5603. begin
  5604. TmpBool1 := True;
  5605. TmpBool2 := True;
  5606. case taicpu(hp1).opcode of
  5607. A_ADD:
  5608. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5609. A_SUB:
  5610. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5611. else
  5612. internalerror(2019050536);
  5613. end;
  5614. RemoveInstruction(hp1);
  5615. end
  5616. else
  5617. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5618. (((taicpu(hp1).opcode = A_ADD) and
  5619. (TmpRef.base = NR_NO)) or
  5620. (taicpu(hp1).opcode = A_INC) or
  5621. (taicpu(hp1).opcode = A_DEC)) then
  5622. begin
  5623. TmpBool1 := True;
  5624. TmpBool2 := True;
  5625. case taicpu(hp1).opcode of
  5626. A_ADD:
  5627. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5628. A_INC:
  5629. inc(TmpRef.offset);
  5630. A_DEC:
  5631. dec(TmpRef.offset);
  5632. else
  5633. internalerror(2019050535);
  5634. end;
  5635. RemoveInstruction(hp1);
  5636. end;
  5637. end;
  5638. if TmpBool2
  5639. {$ifndef x86_64}
  5640. or
  5641. ((current_settings.optimizecputype < cpu_Pentium2) and
  5642. (taicpu(p).oper[0]^.val <= 3) and
  5643. not(cs_opt_size in current_settings.optimizerswitches))
  5644. {$endif x86_64}
  5645. then
  5646. begin
  5647. if not(TmpBool2) and
  5648. (taicpu(p).oper[0]^.val=1) then
  5649. begin
  5650. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5651. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5652. end
  5653. else
  5654. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5655. taicpu(p).oper[1]^.reg);
  5656. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5657. InsertLLItem(p.previous, p.next, hp1);
  5658. p.free;
  5659. p := hp1;
  5660. end;
  5661. end
  5662. {$ifndef x86_64}
  5663. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5664. begin
  5665. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5666. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5667. (unlike shl, which is only Tairable in the U pipe) }
  5668. if taicpu(p).oper[0]^.val=1 then
  5669. begin
  5670. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5671. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5672. InsertLLItem(p.previous, p.next, hp1);
  5673. p.free;
  5674. p := hp1;
  5675. end
  5676. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5677. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5678. else if (taicpu(p).opsize = S_L) and
  5679. (taicpu(p).oper[0]^.val<= 3) then
  5680. begin
  5681. reference_reset(tmpref,2,[]);
  5682. TmpRef.index := taicpu(p).oper[1]^.reg;
  5683. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5684. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5685. InsertLLItem(p.previous, p.next, hp1);
  5686. p.free;
  5687. p := hp1;
  5688. end;
  5689. end
  5690. {$endif x86_64}
  5691. else if
  5692. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5693. (
  5694. (
  5695. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5696. SetAndTest(hp1, hp2)
  5697. {$ifdef x86_64}
  5698. ) or
  5699. (
  5700. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5701. GetNextInstruction(hp1, hp2) and
  5702. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5703. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5704. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5705. {$endif x86_64}
  5706. )
  5707. ) and
  5708. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5709. begin
  5710. { Change:
  5711. shl x, %reg1
  5712. mov -(1<<x), %reg2
  5713. and %reg2, %reg1
  5714. Or:
  5715. shl x, %reg1
  5716. and -(1<<x), %reg1
  5717. To just:
  5718. shl x, %reg1
  5719. Since the and operation only zeroes bits that are already zero from the shl operation
  5720. }
  5721. case taicpu(p).oper[0]^.val of
  5722. 8:
  5723. mask:=$FFFFFFFFFFFFFF00;
  5724. 16:
  5725. mask:=$FFFFFFFFFFFF0000;
  5726. 32:
  5727. mask:=$FFFFFFFF00000000;
  5728. 63:
  5729. { Constant pre-calculated to prevent overflow errors with Int64 }
  5730. mask:=$8000000000000000;
  5731. else
  5732. begin
  5733. if taicpu(p).oper[0]^.val >= 64 then
  5734. { Shouldn't happen realistically, since the register
  5735. is guaranteed to be set to zero at this point }
  5736. mask := 0
  5737. else
  5738. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5739. end;
  5740. end;
  5741. if taicpu(hp1).oper[0]^.val = mask then
  5742. begin
  5743. { Everything checks out, perform the optimisation, as long as
  5744. the FLAGS register isn't being used}
  5745. TransferUsedRegs(TmpUsedRegs);
  5746. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5747. {$ifdef x86_64}
  5748. if (hp1 <> hp2) then
  5749. begin
  5750. { "shl/mov/and" version }
  5751. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5752. { Don't do the optimisation if the FLAGS register is in use }
  5753. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5754. begin
  5755. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5756. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5757. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5758. begin
  5759. RemoveInstruction(hp1);
  5760. Result := True;
  5761. end;
  5762. { Only set Result to True if the 'mov' instruction was removed }
  5763. RemoveInstruction(hp2);
  5764. end;
  5765. end
  5766. else
  5767. {$endif x86_64}
  5768. begin
  5769. { "shl/and" version }
  5770. { Don't do the optimisation if the FLAGS register is in use }
  5771. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5772. begin
  5773. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5774. RemoveInstruction(hp1);
  5775. Result := True;
  5776. end;
  5777. end;
  5778. Exit;
  5779. end
  5780. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5781. begin
  5782. { Even if the mask doesn't allow for its removal, we might be
  5783. able to optimise the mask for the "shl/and" version, which
  5784. may permit other peephole optimisations }
  5785. {$ifdef DEBUG_AOPTCPU}
  5786. mask := taicpu(hp1).oper[0]^.val and mask;
  5787. if taicpu(hp1).oper[0]^.val <> mask then
  5788. begin
  5789. DebugMsg(
  5790. SPeepholeOptimization +
  5791. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5792. ' to $' + debug_tostr(mask) +
  5793. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5794. taicpu(hp1).oper[0]^.val := mask;
  5795. end;
  5796. {$else DEBUG_AOPTCPU}
  5797. { If debugging is off, just set the operand even if it's the same }
  5798. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5799. {$endif DEBUG_AOPTCPU}
  5800. end;
  5801. end;
  5802. {
  5803. change
  5804. shl/sal const,reg
  5805. <op> ...(...,reg,1),...
  5806. into
  5807. <op> ...(...,reg,1 shl const),...
  5808. if const in 1..3
  5809. }
  5810. if MatchOpType(taicpu(p), top_const, top_reg) and
  5811. (taicpu(p).oper[0]^.val in [1..3]) and
  5812. GetNextInstruction(p, hp1) and
  5813. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5814. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5815. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5816. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5817. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5818. begin
  5819. TransferUsedRegs(TmpUsedRegs);
  5820. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5821. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5822. begin
  5823. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5824. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5825. RemoveCurrentP(p);
  5826. Result:=true;
  5827. end;
  5828. end;
  5829. end;
  5830. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5831. var
  5832. CurrentRef: TReference;
  5833. FullReg: TRegister;
  5834. hp1, hp2: tai;
  5835. begin
  5836. Result := False;
  5837. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5838. Exit;
  5839. { We assume you've checked if the operand is actually a reference by
  5840. this point. If it isn't, you'll most likely get an access violation }
  5841. CurrentRef := first_mov.oper[1]^.ref^;
  5842. { Memory must be aligned }
  5843. if (CurrentRef.offset mod 4) <> 0 then
  5844. Exit;
  5845. Inc(CurrentRef.offset);
  5846. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5847. if MatchOperand(second_mov.oper[0]^, 0) and
  5848. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5849. GetNextInstruction(second_mov, hp1) and
  5850. (hp1.typ = ait_instruction) and
  5851. (taicpu(hp1).opcode = A_MOV) and
  5852. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5853. (taicpu(hp1).oper[0]^.val = 0) then
  5854. begin
  5855. Inc(CurrentRef.offset);
  5856. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5857. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5858. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5859. begin
  5860. case taicpu(hp1).opsize of
  5861. S_B:
  5862. if GetNextInstruction(hp1, hp2) and
  5863. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5864. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5865. (taicpu(hp2).oper[0]^.val = 0) then
  5866. begin
  5867. Inc(CurrentRef.offset);
  5868. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5869. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5870. (taicpu(hp2).opsize = S_B) then
  5871. begin
  5872. RemoveInstruction(hp1);
  5873. RemoveInstruction(hp2);
  5874. first_mov.opsize := S_L;
  5875. if first_mov.oper[0]^.typ = top_reg then
  5876. begin
  5877. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5878. { Reuse second_mov as a MOVZX instruction }
  5879. second_mov.opcode := A_MOVZX;
  5880. second_mov.opsize := S_BL;
  5881. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5882. second_mov.loadreg(1, FullReg);
  5883. first_mov.oper[0]^.reg := FullReg;
  5884. asml.Remove(second_mov);
  5885. asml.InsertBefore(second_mov, first_mov);
  5886. end
  5887. else
  5888. { It's a value }
  5889. begin
  5890. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5891. RemoveInstruction(second_mov);
  5892. end;
  5893. Result := True;
  5894. Exit;
  5895. end;
  5896. end;
  5897. S_W:
  5898. begin
  5899. RemoveInstruction(hp1);
  5900. first_mov.opsize := S_L;
  5901. if first_mov.oper[0]^.typ = top_reg then
  5902. begin
  5903. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5904. { Reuse second_mov as a MOVZX instruction }
  5905. second_mov.opcode := A_MOVZX;
  5906. second_mov.opsize := S_BL;
  5907. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5908. second_mov.loadreg(1, FullReg);
  5909. first_mov.oper[0]^.reg := FullReg;
  5910. asml.Remove(second_mov);
  5911. asml.InsertBefore(second_mov, first_mov);
  5912. end
  5913. else
  5914. { It's a value }
  5915. begin
  5916. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5917. RemoveInstruction(second_mov);
  5918. end;
  5919. Result := True;
  5920. Exit;
  5921. end;
  5922. else
  5923. ;
  5924. end;
  5925. end;
  5926. end;
  5927. end;
  5928. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5929. { returns true if a "continue" should be done after this optimization }
  5930. var
  5931. hp1, hp2: tai;
  5932. begin
  5933. Result := false;
  5934. if MatchOpType(taicpu(p),top_ref) and
  5935. GetNextInstruction(p, hp1) and
  5936. (hp1.typ = ait_instruction) and
  5937. (((taicpu(hp1).opcode = A_FLD) and
  5938. (taicpu(p).opcode = A_FSTP)) or
  5939. ((taicpu(p).opcode = A_FISTP) and
  5940. (taicpu(hp1).opcode = A_FILD))) and
  5941. MatchOpType(taicpu(hp1),top_ref) and
  5942. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5943. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5944. begin
  5945. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5946. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5947. GetNextInstruction(hp1, hp2) and
  5948. (hp2.typ = ait_instruction) and
  5949. IsExitCode(hp2) and
  5950. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5951. not(assigned(current_procinfo.procdef.funcretsym) and
  5952. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5953. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5954. begin
  5955. RemoveInstruction(hp1);
  5956. RemoveCurrentP(p, hp2);
  5957. RemoveLastDeallocForFuncRes(p);
  5958. Result := true;
  5959. end
  5960. else
  5961. { we can do this only in fast math mode as fstp is rounding ...
  5962. ... still disabled as it breaks the compiler and/or rtl }
  5963. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5964. { ... or if another fstp equal to the first one follows }
  5965. (GetNextInstruction(hp1,hp2) and
  5966. (hp2.typ = ait_instruction) and
  5967. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5968. (taicpu(p).opsize=taicpu(hp2).opsize))
  5969. ) and
  5970. { fst can't store an extended/comp value }
  5971. (taicpu(p).opsize <> S_FX) and
  5972. (taicpu(p).opsize <> S_IQ) then
  5973. begin
  5974. if (taicpu(p).opcode = A_FSTP) then
  5975. taicpu(p).opcode := A_FST
  5976. else
  5977. taicpu(p).opcode := A_FIST;
  5978. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5979. RemoveInstruction(hp1);
  5980. end;
  5981. end;
  5982. end;
  5983. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5984. var
  5985. hp1, hp2: tai;
  5986. begin
  5987. result:=false;
  5988. if MatchOpType(taicpu(p),top_reg) and
  5989. GetNextInstruction(p, hp1) and
  5990. (hp1.typ = Ait_Instruction) and
  5991. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5992. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5993. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5994. { change to
  5995. fld reg fxxx reg,st
  5996. fxxxp st, st1 (hp1)
  5997. Remark: non commutative operations must be reversed!
  5998. }
  5999. begin
  6000. case taicpu(hp1).opcode Of
  6001. A_FMULP,A_FADDP,
  6002. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6003. begin
  6004. case taicpu(hp1).opcode Of
  6005. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6006. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6007. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6008. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6009. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6010. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6011. else
  6012. internalerror(2019050534);
  6013. end;
  6014. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6015. taicpu(hp1).oper[1]^.reg := NR_ST;
  6016. RemoveCurrentP(p, hp1);
  6017. Result:=true;
  6018. exit;
  6019. end;
  6020. else
  6021. ;
  6022. end;
  6023. end
  6024. else
  6025. if MatchOpType(taicpu(p),top_ref) and
  6026. GetNextInstruction(p, hp2) and
  6027. (hp2.typ = Ait_Instruction) and
  6028. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6029. (taicpu(p).opsize in [S_FS, S_FL]) and
  6030. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6031. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6032. if GetLastInstruction(p, hp1) and
  6033. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6034. MatchOpType(taicpu(hp1),top_ref) and
  6035. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6036. if ((taicpu(hp2).opcode = A_FMULP) or
  6037. (taicpu(hp2).opcode = A_FADDP)) then
  6038. { change to
  6039. fld/fst mem1 (hp1) fld/fst mem1
  6040. fld mem1 (p) fadd/
  6041. faddp/ fmul st, st
  6042. fmulp st, st1 (hp2) }
  6043. begin
  6044. RemoveCurrentP(p, hp1);
  6045. if (taicpu(hp2).opcode = A_FADDP) then
  6046. taicpu(hp2).opcode := A_FADD
  6047. else
  6048. taicpu(hp2).opcode := A_FMUL;
  6049. taicpu(hp2).oper[1]^.reg := NR_ST;
  6050. end
  6051. else
  6052. { change to
  6053. fld/fst mem1 (hp1) fld/fst mem1
  6054. fld mem1 (p) fld st}
  6055. begin
  6056. taicpu(p).changeopsize(S_FL);
  6057. taicpu(p).loadreg(0,NR_ST);
  6058. end
  6059. else
  6060. begin
  6061. case taicpu(hp2).opcode Of
  6062. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6063. { change to
  6064. fld/fst mem1 (hp1) fld/fst mem1
  6065. fld mem2 (p) fxxx mem2
  6066. fxxxp st, st1 (hp2) }
  6067. begin
  6068. case taicpu(hp2).opcode Of
  6069. A_FADDP: taicpu(p).opcode := A_FADD;
  6070. A_FMULP: taicpu(p).opcode := A_FMUL;
  6071. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6072. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6073. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6074. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6075. else
  6076. internalerror(2019050533);
  6077. end;
  6078. RemoveInstruction(hp2);
  6079. end
  6080. else
  6081. ;
  6082. end
  6083. end
  6084. end;
  6085. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6086. begin
  6087. Result := condition_in(cond1, cond2) or
  6088. { Not strictly subsets due to the actual flags checked, but because we're
  6089. comparing integers, E is a subset of AE and GE and their aliases }
  6090. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6091. end;
  6092. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6093. var
  6094. v: TCGInt;
  6095. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6096. FirstMatch: Boolean;
  6097. NewReg: TRegister;
  6098. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6099. begin
  6100. Result:=false;
  6101. { All these optimisations need a next instruction }
  6102. if not GetNextInstruction(p, hp1) then
  6103. Exit;
  6104. { Search for:
  6105. cmp ###,###
  6106. j(c1) @lbl1
  6107. ...
  6108. @lbl:
  6109. cmp ###,### (same comparison as above)
  6110. j(c2) @lbl2
  6111. If c1 is a subset of c2, change to:
  6112. cmp ###,###
  6113. j(c1) @lbl2
  6114. (@lbl1 may become a dead label as a result)
  6115. }
  6116. { Also handle cases where there are multiple jumps in a row }
  6117. p_jump := hp1;
  6118. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6119. begin
  6120. if IsJumpToLabel(taicpu(p_jump)) then
  6121. begin
  6122. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6123. p_label := nil;
  6124. if Assigned(JumpLabel) then
  6125. p_label := getlabelwithsym(JumpLabel);
  6126. if Assigned(p_label) and
  6127. GetNextInstruction(p_label, p_dist) and
  6128. MatchInstruction(p_dist, A_CMP, []) and
  6129. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6130. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6131. GetNextInstruction(p_dist, hp1_dist) and
  6132. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6133. begin
  6134. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6135. if JumpLabel = JumpLabel_dist then
  6136. { This is an infinite loop }
  6137. Exit;
  6138. { Best optimisation when the first condition is a subset (or equal) of the second }
  6139. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6140. begin
  6141. { Any registers used here will already be allocated }
  6142. if Assigned(JumpLabel) then
  6143. JumpLabel.DecRefs;
  6144. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6145. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6146. Result := True;
  6147. { Don't exit yet. Since p and p_jump haven't actually been
  6148. removed, we can check for more on this iteration }
  6149. end
  6150. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6151. GetNextInstruction(hp1_dist, hp1_label) and
  6152. SkipAligns(hp1_label, hp1_label) and
  6153. (hp1_label.typ = ait_label) then
  6154. begin
  6155. JumpLabel_far := tai_label(hp1_label).labsym;
  6156. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6157. { This is an infinite loop }
  6158. Exit;
  6159. if Assigned(JumpLabel_far) then
  6160. begin
  6161. { In this situation, if the first jump branches, the second one will never,
  6162. branch so change the destination label to after the second jump }
  6163. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6164. if Assigned(JumpLabel) then
  6165. JumpLabel.DecRefs;
  6166. JumpLabel_far.IncRefs;
  6167. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6168. Result := True;
  6169. { Don't exit yet. Since p and p_jump haven't actually been
  6170. removed, we can check for more on this iteration }
  6171. Continue;
  6172. end;
  6173. end;
  6174. end;
  6175. end;
  6176. { Search for:
  6177. cmp ###,###
  6178. j(c1) @lbl1
  6179. cmp ###,### (same as first)
  6180. Remove second cmp
  6181. }
  6182. if GetNextInstruction(p_jump, hp2) and
  6183. (
  6184. (
  6185. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6186. (
  6187. (
  6188. MatchOpType(taicpu(p), top_const, top_reg) and
  6189. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6190. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6191. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6192. ) or (
  6193. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6194. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6195. )
  6196. )
  6197. ) or (
  6198. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6199. MatchOperand(taicpu(p).oper[0]^, 0) and
  6200. (taicpu(p).oper[1]^.typ = top_reg) and
  6201. MatchInstruction(hp2, A_TEST, []) and
  6202. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6203. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6204. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6205. )
  6206. ) then
  6207. begin
  6208. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6209. RemoveInstruction(hp2);
  6210. Result := True;
  6211. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6212. end;
  6213. GetNextInstruction(p_jump, p_jump);
  6214. end;
  6215. {
  6216. Try to optimise the following:
  6217. cmp $x,### ($x and $y can be registers or constants)
  6218. je @lbl1 (only reference)
  6219. cmp $y,### (### are identical)
  6220. @Lbl:
  6221. sete %reg1
  6222. Change to:
  6223. cmp $x,###
  6224. sete %reg2 (allocate new %reg2)
  6225. cmp $y,###
  6226. sete %reg1
  6227. orb %reg2,%reg1
  6228. (dealloc %reg2)
  6229. This adds an instruction (so don't perform under -Os), but it removes
  6230. a conditional branch.
  6231. }
  6232. if not (cs_opt_size in current_settings.optimizerswitches) and
  6233. (
  6234. (hp1 = p_jump) or
  6235. GetNextInstruction(p, hp1)
  6236. ) and
  6237. MatchInstruction(hp1, A_Jcc, []) and
  6238. IsJumpToLabel(taicpu(hp1)) and
  6239. (taicpu(hp1).condition in [C_E, C_Z]) and
  6240. GetNextInstruction(hp1, hp2) and
  6241. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6242. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6243. { The first operand of CMP instructions can only be a register or
  6244. immediate anyway, so no need to check }
  6245. GetNextInstruction(hp2, p_label) and
  6246. (
  6247. (p_label.typ = ait_label) or
  6248. (
  6249. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6250. to potentially cut down on the iterations of Pass 1 }
  6251. MatchInstruction(p_label, A_Jcc, []) and
  6252. IsJumpToLabel(taicpu(p_label)) and
  6253. { Use p_dist to hold the jump briefly }
  6254. SetAndTest(p_label, p_dist) and
  6255. GetNextInstruction(p_dist, p_label) and
  6256. (p_label.typ = ait_label) and
  6257. (tai_label(p_label).labsym.getrefs >= 2) and
  6258. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6259. { We might as well collapse the jump now }
  6260. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6261. )
  6262. ) and
  6263. (tai_label(p_label).labsym.getrefs = 1) and
  6264. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6265. GetNextInstruction(p_label, p_dist) and
  6266. MatchInstruction(p_dist, A_SETcc, []) and
  6267. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6268. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6269. { Get the instruction after the SETcc instruction so we can
  6270. allocate a new register over the entire range }
  6271. GetNextInstruction(p_dist, hp1_dist) then
  6272. begin
  6273. TransferUsedRegs(TmpUsedRegs);
  6274. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6275. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6276. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6277. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6278. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6279. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6280. begin
  6281. { Register can appear in p if it's not used afterwards, so only
  6282. allocate between hp1 and hp1_dist }
  6283. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6284. if NewReg <> NR_NO then
  6285. begin
  6286. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6287. { Change the jump instruction into a SETcc instruction }
  6288. taicpu(hp1).opcode := A_SETcc;
  6289. taicpu(hp1).opsize := S_B;
  6290. taicpu(hp1).loadreg(0, NewReg);
  6291. { This is now a dead label }
  6292. tai_label(p_label).labsym.decrefs;
  6293. { Prefer adding before the next instruction so the FLAGS
  6294. register is deallocated first }
  6295. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6296. AsmL.InsertBefore(
  6297. hp2,
  6298. hp1_dist
  6299. );
  6300. { Make sure the new register is in use over the new instruction
  6301. (long-winded, but things work best when the FLAGS register
  6302. is not allocated here) }
  6303. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6304. Result := True;
  6305. { Don't exit yet, as p wasn't changed and hp1, while
  6306. modified, is still intact and might be optimised by the
  6307. SETcc optimisation below }
  6308. end;
  6309. end;
  6310. end;
  6311. if taicpu(p).oper[0]^.typ = top_const then
  6312. begin
  6313. if (taicpu(p).oper[0]^.val = 0) and
  6314. (taicpu(p).oper[1]^.typ = top_reg) and
  6315. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6316. begin
  6317. hp2 := p;
  6318. FirstMatch := True;
  6319. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6320. anything meaningful once it's converted to "test %reg,%reg";
  6321. additionally, some jumps will always (or never) branch, so
  6322. evaluate every jump immediately following the
  6323. comparison, optimising the conditions if possible.
  6324. Similarly with SETcc... those that are always set to 0 or 1
  6325. are changed to MOV instructions }
  6326. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6327. (
  6328. GetNextInstruction(hp2, hp1) and
  6329. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6330. ) do
  6331. begin
  6332. FirstMatch := False;
  6333. case taicpu(hp1).condition of
  6334. C_B, C_C, C_NAE, C_O:
  6335. { For B/NAE:
  6336. Will never branch since an unsigned integer can never be below zero
  6337. For C/O:
  6338. Result cannot overflow because 0 is being subtracted
  6339. }
  6340. begin
  6341. if taicpu(hp1).opcode = A_Jcc then
  6342. begin
  6343. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6344. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6345. RemoveInstruction(hp1);
  6346. { Since hp1 was deleted, hp2 must not be updated }
  6347. Continue;
  6348. end
  6349. else
  6350. begin
  6351. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6352. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6353. taicpu(hp1).opcode := A_MOV;
  6354. taicpu(hp1).ops := 2;
  6355. taicpu(hp1).condition := C_None;
  6356. taicpu(hp1).opsize := S_B;
  6357. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6358. taicpu(hp1).loadconst(0, 0);
  6359. end;
  6360. end;
  6361. C_BE, C_NA:
  6362. begin
  6363. { Will only branch if equal to zero }
  6364. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6365. taicpu(hp1).condition := C_E;
  6366. end;
  6367. C_A, C_NBE:
  6368. begin
  6369. { Will only branch if not equal to zero }
  6370. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6371. taicpu(hp1).condition := C_NE;
  6372. end;
  6373. C_AE, C_NB, C_NC, C_NO:
  6374. begin
  6375. { Will always branch }
  6376. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6377. if taicpu(hp1).opcode = A_Jcc then
  6378. begin
  6379. MakeUnconditional(taicpu(hp1));
  6380. { Any jumps/set that follow will now be dead code }
  6381. RemoveDeadCodeAfterJump(taicpu(hp1));
  6382. Break;
  6383. end
  6384. else
  6385. begin
  6386. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6387. taicpu(hp1).opcode := A_MOV;
  6388. taicpu(hp1).ops := 2;
  6389. taicpu(hp1).condition := C_None;
  6390. taicpu(hp1).opsize := S_B;
  6391. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6392. taicpu(hp1).loadconst(0, 1);
  6393. end;
  6394. end;
  6395. C_None:
  6396. InternalError(2020012201);
  6397. C_P, C_PE, C_NP, C_PO:
  6398. { We can't handle parity checks and they should never be generated
  6399. after a general-purpose CMP (it's used in some floating-point
  6400. comparisons that don't use CMP) }
  6401. InternalError(2020012202);
  6402. else
  6403. { Zero/Equality, Sign, their complements and all of the
  6404. signed comparisons do not need to be converted };
  6405. end;
  6406. hp2 := hp1;
  6407. end;
  6408. { Convert the instruction to a TEST }
  6409. taicpu(p).opcode := A_TEST;
  6410. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6411. Result := True;
  6412. Exit;
  6413. end
  6414. else if (taicpu(p).oper[0]^.val = 1) and
  6415. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6416. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6417. begin
  6418. { Convert; To:
  6419. cmp $1,r/m cmp $0,r/m
  6420. jl @lbl jle @lbl
  6421. }
  6422. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6423. taicpu(p).oper[0]^.val := 0;
  6424. taicpu(hp1).condition := C_LE;
  6425. { If the instruction is now "cmp $0,%reg", convert it to a
  6426. TEST (and effectively do the work of the "cmp $0,%reg" in
  6427. the block above)
  6428. If it's a reference, we can get away with not setting
  6429. Result to True because he haven't evaluated the jump
  6430. in this pass yet.
  6431. }
  6432. if (taicpu(p).oper[1]^.typ = top_reg) then
  6433. begin
  6434. taicpu(p).opcode := A_TEST;
  6435. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6436. Result := True;
  6437. end;
  6438. Exit;
  6439. end
  6440. else if (taicpu(p).oper[1]^.typ = top_reg)
  6441. {$ifdef x86_64}
  6442. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6443. {$endif x86_64}
  6444. then
  6445. begin
  6446. { cmp register,$8000 neg register
  6447. je target --> jo target
  6448. .... only if register is deallocated before jump.}
  6449. case Taicpu(p).opsize of
  6450. S_B: v:=$80;
  6451. S_W: v:=$8000;
  6452. S_L: v:=qword($80000000);
  6453. else
  6454. internalerror(2013112905);
  6455. end;
  6456. if (taicpu(p).oper[0]^.val=v) and
  6457. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6458. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6459. begin
  6460. TransferUsedRegs(TmpUsedRegs);
  6461. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6462. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6463. begin
  6464. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6465. Taicpu(p).opcode:=A_NEG;
  6466. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6467. Taicpu(p).clearop(1);
  6468. Taicpu(p).ops:=1;
  6469. if Taicpu(hp1).condition=C_E then
  6470. Taicpu(hp1).condition:=C_O
  6471. else
  6472. Taicpu(hp1).condition:=C_NO;
  6473. Result:=true;
  6474. exit;
  6475. end;
  6476. end;
  6477. end;
  6478. end;
  6479. if TrySwapMovCmp(p, hp1) then
  6480. begin
  6481. Result := True;
  6482. Exit;
  6483. end;
  6484. end;
  6485. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6486. var
  6487. hp1: tai;
  6488. begin
  6489. {
  6490. remove the second (v)pxor from
  6491. pxor reg,reg
  6492. ...
  6493. pxor reg,reg
  6494. }
  6495. Result:=false;
  6496. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6497. MatchOpType(taicpu(p),top_reg,top_reg) and
  6498. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6499. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6500. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6501. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6502. begin
  6503. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6504. RemoveInstruction(hp1);
  6505. Result:=true;
  6506. Exit;
  6507. end
  6508. {
  6509. replace
  6510. pxor reg1,reg1
  6511. movapd/s reg1,reg2
  6512. dealloc reg1
  6513. by
  6514. pxor reg2,reg2
  6515. }
  6516. else if GetNextInstruction(p,hp1) and
  6517. { we mix single and double opperations here because we assume that the compiler
  6518. generates vmovapd only after double operations and vmovaps only after single operations }
  6519. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6520. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6521. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6522. (taicpu(p).oper[0]^.typ=top_reg) then
  6523. begin
  6524. TransferUsedRegs(TmpUsedRegs);
  6525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6526. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6527. begin
  6528. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6529. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6530. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6531. RemoveInstruction(hp1);
  6532. result:=true;
  6533. end;
  6534. end;
  6535. end;
  6536. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6537. var
  6538. hp1: tai;
  6539. begin
  6540. {
  6541. remove the second (v)pxor from
  6542. (v)pxor reg,reg
  6543. ...
  6544. (v)pxor reg,reg
  6545. }
  6546. Result:=false;
  6547. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6548. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6549. begin
  6550. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6551. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6552. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6553. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6554. begin
  6555. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6556. RemoveInstruction(hp1);
  6557. Result:=true;
  6558. Exit;
  6559. end;
  6560. {$ifdef x86_64}
  6561. {
  6562. replace
  6563. vpxor reg1,reg1,reg1
  6564. vmov reg,mem
  6565. by
  6566. movq $0,mem
  6567. }
  6568. if GetNextInstruction(p,hp1) and
  6569. MatchInstruction(hp1,A_VMOVSD,[]) and
  6570. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6571. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6572. begin
  6573. TransferUsedRegs(TmpUsedRegs);
  6574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6575. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6576. begin
  6577. taicpu(hp1).loadconst(0,0);
  6578. taicpu(hp1).opcode:=A_MOV;
  6579. taicpu(hp1).opsize:=S_Q;
  6580. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6581. RemoveCurrentP(p);
  6582. result:=true;
  6583. Exit;
  6584. end;
  6585. end;
  6586. {$endif x86_64}
  6587. end
  6588. {
  6589. replace
  6590. vpxor reg1,reg1,reg2
  6591. by
  6592. vpxor reg2,reg2,reg2
  6593. to avoid unncessary data dependencies
  6594. }
  6595. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6596. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6597. begin
  6598. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6599. { avoid unncessary data dependency }
  6600. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6601. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6602. result:=true;
  6603. exit;
  6604. end;
  6605. Result:=OptPass1VOP(p);
  6606. end;
  6607. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6608. var
  6609. hp1 : tai;
  6610. begin
  6611. result:=false;
  6612. { replace
  6613. IMul const,%mreg1,%mreg2
  6614. Mov %reg2,%mreg3
  6615. dealloc %mreg3
  6616. by
  6617. Imul const,%mreg1,%mreg23
  6618. }
  6619. if (taicpu(p).ops=3) and
  6620. GetNextInstruction(p,hp1) and
  6621. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6622. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6623. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6624. begin
  6625. TransferUsedRegs(TmpUsedRegs);
  6626. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6627. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6628. begin
  6629. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6630. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6631. RemoveInstruction(hp1);
  6632. result:=true;
  6633. end;
  6634. end;
  6635. end;
  6636. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6637. var
  6638. hp1 : tai;
  6639. begin
  6640. result:=false;
  6641. { replace
  6642. IMul %reg0,%reg1,%reg2
  6643. Mov %reg2,%reg3
  6644. dealloc %reg2
  6645. by
  6646. Imul %reg0,%reg1,%reg3
  6647. }
  6648. if GetNextInstruction(p,hp1) and
  6649. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6650. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6651. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6652. begin
  6653. TransferUsedRegs(TmpUsedRegs);
  6654. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6655. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6656. begin
  6657. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6658. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6659. RemoveInstruction(hp1);
  6660. result:=true;
  6661. end;
  6662. end;
  6663. end;
  6664. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6665. var
  6666. hp1: tai;
  6667. begin
  6668. Result:=false;
  6669. { get rid of
  6670. (v)cvtss2sd reg0,<reg1,>reg2
  6671. (v)cvtss2sd reg2,<reg2,>reg0
  6672. }
  6673. if GetNextInstruction(p,hp1) and
  6674. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6675. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6676. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6677. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6678. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6679. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6680. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6681. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6682. )
  6683. ) then
  6684. begin
  6685. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6686. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6687. begin
  6688. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6689. RemoveCurrentP(p);
  6690. RemoveInstruction(hp1);
  6691. end
  6692. else
  6693. begin
  6694. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6695. if taicpu(hp1).opcode=A_CVTSD2SS then
  6696. begin
  6697. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6698. taicpu(p).opcode:=A_MOVAPS;
  6699. end
  6700. else
  6701. begin
  6702. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6703. taicpu(p).opcode:=A_VMOVAPS;
  6704. end;
  6705. taicpu(p).ops:=2;
  6706. RemoveInstruction(hp1);
  6707. end;
  6708. Result:=true;
  6709. Exit;
  6710. end;
  6711. end;
  6712. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6713. var
  6714. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6715. ThisReg: TRegister;
  6716. begin
  6717. Result := False;
  6718. if not GetNextInstruction(p,hp1) then
  6719. Exit;
  6720. {
  6721. convert
  6722. j<c> .L1
  6723. mov 1,reg
  6724. jmp .L2
  6725. .L1
  6726. mov 0,reg
  6727. .L2
  6728. into
  6729. mov 0,reg
  6730. set<not(c)> reg
  6731. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6732. would destroy the flag contents
  6733. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6734. executed at the same time as a previous comparison.
  6735. set<not(c)> reg
  6736. movzx reg, reg
  6737. }
  6738. if MatchInstruction(hp1,A_MOV,[]) and
  6739. (taicpu(hp1).oper[0]^.typ = top_const) and
  6740. (
  6741. (
  6742. (taicpu(hp1).oper[1]^.typ = top_reg)
  6743. {$ifdef i386}
  6744. { Under i386, ESI, EDI, EBP and ESP
  6745. don't have an 8-bit representation }
  6746. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6747. {$endif i386}
  6748. ) or (
  6749. {$ifdef i386}
  6750. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6751. {$endif i386}
  6752. (taicpu(hp1).opsize = S_B)
  6753. )
  6754. ) and
  6755. GetNextInstruction(hp1,hp2) and
  6756. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6757. GetNextInstruction(hp2,hp3) and
  6758. SkipAligns(hp3, hp3) and
  6759. (hp3.typ=ait_label) and
  6760. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6761. GetNextInstruction(hp3,hp4) and
  6762. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6763. (taicpu(hp4).oper[0]^.typ = top_const) and
  6764. (
  6765. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6766. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6767. ) and
  6768. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6769. GetNextInstruction(hp4,hp5) and
  6770. SkipAligns(hp5, hp5) and
  6771. (hp5.typ=ait_label) and
  6772. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6773. begin
  6774. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6775. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6776. tai_label(hp3).labsym.DecRefs;
  6777. { If this isn't the only reference to the middle label, we can
  6778. still make a saving - only that the first jump and everything
  6779. that follows will remain. }
  6780. if (tai_label(hp3).labsym.getrefs = 0) then
  6781. begin
  6782. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6783. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6784. else
  6785. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6786. { remove jump, first label and second MOV (also catching any aligns) }
  6787. repeat
  6788. if not GetNextInstruction(hp2, hp3) then
  6789. InternalError(2021040810);
  6790. RemoveInstruction(hp2);
  6791. hp2 := hp3;
  6792. until hp2 = hp5;
  6793. { Don't decrement reference count before the removal loop
  6794. above, otherwise GetNextInstruction won't stop on the
  6795. the label }
  6796. tai_label(hp5).labsym.DecRefs;
  6797. end
  6798. else
  6799. begin
  6800. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6801. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6802. else
  6803. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6804. end;
  6805. taicpu(p).opcode:=A_SETcc;
  6806. taicpu(p).opsize:=S_B;
  6807. taicpu(p).is_jmp:=False;
  6808. if taicpu(hp1).opsize=S_B then
  6809. begin
  6810. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6811. if taicpu(hp1).oper[1]^.typ = top_reg then
  6812. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6813. RemoveInstruction(hp1);
  6814. end
  6815. else
  6816. begin
  6817. { Will be a register because the size can't be S_B otherwise }
  6818. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6819. taicpu(p).loadreg(0, ThisReg);
  6820. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6821. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6822. begin
  6823. case taicpu(hp1).opsize of
  6824. S_W:
  6825. taicpu(hp1).opsize := S_BW;
  6826. S_L:
  6827. taicpu(hp1).opsize := S_BL;
  6828. {$ifdef x86_64}
  6829. S_Q:
  6830. begin
  6831. taicpu(hp1).opsize := S_BL;
  6832. { Change the destination register to 32-bit }
  6833. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6834. end;
  6835. {$endif x86_64}
  6836. else
  6837. InternalError(2021040820);
  6838. end;
  6839. taicpu(hp1).opcode := A_MOVZX;
  6840. taicpu(hp1).loadreg(0, ThisReg);
  6841. end
  6842. else
  6843. begin
  6844. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6845. { hp1 is already a MOV instruction with the correct register }
  6846. taicpu(hp1).loadconst(0, 0);
  6847. { Inserting it right before p will guarantee that the flags are also tracked }
  6848. asml.Remove(hp1);
  6849. asml.InsertBefore(hp1, p);
  6850. end;
  6851. end;
  6852. Result:=true;
  6853. exit;
  6854. end
  6855. else if (hp1.typ = ait_label) then
  6856. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6857. end;
  6858. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6859. var
  6860. hp1, hp2, hp3: tai;
  6861. SourceRef, TargetRef: TReference;
  6862. CurrentReg: TRegister;
  6863. begin
  6864. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6865. if not UseAVX then
  6866. InternalError(2021100501);
  6867. Result := False;
  6868. { Look for the following to simplify:
  6869. vmovdqa/u x(mem1), %xmmreg
  6870. vmovdqa/u %xmmreg, y(mem2)
  6871. vmovdqa/u x+16(mem1), %xmmreg
  6872. vmovdqa/u %xmmreg, y+16(mem2)
  6873. Change to:
  6874. vmovdqa/u x(mem1), %ymmreg
  6875. vmovdqa/u %ymmreg, y(mem2)
  6876. vpxor %ymmreg, %ymmreg, %ymmreg
  6877. ( The VPXOR instruction is to zero the upper half, thus removing the
  6878. need to call the potentially expensive VZEROUPPER instruction. Other
  6879. peephole optimisations can remove VPXOR if it's unnecessary )
  6880. }
  6881. TransferUsedRegs(TmpUsedRegs);
  6882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6883. { NOTE: In the optimisations below, if the references dictate that an
  6884. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6885. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6886. if (taicpu(p).opsize = S_XMM) and
  6887. MatchOpType(taicpu(p), top_ref, top_reg) and
  6888. GetNextInstruction(p, hp1) and
  6889. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6890. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6891. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6892. begin
  6893. SourceRef := taicpu(p).oper[0]^.ref^;
  6894. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6895. if GetNextInstruction(hp1, hp2) and
  6896. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6897. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6898. begin
  6899. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6900. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6901. Inc(SourceRef.offset, 16);
  6902. { Reuse the register in the first block move }
  6903. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6904. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6905. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6906. begin
  6907. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6908. Inc(TargetRef.offset, 16);
  6909. if GetNextInstruction(hp2, hp3) and
  6910. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6911. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6912. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6913. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6914. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6915. begin
  6916. { Update the register tracking to the new size }
  6917. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6918. { Remember that the offsets are 16 ahead }
  6919. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6920. if not (
  6921. ((SourceRef.offset mod 32) = 16) and
  6922. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6923. ) then
  6924. taicpu(p).opcode := A_VMOVDQU;
  6925. taicpu(p).opsize := S_YMM;
  6926. taicpu(p).oper[1]^.reg := CurrentReg;
  6927. if not (
  6928. ((TargetRef.offset mod 32) = 16) and
  6929. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6930. ) then
  6931. taicpu(hp1).opcode := A_VMOVDQU;
  6932. taicpu(hp1).opsize := S_YMM;
  6933. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6934. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6935. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6936. if (pi_uses_ymm in current_procinfo.flags) then
  6937. RemoveInstruction(hp2)
  6938. else
  6939. begin
  6940. taicpu(hp2).opcode := A_VPXOR;
  6941. taicpu(hp2).opsize := S_YMM;
  6942. taicpu(hp2).loadreg(0, CurrentReg);
  6943. taicpu(hp2).loadreg(1, CurrentReg);
  6944. taicpu(hp2).loadreg(2, CurrentReg);
  6945. taicpu(hp2).ops := 3;
  6946. end;
  6947. RemoveInstruction(hp3);
  6948. Result := True;
  6949. Exit;
  6950. end;
  6951. end
  6952. else
  6953. begin
  6954. { See if the next references are 16 less rather than 16 greater }
  6955. Dec(SourceRef.offset, 32); { -16 the other way }
  6956. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6957. begin
  6958. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6959. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6960. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6961. GetNextInstruction(hp2, hp3) and
  6962. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6963. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6964. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6965. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6966. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6967. begin
  6968. { Update the register tracking to the new size }
  6969. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6970. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6971. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6972. if not(
  6973. ((SourceRef.offset mod 32) = 0) and
  6974. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6975. ) then
  6976. taicpu(hp2).opcode := A_VMOVDQU;
  6977. taicpu(hp2).opsize := S_YMM;
  6978. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6979. if not (
  6980. ((TargetRef.offset mod 32) = 0) and
  6981. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6982. ) then
  6983. taicpu(hp3).opcode := A_VMOVDQU;
  6984. taicpu(hp3).opsize := S_YMM;
  6985. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6986. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6987. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6988. if (pi_uses_ymm in current_procinfo.flags) then
  6989. RemoveInstruction(hp1)
  6990. else
  6991. begin
  6992. taicpu(hp1).opcode := A_VPXOR;
  6993. taicpu(hp1).opsize := S_YMM;
  6994. taicpu(hp1).loadreg(0, CurrentReg);
  6995. taicpu(hp1).loadreg(1, CurrentReg);
  6996. taicpu(hp1).loadreg(2, CurrentReg);
  6997. taicpu(hp1).ops := 3;
  6998. Asml.Remove(hp1);
  6999. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7000. end;
  7001. RemoveCurrentP(p, hp2);
  7002. Result := True;
  7003. Exit;
  7004. end;
  7005. end;
  7006. end;
  7007. end;
  7008. end;
  7009. end;
  7010. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7011. var
  7012. hp2, hp3, first_assignment: tai;
  7013. IncCount, OperIdx: Integer;
  7014. OrigLabel: TAsmLabel;
  7015. begin
  7016. Count := 0;
  7017. Result := False;
  7018. first_assignment := nil;
  7019. if (LoopCount >= 20) then
  7020. begin
  7021. { Guard against infinite loops }
  7022. Exit;
  7023. end;
  7024. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7025. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7026. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7027. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7028. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7029. Exit;
  7030. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7031. {
  7032. change
  7033. jmp .L1
  7034. ...
  7035. .L1:
  7036. mov ##, ## ( multiple movs possible )
  7037. jmp/ret
  7038. into
  7039. mov ##, ##
  7040. jmp/ret
  7041. }
  7042. if not Assigned(hp1) then
  7043. begin
  7044. hp1 := GetLabelWithSym(OrigLabel);
  7045. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7046. Exit;
  7047. end;
  7048. hp2 := hp1;
  7049. while Assigned(hp2) do
  7050. begin
  7051. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7052. SkipLabels(hp2,hp2);
  7053. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7054. Break;
  7055. case taicpu(hp2).opcode of
  7056. A_MOVSS:
  7057. begin
  7058. if taicpu(hp2).ops = 0 then
  7059. { Wrong MOVSS }
  7060. Break;
  7061. Inc(Count);
  7062. if Count >= 5 then
  7063. { Too many to be worthwhile }
  7064. Break;
  7065. GetNextInstruction(hp2, hp2);
  7066. Continue;
  7067. end;
  7068. A_MOV,
  7069. A_MOVD,
  7070. A_MOVQ,
  7071. A_MOVSX,
  7072. {$ifdef x86_64}
  7073. A_MOVSXD,
  7074. {$endif x86_64}
  7075. A_MOVZX,
  7076. A_MOVAPS,
  7077. A_MOVUPS,
  7078. A_MOVSD,
  7079. A_MOVAPD,
  7080. A_MOVUPD,
  7081. A_MOVDQA,
  7082. A_MOVDQU,
  7083. A_VMOVSS,
  7084. A_VMOVAPS,
  7085. A_VMOVUPS,
  7086. A_VMOVSD,
  7087. A_VMOVAPD,
  7088. A_VMOVUPD,
  7089. A_VMOVDQA,
  7090. A_VMOVDQU:
  7091. begin
  7092. Inc(Count);
  7093. if Count >= 5 then
  7094. { Too many to be worthwhile }
  7095. Break;
  7096. GetNextInstruction(hp2, hp2);
  7097. Continue;
  7098. end;
  7099. A_JMP:
  7100. begin
  7101. { Guard against infinite loops }
  7102. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7103. Exit;
  7104. { Analyse this jump first in case it also duplicates assignments }
  7105. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7106. begin
  7107. { Something did change! }
  7108. Result := True;
  7109. Inc(Count, IncCount);
  7110. if Count >= 5 then
  7111. begin
  7112. { Too many to be worthwhile }
  7113. Exit;
  7114. end;
  7115. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7116. Break;
  7117. end;
  7118. Result := True;
  7119. Break;
  7120. end;
  7121. A_RET:
  7122. begin
  7123. Result := True;
  7124. Break;
  7125. end;
  7126. else
  7127. Break;
  7128. end;
  7129. end;
  7130. if Result then
  7131. begin
  7132. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7133. if Count = 0 then
  7134. begin
  7135. Result := False;
  7136. Exit;
  7137. end;
  7138. hp3 := p;
  7139. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7140. while True do
  7141. begin
  7142. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7143. SkipLabels(hp1,hp1);
  7144. if (hp1.typ <> ait_instruction) then
  7145. InternalError(2021040720);
  7146. case taicpu(hp1).opcode of
  7147. A_JMP:
  7148. begin
  7149. { Change the original jump to the new destination }
  7150. OrigLabel.decrefs;
  7151. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7152. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7153. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7154. if not Assigned(first_assignment) then
  7155. InternalError(2021040810)
  7156. else
  7157. p := first_assignment;
  7158. Exit;
  7159. end;
  7160. A_RET:
  7161. begin
  7162. { Now change the jump into a RET instruction }
  7163. ConvertJumpToRET(p, hp1);
  7164. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7165. if not Assigned(first_assignment) then
  7166. InternalError(2021040811)
  7167. else
  7168. p := first_assignment;
  7169. Exit;
  7170. end;
  7171. else
  7172. begin
  7173. { Duplicate the MOV instruction }
  7174. hp3:=tai(hp1.getcopy);
  7175. if first_assignment = nil then
  7176. first_assignment := hp3;
  7177. asml.InsertBefore(hp3, p);
  7178. { Make sure the compiler knows about any final registers written here }
  7179. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7180. with taicpu(hp3).oper[OperIdx]^ do
  7181. begin
  7182. case typ of
  7183. top_ref:
  7184. begin
  7185. if (ref^.base <> NR_NO) and
  7186. (getsupreg(ref^.base) <> RS_ESP) and
  7187. (getsupreg(ref^.base) <> RS_EBP)
  7188. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7189. then
  7190. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7191. if (ref^.index <> NR_NO) and
  7192. (getsupreg(ref^.index) <> RS_ESP) and
  7193. (getsupreg(ref^.index) <> RS_EBP)
  7194. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7195. (ref^.index <> ref^.base) then
  7196. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7197. end;
  7198. top_reg:
  7199. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7200. else
  7201. ;
  7202. end;
  7203. end;
  7204. end;
  7205. end;
  7206. if not GetNextInstruction(hp1, hp1) then
  7207. { Should have dropped out earlier }
  7208. InternalError(2021040710);
  7209. end;
  7210. end;
  7211. end;
  7212. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7213. var
  7214. hp2: tai;
  7215. X: Integer;
  7216. const
  7217. WriteOp: array[0..3] of set of TInsChange = (
  7218. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7219. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7220. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7221. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7222. RegWriteFlags: array[0..7] of set of TInsChange = (
  7223. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7224. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7225. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7226. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7227. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7228. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7229. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7230. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7231. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7232. begin
  7233. { If we have something like:
  7234. cmp ###,%reg1
  7235. mov 0,%reg2
  7236. And no modified registers are shared, move the instruction to before
  7237. the comparison as this means it can be optimised without worrying
  7238. about the FLAGS register. (CMP/MOV is generated by
  7239. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7240. As long as the second instruction doesn't use the flags or one of the
  7241. registers used by CMP or TEST (also check any references that use the
  7242. registers), then it can be moved prior to the comparison.
  7243. }
  7244. Result := False;
  7245. if (hp1.typ <> ait_instruction) or
  7246. taicpu(hp1).is_jmp or
  7247. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7248. Exit;
  7249. { NOP is a pipeline fence, likely marking the beginning of the function
  7250. epilogue, so drop out. Similarly, drop out if POP or RET are
  7251. encountered }
  7252. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7253. Exit;
  7254. if (taicpu(hp1).opcode = A_MOVSS) and
  7255. (taicpu(hp1).ops = 0) then
  7256. { Wrong MOVSS }
  7257. Exit;
  7258. { Check for writes to specific registers first }
  7259. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7260. for X := 0 to 7 do
  7261. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7262. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7263. Exit;
  7264. for X := 0 to taicpu(hp1).ops - 1 do
  7265. begin
  7266. { Check to see if this operand writes to something }
  7267. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7268. { And matches something in the CMP/TEST instruction }
  7269. (
  7270. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7271. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7272. (
  7273. { If it's a register, make sure the register written to doesn't
  7274. appear in the cmp instruction as part of a reference }
  7275. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7276. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7277. )
  7278. ) then
  7279. Exit;
  7280. end;
  7281. { The instruction can be safely moved }
  7282. asml.Remove(hp1);
  7283. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7284. can be optimised into "xor %reg,%reg" later }
  7285. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7286. asml.InsertBefore(hp1, hp2)
  7287. else
  7288. { Note, if p.Previous is nil (even if it should logically never be the
  7289. case), FindRegAllocBackward immediately exits with False and so we
  7290. safely land here (we can't just pass p because FindRegAllocBackward
  7291. immediately exits on an instruction). [Kit] }
  7292. asml.InsertBefore(hp1, p);
  7293. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7294. for X := 0 to taicpu(hp1).ops - 1 do
  7295. case taicpu(hp1).oper[X]^.typ of
  7296. top_reg:
  7297. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7298. top_ref:
  7299. begin
  7300. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7301. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7302. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7303. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7304. end;
  7305. else
  7306. ;
  7307. end;
  7308. if taicpu(hp1).opcode = A_LEA then
  7309. { The flags will be overwritten by the CMP/TEST instruction }
  7310. ConvertLEA(taicpu(hp1));
  7311. Result := True;
  7312. end;
  7313. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7314. function IsXCHGAcceptable: Boolean; inline;
  7315. begin
  7316. { Always accept if optimising for size }
  7317. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7318. (
  7319. {$ifdef x86_64}
  7320. { XCHG takes 3 cycles on AMD Athlon64 }
  7321. (current_settings.optimizecputype >= cpu_core_i)
  7322. {$else x86_64}
  7323. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7324. than 3, so it becomes a saving compared to three MOVs with two of
  7325. them able to execute simultaneously. [Kit] }
  7326. (current_settings.optimizecputype >= cpu_PentiumM)
  7327. {$endif x86_64}
  7328. );
  7329. end;
  7330. var
  7331. NewRef: TReference;
  7332. hp1, hp2, hp3, hp4: Tai;
  7333. {$ifndef x86_64}
  7334. OperIdx: Integer;
  7335. {$endif x86_64}
  7336. NewInstr : Taicpu;
  7337. NewAligh : Tai_align;
  7338. DestLabel: TAsmLabel;
  7339. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7340. var
  7341. NextInstr: tai;
  7342. begin
  7343. Result := False;
  7344. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7345. if not GetNextInstruction(InputInstr, NextInstr) or
  7346. (
  7347. { The FLAGS register isn't always tracked properly, so do not
  7348. perform this optimisation if a conditional statement follows }
  7349. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7350. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7351. ) then
  7352. begin
  7353. reference_reset(NewRef, 1, []);
  7354. NewRef.base := taicpu(p).oper[0]^.reg;
  7355. NewRef.scalefactor := 1;
  7356. if taicpu(InputInstr).opcode = A_ADD then
  7357. begin
  7358. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7359. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7360. end
  7361. else
  7362. begin
  7363. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7364. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7365. end;
  7366. taicpu(p).opcode := A_LEA;
  7367. taicpu(p).loadref(0, NewRef);
  7368. RemoveInstruction(InputInstr);
  7369. Result := True;
  7370. end;
  7371. end;
  7372. begin
  7373. Result:=false;
  7374. { This optimisation adds an instruction, so only do it for speed }
  7375. if not (cs_opt_size in current_settings.optimizerswitches) and
  7376. MatchOpType(taicpu(p), top_const, top_reg) and
  7377. (taicpu(p).oper[0]^.val = 0) then
  7378. begin
  7379. { To avoid compiler warning }
  7380. DestLabel := nil;
  7381. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7382. InternalError(2021040750);
  7383. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7384. Exit;
  7385. case hp1.typ of
  7386. ait_label:
  7387. begin
  7388. { Change:
  7389. mov $0,%reg mov $0,%reg
  7390. @Lbl1: @Lbl1:
  7391. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7392. je @Lbl2 jne @Lbl2
  7393. To: To:
  7394. mov $0,%reg mov $0,%reg
  7395. jmp @Lbl2 jmp @Lbl3
  7396. (align) (align)
  7397. @Lbl1: @Lbl1:
  7398. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7399. je @Lbl2 je @Lbl2
  7400. @Lbl3: <-- Only if label exists
  7401. (Not if it's optimised for size)
  7402. }
  7403. if not GetNextInstruction(hp1, hp2) then
  7404. Exit;
  7405. if not (cs_opt_size in current_settings.optimizerswitches) and
  7406. (hp2.typ = ait_instruction) and
  7407. (
  7408. { Register sizes must exactly match }
  7409. (
  7410. (taicpu(hp2).opcode = A_CMP) and
  7411. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7412. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7413. ) or (
  7414. (taicpu(hp2).opcode = A_TEST) and
  7415. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7416. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7417. )
  7418. ) and GetNextInstruction(hp2, hp3) and
  7419. (hp3.typ = ait_instruction) and
  7420. (taicpu(hp3).opcode = A_JCC) and
  7421. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  7422. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7423. begin
  7424. { Check condition of jump }
  7425. { Always true? }
  7426. if condition_in(C_E, taicpu(hp3).condition) then
  7427. begin
  7428. { Copy label symbol and obtain matching label entry for the
  7429. conditional jump, as this will be our destination}
  7430. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7431. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7432. Result := True;
  7433. end
  7434. { Always false? }
  7435. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7436. begin
  7437. { This is only worth it if there's a jump to take }
  7438. case hp2.typ of
  7439. ait_instruction:
  7440. begin
  7441. if taicpu(hp2).opcode = A_JMP then
  7442. begin
  7443. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7444. { An unconditional jump follows the conditional jump which will always be false,
  7445. so use this jump's destination for the new jump }
  7446. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7447. Result := True;
  7448. end
  7449. else if taicpu(hp2).opcode = A_JCC then
  7450. begin
  7451. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7452. if condition_in(C_E, taicpu(hp2).condition) then
  7453. begin
  7454. { A second conditional jump follows the conditional jump which will always be false,
  7455. while the second jump is always True, so use this jump's destination for the new jump }
  7456. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7457. Result := True;
  7458. end;
  7459. { Don't risk it if the jump isn't always true (Result remains False) }
  7460. end;
  7461. end;
  7462. else
  7463. { If anything else don't optimise };
  7464. end;
  7465. end;
  7466. if Result then
  7467. begin
  7468. { Just so we have something to insert as a paremeter}
  7469. reference_reset(NewRef, 1, []);
  7470. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7471. { Now actually load the correct parameter (this also
  7472. increases the reference count) }
  7473. NewInstr.loadsymbol(0, DestLabel, 0);
  7474. { Get instruction before original label (may not be p under -O3) }
  7475. if not GetLastInstruction(hp1, hp2) then
  7476. { Shouldn't fail here }
  7477. InternalError(2021040701);
  7478. AsmL.InsertAfter(NewInstr, hp2);
  7479. { Add new alignment field }
  7480. (* AsmL.InsertAfter(
  7481. cai_align.create_max(
  7482. current_settings.alignment.jumpalign,
  7483. current_settings.alignment.jumpalignskipmax
  7484. ),
  7485. NewInstr
  7486. ); *)
  7487. end;
  7488. Exit;
  7489. end;
  7490. end;
  7491. else
  7492. ;
  7493. end;
  7494. end;
  7495. if not GetNextInstruction(p, hp1) then
  7496. Exit;
  7497. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7498. and DoMovCmpMemOpt(p, hp1, True) then
  7499. begin
  7500. Result := True;
  7501. Exit;
  7502. end
  7503. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7504. begin
  7505. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7506. further, but we can't just put this jump optimisation in pass 1
  7507. because it tends to perform worse when conditional jumps are
  7508. nearby (e.g. when converting CMOV instructions). [Kit] }
  7509. if OptPass2JMP(hp1) then
  7510. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7511. Result := OptPass1MOV(p)
  7512. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7513. returned True and the instruction is still a MOV, thus checking
  7514. the optimisations below }
  7515. { If OptPass2JMP returned False, no optimisations were done to
  7516. the jump and there are no further optimisations that can be done
  7517. to the MOV instruction on this pass }
  7518. end
  7519. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7520. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7521. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7522. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7523. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7524. begin
  7525. { Change:
  7526. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7527. addl/q $x,%reg2 subl/q $x,%reg2
  7528. To:
  7529. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7530. }
  7531. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7532. { be lazy, checking separately for sub would be slightly better }
  7533. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7534. begin
  7535. TransferUsedRegs(TmpUsedRegs);
  7536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7537. if TryMovArith2Lea(hp1) then
  7538. begin
  7539. Result := True;
  7540. Exit;
  7541. end
  7542. end
  7543. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7544. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7545. { Same as above, but also adds or subtracts to %reg2 in between.
  7546. It's still valid as long as the flags aren't in use }
  7547. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7548. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7549. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7550. { be lazy, checking separately for sub would be slightly better }
  7551. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7552. begin
  7553. TransferUsedRegs(TmpUsedRegs);
  7554. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7555. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7556. if TryMovArith2Lea(hp2) then
  7557. begin
  7558. Result := True;
  7559. Exit;
  7560. end;
  7561. end;
  7562. end
  7563. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7564. {$ifdef x86_64}
  7565. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7566. {$else x86_64}
  7567. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7568. {$endif x86_64}
  7569. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7570. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7571. { mov reg1, reg2 mov reg1, reg2
  7572. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7573. begin
  7574. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7575. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7576. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7577. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7578. TransferUsedRegs(TmpUsedRegs);
  7579. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7580. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7581. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7582. then
  7583. begin
  7584. RemoveCurrentP(p, hp1);
  7585. Result:=true;
  7586. end;
  7587. exit;
  7588. end
  7589. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7590. IsXCHGAcceptable and
  7591. { XCHG doesn't support 8-byte registers }
  7592. (taicpu(p).opsize <> S_B) and
  7593. MatchInstruction(hp1, A_MOV, []) and
  7594. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7595. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7596. GetNextInstruction(hp1, hp2) and
  7597. MatchInstruction(hp2, A_MOV, []) and
  7598. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7599. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7600. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7601. begin
  7602. { mov %reg1,%reg2
  7603. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7604. mov %reg2,%reg3
  7605. (%reg2 not used afterwards)
  7606. Note that xchg takes 3 cycles to execute, and generally mov's take
  7607. only one cycle apiece, but the first two mov's can be executed in
  7608. parallel, only taking 2 cycles overall. Older processors should
  7609. therefore only optimise for size. [Kit]
  7610. }
  7611. TransferUsedRegs(TmpUsedRegs);
  7612. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7613. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7614. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7615. begin
  7616. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7617. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7618. taicpu(hp1).opcode := A_XCHG;
  7619. RemoveCurrentP(p, hp1);
  7620. RemoveInstruction(hp2);
  7621. Result := True;
  7622. Exit;
  7623. end;
  7624. end
  7625. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7626. MatchInstruction(hp1, A_SAR, []) then
  7627. begin
  7628. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7629. begin
  7630. { the use of %edx also covers the opsize being S_L }
  7631. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7632. begin
  7633. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7634. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7635. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7636. begin
  7637. { Change:
  7638. movl %eax,%edx
  7639. sarl $31,%edx
  7640. To:
  7641. cltd
  7642. }
  7643. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7644. RemoveInstruction(hp1);
  7645. taicpu(p).opcode := A_CDQ;
  7646. taicpu(p).opsize := S_NO;
  7647. taicpu(p).clearop(1);
  7648. taicpu(p).clearop(0);
  7649. taicpu(p).ops:=0;
  7650. Result := True;
  7651. end
  7652. else if (cs_opt_size in current_settings.optimizerswitches) and
  7653. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7654. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7655. begin
  7656. { Change:
  7657. movl %edx,%eax
  7658. sarl $31,%edx
  7659. To:
  7660. movl %edx,%eax
  7661. cltd
  7662. Note that this creates a dependency between the two instructions,
  7663. so only perform if optimising for size.
  7664. }
  7665. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7666. taicpu(hp1).opcode := A_CDQ;
  7667. taicpu(hp1).opsize := S_NO;
  7668. taicpu(hp1).clearop(1);
  7669. taicpu(hp1).clearop(0);
  7670. taicpu(hp1).ops:=0;
  7671. end;
  7672. {$ifndef x86_64}
  7673. end
  7674. { Don't bother if CMOV is supported, because a more optimal
  7675. sequence would have been generated for the Abs() intrinsic }
  7676. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7677. { the use of %eax also covers the opsize being S_L }
  7678. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7679. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7680. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7681. GetNextInstruction(hp1, hp2) and
  7682. MatchInstruction(hp2, A_XOR, [S_L]) and
  7683. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7684. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7685. GetNextInstruction(hp2, hp3) and
  7686. MatchInstruction(hp3, A_SUB, [S_L]) and
  7687. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7688. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7689. begin
  7690. { Change:
  7691. movl %eax,%edx
  7692. sarl $31,%eax
  7693. xorl %eax,%edx
  7694. subl %eax,%edx
  7695. (Instruction that uses %edx)
  7696. (%eax deallocated)
  7697. (%edx deallocated)
  7698. To:
  7699. cltd
  7700. xorl %edx,%eax <-- Note the registers have swapped
  7701. subl %edx,%eax
  7702. (Instruction that uses %eax) <-- %eax rather than %edx
  7703. }
  7704. TransferUsedRegs(TmpUsedRegs);
  7705. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7706. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7707. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7708. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7709. begin
  7710. if GetNextInstruction(hp3, hp4) and
  7711. not RegModifiedByInstruction(NR_EDX, hp4) and
  7712. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7713. begin
  7714. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7715. taicpu(p).opcode := A_CDQ;
  7716. taicpu(p).clearop(1);
  7717. taicpu(p).clearop(0);
  7718. taicpu(p).ops:=0;
  7719. RemoveInstruction(hp1);
  7720. taicpu(hp2).loadreg(0, NR_EDX);
  7721. taicpu(hp2).loadreg(1, NR_EAX);
  7722. taicpu(hp3).loadreg(0, NR_EDX);
  7723. taicpu(hp3).loadreg(1, NR_EAX);
  7724. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7725. { Convert references in the following instruction (hp4) from %edx to %eax }
  7726. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7727. with taicpu(hp4).oper[OperIdx]^ do
  7728. case typ of
  7729. top_reg:
  7730. if getsupreg(reg) = RS_EDX then
  7731. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7732. top_ref:
  7733. begin
  7734. if getsupreg(reg) = RS_EDX then
  7735. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7736. if getsupreg(reg) = RS_EDX then
  7737. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7738. end;
  7739. else
  7740. ;
  7741. end;
  7742. end;
  7743. end;
  7744. {$else x86_64}
  7745. end;
  7746. end
  7747. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7748. { the use of %rdx also covers the opsize being S_Q }
  7749. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7750. begin
  7751. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7752. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7753. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7754. begin
  7755. { Change:
  7756. movq %rax,%rdx
  7757. sarq $63,%rdx
  7758. To:
  7759. cqto
  7760. }
  7761. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7762. RemoveInstruction(hp1);
  7763. taicpu(p).opcode := A_CQO;
  7764. taicpu(p).opsize := S_NO;
  7765. taicpu(p).clearop(1);
  7766. taicpu(p).clearop(0);
  7767. taicpu(p).ops:=0;
  7768. Result := True;
  7769. end
  7770. else if (cs_opt_size in current_settings.optimizerswitches) and
  7771. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7772. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7773. begin
  7774. { Change:
  7775. movq %rdx,%rax
  7776. sarq $63,%rdx
  7777. To:
  7778. movq %rdx,%rax
  7779. cqto
  7780. Note that this creates a dependency between the two instructions,
  7781. so only perform if optimising for size.
  7782. }
  7783. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7784. taicpu(hp1).opcode := A_CQO;
  7785. taicpu(hp1).opsize := S_NO;
  7786. taicpu(hp1).clearop(1);
  7787. taicpu(hp1).clearop(0);
  7788. taicpu(hp1).ops:=0;
  7789. {$endif x86_64}
  7790. end;
  7791. end;
  7792. end
  7793. else if MatchInstruction(hp1, A_MOV, []) and
  7794. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7795. { Though "GetNextInstruction" could be factored out, along with
  7796. the instructions that depend on hp2, it is an expensive call that
  7797. should be delayed for as long as possible, hence we do cheaper
  7798. checks first that are likely to be False. [Kit] }
  7799. begin
  7800. if (
  7801. (
  7802. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7803. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7804. (
  7805. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7806. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7807. )
  7808. ) or
  7809. (
  7810. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7811. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7812. (
  7813. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7814. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7815. )
  7816. )
  7817. ) and
  7818. GetNextInstruction(hp1, hp2) and
  7819. MatchInstruction(hp2, A_SAR, []) and
  7820. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7821. begin
  7822. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7823. begin
  7824. { Change:
  7825. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7826. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7827. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7828. To:
  7829. movl r/m,%eax <- Note the change in register
  7830. cltd
  7831. }
  7832. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7833. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7834. taicpu(p).loadreg(1, NR_EAX);
  7835. taicpu(hp1).opcode := A_CDQ;
  7836. taicpu(hp1).clearop(1);
  7837. taicpu(hp1).clearop(0);
  7838. taicpu(hp1).ops:=0;
  7839. RemoveInstruction(hp2);
  7840. (*
  7841. {$ifdef x86_64}
  7842. end
  7843. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7844. { This code sequence does not get generated - however it might become useful
  7845. if and when 128-bit signed integer types make an appearance, so the code
  7846. is kept here for when it is eventually needed. [Kit] }
  7847. (
  7848. (
  7849. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7850. (
  7851. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7852. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7853. )
  7854. ) or
  7855. (
  7856. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7857. (
  7858. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7859. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7860. )
  7861. )
  7862. ) and
  7863. GetNextInstruction(hp1, hp2) and
  7864. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7865. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7866. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7867. begin
  7868. { Change:
  7869. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7870. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7871. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7872. To:
  7873. movq r/m,%rax <- Note the change in register
  7874. cqto
  7875. }
  7876. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7877. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7878. taicpu(p).loadreg(1, NR_RAX);
  7879. taicpu(hp1).opcode := A_CQO;
  7880. taicpu(hp1).clearop(1);
  7881. taicpu(hp1).clearop(0);
  7882. taicpu(hp1).ops:=0;
  7883. RemoveInstruction(hp2);
  7884. {$endif x86_64}
  7885. *)
  7886. end;
  7887. end;
  7888. {$ifdef x86_64}
  7889. end
  7890. else if (taicpu(p).opsize = S_L) and
  7891. (taicpu(p).oper[1]^.typ = top_reg) and
  7892. (
  7893. MatchInstruction(hp1, A_MOV,[]) and
  7894. (taicpu(hp1).opsize = S_L) and
  7895. (taicpu(hp1).oper[1]^.typ = top_reg)
  7896. ) and (
  7897. GetNextInstruction(hp1, hp2) and
  7898. (tai(hp2).typ=ait_instruction) and
  7899. (taicpu(hp2).opsize = S_Q) and
  7900. (
  7901. (
  7902. MatchInstruction(hp2, A_ADD,[]) and
  7903. (taicpu(hp2).opsize = S_Q) and
  7904. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7905. (
  7906. (
  7907. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7908. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7909. ) or (
  7910. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7911. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7912. )
  7913. )
  7914. ) or (
  7915. MatchInstruction(hp2, A_LEA,[]) and
  7916. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7917. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7918. (
  7919. (
  7920. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7921. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7922. ) or (
  7923. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7924. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7925. )
  7926. ) and (
  7927. (
  7928. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7929. ) or (
  7930. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7931. )
  7932. )
  7933. )
  7934. )
  7935. ) and (
  7936. GetNextInstruction(hp2, hp3) and
  7937. MatchInstruction(hp3, A_SHR,[]) and
  7938. (taicpu(hp3).opsize = S_Q) and
  7939. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7940. (taicpu(hp3).oper[0]^.val = 1) and
  7941. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7942. ) then
  7943. begin
  7944. { Change movl x, reg1d movl x, reg1d
  7945. movl y, reg2d movl y, reg2d
  7946. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7947. shrq $1, reg1q shrq $1, reg1q
  7948. ( reg1d and reg2d can be switched around in the first two instructions )
  7949. To movl x, reg1d
  7950. addl y, reg1d
  7951. rcrl $1, reg1d
  7952. This corresponds to the common expression (x + y) shr 1, where
  7953. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7954. smaller code, but won't account for x + y causing an overflow). [Kit]
  7955. }
  7956. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7957. { Change first MOV command to have the same register as the final output }
  7958. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7959. else
  7960. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7961. { Change second MOV command to an ADD command. This is easier than
  7962. converting the existing command because it means we don't have to
  7963. touch 'y', which might be a complicated reference, and also the
  7964. fact that the third command might either be ADD or LEA. [Kit] }
  7965. taicpu(hp1).opcode := A_ADD;
  7966. { Delete old ADD/LEA instruction }
  7967. RemoveInstruction(hp2);
  7968. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7969. taicpu(hp3).opcode := A_RCR;
  7970. taicpu(hp3).changeopsize(S_L);
  7971. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7972. {$endif x86_64}
  7973. end;
  7974. end;
  7975. {$push}
  7976. {$q-}{$r-}
  7977. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7978. var
  7979. ThisReg: TRegister;
  7980. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7981. TargetSubReg: TSubRegister;
  7982. hp1, hp2: tai;
  7983. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7984. { Store list of found instructions so we don't have to call
  7985. GetNextInstructionUsingReg multiple times }
  7986. InstrList: array of taicpu;
  7987. InstrMax, Index: Integer;
  7988. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7989. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7990. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7991. WorkingValue: TCgInt;
  7992. PreMessage: string;
  7993. { Data flow analysis }
  7994. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7995. BitwiseOnly, OrXorUsed,
  7996. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7997. function CheckOverflowConditions: Boolean;
  7998. begin
  7999. Result := True;
  8000. if (TestValSignedMax > SignedUpperLimit) then
  8001. UpperSignedOverflow := True;
  8002. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8003. LowerSignedOverflow := True;
  8004. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8005. LowerUnsignedOverflow := True;
  8006. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8007. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8008. begin
  8009. { Absolute overflow }
  8010. Result := False;
  8011. Exit;
  8012. end;
  8013. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8014. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8015. ShiftDownOverflow := True;
  8016. if (TestValMin < 0) or (TestValMax < 0) then
  8017. begin
  8018. LowerUnsignedOverflow := True;
  8019. UpperUnsignedOverflow := True;
  8020. end;
  8021. end;
  8022. function AdjustInitialLoadAndSize: Boolean;
  8023. begin
  8024. Result := False;
  8025. if not p_removed then
  8026. begin
  8027. if TargetSize = MinSize then
  8028. begin
  8029. { Convert the input MOVZX to a MOV }
  8030. if (taicpu(p).oper[0]^.typ = top_reg) and
  8031. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8032. begin
  8033. { Or remove it completely! }
  8034. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8035. RemoveCurrentP(p);
  8036. p_removed := True;
  8037. end
  8038. else
  8039. begin
  8040. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8041. taicpu(p).opcode := A_MOV;
  8042. taicpu(p).oper[1]^.reg := ThisReg;
  8043. taicpu(p).opsize := TargetSize;
  8044. end;
  8045. Result := True;
  8046. end
  8047. else if TargetSize <> MaxSize then
  8048. begin
  8049. case MaxSize of
  8050. S_L:
  8051. if TargetSize = S_W then
  8052. begin
  8053. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8054. taicpu(p).opsize := S_BW;
  8055. taicpu(p).oper[1]^.reg := ThisReg;
  8056. Result := True;
  8057. end
  8058. else
  8059. InternalError(2020112341);
  8060. S_W:
  8061. if TargetSize = S_L then
  8062. begin
  8063. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8064. taicpu(p).opsize := S_BL;
  8065. taicpu(p).oper[1]^.reg := ThisReg;
  8066. Result := True;
  8067. end
  8068. else
  8069. InternalError(2020112342);
  8070. else
  8071. ;
  8072. end;
  8073. end
  8074. else if not hp1_removed and not RegInUse then
  8075. begin
  8076. { If we have something like:
  8077. movzbl (oper),%regd
  8078. add x, %regd
  8079. movzbl %regb, %regd
  8080. We can reduce the register size to the input of the final
  8081. movzbl instruction. Overflows won't have any effect.
  8082. }
  8083. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8084. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8085. begin
  8086. TargetSize := S_B;
  8087. setsubreg(ThisReg, R_SUBL);
  8088. Result := True;
  8089. end
  8090. else if (taicpu(p).opsize = S_WL) and
  8091. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8092. begin
  8093. TargetSize := S_W;
  8094. setsubreg(ThisReg, R_SUBW);
  8095. Result := True;
  8096. end;
  8097. if Result then
  8098. begin
  8099. { Convert the input MOVZX to a MOV }
  8100. if (taicpu(p).oper[0]^.typ = top_reg) and
  8101. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8102. begin
  8103. { Or remove it completely! }
  8104. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8105. RemoveCurrentP(p);
  8106. p_removed := True;
  8107. end
  8108. else
  8109. begin
  8110. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8111. taicpu(p).opcode := A_MOV;
  8112. taicpu(p).oper[1]^.reg := ThisReg;
  8113. taicpu(p).opsize := TargetSize;
  8114. end;
  8115. end;
  8116. end;
  8117. end;
  8118. end;
  8119. procedure AdjustFinalLoad;
  8120. begin
  8121. if not LowerUnsignedOverflow then
  8122. begin
  8123. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8124. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8125. begin
  8126. { Convert the output MOVZX to a MOV }
  8127. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8128. begin
  8129. { Or remove it completely! }
  8130. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8131. { Be careful; if p = hp1 and p was also removed, p
  8132. will become a dangling pointer }
  8133. if p = hp1 then
  8134. begin
  8135. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8136. p_removed := True;
  8137. end
  8138. else
  8139. RemoveInstruction(hp1);
  8140. hp1_removed := True;
  8141. end
  8142. else
  8143. begin
  8144. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8145. taicpu(hp1).opcode := A_MOV;
  8146. taicpu(hp1).oper[0]^.reg := ThisReg;
  8147. taicpu(hp1).opsize := TargetSize;
  8148. end;
  8149. end
  8150. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8151. begin
  8152. { Need to change the size of the output }
  8153. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8154. taicpu(hp1).oper[0]^.reg := ThisReg;
  8155. taicpu(hp1).opsize := S_BL;
  8156. end;
  8157. end;
  8158. end;
  8159. function CompressInstructions: Boolean;
  8160. var
  8161. LocalIndex: Integer;
  8162. begin
  8163. Result := False;
  8164. { The objective here is to try to find a combination that
  8165. removes one of the MOV/Z instructions. }
  8166. if (
  8167. (taicpu(p).oper[0]^.typ <> top_reg) or
  8168. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8169. ) and
  8170. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8171. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8172. begin
  8173. { Make a preference to remove the second MOVZX instruction }
  8174. case taicpu(hp1).opsize of
  8175. S_BL, S_WL:
  8176. begin
  8177. TargetSize := S_L;
  8178. TargetSubReg := R_SUBD;
  8179. end;
  8180. S_BW:
  8181. begin
  8182. TargetSize := S_W;
  8183. TargetSubReg := R_SUBW;
  8184. end;
  8185. else
  8186. InternalError(2020112302);
  8187. end;
  8188. end
  8189. else
  8190. begin
  8191. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8192. begin
  8193. { Exceeded lower bound but not upper bound }
  8194. TargetSize := MaxSize;
  8195. end
  8196. else if not LowerUnsignedOverflow then
  8197. begin
  8198. { Size didn't exceed lower bound }
  8199. TargetSize := MinSize;
  8200. end
  8201. else
  8202. Exit;
  8203. end;
  8204. case TargetSize of
  8205. S_B:
  8206. TargetSubReg := R_SUBL;
  8207. S_W:
  8208. TargetSubReg := R_SUBW;
  8209. S_L:
  8210. TargetSubReg := R_SUBD;
  8211. else
  8212. InternalError(2020112350);
  8213. end;
  8214. { Update the register to its new size }
  8215. setsubreg(ThisReg, TargetSubReg);
  8216. RegInUse := False;
  8217. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8218. begin
  8219. { Check to see if the active register is used afterwards;
  8220. if not, we can change it and make a saving. }
  8221. TransferUsedRegs(TmpUsedRegs);
  8222. { The target register may be marked as in use to cross
  8223. a jump to a distant label, so exclude it }
  8224. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8225. hp2 := p;
  8226. repeat
  8227. { Explicitly check for the excluded register (don't include the first
  8228. instruction as it may be reading from here }
  8229. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8230. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8231. begin
  8232. RegInUse := True;
  8233. Break;
  8234. end;
  8235. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8236. if not GetNextInstruction(hp2, hp2) then
  8237. InternalError(2020112340);
  8238. until (hp2 = hp1);
  8239. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8240. { We might still be able to get away with this }
  8241. RegInUse := not
  8242. (
  8243. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8244. (hp2.typ = ait_instruction) and
  8245. (
  8246. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8247. instruction that doesn't actually contain ThisReg }
  8248. (cs_opt_level3 in current_settings.optimizerswitches) or
  8249. RegInInstruction(ThisReg, hp2)
  8250. ) and
  8251. RegLoadedWithNewValue(ThisReg, hp2)
  8252. );
  8253. if not RegInUse then
  8254. begin
  8255. { Force the register size to the same as this instruction so it can be removed}
  8256. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8257. begin
  8258. TargetSize := S_L;
  8259. TargetSubReg := R_SUBD;
  8260. end
  8261. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8262. begin
  8263. TargetSize := S_W;
  8264. TargetSubReg := R_SUBW;
  8265. end;
  8266. ThisReg := taicpu(hp1).oper[1]^.reg;
  8267. setsubreg(ThisReg, TargetSubReg);
  8268. RegChanged := True;
  8269. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8270. TransferUsedRegs(TmpUsedRegs);
  8271. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8272. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8273. if p = hp1 then
  8274. begin
  8275. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8276. p_removed := True;
  8277. end
  8278. else
  8279. RemoveInstruction(hp1);
  8280. hp1_removed := True;
  8281. { Instruction will become "mov %reg,%reg" }
  8282. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8283. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8284. begin
  8285. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8286. RemoveCurrentP(p);
  8287. p_removed := True;
  8288. end
  8289. else
  8290. taicpu(p).oper[1]^.reg := ThisReg;
  8291. Result := True;
  8292. end
  8293. else
  8294. begin
  8295. if TargetSize <> MaxSize then
  8296. begin
  8297. { Since the register is in use, we have to force it to
  8298. MaxSize otherwise part of it may become undefined later on }
  8299. TargetSize := MaxSize;
  8300. case TargetSize of
  8301. S_B:
  8302. TargetSubReg := R_SUBL;
  8303. S_W:
  8304. TargetSubReg := R_SUBW;
  8305. S_L:
  8306. TargetSubReg := R_SUBD;
  8307. else
  8308. InternalError(2020112351);
  8309. end;
  8310. setsubreg(ThisReg, TargetSubReg);
  8311. end;
  8312. AdjustFinalLoad;
  8313. end;
  8314. end
  8315. else
  8316. AdjustFinalLoad;
  8317. Result := AdjustInitialLoadAndSize or Result;
  8318. { Now go through every instruction we found and change the
  8319. size. If TargetSize = MaxSize, then almost no changes are
  8320. needed and Result can remain False if it hasn't been set
  8321. yet.
  8322. If RegChanged is True, then the register requires changing
  8323. and so the point about TargetSize = MaxSize doesn't apply. }
  8324. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8325. begin
  8326. for LocalIndex := 0 to InstrMax do
  8327. begin
  8328. { If p_removed is true, then the original MOV/Z was removed
  8329. and removing the AND instruction may not be safe if it
  8330. appears first }
  8331. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8332. InternalError(2020112310);
  8333. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8334. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8335. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8336. InstrList[LocalIndex].opsize := TargetSize;
  8337. end;
  8338. Result := True;
  8339. end;
  8340. end;
  8341. begin
  8342. Result := False;
  8343. p_removed := False;
  8344. hp1_removed := False;
  8345. ThisReg := taicpu(p).oper[1]^.reg;
  8346. { Check for:
  8347. movs/z ###,%ecx (or %cx or %rcx)
  8348. ...
  8349. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8350. (dealloc %ecx)
  8351. Change to:
  8352. mov ###,%cl (if ### = %cl, then remove completely)
  8353. ...
  8354. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8355. }
  8356. if (getsupreg(ThisReg) = RS_ECX) and
  8357. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8358. (hp1.typ = ait_instruction) and
  8359. (
  8360. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8361. instruction that doesn't actually contain ECX }
  8362. (cs_opt_level3 in current_settings.optimizerswitches) or
  8363. RegInInstruction(NR_ECX, hp1) or
  8364. (
  8365. { It's common for the shift/rotate's read/write register to be
  8366. initialised in between, so under -O2 and under, search ahead
  8367. one more instruction
  8368. }
  8369. GetNextInstruction(hp1, hp1) and
  8370. (hp1.typ = ait_instruction) and
  8371. RegInInstruction(NR_ECX, hp1)
  8372. )
  8373. ) and
  8374. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8375. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8376. begin
  8377. TransferUsedRegs(TmpUsedRegs);
  8378. hp2 := p;
  8379. repeat
  8380. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8381. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8382. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8383. begin
  8384. case taicpu(p).opsize of
  8385. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8386. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8387. begin
  8388. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8389. RemoveCurrentP(p);
  8390. end
  8391. else
  8392. begin
  8393. taicpu(p).opcode := A_MOV;
  8394. taicpu(p).opsize := S_B;
  8395. taicpu(p).oper[1]^.reg := NR_CL;
  8396. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8397. end;
  8398. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8399. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8400. begin
  8401. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8402. RemoveCurrentP(p);
  8403. end
  8404. else
  8405. begin
  8406. taicpu(p).opcode := A_MOV;
  8407. taicpu(p).opsize := S_W;
  8408. taicpu(p).oper[1]^.reg := NR_CX;
  8409. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8410. end;
  8411. {$ifdef x86_64}
  8412. S_LQ:
  8413. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8414. begin
  8415. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8416. RemoveCurrentP(p);
  8417. end
  8418. else
  8419. begin
  8420. taicpu(p).opcode := A_MOV;
  8421. taicpu(p).opsize := S_L;
  8422. taicpu(p).oper[1]^.reg := NR_ECX;
  8423. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8424. end;
  8425. {$endif x86_64}
  8426. else
  8427. InternalError(2021120401);
  8428. end;
  8429. Result := True;
  8430. Exit;
  8431. end;
  8432. end;
  8433. { This is anything but quick! }
  8434. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8435. Exit;
  8436. SetLength(InstrList, 0);
  8437. InstrMax := -1;
  8438. case taicpu(p).opsize of
  8439. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8440. begin
  8441. {$if defined(i386) or defined(i8086)}
  8442. { If the target size is 8-bit, make sure we can actually encode it }
  8443. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8444. Exit;
  8445. {$endif i386 or i8086}
  8446. LowerLimit := $FF;
  8447. SignedLowerLimit := $7F;
  8448. SignedLowerLimitBottom := -128;
  8449. MinSize := S_B;
  8450. if taicpu(p).opsize = S_BW then
  8451. begin
  8452. MaxSize := S_W;
  8453. UpperLimit := $FFFF;
  8454. SignedUpperLimit := $7FFF;
  8455. SignedUpperLimitBottom := -32768;
  8456. end
  8457. else
  8458. begin
  8459. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8460. MaxSize := S_L;
  8461. UpperLimit := $FFFFFFFF;
  8462. SignedUpperLimit := $7FFFFFFF;
  8463. SignedUpperLimitBottom := -2147483648;
  8464. end;
  8465. end;
  8466. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8467. begin
  8468. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8469. LowerLimit := $FFFF;
  8470. SignedLowerLimit := $7FFF;
  8471. SignedLowerLimitBottom := -32768;
  8472. UpperLimit := $FFFFFFFF;
  8473. SignedUpperLimit := $7FFFFFFF;
  8474. SignedUpperLimitBottom := -2147483648;
  8475. MinSize := S_W;
  8476. MaxSize := S_L;
  8477. end;
  8478. {$ifdef x86_64}
  8479. S_LQ:
  8480. begin
  8481. { Both the lower and upper limits are set to 32-bit. If a limit
  8482. is breached, then optimisation is impossible }
  8483. LowerLimit := $FFFFFFFF;
  8484. SignedLowerLimit := $7FFFFFFF;
  8485. SignedLowerLimitBottom := -2147483648;
  8486. UpperLimit := $FFFFFFFF;
  8487. SignedUpperLimit := $7FFFFFFF;
  8488. SignedUpperLimitBottom := -2147483648;
  8489. MinSize := S_L;
  8490. MaxSize := S_L;
  8491. end;
  8492. {$endif x86_64}
  8493. else
  8494. InternalError(2020112301);
  8495. end;
  8496. TestValMin := 0;
  8497. TestValMax := LowerLimit;
  8498. TestValSignedMax := SignedLowerLimit;
  8499. TryShiftDownLimit := LowerLimit;
  8500. TryShiftDown := S_NO;
  8501. ShiftDownOverflow := False;
  8502. RegChanged := False;
  8503. BitwiseOnly := True;
  8504. OrXorUsed := False;
  8505. UpperSignedOverflow := False;
  8506. LowerSignedOverflow := False;
  8507. UpperUnsignedOverflow := False;
  8508. LowerUnsignedOverflow := False;
  8509. hp1 := p;
  8510. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8511. (hp1.typ = ait_instruction) and
  8512. (
  8513. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8514. instruction that doesn't actually contain ThisReg }
  8515. (cs_opt_level3 in current_settings.optimizerswitches) or
  8516. { This allows this Movx optimisation to work through the SETcc instructions
  8517. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8518. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8519. skip over these SETcc instructions). }
  8520. (taicpu(hp1).opcode = A_SETcc) or
  8521. RegInInstruction(ThisReg, hp1)
  8522. ) do
  8523. begin
  8524. case taicpu(hp1).opcode of
  8525. A_INC,A_DEC:
  8526. begin
  8527. { Has to be an exact match on the register }
  8528. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8529. Break;
  8530. if taicpu(hp1).opcode = A_INC then
  8531. begin
  8532. Inc(TestValMin);
  8533. Inc(TestValMax);
  8534. Inc(TestValSignedMax);
  8535. end
  8536. else
  8537. begin
  8538. Dec(TestValMin);
  8539. Dec(TestValMax);
  8540. Dec(TestValSignedMax);
  8541. end;
  8542. end;
  8543. A_TEST, A_CMP:
  8544. begin
  8545. if (
  8546. { Too high a risk of non-linear behaviour that breaks DFA
  8547. here, unless it's cmp $0,%reg, which is equivalent to
  8548. test %reg,%reg }
  8549. OrXorUsed and
  8550. (taicpu(hp1).opcode = A_CMP) and
  8551. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8552. ) or
  8553. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8554. { Has to be an exact match on the register }
  8555. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8556. (
  8557. { Permit "test %reg,%reg" }
  8558. (taicpu(hp1).opcode = A_TEST) and
  8559. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8560. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8561. ) or
  8562. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8563. { Make sure the comparison value is not smaller than the
  8564. smallest allowed signed value for the minimum size (e.g.
  8565. -128 for 8-bit) }
  8566. not (
  8567. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8568. { Is it in the negative range? }
  8569. (
  8570. (taicpu(hp1).oper[0]^.val < 0) and
  8571. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8572. )
  8573. ) then
  8574. Break;
  8575. { Check to see if the active register is used afterwards }
  8576. TransferUsedRegs(TmpUsedRegs);
  8577. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8578. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8579. begin
  8580. { Make sure the comparison or any previous instructions
  8581. hasn't pushed the test values outside of the range of
  8582. MinSize }
  8583. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8584. begin
  8585. { Exceeded lower bound but not upper bound }
  8586. Exit;
  8587. end
  8588. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8589. begin
  8590. { Size didn't exceed lower bound }
  8591. TargetSize := MinSize;
  8592. end
  8593. else
  8594. Break;
  8595. case TargetSize of
  8596. S_B:
  8597. TargetSubReg := R_SUBL;
  8598. S_W:
  8599. TargetSubReg := R_SUBW;
  8600. S_L:
  8601. TargetSubReg := R_SUBD;
  8602. else
  8603. InternalError(2021051002);
  8604. end;
  8605. if TargetSize <> MaxSize then
  8606. begin
  8607. { Update the register to its new size }
  8608. setsubreg(ThisReg, TargetSubReg);
  8609. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8610. taicpu(hp1).oper[1]^.reg := ThisReg;
  8611. taicpu(hp1).opsize := TargetSize;
  8612. { Convert the input MOVZX to a MOV if necessary }
  8613. AdjustInitialLoadAndSize;
  8614. if (InstrMax >= 0) then
  8615. begin
  8616. for Index := 0 to InstrMax do
  8617. begin
  8618. { If p_removed is true, then the original MOV/Z was removed
  8619. and removing the AND instruction may not be safe if it
  8620. appears first }
  8621. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8622. InternalError(2020112311);
  8623. if InstrList[Index].oper[0]^.typ = top_reg then
  8624. InstrList[Index].oper[0]^.reg := ThisReg;
  8625. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8626. InstrList[Index].opsize := MinSize;
  8627. end;
  8628. end;
  8629. Result := True;
  8630. end;
  8631. Exit;
  8632. end;
  8633. end;
  8634. A_SETcc:
  8635. begin
  8636. { This allows this Movx optimisation to work through the SETcc instructions
  8637. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8638. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8639. skip over these SETcc instructions). }
  8640. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8641. { Of course, break out if the current register is used }
  8642. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8643. Break
  8644. else
  8645. { We must use Continue so the instruction doesn't get added
  8646. to InstrList }
  8647. Continue;
  8648. end;
  8649. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8650. begin
  8651. if
  8652. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8653. { Has to be an exact match on the register }
  8654. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8655. (
  8656. (
  8657. (taicpu(hp1).oper[0]^.typ = top_const) and
  8658. (
  8659. (
  8660. (taicpu(hp1).opcode = A_SHL) and
  8661. (
  8662. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8663. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8664. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8665. )
  8666. ) or (
  8667. (taicpu(hp1).opcode <> A_SHL) and
  8668. (
  8669. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8670. { Is it in the negative range? }
  8671. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8672. )
  8673. )
  8674. )
  8675. ) or (
  8676. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8677. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8678. )
  8679. ) then
  8680. Break;
  8681. { Only process OR and XOR if there are only bitwise operations,
  8682. since otherwise they can too easily fool the data flow
  8683. analysis (they can cause non-linear behaviour) }
  8684. case taicpu(hp1).opcode of
  8685. A_ADD:
  8686. begin
  8687. if OrXorUsed then
  8688. { Too high a risk of non-linear behaviour that breaks DFA here }
  8689. Break
  8690. else
  8691. BitwiseOnly := False;
  8692. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8693. begin
  8694. TestValMin := TestValMin * 2;
  8695. TestValMax := TestValMax * 2;
  8696. TestValSignedMax := TestValSignedMax * 2;
  8697. end
  8698. else
  8699. begin
  8700. WorkingValue := taicpu(hp1).oper[0]^.val;
  8701. TestValMin := TestValMin + WorkingValue;
  8702. TestValMax := TestValMax + WorkingValue;
  8703. TestValSignedMax := TestValSignedMax + WorkingValue;
  8704. end;
  8705. end;
  8706. A_SUB:
  8707. begin
  8708. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8709. begin
  8710. TestValMin := 0;
  8711. TestValMax := 0;
  8712. TestValSignedMax := 0;
  8713. end
  8714. else
  8715. begin
  8716. if OrXorUsed then
  8717. { Too high a risk of non-linear behaviour that breaks DFA here }
  8718. Break
  8719. else
  8720. BitwiseOnly := False;
  8721. WorkingValue := taicpu(hp1).oper[0]^.val;
  8722. TestValMin := TestValMin - WorkingValue;
  8723. TestValMax := TestValMax - WorkingValue;
  8724. TestValSignedMax := TestValSignedMax - WorkingValue;
  8725. end;
  8726. end;
  8727. A_AND:
  8728. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8729. begin
  8730. { we might be able to go smaller if AND appears first }
  8731. if InstrMax = -1 then
  8732. case MinSize of
  8733. S_B:
  8734. ;
  8735. S_W:
  8736. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8737. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8738. begin
  8739. TryShiftDown := S_B;
  8740. TryShiftDownLimit := $FF;
  8741. end;
  8742. S_L:
  8743. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8744. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8745. begin
  8746. TryShiftDown := S_B;
  8747. TryShiftDownLimit := $FF;
  8748. end
  8749. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8750. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8751. begin
  8752. TryShiftDown := S_W;
  8753. TryShiftDownLimit := $FFFF;
  8754. end;
  8755. else
  8756. InternalError(2020112320);
  8757. end;
  8758. WorkingValue := taicpu(hp1).oper[0]^.val;
  8759. TestValMin := TestValMin and WorkingValue;
  8760. TestValMax := TestValMax and WorkingValue;
  8761. TestValSignedMax := TestValSignedMax and WorkingValue;
  8762. end;
  8763. A_OR:
  8764. begin
  8765. if not BitwiseOnly then
  8766. Break;
  8767. OrXorUsed := True;
  8768. WorkingValue := taicpu(hp1).oper[0]^.val;
  8769. TestValMin := TestValMin or WorkingValue;
  8770. TestValMax := TestValMax or WorkingValue;
  8771. TestValSignedMax := TestValSignedMax or WorkingValue;
  8772. end;
  8773. A_XOR:
  8774. begin
  8775. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8776. begin
  8777. TestValMin := 0;
  8778. TestValMax := 0;
  8779. TestValSignedMax := 0;
  8780. end
  8781. else
  8782. begin
  8783. if not BitwiseOnly then
  8784. Break;
  8785. OrXorUsed := True;
  8786. WorkingValue := taicpu(hp1).oper[0]^.val;
  8787. TestValMin := TestValMin xor WorkingValue;
  8788. TestValMax := TestValMax xor WorkingValue;
  8789. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8790. end;
  8791. end;
  8792. A_SHL:
  8793. begin
  8794. BitwiseOnly := False;
  8795. WorkingValue := taicpu(hp1).oper[0]^.val;
  8796. TestValMin := TestValMin shl WorkingValue;
  8797. TestValMax := TestValMax shl WorkingValue;
  8798. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8799. end;
  8800. A_SHR,
  8801. { The first instruction was MOVZX, so the value won't be negative }
  8802. A_SAR:
  8803. begin
  8804. if InstrMax <> -1 then
  8805. BitwiseOnly := False
  8806. else
  8807. { we might be able to go smaller if SHR appears first }
  8808. case MinSize of
  8809. S_B:
  8810. ;
  8811. S_W:
  8812. if (taicpu(hp1).oper[0]^.val >= 8) then
  8813. begin
  8814. TryShiftDown := S_B;
  8815. TryShiftDownLimit := $FF;
  8816. TryShiftDownSignedLimit := $7F;
  8817. TryShiftDownSignedLimitLower := -128;
  8818. end;
  8819. S_L:
  8820. if (taicpu(hp1).oper[0]^.val >= 24) then
  8821. begin
  8822. TryShiftDown := S_B;
  8823. TryShiftDownLimit := $FF;
  8824. TryShiftDownSignedLimit := $7F;
  8825. TryShiftDownSignedLimitLower := -128;
  8826. end
  8827. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8828. begin
  8829. TryShiftDown := S_W;
  8830. TryShiftDownLimit := $FFFF;
  8831. TryShiftDownSignedLimit := $7FFF;
  8832. TryShiftDownSignedLimitLower := -32768;
  8833. end;
  8834. else
  8835. InternalError(2020112321);
  8836. end;
  8837. WorkingValue := taicpu(hp1).oper[0]^.val;
  8838. if taicpu(hp1).opcode = A_SAR then
  8839. begin
  8840. TestValMin := SarInt64(TestValMin, WorkingValue);
  8841. TestValMax := SarInt64(TestValMax, WorkingValue);
  8842. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8843. end
  8844. else
  8845. begin
  8846. TestValMin := TestValMin shr WorkingValue;
  8847. TestValMax := TestValMax shr WorkingValue;
  8848. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8849. end;
  8850. end;
  8851. else
  8852. InternalError(2020112303);
  8853. end;
  8854. end;
  8855. (*
  8856. A_IMUL:
  8857. case taicpu(hp1).ops of
  8858. 2:
  8859. begin
  8860. if not MatchOpType(hp1, top_reg, top_reg) or
  8861. { Has to be an exact match on the register }
  8862. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8863. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8864. Break;
  8865. TestValMin := TestValMin * TestValMin;
  8866. TestValMax := TestValMax * TestValMax;
  8867. TestValSignedMax := TestValSignedMax * TestValMax;
  8868. end;
  8869. 3:
  8870. begin
  8871. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8872. { Has to be an exact match on the register }
  8873. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8874. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8875. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8876. { Is it in the negative range? }
  8877. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8878. Break;
  8879. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8880. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8881. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8882. end;
  8883. else
  8884. Break;
  8885. end;
  8886. A_IDIV:
  8887. case taicpu(hp1).ops of
  8888. 3:
  8889. begin
  8890. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8891. { Has to be an exact match on the register }
  8892. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8893. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8894. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8895. { Is it in the negative range? }
  8896. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8897. Break;
  8898. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8899. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8900. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8901. end;
  8902. else
  8903. Break;
  8904. end;
  8905. *)
  8906. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8907. begin
  8908. { If there are no instructions in between, then we might be able to make a saving }
  8909. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8910. Break;
  8911. { We have something like:
  8912. movzbw %dl,%dx
  8913. ...
  8914. movswl %dx,%edx
  8915. Change the latter to a zero-extension then enter the
  8916. A_MOVZX case branch.
  8917. }
  8918. {$ifdef x86_64}
  8919. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8920. begin
  8921. { this becomes a zero extension from 32-bit to 64-bit, but
  8922. the upper 32 bits are already zero, so just delete the
  8923. instruction }
  8924. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8925. RemoveInstruction(hp1);
  8926. Result := True;
  8927. Exit;
  8928. end
  8929. else
  8930. {$endif x86_64}
  8931. begin
  8932. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8933. taicpu(hp1).opcode := A_MOVZX;
  8934. {$ifdef x86_64}
  8935. case taicpu(hp1).opsize of
  8936. S_BQ:
  8937. begin
  8938. taicpu(hp1).opsize := S_BL;
  8939. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8940. end;
  8941. S_WQ:
  8942. begin
  8943. taicpu(hp1).opsize := S_WL;
  8944. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8945. end;
  8946. S_LQ:
  8947. begin
  8948. taicpu(hp1).opcode := A_MOV;
  8949. taicpu(hp1).opsize := S_L;
  8950. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8951. { In this instance, we need to break out because the
  8952. instruction is no longer MOVZX or MOVSXD }
  8953. Result := True;
  8954. Exit;
  8955. end;
  8956. else
  8957. ;
  8958. end;
  8959. {$endif x86_64}
  8960. Result := CompressInstructions;
  8961. Exit;
  8962. end;
  8963. end;
  8964. A_MOVZX:
  8965. begin
  8966. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8967. Break;
  8968. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8969. begin
  8970. if (InstrMax = -1) and
  8971. { Will return false if the second parameter isn't ThisReg
  8972. (can happen on -O2 and under) }
  8973. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8974. begin
  8975. { The two MOVZX instructions are adjacent, so remove the first one }
  8976. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8977. RemoveCurrentP(p);
  8978. Result := True;
  8979. Exit;
  8980. end;
  8981. Break;
  8982. end;
  8983. Result := CompressInstructions;
  8984. Exit;
  8985. end;
  8986. else
  8987. { This includes ADC, SBB and IDIV }
  8988. Break;
  8989. end;
  8990. if not CheckOverflowConditions then
  8991. Break;
  8992. { Contains highest index (so instruction count - 1) }
  8993. Inc(InstrMax);
  8994. if InstrMax > High(InstrList) then
  8995. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8996. InstrList[InstrMax] := taicpu(hp1);
  8997. end;
  8998. end;
  8999. {$pop}
  9000. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9001. var
  9002. hp1 : tai;
  9003. begin
  9004. Result:=false;
  9005. if (taicpu(p).ops >= 2) and
  9006. ((taicpu(p).oper[0]^.typ = top_const) or
  9007. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9008. (taicpu(p).oper[1]^.typ = top_reg) and
  9009. ((taicpu(p).ops = 2) or
  9010. ((taicpu(p).oper[2]^.typ = top_reg) and
  9011. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9012. GetLastInstruction(p,hp1) and
  9013. MatchInstruction(hp1,A_MOV,[]) and
  9014. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9015. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9016. begin
  9017. TransferUsedRegs(TmpUsedRegs);
  9018. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9019. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9020. { change
  9021. mov reg1,reg2
  9022. imul y,reg2 to imul y,reg1,reg2 }
  9023. begin
  9024. taicpu(p).ops := 3;
  9025. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9026. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9027. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9028. RemoveInstruction(hp1);
  9029. result:=true;
  9030. end;
  9031. end;
  9032. end;
  9033. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9034. var
  9035. ThisLabel: TAsmLabel;
  9036. begin
  9037. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9038. ThisLabel.decrefs;
  9039. taicpu(p).opcode := A_RET;
  9040. taicpu(p).is_jmp := false;
  9041. taicpu(p).ops := taicpu(ret_p).ops;
  9042. case taicpu(ret_p).ops of
  9043. 0:
  9044. taicpu(p).clearop(0);
  9045. 1:
  9046. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9047. else
  9048. internalerror(2016041301);
  9049. end;
  9050. { If the original label is now dead, it might turn out that the label
  9051. immediately follows p. As a result, everything beyond it, which will
  9052. be just some final register configuration and a RET instruction, is
  9053. now dead code. [Kit] }
  9054. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9055. running RemoveDeadCodeAfterJump for each RET instruction, because
  9056. this optimisation rarely happens and most RETs appear at the end of
  9057. routines where there is nothing that can be stripped. [Kit] }
  9058. if not ThisLabel.is_used then
  9059. RemoveDeadCodeAfterJump(p);
  9060. end;
  9061. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9062. var
  9063. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9064. Unconditional, PotentialModified: Boolean;
  9065. OperPtr: POper;
  9066. NewRef: TReference;
  9067. InstrList: array of taicpu;
  9068. InstrMax, Index: Integer;
  9069. const
  9070. {$ifdef DEBUG_AOPTCPU}
  9071. SNoFlags: shortstring = ' so the flags aren''t modified';
  9072. {$else DEBUG_AOPTCPU}
  9073. SNoFlags = '';
  9074. {$endif DEBUG_AOPTCPU}
  9075. begin
  9076. Result:=false;
  9077. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9078. begin
  9079. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9080. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9081. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9082. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9083. GetNextInstruction(hp1, hp2) and
  9084. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9085. { Change from: To:
  9086. set(C) %reg j(~C) label
  9087. test %reg,%reg/cmp $0,%reg
  9088. je label
  9089. set(C) %reg j(C) label
  9090. test %reg,%reg/cmp $0,%reg
  9091. jne label
  9092. (Also do something similar with sete/setne instead of je/jne)
  9093. }
  9094. begin
  9095. { Before we do anything else, we need to check the instructions
  9096. in between SETcc and TEST to make sure they don't modify the
  9097. FLAGS register - if -O2 or under, there won't be any
  9098. instructions between SET and TEST }
  9099. TransferUsedRegs(TmpUsedRegs);
  9100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9101. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9102. begin
  9103. next := p;
  9104. SetLength(InstrList, 0);
  9105. InstrMax := -1;
  9106. PotentialModified := False;
  9107. { Make a note of every instruction that modifies the FLAGS
  9108. register }
  9109. while GetNextInstruction(next, next) and (next <> hp1) do
  9110. begin
  9111. if next.typ <> ait_instruction then
  9112. { GetNextInstructionUsingReg should have returned False }
  9113. InternalError(2021051701);
  9114. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9115. begin
  9116. case taicpu(next).opcode of
  9117. A_SETcc,
  9118. A_CMOVcc,
  9119. A_Jcc:
  9120. begin
  9121. if PotentialModified then
  9122. { Not safe because the flags were modified earlier }
  9123. Exit
  9124. else
  9125. { Condition is the same as the initial SETcc, so this is safe
  9126. (don't add to instruction list though) }
  9127. Continue;
  9128. end;
  9129. A_ADD:
  9130. begin
  9131. if (taicpu(next).opsize = S_B) or
  9132. { LEA doesn't support 8-bit operands }
  9133. (taicpu(next).oper[1]^.typ <> top_reg) or
  9134. { Must write to a register }
  9135. (taicpu(next).oper[0]^.typ = top_ref) then
  9136. { Require a constant or a register }
  9137. Exit;
  9138. PotentialModified := True;
  9139. end;
  9140. A_SUB:
  9141. begin
  9142. if (taicpu(next).opsize = S_B) or
  9143. { LEA doesn't support 8-bit operands }
  9144. (taicpu(next).oper[1]^.typ <> top_reg) or
  9145. { Must write to a register }
  9146. (taicpu(next).oper[0]^.typ <> top_const) or
  9147. (taicpu(next).oper[0]^.val = $80000000) then
  9148. { Can't subtract a register with LEA - also
  9149. check that the value isn't -2^31, as this
  9150. can't be negated }
  9151. Exit;
  9152. PotentialModified := True;
  9153. end;
  9154. A_SAL,
  9155. A_SHL:
  9156. begin
  9157. if (taicpu(next).opsize = S_B) or
  9158. { LEA doesn't support 8-bit operands }
  9159. (taicpu(next).oper[1]^.typ <> top_reg) or
  9160. { Must write to a register }
  9161. (taicpu(next).oper[0]^.typ <> top_const) or
  9162. (taicpu(next).oper[0]^.val < 0) or
  9163. (taicpu(next).oper[0]^.val > 3) then
  9164. Exit;
  9165. PotentialModified := True;
  9166. end;
  9167. A_IMUL:
  9168. begin
  9169. if (taicpu(next).ops <> 3) or
  9170. (taicpu(next).oper[1]^.typ <> top_reg) or
  9171. { Must write to a register }
  9172. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9173. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9174. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9175. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9176. Exit
  9177. else
  9178. PotentialModified := True;
  9179. end;
  9180. else
  9181. { Don't know how to change this, so abort }
  9182. Exit;
  9183. end;
  9184. { Contains highest index (so instruction count - 1) }
  9185. Inc(InstrMax);
  9186. if InstrMax > High(InstrList) then
  9187. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9188. InstrList[InstrMax] := taicpu(next);
  9189. end;
  9190. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9191. end;
  9192. if not Assigned(next) or (next <> hp1) then
  9193. { It should be equal to hp1 }
  9194. InternalError(2021051702);
  9195. { Cycle through each instruction and check to see if we can
  9196. change them to versions that don't modify the flags }
  9197. if (InstrMax >= 0) then
  9198. begin
  9199. for Index := 0 to InstrMax do
  9200. case InstrList[Index].opcode of
  9201. A_ADD:
  9202. begin
  9203. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9204. InstrList[Index].opcode := A_LEA;
  9205. reference_reset(NewRef, 1, []);
  9206. NewRef.base := InstrList[Index].oper[1]^.reg;
  9207. if InstrList[Index].oper[0]^.typ = top_reg then
  9208. begin
  9209. NewRef.index := InstrList[Index].oper[0]^.reg;
  9210. NewRef.scalefactor := 1;
  9211. end
  9212. else
  9213. NewRef.offset := InstrList[Index].oper[0]^.val;
  9214. InstrList[Index].loadref(0, NewRef);
  9215. end;
  9216. A_SUB:
  9217. begin
  9218. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9219. InstrList[Index].opcode := A_LEA;
  9220. reference_reset(NewRef, 1, []);
  9221. NewRef.base := InstrList[Index].oper[1]^.reg;
  9222. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9223. InstrList[Index].loadref(0, NewRef);
  9224. end;
  9225. A_SHL,
  9226. A_SAL:
  9227. begin
  9228. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9229. InstrList[Index].opcode := A_LEA;
  9230. reference_reset(NewRef, 1, []);
  9231. NewRef.index := InstrList[Index].oper[1]^.reg;
  9232. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9233. InstrList[Index].loadref(0, NewRef);
  9234. end;
  9235. A_IMUL:
  9236. begin
  9237. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9238. InstrList[Index].opcode := A_LEA;
  9239. reference_reset(NewRef, 1, []);
  9240. NewRef.index := InstrList[Index].oper[1]^.reg;
  9241. case InstrList[Index].oper[0]^.val of
  9242. 2, 4, 8:
  9243. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9244. else {3, 5 and 9}
  9245. begin
  9246. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9247. NewRef.base := InstrList[Index].oper[1]^.reg;
  9248. end;
  9249. end;
  9250. InstrList[Index].loadref(0, NewRef);
  9251. end;
  9252. else
  9253. InternalError(2021051710);
  9254. end;
  9255. end;
  9256. { Mark the FLAGS register as used across this whole block }
  9257. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9258. end;
  9259. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9260. JumpC := taicpu(hp2).condition;
  9261. Unconditional := False;
  9262. if conditions_equal(JumpC, C_E) then
  9263. SetC := inverse_cond(taicpu(p).condition)
  9264. else if conditions_equal(JumpC, C_NE) then
  9265. SetC := taicpu(p).condition
  9266. else
  9267. { We've got something weird here (and inefficent) }
  9268. begin
  9269. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9270. SetC := C_NONE;
  9271. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9272. if condition_in(C_AE, JumpC) then
  9273. Unconditional := True
  9274. else
  9275. { Not sure what to do with this jump - drop out }
  9276. Exit;
  9277. end;
  9278. RemoveInstruction(hp1);
  9279. if Unconditional then
  9280. MakeUnconditional(taicpu(hp2))
  9281. else
  9282. begin
  9283. if SetC = C_NONE then
  9284. InternalError(2018061402);
  9285. taicpu(hp2).SetCondition(SetC);
  9286. end;
  9287. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9288. TmpUsedRegs }
  9289. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9290. begin
  9291. RemoveCurrentp(p, hp2);
  9292. if taicpu(hp2).opcode = A_SETcc then
  9293. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9294. else
  9295. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9296. end
  9297. else
  9298. if taicpu(hp2).opcode = A_SETcc then
  9299. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9300. else
  9301. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9302. Result := True;
  9303. end
  9304. else if
  9305. { Make sure the instructions are adjacent }
  9306. (
  9307. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9308. GetNextInstruction(p, hp1)
  9309. ) and
  9310. MatchInstruction(hp1, A_MOV, [S_B]) and
  9311. { Writing to memory is allowed }
  9312. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9313. begin
  9314. {
  9315. Watch out for sequences such as:
  9316. set(c)b %regb
  9317. movb %regb,(ref)
  9318. movb $0,1(ref)
  9319. movb $0,2(ref)
  9320. movb $0,3(ref)
  9321. Much more efficient to turn it into:
  9322. movl $0,%regl
  9323. set(c)b %regb
  9324. movl %regl,(ref)
  9325. Or:
  9326. set(c)b %regb
  9327. movzbl %regb,%regl
  9328. movl %regl,(ref)
  9329. }
  9330. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9331. GetNextInstruction(hp1, hp2) and
  9332. MatchInstruction(hp2, A_MOV, [S_B]) and
  9333. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9334. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9335. begin
  9336. { Don't do anything else except set Result to True }
  9337. end
  9338. else
  9339. begin
  9340. if taicpu(p).oper[0]^.typ = top_reg then
  9341. begin
  9342. TransferUsedRegs(TmpUsedRegs);
  9343. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9344. end;
  9345. { If it's not a register, it's a memory address }
  9346. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9347. begin
  9348. { Even if the register is still in use, we can minimise the
  9349. pipeline stall by changing the MOV into another SETcc. }
  9350. taicpu(hp1).opcode := A_SETcc;
  9351. taicpu(hp1).condition := taicpu(p).condition;
  9352. if taicpu(hp1).oper[1]^.typ = top_ref then
  9353. begin
  9354. { Swapping the operand pointers like this is probably a
  9355. bit naughty, but it is far faster than using loadoper
  9356. to transfer the reference from oper[1] to oper[0] if
  9357. you take into account the extra procedure calls and
  9358. the memory allocation and deallocation required }
  9359. OperPtr := taicpu(hp1).oper[1];
  9360. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9361. taicpu(hp1).oper[0] := OperPtr;
  9362. end
  9363. else
  9364. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9365. taicpu(hp1).clearop(1);
  9366. taicpu(hp1).ops := 1;
  9367. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9368. end
  9369. else
  9370. begin
  9371. if taicpu(hp1).oper[1]^.typ = top_reg then
  9372. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9373. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9374. RemoveInstruction(hp1);
  9375. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9376. end
  9377. end;
  9378. Result := True;
  9379. end;
  9380. end;
  9381. end;
  9382. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9383. var
  9384. hp1: tai;
  9385. Count: Integer;
  9386. OrigLabel: TAsmLabel;
  9387. begin
  9388. result := False;
  9389. { Sometimes, the optimisations below can permit this }
  9390. RemoveDeadCodeAfterJump(p);
  9391. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  9392. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9393. begin
  9394. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9395. { Also a side-effect of optimisations }
  9396. if CollapseZeroDistJump(p, OrigLabel) then
  9397. begin
  9398. Result := True;
  9399. Exit;
  9400. end;
  9401. hp1 := GetLabelWithSym(OrigLabel);
  9402. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9403. begin
  9404. if taicpu(hp1).opcode = A_RET then
  9405. begin
  9406. {
  9407. change
  9408. jmp .L1
  9409. ...
  9410. .L1:
  9411. ret
  9412. into
  9413. ret
  9414. }
  9415. begin
  9416. ConvertJumpToRET(p, hp1);
  9417. result:=true;
  9418. end;
  9419. end
  9420. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9421. not (cs_opt_size in current_settings.optimizerswitches) and
  9422. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9423. begin
  9424. Result := True;
  9425. Exit;
  9426. end;
  9427. end;
  9428. end;
  9429. end;
  9430. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9431. begin
  9432. CanBeCMOV:=assigned(p) and
  9433. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9434. { we can't use cmov ref,reg because
  9435. ref could be nil and cmov still throws an exception
  9436. if ref=nil but the mov isn't done (FK)
  9437. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9438. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9439. }
  9440. (taicpu(p).oper[1]^.typ = top_reg) and
  9441. (
  9442. (taicpu(p).oper[0]^.typ = top_reg) or
  9443. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9444. it is not expected that this can cause a seg. violation }
  9445. (
  9446. (taicpu(p).oper[0]^.typ = top_ref) and
  9447. IsRefSafe(taicpu(p).oper[0]^.ref)
  9448. )
  9449. );
  9450. end;
  9451. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9452. var
  9453. hp1,hp2: tai;
  9454. {$ifndef i8086}
  9455. hp3,hp4,hpmov2, hp5: tai;
  9456. l : Longint;
  9457. condition : TAsmCond;
  9458. {$endif i8086}
  9459. carryadd_opcode : TAsmOp;
  9460. symbol: TAsmSymbol;
  9461. increg, tmpreg: TRegister;
  9462. begin
  9463. result:=false;
  9464. if GetNextInstruction(p,hp1) then
  9465. begin
  9466. if (hp1.typ=ait_label) then
  9467. begin
  9468. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9469. Exit;
  9470. end
  9471. else if (hp1.typ<>ait_instruction) then
  9472. Exit;
  9473. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9474. if (
  9475. (
  9476. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9477. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9478. (Taicpu(hp1).oper[0]^.val=1)
  9479. ) or
  9480. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9481. ) and
  9482. GetNextInstruction(hp1,hp2) and
  9483. SkipAligns(hp2, hp2) and
  9484. (hp2.typ = ait_label) and
  9485. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9486. { jb @@1 cmc
  9487. inc/dec operand --> adc/sbb operand,0
  9488. @@1:
  9489. ... and ...
  9490. jnb @@1
  9491. inc/dec operand --> adc/sbb operand,0
  9492. @@1: }
  9493. begin
  9494. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9495. begin
  9496. case taicpu(hp1).opcode of
  9497. A_INC,
  9498. A_ADD:
  9499. carryadd_opcode:=A_ADC;
  9500. A_DEC,
  9501. A_SUB:
  9502. carryadd_opcode:=A_SBB;
  9503. else
  9504. InternalError(2021011001);
  9505. end;
  9506. Taicpu(p).clearop(0);
  9507. Taicpu(p).ops:=0;
  9508. Taicpu(p).is_jmp:=false;
  9509. Taicpu(p).opcode:=A_CMC;
  9510. Taicpu(p).condition:=C_NONE;
  9511. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9512. Taicpu(hp1).ops:=2;
  9513. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9514. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9515. else
  9516. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9517. Taicpu(hp1).loadconst(0,0);
  9518. Taicpu(hp1).opcode:=carryadd_opcode;
  9519. result:=true;
  9520. exit;
  9521. end
  9522. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9523. begin
  9524. case taicpu(hp1).opcode of
  9525. A_INC,
  9526. A_ADD:
  9527. carryadd_opcode:=A_ADC;
  9528. A_DEC,
  9529. A_SUB:
  9530. carryadd_opcode:=A_SBB;
  9531. else
  9532. InternalError(2021011002);
  9533. end;
  9534. Taicpu(hp1).ops:=2;
  9535. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9536. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9537. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9538. else
  9539. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9540. Taicpu(hp1).loadconst(0,0);
  9541. Taicpu(hp1).opcode:=carryadd_opcode;
  9542. RemoveCurrentP(p, hp1);
  9543. result:=true;
  9544. exit;
  9545. end
  9546. {
  9547. jcc @@1 setcc tmpreg
  9548. inc/dec/add/sub operand -> (movzx tmpreg)
  9549. @@1: add/sub tmpreg,operand
  9550. While this increases code size slightly, it makes the code much faster if the
  9551. jump is unpredictable
  9552. }
  9553. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9554. begin
  9555. { search for an available register which is volatile }
  9556. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9557. if increg <> NR_NO then
  9558. begin
  9559. { We don't need to check if tmpreg is in hp1 or not, because
  9560. it will be marked as in use at p (if not, this is
  9561. indictive of a compiler bug). }
  9562. TAsmLabel(symbol).decrefs;
  9563. Taicpu(p).clearop(0);
  9564. Taicpu(p).ops:=1;
  9565. Taicpu(p).is_jmp:=false;
  9566. Taicpu(p).opcode:=A_SETcc;
  9567. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9568. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9569. Taicpu(p).loadreg(0,increg);
  9570. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9571. begin
  9572. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9573. R_SUBW:
  9574. begin
  9575. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9576. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9577. end;
  9578. R_SUBD:
  9579. begin
  9580. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9581. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9582. end;
  9583. {$ifdef x86_64}
  9584. R_SUBQ:
  9585. begin
  9586. { MOVZX doesn't have a 64-bit variant, because
  9587. the 32-bit version implicitly zeroes the
  9588. upper 32-bits of the destination register }
  9589. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9590. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9591. setsubreg(tmpreg, R_SUBQ);
  9592. end;
  9593. {$endif x86_64}
  9594. else
  9595. Internalerror(2020030601);
  9596. end;
  9597. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9598. asml.InsertAfter(hp2,p);
  9599. end
  9600. else
  9601. tmpreg := increg;
  9602. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9603. begin
  9604. Taicpu(hp1).ops:=2;
  9605. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9606. end;
  9607. Taicpu(hp1).loadreg(0,tmpreg);
  9608. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9609. Result := True;
  9610. { p is no longer a Jcc instruction, so exit }
  9611. Exit;
  9612. end;
  9613. end;
  9614. end;
  9615. { Detect the following:
  9616. jmp<cond> @Lbl1
  9617. jmp @Lbl2
  9618. ...
  9619. @Lbl1:
  9620. ret
  9621. Change to:
  9622. jmp<inv_cond> @Lbl2
  9623. ret
  9624. }
  9625. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9626. begin
  9627. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9628. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9629. MatchInstruction(hp2,A_RET,[S_NO]) then
  9630. begin
  9631. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9632. { Change label address to that of the unconditional jump }
  9633. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9634. TAsmLabel(symbol).DecRefs;
  9635. taicpu(hp1).opcode := A_RET;
  9636. taicpu(hp1).is_jmp := false;
  9637. taicpu(hp1).ops := taicpu(hp2).ops;
  9638. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9639. case taicpu(hp2).ops of
  9640. 0:
  9641. taicpu(hp1).clearop(0);
  9642. 1:
  9643. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9644. else
  9645. internalerror(2016041302);
  9646. end;
  9647. end;
  9648. {$ifndef i8086}
  9649. end
  9650. {
  9651. convert
  9652. j<c> .L1
  9653. mov 1,reg
  9654. jmp .L2
  9655. .L1
  9656. mov 0,reg
  9657. .L2
  9658. into
  9659. mov 0,reg
  9660. set<not(c)> reg
  9661. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9662. would destroy the flag contents
  9663. }
  9664. else if MatchInstruction(hp1,A_MOV,[]) and
  9665. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9666. {$ifdef i386}
  9667. (
  9668. { Under i386, ESI, EDI, EBP and ESP
  9669. don't have an 8-bit representation }
  9670. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9671. ) and
  9672. {$endif i386}
  9673. (taicpu(hp1).oper[0]^.val=1) and
  9674. GetNextInstruction(hp1,hp2) and
  9675. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9676. GetNextInstruction(hp2,hp3) and
  9677. { skip align }
  9678. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9679. (hp3.typ=ait_label) and
  9680. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9681. (tai_label(hp3).labsym.getrefs=1) and
  9682. GetNextInstruction(hp3,hp4) and
  9683. MatchInstruction(hp4,A_MOV,[]) and
  9684. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9685. (taicpu(hp4).oper[0]^.val=0) and
  9686. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9687. GetNextInstruction(hp4,hp5) and
  9688. (hp5.typ=ait_label) and
  9689. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9690. (tai_label(hp5).labsym.getrefs=1) then
  9691. begin
  9692. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9693. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9694. { remove last label }
  9695. RemoveInstruction(hp5);
  9696. { remove second label }
  9697. RemoveInstruction(hp3);
  9698. { if align is present remove it }
  9699. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9700. RemoveInstruction(hp3);
  9701. { remove jmp }
  9702. RemoveInstruction(hp2);
  9703. if taicpu(hp1).opsize=S_B then
  9704. RemoveInstruction(hp1)
  9705. else
  9706. taicpu(hp1).loadconst(0,0);
  9707. taicpu(hp4).opcode:=A_SETcc;
  9708. taicpu(hp4).opsize:=S_B;
  9709. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9710. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9711. taicpu(hp4).opercnt:=1;
  9712. taicpu(hp4).ops:=1;
  9713. taicpu(hp4).freeop(1);
  9714. RemoveCurrentP(p);
  9715. Result:=true;
  9716. exit;
  9717. end
  9718. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9719. begin
  9720. { check for
  9721. jCC xxx
  9722. <several movs>
  9723. xxx:
  9724. Also spot:
  9725. Jcc xxx
  9726. <several movs>
  9727. jmp xxx
  9728. Change to:
  9729. <several cmovs with inverted condition>
  9730. jmp xxx
  9731. }
  9732. l:=0;
  9733. while assigned(hp1) and
  9734. CanBeCMOV(hp1) and
  9735. { stop on labels }
  9736. not(hp1.typ=ait_label) do
  9737. begin
  9738. inc(l);
  9739. hp5 := hp1;
  9740. GetNextInstruction(hp1,hp1);
  9741. end;
  9742. if assigned(hp1) then
  9743. begin
  9744. TransferUsedRegs(TmpUsedRegs);
  9745. if (
  9746. MatchInstruction(hp1, A_JMP, []) and
  9747. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9748. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9749. ) or
  9750. FindLabel(tasmlabel(symbol),hp1) then
  9751. begin
  9752. if (l<=4) and (l>0) then
  9753. begin
  9754. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9755. condition:=inverse_cond(taicpu(p).condition);
  9756. UpdateUsedRegs(tai(p.next));
  9757. GetNextInstruction(p,hp1);
  9758. repeat
  9759. if not Assigned(hp1) then
  9760. InternalError(2018062900);
  9761. taicpu(hp1).opcode:=A_CMOVcc;
  9762. taicpu(hp1).condition:=condition;
  9763. UpdateUsedRegs(tai(hp1.next));
  9764. GetNextInstruction(hp1,hp1);
  9765. until not(CanBeCMOV(hp1));
  9766. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9767. hp2 := hp1;
  9768. repeat
  9769. if not Assigned(hp2) then
  9770. InternalError(2018062910);
  9771. case hp2.typ of
  9772. ait_label:
  9773. { What we expected - break out of the loop (it won't be a dead label at the top of
  9774. a cluster because that was optimised at an earlier stage) }
  9775. Break;
  9776. ait_align:
  9777. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9778. begin
  9779. hp2 := tai(hp2.Next);
  9780. Continue;
  9781. end;
  9782. ait_instruction:
  9783. begin
  9784. if taicpu(hp2).opcode<>A_JMP then
  9785. InternalError(2018062912);
  9786. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9787. Break;
  9788. end
  9789. else
  9790. begin
  9791. { Might be a comment or temporary allocation entry }
  9792. if not (hp2.typ in SkipInstr) then
  9793. InternalError(2018062911);
  9794. hp2 := tai(hp2.Next);
  9795. Continue;
  9796. end;
  9797. end;
  9798. until False;
  9799. { Now we can safely decrement the reference count }
  9800. tasmlabel(symbol).decrefs;
  9801. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9802. { Remove the original jump }
  9803. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9804. if hp2.typ=ait_instruction then
  9805. begin
  9806. p:=hp2;
  9807. Result:=True;
  9808. end
  9809. else
  9810. begin
  9811. UpdateUsedRegs(tai(hp2.next));
  9812. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9813. { Remove the label if this is its final reference }
  9814. if (tasmlabel(symbol).getrefs=0) then
  9815. StripLabelFast(hp1);
  9816. end;
  9817. exit;
  9818. end;
  9819. end
  9820. else
  9821. begin
  9822. { check further for
  9823. jCC xxx
  9824. <several movs 1>
  9825. jmp yyy
  9826. xxx:
  9827. <several movs 2>
  9828. yyy:
  9829. }
  9830. { hp2 points to jmp yyy }
  9831. hp2:=hp1;
  9832. { skip hp1 to xxx (or an align right before it) }
  9833. GetNextInstruction(hp1, hp1);
  9834. if assigned(hp2) and
  9835. assigned(hp1) and
  9836. (l<=3) and
  9837. (hp2.typ=ait_instruction) and
  9838. (taicpu(hp2).is_jmp) and
  9839. (taicpu(hp2).condition=C_None) and
  9840. { real label and jump, no further references to the
  9841. label are allowed }
  9842. (tasmlabel(symbol).getrefs=1) and
  9843. FindLabel(tasmlabel(symbol),hp1) then
  9844. begin
  9845. l:=0;
  9846. { skip hp1 to <several moves 2> }
  9847. if (hp1.typ = ait_align) then
  9848. GetNextInstruction(hp1, hp1);
  9849. GetNextInstruction(hp1, hpmov2);
  9850. hp1 := hpmov2;
  9851. while assigned(hp1) and
  9852. CanBeCMOV(hp1) do
  9853. begin
  9854. inc(l);
  9855. hp5 := hp1;
  9856. GetNextInstruction(hp1, hp1);
  9857. end;
  9858. { hp1 points to yyy (or an align right before it) }
  9859. hp3 := hp1;
  9860. if assigned(hp1) and
  9861. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9862. begin
  9863. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9864. condition:=inverse_cond(taicpu(p).condition);
  9865. UpdateUsedRegs(tai(p.next));
  9866. GetNextInstruction(p,hp1);
  9867. repeat
  9868. taicpu(hp1).opcode:=A_CMOVcc;
  9869. taicpu(hp1).condition:=condition;
  9870. UpdateUsedRegs(tai(hp1.next));
  9871. GetNextInstruction(hp1,hp1);
  9872. until not(assigned(hp1)) or
  9873. not(CanBeCMOV(hp1));
  9874. condition:=inverse_cond(condition);
  9875. if GetLastInstruction(hpmov2,hp1) then
  9876. UpdateUsedRegs(tai(hp1.next));
  9877. hp1 := hpmov2;
  9878. { hp1 is now at <several movs 2> }
  9879. while Assigned(hp1) and CanBeCMOV(hp1) do
  9880. begin
  9881. taicpu(hp1).opcode:=A_CMOVcc;
  9882. taicpu(hp1).condition:=condition;
  9883. UpdateUsedRegs(tai(hp1.next));
  9884. GetNextInstruction(hp1,hp1);
  9885. end;
  9886. hp1 := p;
  9887. { Get first instruction after label }
  9888. UpdateUsedRegs(tai(hp3.next));
  9889. GetNextInstruction(hp3, p);
  9890. if assigned(p) and (hp3.typ = ait_align) then
  9891. GetNextInstruction(p, p);
  9892. { Don't dereference yet, as doing so will cause
  9893. GetNextInstruction to skip the label and
  9894. optional align marker. [Kit] }
  9895. GetNextInstruction(hp2, hp4);
  9896. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9897. { remove jCC }
  9898. RemoveInstruction(hp1);
  9899. { Now we can safely decrement it }
  9900. tasmlabel(symbol).decrefs;
  9901. { Remove label xxx (it will have a ref of zero due to the initial check }
  9902. StripLabelFast(hp4);
  9903. { remove jmp }
  9904. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9905. RemoveInstruction(hp2);
  9906. { As before, now we can safely decrement it }
  9907. tasmlabel(symbol).decrefs;
  9908. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9909. if tasmlabel(symbol).getrefs = 0 then
  9910. StripLabelFast(hp3);
  9911. if Assigned(p) then
  9912. result:=true;
  9913. exit;
  9914. end;
  9915. end;
  9916. end;
  9917. end;
  9918. {$endif i8086}
  9919. end;
  9920. end;
  9921. end;
  9922. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9923. var
  9924. hp1,hp2,hp3: tai;
  9925. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9926. NewSize: TOpSize;
  9927. NewRegSize: TSubRegister;
  9928. Limit: TCgInt;
  9929. SwapOper: POper;
  9930. begin
  9931. result:=false;
  9932. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9933. GetNextInstruction(p,hp1) and
  9934. (hp1.typ = ait_instruction);
  9935. if reg_and_hp1_is_instr and
  9936. (
  9937. (taicpu(hp1).opcode <> A_LEA) or
  9938. { If the LEA instruction can be converted into an arithmetic instruction,
  9939. it may be possible to then fold it. }
  9940. (
  9941. { If the flags register is in use, don't change the instruction
  9942. to an ADD otherwise this will scramble the flags. [Kit] }
  9943. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9944. ConvertLEA(taicpu(hp1))
  9945. )
  9946. ) and
  9947. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9948. GetNextInstruction(hp1,hp2) and
  9949. MatchInstruction(hp2,A_MOV,[]) and
  9950. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9951. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9952. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9953. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9954. {$ifdef i386}
  9955. { not all registers have byte size sub registers on i386 }
  9956. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9957. {$endif i386}
  9958. (((taicpu(hp1).ops=2) and
  9959. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9960. ((taicpu(hp1).ops=1) and
  9961. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9962. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9963. begin
  9964. { change movsX/movzX reg/ref, reg2
  9965. add/sub/or/... reg3/$const, reg2
  9966. mov reg2 reg/ref
  9967. to add/sub/or/... reg3/$const, reg/ref }
  9968. { by example:
  9969. movswl %si,%eax movswl %si,%eax p
  9970. decl %eax addl %edx,%eax hp1
  9971. movw %ax,%si movw %ax,%si hp2
  9972. ->
  9973. movswl %si,%eax movswl %si,%eax p
  9974. decw %eax addw %edx,%eax hp1
  9975. movw %ax,%si movw %ax,%si hp2
  9976. }
  9977. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9978. {
  9979. ->
  9980. movswl %si,%eax movswl %si,%eax p
  9981. decw %si addw %dx,%si hp1
  9982. movw %ax,%si movw %ax,%si hp2
  9983. }
  9984. case taicpu(hp1).ops of
  9985. 1:
  9986. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9987. 2:
  9988. begin
  9989. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9990. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9991. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9992. end;
  9993. else
  9994. internalerror(2008042702);
  9995. end;
  9996. {
  9997. ->
  9998. decw %si addw %dx,%si p
  9999. }
  10000. DebugMsg(SPeepholeOptimization + 'var3',p);
  10001. RemoveCurrentP(p, hp1);
  10002. RemoveInstruction(hp2);
  10003. Result := True;
  10004. Exit;
  10005. end;
  10006. if reg_and_hp1_is_instr and
  10007. (taicpu(hp1).opcode = A_MOV) and
  10008. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10009. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10010. {$ifdef x86_64}
  10011. { check for implicit extension to 64 bit }
  10012. or
  10013. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10014. (taicpu(hp1).opsize=S_Q) and
  10015. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10016. )
  10017. {$endif x86_64}
  10018. )
  10019. then
  10020. begin
  10021. { change
  10022. movx %reg1,%reg2
  10023. mov %reg2,%reg3
  10024. dealloc %reg2
  10025. into
  10026. movx %reg,%reg3
  10027. }
  10028. TransferUsedRegs(TmpUsedRegs);
  10029. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10030. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10031. begin
  10032. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10033. {$ifdef x86_64}
  10034. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10035. (taicpu(hp1).opsize=S_Q) then
  10036. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10037. else
  10038. {$endif x86_64}
  10039. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10040. RemoveInstruction(hp1);
  10041. Result := True;
  10042. Exit;
  10043. end;
  10044. end;
  10045. if reg_and_hp1_is_instr and
  10046. ((taicpu(hp1).opcode=A_MOV) or
  10047. (taicpu(hp1).opcode=A_ADD) or
  10048. (taicpu(hp1).opcode=A_SUB) or
  10049. (taicpu(hp1).opcode=A_CMP) or
  10050. (taicpu(hp1).opcode=A_OR) or
  10051. (taicpu(hp1).opcode=A_XOR) or
  10052. (taicpu(hp1).opcode=A_AND)
  10053. ) and
  10054. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10055. begin
  10056. AndTest := (taicpu(hp1).opcode=A_AND) and
  10057. GetNextInstruction(hp1, hp2) and
  10058. (hp2.typ = ait_instruction) and
  10059. (
  10060. (
  10061. (taicpu(hp2).opcode=A_TEST) and
  10062. (
  10063. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10064. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10065. (
  10066. { If the AND and TEST instructions share a constant, this is also valid }
  10067. (taicpu(hp1).oper[0]^.typ = top_const) and
  10068. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10069. )
  10070. ) and
  10071. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10072. ) or
  10073. (
  10074. (taicpu(hp2).opcode=A_CMP) and
  10075. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10076. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10077. )
  10078. );
  10079. { change
  10080. movx (oper),%reg2
  10081. and $x,%reg2
  10082. test %reg2,%reg2
  10083. dealloc %reg2
  10084. into
  10085. op %reg1,%reg3
  10086. if the second op accesses only the bits stored in reg1
  10087. }
  10088. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10089. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10090. (taicpu(hp1).oper[0]^.typ = top_const) and
  10091. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10092. AndTest then
  10093. begin
  10094. { Check if the AND constant is in range }
  10095. case taicpu(p).opsize of
  10096. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10097. begin
  10098. NewSize := S_B;
  10099. Limit := $FF;
  10100. end;
  10101. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10102. begin
  10103. NewSize := S_W;
  10104. Limit := $FFFF;
  10105. end;
  10106. {$ifdef x86_64}
  10107. S_LQ:
  10108. begin
  10109. NewSize := S_L;
  10110. Limit := $FFFFFFFF;
  10111. end;
  10112. {$endif x86_64}
  10113. else
  10114. InternalError(2021120303);
  10115. end;
  10116. if (
  10117. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10118. { Check for negative operands }
  10119. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10120. ) and
  10121. GetNextInstruction(hp2,hp3) and
  10122. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10123. (taicpu(hp3).condition in [C_E,C_NE]) then
  10124. begin
  10125. TransferUsedRegs(TmpUsedRegs);
  10126. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10127. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10128. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10129. begin
  10130. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10131. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10132. taicpu(hp1).opcode := A_TEST;
  10133. taicpu(hp1).opsize := NewSize;
  10134. RemoveInstruction(hp2);
  10135. RemoveCurrentP(p, hp1);
  10136. Result:=true;
  10137. exit;
  10138. end;
  10139. end;
  10140. end;
  10141. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10142. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10143. (taicpu(hp1).opsize=S_B)) or
  10144. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10145. (taicpu(hp1).opsize=S_W))
  10146. {$ifdef x86_64}
  10147. or ((taicpu(p).opsize=S_LQ) and
  10148. (taicpu(hp1).opsize=S_L))
  10149. {$endif x86_64}
  10150. ) and
  10151. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10152. begin
  10153. { change
  10154. movx %reg1,%reg2
  10155. op %reg2,%reg3
  10156. dealloc %reg2
  10157. into
  10158. op %reg1,%reg3
  10159. if the second op accesses only the bits stored in reg1
  10160. }
  10161. TransferUsedRegs(TmpUsedRegs);
  10162. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10163. if AndTest then
  10164. begin
  10165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10166. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10167. end
  10168. else
  10169. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10170. if not RegUsed then
  10171. begin
  10172. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10173. if taicpu(p).oper[0]^.typ=top_reg then
  10174. begin
  10175. case taicpu(hp1).opsize of
  10176. S_B:
  10177. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10178. S_W:
  10179. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10180. S_L:
  10181. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10182. else
  10183. Internalerror(2020102301);
  10184. end;
  10185. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10186. end
  10187. else
  10188. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10189. RemoveCurrentP(p);
  10190. if AndTest then
  10191. RemoveInstruction(hp2);
  10192. result:=true;
  10193. exit;
  10194. end;
  10195. end
  10196. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10197. (
  10198. { Bitwise operations only }
  10199. (taicpu(hp1).opcode=A_AND) or
  10200. (taicpu(hp1).opcode=A_TEST) or
  10201. (
  10202. (taicpu(hp1).oper[0]^.typ = top_const) and
  10203. (
  10204. (taicpu(hp1).opcode=A_OR) or
  10205. (taicpu(hp1).opcode=A_XOR)
  10206. )
  10207. )
  10208. ) and
  10209. (
  10210. (taicpu(hp1).oper[0]^.typ = top_const) or
  10211. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10212. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10213. ) then
  10214. begin
  10215. { change
  10216. movx %reg2,%reg2
  10217. op const,%reg2
  10218. into
  10219. op const,%reg2 (smaller version)
  10220. movx %reg2,%reg2
  10221. also change
  10222. movx %reg1,%reg2
  10223. and/test (oper),%reg2
  10224. dealloc %reg2
  10225. into
  10226. and/test (oper),%reg1
  10227. }
  10228. case taicpu(p).opsize of
  10229. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10230. begin
  10231. NewSize := S_B;
  10232. NewRegSize := R_SUBL;
  10233. Limit := $FF;
  10234. end;
  10235. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10236. begin
  10237. NewSize := S_W;
  10238. NewRegSize := R_SUBW;
  10239. Limit := $FFFF;
  10240. end;
  10241. {$ifdef x86_64}
  10242. S_LQ:
  10243. begin
  10244. NewSize := S_L;
  10245. NewRegSize := R_SUBD;
  10246. Limit := $FFFFFFFF;
  10247. end;
  10248. {$endif x86_64}
  10249. else
  10250. Internalerror(2021120302);
  10251. end;
  10252. TransferUsedRegs(TmpUsedRegs);
  10253. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10254. if AndTest then
  10255. begin
  10256. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10257. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10258. end
  10259. else
  10260. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10261. if
  10262. (
  10263. (taicpu(p).opcode = A_MOVZX) and
  10264. (
  10265. (taicpu(hp1).opcode=A_AND) or
  10266. (taicpu(hp1).opcode=A_TEST)
  10267. ) and
  10268. not (
  10269. { If both are references, then the final instruction will have
  10270. both operands as references, which is not allowed }
  10271. (taicpu(p).oper[0]^.typ = top_ref) and
  10272. (taicpu(hp1).oper[0]^.typ = top_ref)
  10273. ) and
  10274. not RegUsed
  10275. ) or
  10276. (
  10277. (
  10278. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10279. not RegUsed
  10280. ) and
  10281. (taicpu(p).oper[0]^.typ = top_reg) and
  10282. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10283. (taicpu(hp1).oper[0]^.typ = top_const) and
  10284. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10285. ) then
  10286. begin
  10287. {$if defined(i386) or defined(i8086)}
  10288. { If the target size is 8-bit, make sure we can actually encode it }
  10289. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10290. Exit;
  10291. {$endif i386 or i8086}
  10292. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10293. taicpu(hp1).opsize := NewSize;
  10294. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10295. if AndTest then
  10296. begin
  10297. RemoveInstruction(hp2);
  10298. if not RegUsed then
  10299. begin
  10300. taicpu(hp1).opcode := A_TEST;
  10301. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10302. begin
  10303. { Make sure the reference is the second operand }
  10304. SwapOper := taicpu(hp1).oper[0];
  10305. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10306. taicpu(hp1).oper[1] := SwapOper;
  10307. end;
  10308. end;
  10309. end;
  10310. case taicpu(hp1).oper[0]^.typ of
  10311. top_reg:
  10312. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10313. top_const:
  10314. { For the AND/TEST case }
  10315. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10316. else
  10317. ;
  10318. end;
  10319. if RegUsed then
  10320. begin
  10321. AsmL.Remove(p);
  10322. AsmL.InsertAfter(p, hp1);
  10323. p := hp1;
  10324. end
  10325. else
  10326. RemoveCurrentP(p, hp1);
  10327. result:=true;
  10328. exit;
  10329. end;
  10330. end;
  10331. end;
  10332. if reg_and_hp1_is_instr and
  10333. (taicpu(p).oper[0]^.typ = top_reg) and
  10334. (
  10335. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10336. ) and
  10337. (taicpu(hp1).oper[0]^.typ = top_const) and
  10338. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10339. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10340. { Minimum shift value allowed is the bit difference between the sizes }
  10341. (taicpu(hp1).oper[0]^.val >=
  10342. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10343. 8 * (
  10344. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10345. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10346. )
  10347. ) then
  10348. begin
  10349. { For:
  10350. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10351. shl/sal ##, %reg1
  10352. Remove the movsx/movzx instruction if the shift overwrites the
  10353. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10354. }
  10355. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10356. RemoveCurrentP(p, hp1);
  10357. Result := True;
  10358. Exit;
  10359. end
  10360. else if reg_and_hp1_is_instr and
  10361. (taicpu(p).oper[0]^.typ = top_reg) and
  10362. (
  10363. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10364. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10365. ) and
  10366. (taicpu(hp1).oper[0]^.typ = top_const) and
  10367. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10368. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10369. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10370. (taicpu(hp1).oper[0]^.val <
  10371. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10372. 8 * (
  10373. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10374. )
  10375. ) then
  10376. begin
  10377. { For:
  10378. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10379. sar ##, %reg1 shr ##, %reg1
  10380. Move the shift to before the movx instruction if the shift value
  10381. is not too large.
  10382. }
  10383. asml.Remove(hp1);
  10384. asml.InsertBefore(hp1, p);
  10385. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10386. case taicpu(p).opsize of
  10387. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10388. taicpu(hp1).opsize := S_B;
  10389. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10390. taicpu(hp1).opsize := S_W;
  10391. {$ifdef x86_64}
  10392. S_LQ:
  10393. taicpu(hp1).opsize := S_L;
  10394. {$endif}
  10395. else
  10396. InternalError(2020112401);
  10397. end;
  10398. if (taicpu(hp1).opcode = A_SHR) then
  10399. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10400. else
  10401. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10402. Result := True;
  10403. end;
  10404. if reg_and_hp1_is_instr and
  10405. (taicpu(p).oper[0]^.typ = top_reg) and
  10406. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10407. (
  10408. (taicpu(hp1).opcode = taicpu(p).opcode)
  10409. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10410. {$ifdef x86_64}
  10411. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10412. {$endif x86_64}
  10413. ) then
  10414. begin
  10415. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10416. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10417. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10418. begin
  10419. {
  10420. For example:
  10421. movzbw %al,%ax
  10422. movzwl %ax,%eax
  10423. Compress into:
  10424. movzbl %al,%eax
  10425. }
  10426. RegUsed := False;
  10427. case taicpu(p).opsize of
  10428. S_BW:
  10429. case taicpu(hp1).opsize of
  10430. S_WL:
  10431. begin
  10432. taicpu(p).opsize := S_BL;
  10433. RegUsed := True;
  10434. end;
  10435. {$ifdef x86_64}
  10436. S_WQ:
  10437. begin
  10438. if taicpu(p).opcode = A_MOVZX then
  10439. begin
  10440. taicpu(p).opsize := S_BL;
  10441. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10442. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10443. end
  10444. else
  10445. taicpu(p).opsize := S_BQ;
  10446. RegUsed := True;
  10447. end;
  10448. {$endif x86_64}
  10449. else
  10450. ;
  10451. end;
  10452. {$ifdef x86_64}
  10453. S_BL:
  10454. case taicpu(hp1).opsize of
  10455. S_LQ:
  10456. begin
  10457. if taicpu(p).opcode = A_MOVZX then
  10458. begin
  10459. taicpu(p).opsize := S_BL;
  10460. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10461. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10462. end
  10463. else
  10464. taicpu(p).opsize := S_BQ;
  10465. RegUsed := True;
  10466. end;
  10467. else
  10468. ;
  10469. end;
  10470. S_WL:
  10471. case taicpu(hp1).opsize of
  10472. S_LQ:
  10473. begin
  10474. if taicpu(p).opcode = A_MOVZX then
  10475. begin
  10476. taicpu(p).opsize := S_WL;
  10477. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10478. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10479. end
  10480. else
  10481. taicpu(p).opsize := S_WQ;
  10482. RegUsed := True;
  10483. end;
  10484. else
  10485. ;
  10486. end;
  10487. {$endif x86_64}
  10488. else
  10489. ;
  10490. end;
  10491. if RegUsed then
  10492. begin
  10493. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10494. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10495. RemoveInstruction(hp1);
  10496. Result := True;
  10497. Exit;
  10498. end;
  10499. end;
  10500. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10501. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10502. GetNextInstruction(hp1, hp2) and
  10503. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10504. (
  10505. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10506. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10507. {$ifdef x86_64}
  10508. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10509. {$endif x86_64}
  10510. ) and
  10511. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10512. (
  10513. (
  10514. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10515. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10516. ) or
  10517. (
  10518. { Only allow the operands in reverse order for TEST instructions }
  10519. (taicpu(hp2).opcode = A_TEST) and
  10520. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10521. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10522. )
  10523. ) then
  10524. begin
  10525. {
  10526. For example:
  10527. movzbl %al,%eax
  10528. movzbl (ref),%edx
  10529. andl %edx,%eax
  10530. (%edx deallocated)
  10531. Change to:
  10532. andb (ref),%al
  10533. movzbl %al,%eax
  10534. Rules are:
  10535. - First two instructions have the same opcode and opsize
  10536. - First instruction's operands are the same super-register
  10537. - Second instruction operates on a different register
  10538. - Third instruction is AND, OR, XOR or TEST
  10539. - Third instruction's operands are the destination registers of the first two instructions
  10540. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10541. - Second instruction's destination register is deallocated afterwards
  10542. }
  10543. TransferUsedRegs(TmpUsedRegs);
  10544. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10545. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10546. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10547. begin
  10548. case taicpu(p).opsize of
  10549. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10550. NewSize := S_B;
  10551. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10552. NewSize := S_W;
  10553. {$ifdef x86_64}
  10554. S_LQ:
  10555. NewSize := S_L;
  10556. {$endif x86_64}
  10557. else
  10558. InternalError(2021120301);
  10559. end;
  10560. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10561. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10562. taicpu(hp2).opsize := NewSize;
  10563. RemoveInstruction(hp1);
  10564. { With TEST, it's best to keep the MOVX instruction at the top }
  10565. if (taicpu(hp2).opcode <> A_TEST) then
  10566. begin
  10567. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10568. asml.Remove(p);
  10569. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10570. asml.InsertAfter(p, hp2);
  10571. p := hp2;
  10572. end
  10573. else
  10574. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10575. Result := True;
  10576. Exit;
  10577. end;
  10578. end;
  10579. end;
  10580. if taicpu(p).opcode=A_MOVZX then
  10581. begin
  10582. { removes superfluous And's after movzx's }
  10583. if reg_and_hp1_is_instr and
  10584. (taicpu(hp1).opcode = A_AND) and
  10585. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10586. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10587. {$ifdef x86_64}
  10588. { check for implicit extension to 64 bit }
  10589. or
  10590. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10591. (taicpu(hp1).opsize=S_Q) and
  10592. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10593. )
  10594. {$endif x86_64}
  10595. )
  10596. then
  10597. begin
  10598. case taicpu(p).opsize Of
  10599. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10600. if (taicpu(hp1).oper[0]^.val = $ff) then
  10601. begin
  10602. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10603. RemoveInstruction(hp1);
  10604. Result:=true;
  10605. exit;
  10606. end;
  10607. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10608. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10609. begin
  10610. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10611. RemoveInstruction(hp1);
  10612. Result:=true;
  10613. exit;
  10614. end;
  10615. {$ifdef x86_64}
  10616. S_LQ:
  10617. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10618. begin
  10619. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10620. RemoveInstruction(hp1);
  10621. Result:=true;
  10622. exit;
  10623. end;
  10624. {$endif x86_64}
  10625. else
  10626. ;
  10627. end;
  10628. { we cannot get rid of the and, but can we get rid of the movz ?}
  10629. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10630. begin
  10631. case taicpu(p).opsize Of
  10632. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10633. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10634. begin
  10635. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10636. RemoveCurrentP(p,hp1);
  10637. Result:=true;
  10638. exit;
  10639. end;
  10640. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10641. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10642. begin
  10643. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10644. RemoveCurrentP(p,hp1);
  10645. Result:=true;
  10646. exit;
  10647. end;
  10648. {$ifdef x86_64}
  10649. S_LQ:
  10650. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10651. begin
  10652. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10653. RemoveCurrentP(p,hp1);
  10654. Result:=true;
  10655. exit;
  10656. end;
  10657. {$endif x86_64}
  10658. else
  10659. ;
  10660. end;
  10661. end;
  10662. end;
  10663. { changes some movzx constructs to faster synonyms (all examples
  10664. are given with eax/ax, but are also valid for other registers)}
  10665. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10666. begin
  10667. case taicpu(p).opsize of
  10668. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10669. (the machine code is equivalent to movzbl %al,%eax), but the
  10670. code generator still generates that assembler instruction and
  10671. it is silently converted. This should probably be checked.
  10672. [Kit] }
  10673. S_BW:
  10674. begin
  10675. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10676. (
  10677. not IsMOVZXAcceptable
  10678. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10679. or (
  10680. (cs_opt_size in current_settings.optimizerswitches) and
  10681. (taicpu(p).oper[1]^.reg = NR_AX)
  10682. )
  10683. ) then
  10684. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10685. begin
  10686. DebugMsg(SPeepholeOptimization + 'var7',p);
  10687. taicpu(p).opcode := A_AND;
  10688. taicpu(p).changeopsize(S_W);
  10689. taicpu(p).loadConst(0,$ff);
  10690. Result := True;
  10691. end
  10692. else if not IsMOVZXAcceptable and
  10693. GetNextInstruction(p, hp1) and
  10694. (tai(hp1).typ = ait_instruction) and
  10695. (taicpu(hp1).opcode = A_AND) and
  10696. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10697. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10698. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10699. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10700. begin
  10701. DebugMsg(SPeepholeOptimization + 'var8',p);
  10702. taicpu(p).opcode := A_MOV;
  10703. taicpu(p).changeopsize(S_W);
  10704. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10705. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10706. Result := True;
  10707. end;
  10708. end;
  10709. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10710. S_BL:
  10711. begin
  10712. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10713. (
  10714. not IsMOVZXAcceptable
  10715. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10716. or (
  10717. (cs_opt_size in current_settings.optimizerswitches) and
  10718. (taicpu(p).oper[1]^.reg = NR_EAX)
  10719. )
  10720. ) then
  10721. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10722. begin
  10723. DebugMsg(SPeepholeOptimization + 'var9',p);
  10724. taicpu(p).opcode := A_AND;
  10725. taicpu(p).changeopsize(S_L);
  10726. taicpu(p).loadConst(0,$ff);
  10727. Result := True;
  10728. end
  10729. else if not IsMOVZXAcceptable and
  10730. GetNextInstruction(p, hp1) and
  10731. (tai(hp1).typ = ait_instruction) and
  10732. (taicpu(hp1).opcode = A_AND) and
  10733. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10734. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10735. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10736. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10737. begin
  10738. DebugMsg(SPeepholeOptimization + 'var10',p);
  10739. taicpu(p).opcode := A_MOV;
  10740. taicpu(p).changeopsize(S_L);
  10741. { do not use R_SUBWHOLE
  10742. as movl %rdx,%eax
  10743. is invalid in assembler PM }
  10744. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10745. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10746. Result := True;
  10747. end;
  10748. end;
  10749. {$endif i8086}
  10750. S_WL:
  10751. if not IsMOVZXAcceptable then
  10752. begin
  10753. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10754. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10755. begin
  10756. DebugMsg(SPeepholeOptimization + 'var11',p);
  10757. taicpu(p).opcode := A_AND;
  10758. taicpu(p).changeopsize(S_L);
  10759. taicpu(p).loadConst(0,$ffff);
  10760. Result := True;
  10761. end
  10762. else if GetNextInstruction(p, hp1) and
  10763. (tai(hp1).typ = ait_instruction) and
  10764. (taicpu(hp1).opcode = A_AND) and
  10765. (taicpu(hp1).oper[0]^.typ = top_const) and
  10766. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10767. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10768. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10769. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10770. begin
  10771. DebugMsg(SPeepholeOptimization + 'var12',p);
  10772. taicpu(p).opcode := A_MOV;
  10773. taicpu(p).changeopsize(S_L);
  10774. { do not use R_SUBWHOLE
  10775. as movl %rdx,%eax
  10776. is invalid in assembler PM }
  10777. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10778. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10779. Result := True;
  10780. end;
  10781. end;
  10782. else
  10783. InternalError(2017050705);
  10784. end;
  10785. end
  10786. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10787. begin
  10788. if GetNextInstruction(p, hp1) and
  10789. (tai(hp1).typ = ait_instruction) and
  10790. (taicpu(hp1).opcode = A_AND) and
  10791. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10792. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10793. begin
  10794. //taicpu(p).opcode := A_MOV;
  10795. case taicpu(p).opsize Of
  10796. S_BL:
  10797. begin
  10798. DebugMsg(SPeepholeOptimization + 'var13',p);
  10799. taicpu(hp1).changeopsize(S_L);
  10800. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10801. end;
  10802. S_WL:
  10803. begin
  10804. DebugMsg(SPeepholeOptimization + 'var14',p);
  10805. taicpu(hp1).changeopsize(S_L);
  10806. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10807. end;
  10808. S_BW:
  10809. begin
  10810. DebugMsg(SPeepholeOptimization + 'var15',p);
  10811. taicpu(hp1).changeopsize(S_W);
  10812. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10813. end;
  10814. else
  10815. Internalerror(2017050704)
  10816. end;
  10817. Result := True;
  10818. end;
  10819. end;
  10820. end;
  10821. end;
  10822. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10823. var
  10824. hp1, hp2 : tai;
  10825. MaskLength : Cardinal;
  10826. MaskedBits : TCgInt;
  10827. ActiveReg : TRegister;
  10828. begin
  10829. Result:=false;
  10830. { There are no optimisations for reference targets }
  10831. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10832. Exit;
  10833. while GetNextInstruction(p, hp1) and
  10834. (hp1.typ = ait_instruction) do
  10835. begin
  10836. if (taicpu(p).oper[0]^.typ = top_const) then
  10837. begin
  10838. case taicpu(hp1).opcode of
  10839. A_AND:
  10840. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10841. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10842. { the second register must contain the first one, so compare their subreg types }
  10843. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10844. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10845. { change
  10846. and const1, reg
  10847. and const2, reg
  10848. to
  10849. and (const1 and const2), reg
  10850. }
  10851. begin
  10852. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10853. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10854. RemoveCurrentP(p, hp1);
  10855. Result:=true;
  10856. exit;
  10857. end;
  10858. A_CMP:
  10859. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10860. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10861. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10862. { Just check that the condition on the next instruction is compatible }
  10863. GetNextInstruction(hp1, hp2) and
  10864. (hp2.typ = ait_instruction) and
  10865. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10866. then
  10867. { change
  10868. and 2^n, reg
  10869. cmp 2^n, reg
  10870. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10871. to
  10872. and 2^n, reg
  10873. test reg, reg
  10874. j(~c) / set(~c) / cmov(~c)
  10875. }
  10876. begin
  10877. { Keep TEST instruction in, rather than remove it, because
  10878. it may trigger other optimisations such as MovAndTest2Test }
  10879. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10880. taicpu(hp1).opcode := A_TEST;
  10881. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10882. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10883. Result := True;
  10884. Exit;
  10885. end;
  10886. A_MOVZX:
  10887. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10888. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10889. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10890. (
  10891. (
  10892. (taicpu(p).opsize=S_W) and
  10893. (taicpu(hp1).opsize=S_BW)
  10894. ) or
  10895. (
  10896. (taicpu(p).opsize=S_L) and
  10897. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10898. )
  10899. {$ifdef x86_64}
  10900. or
  10901. (
  10902. (taicpu(p).opsize=S_Q) and
  10903. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10904. )
  10905. {$endif x86_64}
  10906. ) then
  10907. begin
  10908. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10909. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10910. ) or
  10911. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10912. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10913. then
  10914. begin
  10915. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10916. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10917. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10918. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10919. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10920. }
  10921. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10922. RemoveInstruction(hp1);
  10923. { See if there are other optimisations possible }
  10924. Continue;
  10925. end;
  10926. end;
  10927. A_SHL:
  10928. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10929. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10930. begin
  10931. {$ifopt R+}
  10932. {$define RANGE_WAS_ON}
  10933. {$R-}
  10934. {$endif}
  10935. { get length of potential and mask }
  10936. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10937. { really a mask? }
  10938. {$ifdef RANGE_WAS_ON}
  10939. {$R+}
  10940. {$endif}
  10941. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10942. { unmasked part shifted out? }
  10943. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10944. begin
  10945. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10946. RemoveCurrentP(p, hp1);
  10947. Result:=true;
  10948. exit;
  10949. end;
  10950. end;
  10951. A_SHR:
  10952. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10953. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10954. (taicpu(hp1).oper[0]^.val <= 63) then
  10955. begin
  10956. { Does SHR combined with the AND cover all the bits?
  10957. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10958. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10959. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10960. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10961. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10962. begin
  10963. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10964. RemoveCurrentP(p, hp1);
  10965. Result := True;
  10966. Exit;
  10967. end;
  10968. end;
  10969. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10970. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10971. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10972. begin
  10973. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10974. (
  10975. (
  10976. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10977. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10978. ) or (
  10979. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10980. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10981. {$ifdef x86_64}
  10982. ) or (
  10983. (taicpu(hp1).opsize = S_LQ) and
  10984. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10985. {$endif x86_64}
  10986. )
  10987. ) then
  10988. begin
  10989. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10990. begin
  10991. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10992. RemoveInstruction(hp1);
  10993. { See if there are other optimisations possible }
  10994. Continue;
  10995. end;
  10996. { The super-registers are the same though.
  10997. Note that this change by itself doesn't improve
  10998. code speed, but it opens up other optimisations. }
  10999. {$ifdef x86_64}
  11000. { Convert 64-bit register to 32-bit }
  11001. case taicpu(hp1).opsize of
  11002. S_BQ:
  11003. begin
  11004. taicpu(hp1).opsize := S_BL;
  11005. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11006. end;
  11007. S_WQ:
  11008. begin
  11009. taicpu(hp1).opsize := S_WL;
  11010. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11011. end
  11012. else
  11013. ;
  11014. end;
  11015. {$endif x86_64}
  11016. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11017. taicpu(hp1).opcode := A_MOVZX;
  11018. { See if there are other optimisations possible }
  11019. Continue;
  11020. end;
  11021. end;
  11022. else
  11023. ;
  11024. end;
  11025. end
  11026. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11027. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11028. begin
  11029. {$ifdef x86_64}
  11030. if (taicpu(p).opsize = S_Q) then
  11031. begin
  11032. { Never necessary }
  11033. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11034. RemoveCurrentP(p, hp1);
  11035. Result := True;
  11036. Exit;
  11037. end;
  11038. {$endif x86_64}
  11039. { Forward check to determine necessity of and %reg,%reg }
  11040. TransferUsedRegs(TmpUsedRegs);
  11041. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11042. { Saves on a bunch of dereferences }
  11043. ActiveReg := taicpu(p).oper[1]^.reg;
  11044. case taicpu(hp1).opcode of
  11045. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11046. if (
  11047. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11048. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11049. ) and
  11050. (
  11051. (taicpu(hp1).opcode <> A_MOV) or
  11052. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11053. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11054. ) and
  11055. not (
  11056. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11057. (taicpu(hp1).opcode = A_MOV) and
  11058. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11059. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11060. ) and
  11061. (
  11062. (
  11063. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11064. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11065. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11066. ) or
  11067. (
  11068. {$ifdef x86_64}
  11069. (
  11070. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11071. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11072. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11073. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11074. ) and
  11075. {$endif x86_64}
  11076. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11077. )
  11078. ) then
  11079. begin
  11080. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11081. RemoveCurrentP(p, hp1);
  11082. Result := True;
  11083. Exit;
  11084. end;
  11085. A_ADD,
  11086. A_AND,
  11087. A_BSF,
  11088. A_BSR,
  11089. A_BTC,
  11090. A_BTR,
  11091. A_BTS,
  11092. A_OR,
  11093. A_SUB,
  11094. A_XOR:
  11095. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11096. if (
  11097. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11098. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11099. ) and
  11100. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11101. begin
  11102. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11103. RemoveCurrentP(p, hp1);
  11104. Result := True;
  11105. Exit;
  11106. end;
  11107. A_CMP,
  11108. A_TEST:
  11109. if (
  11110. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11111. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11112. ) and
  11113. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11114. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11115. begin
  11116. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11117. RemoveCurrentP(p, hp1);
  11118. Result := True;
  11119. Exit;
  11120. end;
  11121. A_BSWAP,
  11122. A_NEG,
  11123. A_NOT:
  11124. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11125. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11126. begin
  11127. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11128. RemoveCurrentP(p, hp1);
  11129. Result := True;
  11130. Exit;
  11131. end;
  11132. else
  11133. ;
  11134. end;
  11135. end;
  11136. if (taicpu(hp1).is_jmp) and
  11137. (taicpu(hp1).opcode<>A_JMP) and
  11138. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11139. begin
  11140. { change
  11141. and x, reg
  11142. jxx
  11143. to
  11144. test x, reg
  11145. jxx
  11146. if reg is deallocated before the
  11147. jump, but only if it's a conditional jump (PFV)
  11148. }
  11149. taicpu(p).opcode := A_TEST;
  11150. Exit;
  11151. end;
  11152. Break;
  11153. end;
  11154. { Lone AND tests }
  11155. if (taicpu(p).oper[0]^.typ = top_const) then
  11156. begin
  11157. {
  11158. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11159. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11160. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11161. }
  11162. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11163. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11164. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11165. begin
  11166. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11167. if taicpu(p).opsize = S_L then
  11168. begin
  11169. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11170. Result := True;
  11171. end;
  11172. end;
  11173. end;
  11174. { Backward check to determine necessity of and %reg,%reg }
  11175. if (taicpu(p).oper[0]^.typ = top_reg) and
  11176. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11177. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11178. GetLastInstruction(p, hp2) and
  11179. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11180. { Check size of adjacent instruction to determine if the AND is
  11181. effectively a null operation }
  11182. (
  11183. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11184. { Note: Don't include S_Q }
  11185. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11186. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11187. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11188. ) then
  11189. begin
  11190. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11191. { If GetNextInstruction returned False, hp1 will be nil }
  11192. RemoveCurrentP(p, hp1);
  11193. Result := True;
  11194. Exit;
  11195. end;
  11196. end;
  11197. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11198. var
  11199. hp1: tai; NewRef: TReference;
  11200. { This entire nested function is used in an if-statement below, but we
  11201. want to avoid all the used reg transfers and GetNextInstruction calls
  11202. until we really have to check }
  11203. function MemRegisterNotUsedLater: Boolean; inline;
  11204. var
  11205. hp2: tai;
  11206. begin
  11207. TransferUsedRegs(TmpUsedRegs);
  11208. hp2 := p;
  11209. repeat
  11210. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11211. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11212. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11213. end;
  11214. begin
  11215. Result := False;
  11216. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11217. Exit;
  11218. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11219. begin
  11220. { Change:
  11221. add %reg2,%reg1
  11222. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11223. To:
  11224. mov/s/z #(%reg1,%reg2),%reg1
  11225. }
  11226. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11227. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11228. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11229. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11230. (
  11231. (
  11232. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11233. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11234. { r/esp cannot be an index }
  11235. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11236. ) or (
  11237. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11238. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11239. )
  11240. ) and (
  11241. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11242. (
  11243. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11244. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11245. MemRegisterNotUsedLater
  11246. )
  11247. ) then
  11248. begin
  11249. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11250. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11251. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11252. RemoveCurrentp(p, hp1);
  11253. Result := True;
  11254. Exit;
  11255. end;
  11256. { Change:
  11257. addl/q $x,%reg1
  11258. movl/q %reg1,%reg2
  11259. To:
  11260. leal/q $x(%reg1),%reg2
  11261. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11262. Breaks the dependency chain.
  11263. }
  11264. if MatchOpType(taicpu(p),top_const,top_reg) and
  11265. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11266. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11267. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11268. (
  11269. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11270. not (cs_opt_size in current_settings.optimizerswitches) or
  11271. (
  11272. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11273. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11274. )
  11275. ) then
  11276. begin
  11277. { Change the MOV instruction to a LEA instruction, and update the
  11278. first operand }
  11279. reference_reset(NewRef, 1, []);
  11280. NewRef.base := taicpu(p).oper[1]^.reg;
  11281. NewRef.scalefactor := 1;
  11282. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11283. taicpu(hp1).opcode := A_LEA;
  11284. taicpu(hp1).loadref(0, NewRef);
  11285. TransferUsedRegs(TmpUsedRegs);
  11286. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11287. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11288. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11289. begin
  11290. { Move what is now the LEA instruction to before the SUB instruction }
  11291. Asml.Remove(hp1);
  11292. Asml.InsertBefore(hp1, p);
  11293. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11294. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11295. p := hp1;
  11296. end
  11297. else
  11298. begin
  11299. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11300. RemoveCurrentP(p, hp1);
  11301. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11302. end;
  11303. Result := True;
  11304. end;
  11305. end;
  11306. end;
  11307. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11308. var
  11309. SubReg: TSubRegister;
  11310. begin
  11311. Result:=false;
  11312. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11313. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11314. with taicpu(p).oper[0]^.ref^ do
  11315. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11316. begin
  11317. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11318. begin
  11319. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11320. taicpu(p).opcode := A_ADD;
  11321. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11322. Result := True;
  11323. end
  11324. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11325. begin
  11326. if (base <> NR_NO) then
  11327. begin
  11328. if (scalefactor <= 1) then
  11329. begin
  11330. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11331. taicpu(p).opcode := A_ADD;
  11332. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11333. Result := True;
  11334. end;
  11335. end
  11336. else
  11337. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11338. if (scalefactor in [2, 4, 8]) then
  11339. begin
  11340. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11341. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11342. taicpu(p).opcode := A_SHL;
  11343. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11344. Result := True;
  11345. end;
  11346. end;
  11347. end;
  11348. end;
  11349. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11350. var
  11351. hp1: tai; NewRef: TReference;
  11352. begin
  11353. { Change:
  11354. subl/q $x,%reg1
  11355. movl/q %reg1,%reg2
  11356. To:
  11357. leal/q $-x(%reg1),%reg2
  11358. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11359. Breaks the dependency chain and potentially permits the removal of
  11360. a CMP instruction if one follows.
  11361. }
  11362. Result := False;
  11363. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11364. MatchOpType(taicpu(p),top_const,top_reg) and
  11365. GetNextInstruction(p, hp1) and
  11366. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11367. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11368. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11369. (
  11370. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11371. not (cs_opt_size in current_settings.optimizerswitches) or
  11372. (
  11373. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11374. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11375. )
  11376. ) then
  11377. begin
  11378. { Change the MOV instruction to a LEA instruction, and update the
  11379. first operand }
  11380. reference_reset(NewRef, 1, []);
  11381. NewRef.base := taicpu(p).oper[1]^.reg;
  11382. NewRef.scalefactor := 1;
  11383. NewRef.offset := -taicpu(p).oper[0]^.val;
  11384. taicpu(hp1).opcode := A_LEA;
  11385. taicpu(hp1).loadref(0, NewRef);
  11386. TransferUsedRegs(TmpUsedRegs);
  11387. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11388. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11389. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11390. begin
  11391. { Move what is now the LEA instruction to before the SUB instruction }
  11392. Asml.Remove(hp1);
  11393. Asml.InsertBefore(hp1, p);
  11394. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11395. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11396. p := hp1;
  11397. end
  11398. else
  11399. begin
  11400. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11401. RemoveCurrentP(p, hp1);
  11402. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11403. end;
  11404. Result := True;
  11405. end;
  11406. end;
  11407. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11408. begin
  11409. { we can skip all instructions not messing with the stack pointer }
  11410. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11411. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11412. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11413. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11414. ({(taicpu(hp1).ops=0) or }
  11415. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11416. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11417. ) and }
  11418. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11419. )
  11420. ) do
  11421. GetNextInstruction(hp1,hp1);
  11422. Result:=assigned(hp1);
  11423. end;
  11424. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11425. var
  11426. hp1, hp2, hp3, hp4, hp5: tai;
  11427. begin
  11428. Result:=false;
  11429. hp5:=nil;
  11430. { replace
  11431. leal(q) x(<stackpointer>),<stackpointer>
  11432. call procname
  11433. leal(q) -x(<stackpointer>),<stackpointer>
  11434. ret
  11435. by
  11436. jmp procname
  11437. but do it only on level 4 because it destroys stack back traces
  11438. }
  11439. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11440. MatchOpType(taicpu(p),top_ref,top_reg) and
  11441. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11442. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11443. { the -8 or -24 are not required, but bail out early if possible,
  11444. higher values are unlikely }
  11445. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11446. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11447. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11448. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11449. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11450. GetNextInstruction(p, hp1) and
  11451. { Take a copy of hp1 }
  11452. SetAndTest(hp1, hp4) and
  11453. { trick to skip label }
  11454. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11455. SkipSimpleInstructions(hp1) and
  11456. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11457. GetNextInstruction(hp1, hp2) and
  11458. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11459. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11460. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11461. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11462. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11463. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11464. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11465. { Segment register will be NR_NO }
  11466. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11467. GetNextInstruction(hp2, hp3) and
  11468. { trick to skip label }
  11469. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11470. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11471. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11472. SetAndTest(hp3,hp5) and
  11473. GetNextInstruction(hp3,hp3) and
  11474. MatchInstruction(hp3,A_RET,[S_NO])
  11475. )
  11476. ) and
  11477. (taicpu(hp3).ops=0) then
  11478. begin
  11479. taicpu(hp1).opcode := A_JMP;
  11480. taicpu(hp1).is_jmp := true;
  11481. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11482. RemoveCurrentP(p, hp4);
  11483. RemoveInstruction(hp2);
  11484. RemoveInstruction(hp3);
  11485. if Assigned(hp5) then
  11486. begin
  11487. AsmL.Remove(hp5);
  11488. ASmL.InsertBefore(hp5,hp1)
  11489. end;
  11490. Result:=true;
  11491. end;
  11492. end;
  11493. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11494. {$ifdef x86_64}
  11495. var
  11496. hp1, hp2, hp3, hp4, hp5: tai;
  11497. {$endif x86_64}
  11498. begin
  11499. Result:=false;
  11500. {$ifdef x86_64}
  11501. hp5:=nil;
  11502. { replace
  11503. push %rax
  11504. call procname
  11505. pop %rcx
  11506. ret
  11507. by
  11508. jmp procname
  11509. but do it only on level 4 because it destroys stack back traces
  11510. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11511. for all supported calling conventions
  11512. }
  11513. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11514. MatchOpType(taicpu(p),top_reg) and
  11515. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11516. GetNextInstruction(p, hp1) and
  11517. { Take a copy of hp1 }
  11518. SetAndTest(hp1, hp4) and
  11519. { trick to skip label }
  11520. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11521. SkipSimpleInstructions(hp1) and
  11522. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11523. GetNextInstruction(hp1, hp2) and
  11524. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11525. MatchOpType(taicpu(hp2),top_reg) and
  11526. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11527. GetNextInstruction(hp2, hp3) and
  11528. { trick to skip label }
  11529. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11530. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11531. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11532. SetAndTest(hp3,hp5) and
  11533. GetNextInstruction(hp3,hp3) and
  11534. MatchInstruction(hp3,A_RET,[S_NO])
  11535. )
  11536. ) and
  11537. (taicpu(hp3).ops=0) then
  11538. begin
  11539. taicpu(hp1).opcode := A_JMP;
  11540. taicpu(hp1).is_jmp := true;
  11541. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11542. RemoveCurrentP(p, hp4);
  11543. RemoveInstruction(hp2);
  11544. RemoveInstruction(hp3);
  11545. if Assigned(hp5) then
  11546. begin
  11547. AsmL.Remove(hp5);
  11548. ASmL.InsertBefore(hp5,hp1)
  11549. end;
  11550. Result:=true;
  11551. end;
  11552. {$endif x86_64}
  11553. end;
  11554. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11555. var
  11556. Value, RegName: string;
  11557. begin
  11558. Result:=false;
  11559. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11560. begin
  11561. case taicpu(p).oper[0]^.val of
  11562. 0:
  11563. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11564. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11565. begin
  11566. { change "mov $0,%reg" into "xor %reg,%reg" }
  11567. taicpu(p).opcode := A_XOR;
  11568. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11569. Result := True;
  11570. {$ifdef x86_64}
  11571. end
  11572. else if (taicpu(p).opsize = S_Q) then
  11573. begin
  11574. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11575. { The actual optimization }
  11576. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11577. taicpu(p).changeopsize(S_L);
  11578. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11579. Result := True;
  11580. end;
  11581. $1..$FFFFFFFF:
  11582. begin
  11583. { Code size reduction by J. Gareth "Kit" Moreton }
  11584. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11585. case taicpu(p).opsize of
  11586. S_Q:
  11587. begin
  11588. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11589. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11590. { The actual optimization }
  11591. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11592. taicpu(p).changeopsize(S_L);
  11593. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11594. Result := True;
  11595. end;
  11596. else
  11597. { Do nothing };
  11598. end;
  11599. {$endif x86_64}
  11600. end;
  11601. -1:
  11602. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11603. if (cs_opt_size in current_settings.optimizerswitches) and
  11604. (taicpu(p).opsize <> S_B) and
  11605. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11606. begin
  11607. { change "mov $-1,%reg" into "or $-1,%reg" }
  11608. { NOTES:
  11609. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11610. - This operation creates a false dependency on the register, so only do it when optimising for size
  11611. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  11612. }
  11613. taicpu(p).opcode := A_OR;
  11614. Result := True;
  11615. end;
  11616. else
  11617. { Do nothing };
  11618. end;
  11619. end;
  11620. end;
  11621. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11622. var
  11623. hp1: tai;
  11624. begin
  11625. { Detect:
  11626. andw x, %ax (0 <= x < $8000)
  11627. ...
  11628. movzwl %ax,%eax
  11629. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11630. }
  11631. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11632. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11633. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11634. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11635. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11636. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11637. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11638. begin
  11639. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11640. taicpu(hp1).opcode := A_CWDE;
  11641. taicpu(hp1).clearop(0);
  11642. taicpu(hp1).clearop(1);
  11643. taicpu(hp1).ops := 0;
  11644. { A change was made, but not with p, so move forward 1 }
  11645. p := tai(p.Next);
  11646. Result := True;
  11647. end;
  11648. end;
  11649. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11650. begin
  11651. Result := False;
  11652. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11653. Exit;
  11654. { Convert:
  11655. movswl %ax,%eax -> cwtl
  11656. movslq %eax,%rax -> cdqe
  11657. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11658. refer to the same opcode and depends only on the assembler's
  11659. current operand-size attribute. [Kit]
  11660. }
  11661. with taicpu(p) do
  11662. case opsize of
  11663. S_WL:
  11664. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11665. begin
  11666. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11667. opcode := A_CWDE;
  11668. clearop(0);
  11669. clearop(1);
  11670. ops := 0;
  11671. Result := True;
  11672. end;
  11673. {$ifdef x86_64}
  11674. S_LQ:
  11675. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11676. begin
  11677. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11678. opcode := A_CDQE;
  11679. clearop(0);
  11680. clearop(1);
  11681. ops := 0;
  11682. Result := True;
  11683. end;
  11684. {$endif x86_64}
  11685. else
  11686. ;
  11687. end;
  11688. end;
  11689. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11690. var
  11691. hp1: tai;
  11692. begin
  11693. { Detect:
  11694. shr x, %ax (x > 0)
  11695. ...
  11696. movzwl %ax,%eax
  11697. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11698. }
  11699. Result := False;
  11700. if MatchOpType(taicpu(p), top_const, top_reg) and
  11701. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11702. (taicpu(p).oper[0]^.val > 0) and
  11703. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11704. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11705. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11706. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11707. begin
  11708. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11709. taicpu(hp1).opcode := A_CWDE;
  11710. taicpu(hp1).clearop(0);
  11711. taicpu(hp1).clearop(1);
  11712. taicpu(hp1).ops := 0;
  11713. { A change was made, but not with p, so move forward 1 }
  11714. p := tai(p.Next);
  11715. Result := True;
  11716. end;
  11717. end;
  11718. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11719. var
  11720. hp1, hp2: tai;
  11721. Opposite, SecondOpposite: TAsmOp;
  11722. NewCond: TAsmCond;
  11723. begin
  11724. Result := False;
  11725. { Change:
  11726. add/sub 128,(dest)
  11727. To:
  11728. sub/add -128,(dest)
  11729. This generaally takes fewer bytes to encode because -128 can be stored
  11730. in a signed byte, whereas +128 cannot.
  11731. }
  11732. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11733. begin
  11734. if taicpu(p).opcode = A_ADD then
  11735. Opposite := A_SUB
  11736. else
  11737. Opposite := A_ADD;
  11738. { Be careful if the flags are in use, because the CF flag inverts
  11739. when changing from ADD to SUB and vice versa }
  11740. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11741. GetNextInstruction(p, hp1) then
  11742. begin
  11743. TransferUsedRegs(TmpUsedRegs);
  11744. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11745. hp2 := hp1;
  11746. { Scan ahead to check if everything's safe }
  11747. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11748. begin
  11749. if (hp1.typ <> ait_instruction) then
  11750. { Probably unsafe since the flags are still in use }
  11751. Exit;
  11752. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11753. { Stop searching at an unconditional jump }
  11754. Break;
  11755. if not
  11756. (
  11757. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11758. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11759. ) and
  11760. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11761. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11762. Exit;
  11763. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11764. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11765. { Move to the next instruction }
  11766. GetNextInstruction(hp1, hp1);
  11767. end;
  11768. while Assigned(hp2) and (hp2 <> hp1) do
  11769. begin
  11770. NewCond := C_None;
  11771. case taicpu(hp2).condition of
  11772. C_A, C_NBE:
  11773. NewCond := C_BE;
  11774. C_B, C_C, C_NAE:
  11775. NewCond := C_AE;
  11776. C_AE, C_NB, C_NC:
  11777. NewCond := C_B;
  11778. C_BE, C_NA:
  11779. NewCond := C_A;
  11780. else
  11781. { No change needed };
  11782. end;
  11783. if NewCond <> C_None then
  11784. begin
  11785. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11786. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11787. taicpu(hp2).condition := NewCond;
  11788. end
  11789. else
  11790. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11791. begin
  11792. { Because of the flipping of the carry bit, to ensure
  11793. the operation remains equivalent, ADC becomes SBB
  11794. and vice versa, and the constant is not-inverted.
  11795. If multiple ADCs or SBBs appear in a row, each one
  11796. changed causes the carry bit to invert, so they all
  11797. need to be flipped }
  11798. if taicpu(hp2).opcode = A_ADC then
  11799. SecondOpposite := A_SBB
  11800. else
  11801. SecondOpposite := A_ADC;
  11802. if taicpu(hp2).oper[0]^.typ <> top_const then
  11803. { Should have broken out of this optimisation already }
  11804. InternalError(2021112901);
  11805. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  11806. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  11807. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11808. taicpu(hp2).opcode := SecondOpposite;
  11809. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11810. end;
  11811. { Move to the next instruction }
  11812. GetNextInstruction(hp2, hp2);
  11813. end;
  11814. if (hp2 <> hp1) then
  11815. InternalError(2021111501);
  11816. end;
  11817. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11818. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11819. taicpu(p).opcode := Opposite;
  11820. taicpu(p).oper[0]^.val := -128;
  11821. { No further optimisations can be made on this instruction, so move
  11822. onto the next one to save time }
  11823. p := tai(p.Next);
  11824. UpdateUsedRegs(p);
  11825. Result := True;
  11826. Exit;
  11827. end;
  11828. { Detect:
  11829. add/sub %reg2,(dest)
  11830. add/sub x, (dest)
  11831. (dest can be a register or a reference)
  11832. Swap the instructions to minimise a pipeline stall. This reverses the
  11833. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11834. optimisations could be made.
  11835. }
  11836. if (taicpu(p).oper[0]^.typ = top_reg) and
  11837. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11838. (
  11839. (
  11840. (taicpu(p).oper[1]^.typ = top_reg) and
  11841. { We can try searching further ahead if we're writing to a register }
  11842. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11843. ) or
  11844. (
  11845. (taicpu(p).oper[1]^.typ = top_ref) and
  11846. GetNextInstruction(p, hp1)
  11847. )
  11848. ) and
  11849. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11850. (taicpu(hp1).oper[0]^.typ = top_const) and
  11851. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11852. begin
  11853. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11854. TransferUsedRegs(TmpUsedRegs);
  11855. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11856. hp2 := p;
  11857. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11858. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11859. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11860. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11861. begin
  11862. asml.remove(hp1);
  11863. asml.InsertBefore(hp1, p);
  11864. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11865. Result := True;
  11866. end;
  11867. end;
  11868. end;
  11869. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11870. begin
  11871. Result:=false;
  11872. { change "cmp $0, %reg" to "test %reg, %reg" }
  11873. if MatchOpType(taicpu(p),top_const,top_reg) and
  11874. (taicpu(p).oper[0]^.val = 0) then
  11875. begin
  11876. taicpu(p).opcode := A_TEST;
  11877. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11878. Result:=true;
  11879. end;
  11880. end;
  11881. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11882. var
  11883. IsTestConstX : Boolean;
  11884. hp1,hp2 : tai;
  11885. begin
  11886. Result:=false;
  11887. { removes the line marked with (x) from the sequence
  11888. and/or/xor/add/sub/... $x, %y
  11889. test/or %y, %y | test $-1, %y (x)
  11890. j(n)z _Label
  11891. as the first instruction already adjusts the ZF
  11892. %y operand may also be a reference }
  11893. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11894. MatchOperand(taicpu(p).oper[0]^,-1);
  11895. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11896. GetLastInstruction(p, hp1) and
  11897. (tai(hp1).typ = ait_instruction) and
  11898. GetNextInstruction(p,hp2) and
  11899. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11900. case taicpu(hp1).opcode Of
  11901. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11902. { These two instructions set the zero flag if the result is zero }
  11903. A_POPCNT, A_LZCNT:
  11904. begin
  11905. if (
  11906. { With POPCNT, an input of zero will set the zero flag
  11907. because the population count of zero is zero }
  11908. (taicpu(hp1).opcode = A_POPCNT) and
  11909. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11910. (
  11911. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11912. { Faster than going through the second half of the 'or'
  11913. condition below }
  11914. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11915. )
  11916. ) or (
  11917. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11918. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11919. { and in case of carry for A(E)/B(E)/C/NC }
  11920. (
  11921. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11922. (
  11923. (taicpu(hp1).opcode <> A_ADD) and
  11924. (taicpu(hp1).opcode <> A_SUB) and
  11925. (taicpu(hp1).opcode <> A_LZCNT)
  11926. )
  11927. )
  11928. ) then
  11929. begin
  11930. RemoveCurrentP(p, hp2);
  11931. Result:=true;
  11932. Exit;
  11933. end;
  11934. end;
  11935. A_SHL, A_SAL, A_SHR, A_SAR:
  11936. begin
  11937. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11938. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11939. { therefore, it's only safe to do this optimization for }
  11940. { shifts by a (nonzero) constant }
  11941. (taicpu(hp1).oper[0]^.typ = top_const) and
  11942. (taicpu(hp1).oper[0]^.val <> 0) and
  11943. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11944. { and in case of carry for A(E)/B(E)/C/NC }
  11945. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11946. begin
  11947. RemoveCurrentP(p, hp2);
  11948. Result:=true;
  11949. Exit;
  11950. end;
  11951. end;
  11952. A_DEC, A_INC, A_NEG:
  11953. begin
  11954. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11955. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11956. { and in case of carry for A(E)/B(E)/C/NC }
  11957. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11958. begin
  11959. RemoveCurrentP(p, hp2);
  11960. Result:=true;
  11961. Exit;
  11962. end;
  11963. end
  11964. else
  11965. ;
  11966. end; { case }
  11967. { change "test $-1,%reg" into "test %reg,%reg" }
  11968. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11969. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11970. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11971. if MatchInstruction(p, A_OR, []) and
  11972. { Can only match if they're both registers }
  11973. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11974. begin
  11975. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11976. taicpu(p).opcode := A_TEST;
  11977. { No need to set Result to True, as we've done all the optimisations we can }
  11978. end;
  11979. end;
  11980. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11981. var
  11982. hp1,hp3 : tai;
  11983. {$ifndef x86_64}
  11984. hp2 : taicpu;
  11985. {$endif x86_64}
  11986. begin
  11987. Result:=false;
  11988. hp3:=nil;
  11989. {$ifndef x86_64}
  11990. { don't do this on modern CPUs, this really hurts them due to
  11991. broken call/ret pairing }
  11992. if (current_settings.optimizecputype < cpu_Pentium2) and
  11993. not(cs_create_pic in current_settings.moduleswitches) and
  11994. GetNextInstruction(p, hp1) and
  11995. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11996. MatchOpType(taicpu(hp1),top_ref) and
  11997. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11998. begin
  11999. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  12000. InsertLLItem(p.previous, p, hp2);
  12001. taicpu(p).opcode := A_JMP;
  12002. taicpu(p).is_jmp := true;
  12003. RemoveInstruction(hp1);
  12004. Result:=true;
  12005. end
  12006. else
  12007. {$endif x86_64}
  12008. { replace
  12009. call procname
  12010. ret
  12011. by
  12012. jmp procname
  12013. but do it only on level 4 because it destroys stack back traces
  12014. else if the subroutine is marked as no return, remove the ret
  12015. }
  12016. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12017. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12018. GetNextInstruction(p, hp1) and
  12019. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12020. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12021. SetAndTest(hp1,hp3) and
  12022. GetNextInstruction(hp1,hp1) and
  12023. MatchInstruction(hp1,A_RET,[S_NO])
  12024. )
  12025. ) and
  12026. (taicpu(hp1).ops=0) then
  12027. begin
  12028. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12029. { we might destroy stack alignment here if we do not do a call }
  12030. (target_info.stackalign<=sizeof(SizeUInt)) then
  12031. begin
  12032. taicpu(p).opcode := A_JMP;
  12033. taicpu(p).is_jmp := true;
  12034. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12035. end
  12036. else
  12037. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12038. RemoveInstruction(hp1);
  12039. if Assigned(hp3) then
  12040. begin
  12041. AsmL.Remove(hp3);
  12042. AsmL.InsertBefore(hp3,p)
  12043. end;
  12044. Result:=true;
  12045. end;
  12046. end;
  12047. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12048. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12049. begin
  12050. case OpSize of
  12051. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12052. Result := (Val <= $FF) and (Val >= -128);
  12053. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12054. Result := (Val <= $FFFF) and (Val >= -32768);
  12055. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12056. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12057. else
  12058. Result := True;
  12059. end;
  12060. end;
  12061. var
  12062. hp1, hp2 : tai;
  12063. SizeChange: Boolean;
  12064. PreMessage: string;
  12065. begin
  12066. Result := False;
  12067. if (taicpu(p).oper[0]^.typ = top_reg) and
  12068. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12069. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12070. begin
  12071. { Change (using movzbl %al,%eax as an example):
  12072. movzbl %al, %eax movzbl %al, %eax
  12073. cmpl x, %eax testl %eax,%eax
  12074. To:
  12075. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12076. movzbl %al, %eax movzbl %al, %eax
  12077. Smaller instruction and minimises pipeline stall as the CPU
  12078. doesn't have to wait for the register to get zero-extended. [Kit]
  12079. Also allow if the smaller of the two registers is being checked,
  12080. as this still removes the false dependency.
  12081. }
  12082. if
  12083. (
  12084. (
  12085. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12086. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12087. ) or (
  12088. { If MatchOperand returns True, they must both be registers }
  12089. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12090. )
  12091. ) and
  12092. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12093. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12094. begin
  12095. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  12096. asml.Remove(hp1);
  12097. asml.InsertBefore(hp1, p);
  12098. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12099. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12100. begin
  12101. taicpu(hp1).opcode := A_TEST;
  12102. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12103. end;
  12104. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12105. case taicpu(p).opsize of
  12106. S_BW, S_BL:
  12107. begin
  12108. SizeChange := taicpu(hp1).opsize <> S_B;
  12109. taicpu(hp1).changeopsize(S_B);
  12110. end;
  12111. S_WL:
  12112. begin
  12113. SizeChange := taicpu(hp1).opsize <> S_W;
  12114. taicpu(hp1).changeopsize(S_W);
  12115. end
  12116. else
  12117. InternalError(2020112701);
  12118. end;
  12119. UpdateUsedRegs(tai(p.Next));
  12120. { Check if the register is used aferwards - if not, we can
  12121. remove the movzx instruction completely }
  12122. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12123. begin
  12124. { Hp1 is a better position than p for debugging purposes }
  12125. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12126. RemoveCurrentp(p, hp1);
  12127. Result := True;
  12128. end;
  12129. if SizeChange then
  12130. DebugMsg(SPeepholeOptimization + PreMessage +
  12131. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  12132. else
  12133. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12134. Exit;
  12135. end;
  12136. { Change (using movzwl %ax,%eax as an example):
  12137. movzwl %ax, %eax
  12138. movb %al, (dest) (Register is smaller than read register in movz)
  12139. To:
  12140. movb %al, (dest) (Move one back to avoid a false dependency)
  12141. movzwl %ax, %eax
  12142. }
  12143. if (taicpu(hp1).opcode = A_MOV) and
  12144. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12145. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12146. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12147. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12148. begin
  12149. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12150. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12151. asml.Remove(hp1);
  12152. asml.InsertBefore(hp1, p);
  12153. if taicpu(hp1).oper[1]^.typ = top_reg then
  12154. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12155. { Check if the register is used aferwards - if not, we can
  12156. remove the movzx instruction completely }
  12157. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12158. begin
  12159. { Hp1 is a better position than p for debugging purposes }
  12160. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12161. RemoveCurrentp(p, hp1);
  12162. Result := True;
  12163. end;
  12164. Exit;
  12165. end;
  12166. end;
  12167. end;
  12168. {$ifdef x86_64}
  12169. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12170. var
  12171. PreMessage, RegName: string;
  12172. begin
  12173. { Code size reduction by J. Gareth "Kit" Moreton }
  12174. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12175. as this removes the REX prefix }
  12176. Result := False;
  12177. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12178. Exit;
  12179. if taicpu(p).oper[0]^.typ <> top_reg then
  12180. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12181. InternalError(2018011500);
  12182. case taicpu(p).opsize of
  12183. S_Q:
  12184. begin
  12185. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12186. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12187. { The actual optimization }
  12188. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12189. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12190. taicpu(p).changeopsize(S_L);
  12191. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12192. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12193. end;
  12194. else
  12195. ;
  12196. end;
  12197. end;
  12198. {$endif}
  12199. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12200. var
  12201. XReg: TRegister;
  12202. begin
  12203. Result := False;
  12204. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12205. Smaller encoding and slightly faster on some platforms (also works for
  12206. ZMM-sized registers) }
  12207. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12208. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12209. begin
  12210. XReg := taicpu(p).oper[0]^.reg;
  12211. if (taicpu(p).oper[1]^.reg = XReg) then
  12212. begin
  12213. taicpu(p).changeopsize(S_XMM);
  12214. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12215. if (cs_opt_size in current_settings.optimizerswitches) then
  12216. begin
  12217. { Change input registers to %xmm0 to reduce size. Note that
  12218. there's a risk of a false dependency doing this, so only
  12219. optimise for size here }
  12220. XReg := NR_XMM0;
  12221. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12222. end
  12223. else
  12224. begin
  12225. setsubreg(XReg, R_SUBMMX);
  12226. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12227. end;
  12228. taicpu(p).oper[0]^.reg := XReg;
  12229. taicpu(p).oper[1]^.reg := XReg;
  12230. Result := True;
  12231. end;
  12232. end;
  12233. end;
  12234. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12235. var
  12236. OperIdx: Integer;
  12237. begin
  12238. for OperIdx := 0 to p.ops - 1 do
  12239. if p.oper[OperIdx]^.typ = top_ref then
  12240. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12241. end;
  12242. end.