aoptx86.pas 759 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693
  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. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. function PostPeepholeOptRET(var p: tai): Boolean;
  181. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  182. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  183. function TrySwapMovOp(var p, hp1: tai): Boolean;
  184. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  185. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  186. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  187. { Processor-dependent reference optimisation }
  188. class procedure OptimizeRefs(var p: taicpu); static;
  189. end;
  190. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  194. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  195. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  196. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  197. {$if max_operands>2}
  198. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  199. {$endif max_operands>2}
  200. function RefsEqual(const r1, r2: treference): boolean;
  201. { Like RefsEqual, but doesn't compare the offsets }
  202. function RefsAlmostEqual(const r1, r2: treference): boolean;
  203. { Note that Result is set to True if the references COULD overlap but the
  204. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  205. might still overlap because %reg2 could be equal to %reg1-4 }
  206. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  207. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  208. { returns true, if ref is a reference using only the registers passed as base and index
  209. and having an offset }
  210. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  211. implementation
  212. uses
  213. cutils,verbose,
  214. systems,
  215. globals,
  216. cpuinfo,
  217. procinfo,
  218. paramgr,
  219. aasmbase,
  220. aoptbase,aoptutils,
  221. symconst,symsym,
  222. cgx86,
  223. itcpugas;
  224. {$ifndef 8086}
  225. const
  226. MAX_CMOV_INSTRUCTIONS = 4;
  227. MAX_CMOV_REGISTERS = 8;
  228. type
  229. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  230. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  231. tsProcessed);
  232. { For OptPass2Jcc }
  233. TCMOVTracking = object
  234. private
  235. CMOVScore, ConstCount: LongInt;
  236. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  237. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  238. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  239. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  240. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  241. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  242. fOptimizer: TX86AsmOptimizer;
  243. fLabel: TAsmSymbol;
  244. fInsertionPoint,
  245. fCondition,
  246. fInitialJump,
  247. fFirstMovBlock,
  248. fFirstMovBlockStop,
  249. fSecondJump,
  250. fThirdJump,
  251. fSecondMovBlock,
  252. fSecondMovBlockStop,
  253. fMidLabel,
  254. fEndLabel,
  255. fAllocationRange: tai;
  256. fState: TCMovTrackingState;
  257. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  258. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  259. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  260. public
  261. RegisterTracking: TAllUsedRegs;
  262. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  263. destructor Done;
  264. procedure Process(out new_p: tai);
  265. property State: TCMovTrackingState read fState;
  266. end;
  267. PCMOVTracking = ^TCMOVTracking;
  268. {$endif 8086}
  269. {$ifdef DEBUG_AOPTCPU}
  270. const
  271. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  272. {$else DEBUG_AOPTCPU}
  273. { Empty strings help the optimizer to remove string concatenations that won't
  274. ever appear to the user on release builds. [Kit] }
  275. const
  276. SPeepholeOptimization = '';
  277. {$endif DEBUG_AOPTCPU}
  278. LIST_STEP_SIZE = 4;
  279. type
  280. TJumpTrackingItem = class(TLinkedListItem)
  281. private
  282. FSymbol: TAsmSymbol;
  283. FRefs: LongInt;
  284. public
  285. constructor Create(ASymbol: TAsmSymbol);
  286. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  287. property Symbol: TAsmSymbol read FSymbol;
  288. property Refs: LongInt read FRefs;
  289. end;
  290. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  291. begin
  292. inherited Create;
  293. FSymbol := ASymbol;
  294. FRefs := 0;
  295. end;
  296. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  297. begin
  298. Inc(FRefs);
  299. end;
  300. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. (taicpu(instr).opcode = op) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. ((taicpu(instr).opcode = op1) or
  312. (taicpu(instr).opcode = op2)
  313. ) and
  314. ((opsize = []) or (taicpu(instr).opsize in opsize));
  315. end;
  316. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  317. begin
  318. result :=
  319. (instr.typ = ait_instruction) and
  320. ((taicpu(instr).opcode = op1) or
  321. (taicpu(instr).opcode = op2) or
  322. (taicpu(instr).opcode = op3)
  323. ) and
  324. ((opsize = []) or (taicpu(instr).opsize in opsize));
  325. end;
  326. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  327. const opsize : topsizes) : boolean;
  328. var
  329. op : TAsmOp;
  330. begin
  331. result:=false;
  332. if (instr.typ <> ait_instruction) or
  333. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  334. exit;
  335. for op in ops do
  336. begin
  337. if taicpu(instr).opcode = op then
  338. begin
  339. result:=true;
  340. exit;
  341. end;
  342. end;
  343. end;
  344. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  345. begin
  346. result := (oper.typ = top_reg) and (oper.reg = reg);
  347. end;
  348. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  349. begin
  350. result := (oper.typ = top_const) and (oper.val = a);
  351. end;
  352. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  353. begin
  354. result := oper1.typ = oper2.typ;
  355. if result then
  356. case oper1.typ of
  357. top_const:
  358. Result:=oper1.val = oper2.val;
  359. top_reg:
  360. Result:=oper1.reg = oper2.reg;
  361. top_ref:
  362. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  363. else
  364. internalerror(2013102801);
  365. end
  366. end;
  367. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  368. begin
  369. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  370. if result then
  371. case oper1.typ of
  372. top_const:
  373. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  374. top_reg:
  375. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  376. top_ref:
  377. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  378. else
  379. internalerror(2020052401);
  380. end
  381. end;
  382. function RefsEqual(const r1, r2: treference): boolean;
  383. begin
  384. RefsEqual :=
  385. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  386. (r1.relsymbol = r2.relsymbol) and
  387. (r1.segment = r2.segment) and (r1.base = r2.base) and
  388. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  389. (r1.offset = r2.offset) and
  390. (r1.volatility + r2.volatility = []);
  391. end;
  392. function RefsAlmostEqual(const r1, r2: treference): boolean;
  393. begin
  394. RefsAlmostEqual :=
  395. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  396. (r1.relsymbol = r2.relsymbol) and
  397. (r1.segment = r2.segment) and (r1.base = r2.base) and
  398. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  399. { Don't compare the offsets }
  400. (r1.volatility + r2.volatility = []);
  401. end;
  402. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  403. begin
  404. if (r1.symbol<>r2.symbol) then
  405. { If the index registers are different, there's a chance one could
  406. be set so it equals the other symbol }
  407. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  408. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  409. (r1.relsymbol = r2.relsymbol) and
  410. (r1.segment = r2.segment) and (r1.base = r2.base) and
  411. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  412. (r1.volatility + r2.volatility = []) then
  413. { In this case, it all depends on the offsets }
  414. Exit(abs(r1.offset - r2.offset) < Range);
  415. { There's a chance things MIGHT overlap, so take no chances }
  416. Result := True;
  417. end;
  418. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  419. begin
  420. Result:=(ref.offset=0) and
  421. (ref.scalefactor in [0,1]) and
  422. (ref.segment=NR_NO) and
  423. (ref.symbol=nil) and
  424. (ref.relsymbol=nil) and
  425. ((base=NR_INVALID) or
  426. (ref.base=base)) and
  427. ((index=NR_INVALID) or
  428. (ref.index=index)) and
  429. (ref.volatility=[]);
  430. end;
  431. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  432. begin
  433. Result:=(ref.scalefactor in [0,1]) and
  434. (ref.segment=NR_NO) and
  435. (ref.symbol=nil) and
  436. (ref.relsymbol=nil) and
  437. ((base=NR_INVALID) or
  438. (ref.base=base)) and
  439. ((index=NR_INVALID) or
  440. (ref.index=index)) and
  441. (ref.volatility=[]);
  442. end;
  443. function InstrReadsFlags(p: tai): boolean;
  444. begin
  445. InstrReadsFlags := true;
  446. case p.typ of
  447. ait_instruction:
  448. if InsProp[taicpu(p).opcode].Ch*
  449. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  450. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  451. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  452. exit;
  453. ait_label:
  454. exit;
  455. else
  456. ;
  457. end;
  458. InstrReadsFlags := false;
  459. end;
  460. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  461. begin
  462. Next:=Current;
  463. repeat
  464. Result:=GetNextInstruction(Next,Next);
  465. until not (Result) or
  466. not(cs_opt_level3 in current_settings.optimizerswitches) or
  467. (Next.typ<>ait_instruction) or
  468. RegInInstruction(reg,Next) or
  469. is_calljmp(taicpu(Next).opcode);
  470. end;
  471. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  472. var
  473. GetNextResult: Boolean;
  474. begin
  475. Result:=0;
  476. Next:=Current;
  477. repeat
  478. GetNextResult := GetNextInstruction(Next,Next);
  479. if GetNextResult then
  480. Inc(Result)
  481. else
  482. { Must return zero upon hitting the end of the linked list without a match }
  483. Result := 0;
  484. until not (GetNextResult) or
  485. not(cs_opt_level3 in current_settings.optimizerswitches) or
  486. (Next.typ<>ait_instruction) or
  487. RegInInstruction(reg,Next) or
  488. is_calljmp(taicpu(Next).opcode);
  489. end;
  490. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  491. procedure TrackJump(Symbol: TAsmSymbol);
  492. var
  493. Search: TJumpTrackingItem;
  494. begin
  495. { See if an entry already exists in our jump tracking list
  496. (faster to search backwards due to the higher chance of
  497. matching destinations) }
  498. Search := TJumpTrackingItem(JumpTracking.Last);
  499. while Assigned(Search) do
  500. begin
  501. if Search.Symbol = Symbol then
  502. begin
  503. { Found it - remove it so it can be pushed to the front }
  504. JumpTracking.Remove(Search);
  505. Break;
  506. end;
  507. Search := TJumpTrackingItem(Search.Previous);
  508. end;
  509. if not Assigned(Search) then
  510. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  511. JumpTracking.Concat(Search);
  512. Search.IncRefs;
  513. end;
  514. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  515. var
  516. Search: TJumpTrackingItem;
  517. begin
  518. Result := False;
  519. { See if this label appears in the tracking list }
  520. Search := TJumpTrackingItem(JumpTracking.Last);
  521. while Assigned(Search) do
  522. begin
  523. if Search.Symbol = Symbol then
  524. begin
  525. { Found it - let's see what we can discover }
  526. if Search.Symbol.getrefs = Search.Refs then
  527. begin
  528. { Success - all the references are accounted for }
  529. JumpTracking.Remove(Search);
  530. Search.Free;
  531. { It is logically impossible for CrossJump to be false here
  532. because we must have run into a conditional jump for
  533. this label at some point }
  534. if not CrossJump then
  535. InternalError(2022041710);
  536. if JumpTracking.First = nil then
  537. { Tracking list is now empty - no more cross jumps }
  538. CrossJump := False;
  539. Result := True;
  540. Exit;
  541. end;
  542. { If the references don't match, it's possible to enter
  543. this label through other means, so drop out }
  544. Exit;
  545. end;
  546. Search := TJumpTrackingItem(Search.Previous);
  547. end;
  548. end;
  549. var
  550. Next_Label: tai;
  551. begin
  552. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  553. Next := Current;
  554. repeat
  555. Result := GetNextInstruction(Next,Next);
  556. if not Result then
  557. Break;
  558. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  559. if is_calljmpuncondret(taicpu(Next).opcode) then
  560. begin
  561. if (taicpu(Next).opcode = A_JMP) and
  562. { Remove dead code now to save time }
  563. RemoveDeadCodeAfterJump(taicpu(Next)) then
  564. { A jump was removed, but not the current instruction, and
  565. Result doesn't necessarily translate into an optimisation
  566. routine's Result, so use the "Force New Iteration" flag so
  567. mark a new pass }
  568. Include(OptsToCheck, aoc_ForceNewIteration);
  569. if not Assigned(JumpTracking) then
  570. begin
  571. { Cross-label optimisations often causes other optimisations
  572. to perform worse because they're not given the chance to
  573. optimise locally. In this case, don't do the cross-label
  574. optimisations yet, but flag them as a potential possibility
  575. for the next iteration of Pass 1 }
  576. if not NotFirstIteration then
  577. Include(OptsToCheck, aoc_ForceNewIteration);
  578. end
  579. else if IsJumpToLabel(taicpu(Next)) and
  580. GetNextInstruction(Next, Next_Label) then
  581. begin
  582. { If we have JMP .lbl, and the label after it has all of its
  583. references tracked, then this is probably an if-else style of
  584. block and we can keep tracking. If the label for this jump
  585. then appears later and is fully tracked, then it's the end
  586. of the if-else blocks and the code paths converge (thus
  587. marking the end of the cross-jump) }
  588. if (Next_Label.typ = ait_label) then
  589. begin
  590. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  591. begin
  592. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  593. Next := Next_Label;
  594. { CrossJump gets set to false by LabelAccountedFor if the
  595. list is completely emptied (as it indicates that all
  596. code paths have converged). We could avoid this nuance
  597. by moving the TrackJump call to before the
  598. LabelAccountedFor call, but this is slower in situations
  599. where LabelAccountedFor would return False due to the
  600. creation of a new object that is not used and destroyed
  601. soon after. }
  602. CrossJump := True;
  603. Continue;
  604. end;
  605. end
  606. else if (Next_Label.typ <> ait_marker) then
  607. { We just did a RemoveDeadCodeAfterJump, so either we find
  608. a label, the end of the procedure or some kind of marker}
  609. InternalError(2022041720);
  610. end;
  611. Result := False;
  612. Exit;
  613. end
  614. else
  615. begin
  616. if not Assigned(JumpTracking) then
  617. begin
  618. { Cross-label optimisations often causes other optimisations
  619. to perform worse because they're not given the chance to
  620. optimise locally. In this case, don't do the cross-label
  621. optimisations yet, but flag them as a potential possibility
  622. for the next iteration of Pass 1 }
  623. if not NotFirstIteration then
  624. Include(OptsToCheck, aoc_ForceNewIteration);
  625. end
  626. else if IsJumpToLabel(taicpu(Next)) then
  627. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  628. else
  629. { Conditional jumps should always be a jump to label }
  630. InternalError(2022041701);
  631. CrossJump := True;
  632. Continue;
  633. end;
  634. if Next.typ = ait_label then
  635. begin
  636. if not Assigned(JumpTracking) then
  637. begin
  638. { Cross-label optimisations often causes other optimisations
  639. to perform worse because they're not given the chance to
  640. optimise locally. In this case, don't do the cross-label
  641. optimisations yet, but flag them as a potential possibility
  642. for the next iteration of Pass 1 }
  643. if not NotFirstIteration then
  644. Include(OptsToCheck, aoc_ForceNewIteration);
  645. end
  646. else if LabelAccountedFor(tai_label(Next).labsym) then
  647. Continue;
  648. { If we reach here, we're at a label that hasn't been seen before
  649. (or JumpTracking was nil) }
  650. Break;
  651. end;
  652. until not Result or
  653. not (cs_opt_level3 in current_settings.optimizerswitches) or
  654. not (Next.typ in [ait_label, ait_instruction]) or
  655. RegInInstruction(reg,Next);
  656. end;
  657. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  658. begin
  659. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  660. begin
  661. Result:=GetNextInstruction(Current,Next);
  662. exit;
  663. end;
  664. Next:=tai(Current.Next);
  665. Result:=false;
  666. while assigned(Next) do
  667. begin
  668. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  669. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  670. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  671. exit
  672. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  673. begin
  674. Result:=true;
  675. exit;
  676. end;
  677. Next:=tai(Next.Next);
  678. end;
  679. end;
  680. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  681. begin
  682. Result:=RegReadByInstruction(reg,hp);
  683. end;
  684. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  685. var
  686. p: taicpu;
  687. opcount: longint;
  688. begin
  689. RegReadByInstruction := false;
  690. if hp.typ <> ait_instruction then
  691. exit;
  692. p := taicpu(hp);
  693. case p.opcode of
  694. A_CALL:
  695. regreadbyinstruction := true;
  696. A_IMUL:
  697. case p.ops of
  698. 1:
  699. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  700. (
  701. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  702. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  703. );
  704. 2,3:
  705. regReadByInstruction :=
  706. reginop(reg,p.oper[0]^) or
  707. reginop(reg,p.oper[1]^);
  708. else
  709. InternalError(2019112801);
  710. end;
  711. A_MUL:
  712. begin
  713. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  714. (
  715. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  716. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  717. );
  718. end;
  719. A_IDIV,A_DIV:
  720. begin
  721. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  722. (
  723. (getregtype(reg)=R_INTREGISTER) and
  724. (
  725. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  726. )
  727. );
  728. end;
  729. else
  730. begin
  731. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  732. begin
  733. RegReadByInstruction := false;
  734. exit;
  735. end;
  736. for opcount := 0 to p.ops-1 do
  737. if (p.oper[opCount]^.typ = top_ref) and
  738. RegInRef(reg,p.oper[opcount]^.ref^) then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. { special handling for SSE MOVSD }
  744. if (p.opcode=A_MOVSD) and (p.ops>0) then
  745. begin
  746. if p.ops<>2 then
  747. internalerror(2017042702);
  748. regReadByInstruction := reginop(reg,p.oper[0]^) or
  749. (
  750. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  751. );
  752. exit;
  753. end;
  754. with insprop[p.opcode] do
  755. begin
  756. case getregtype(reg) of
  757. R_INTREGISTER:
  758. begin
  759. case getsupreg(reg) of
  760. RS_EAX:
  761. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  762. begin
  763. RegReadByInstruction := true;
  764. exit
  765. end;
  766. RS_ECX:
  767. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  768. begin
  769. RegReadByInstruction := true;
  770. exit
  771. end;
  772. RS_EDX:
  773. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_EBX:
  779. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_ESP:
  785. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBP:
  791. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESI:
  797. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EDI:
  803. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  804. begin
  805. RegReadByInstruction := true;
  806. exit
  807. end;
  808. end;
  809. end;
  810. R_MMREGISTER:
  811. begin
  812. case getsupreg(reg) of
  813. RS_XMM0:
  814. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  815. begin
  816. RegReadByInstruction := true;
  817. exit
  818. end;
  819. end;
  820. end;
  821. else
  822. ;
  823. end;
  824. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  825. begin
  826. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  827. begin
  828. case p.condition of
  829. C_A,C_NBE, { CF=0 and ZF=0 }
  830. C_BE,C_NA: { CF=1 or ZF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  832. C_AE,C_NB,C_NC, { CF=0 }
  833. C_B,C_NAE,C_C: { CF=1 }
  834. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  835. C_NE,C_NZ, { ZF=0 }
  836. C_E,C_Z: { ZF=1 }
  837. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  838. C_G,C_NLE, { ZF=0 and SF=OF }
  839. C_LE,C_NG: { ZF=1 or SF<>OF }
  840. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  841. C_GE,C_NL, { SF=OF }
  842. C_L,C_NGE: { SF<>OF }
  843. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  844. C_NO, { OF=0 }
  845. C_O: { OF=1 }
  846. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  847. C_NP,C_PO, { PF=0 }
  848. C_P,C_PE: { PF=1 }
  849. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  850. C_NS, { SF=0 }
  851. C_S: { SF=1 }
  852. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  853. else
  854. internalerror(2017042701);
  855. end;
  856. if RegReadByInstruction then
  857. exit;
  858. end;
  859. case getsubreg(reg) of
  860. R_SUBW,R_SUBD,R_SUBQ:
  861. RegReadByInstruction :=
  862. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  863. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  864. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  865. R_SUBFLAGCARRY:
  866. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  867. R_SUBFLAGPARITY:
  868. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  869. R_SUBFLAGAUXILIARY:
  870. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  871. R_SUBFLAGZERO:
  872. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  873. R_SUBFLAGSIGN:
  874. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  875. R_SUBFLAGOVERFLOW:
  876. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  877. R_SUBFLAGINTERRUPT:
  878. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGDIRECTION:
  880. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. else
  882. internalerror(2017042601);
  883. end;
  884. exit;
  885. end;
  886. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  887. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  888. (p.oper[0]^.reg=p.oper[1]^.reg) then
  889. exit;
  890. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  891. begin
  892. RegReadByInstruction := true;
  893. exit
  894. end;
  895. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  896. begin
  897. RegReadByInstruction := true;
  898. exit
  899. end;
  900. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  901. begin
  902. RegReadByInstruction := true;
  903. exit
  904. end;
  905. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  906. begin
  907. RegReadByInstruction := true;
  908. exit
  909. end;
  910. end;
  911. end;
  912. end;
  913. end;
  914. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  915. begin
  916. result:=false;
  917. if p1.typ<>ait_instruction then
  918. exit;
  919. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  920. exit(true);
  921. if (getregtype(reg)=R_INTREGISTER) and
  922. { change information for xmm movsd are not correct }
  923. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  924. begin
  925. { Handle instructions that behave differently depending on the size and operand count }
  926. case taicpu(p1).opcode of
  927. A_MUL, A_DIV, A_IDIV:
  928. if taicpu(p1).opsize = S_B then
  929. Result := (getsupreg(Reg) = RS_EAX)
  930. else
  931. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  932. A_IMUL:
  933. if taicpu(p1).ops = 1 then
  934. begin
  935. if taicpu(p1).opsize = S_B then
  936. Result := (getsupreg(Reg) = RS_EAX)
  937. else
  938. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  939. end;
  940. { If ops are greater than 1, call inherited method }
  941. else
  942. case getsupreg(reg) of
  943. { RS_EAX = RS_RAX on x86-64 }
  944. RS_EAX:
  945. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  946. RS_ECX:
  947. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  948. RS_EDX:
  949. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  950. RS_EBX:
  951. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  952. RS_ESP:
  953. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. RS_EBP:
  955. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  956. RS_ESI:
  957. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_EDI:
  959. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. else
  961. ;
  962. end;
  963. end;
  964. if result then
  965. exit;
  966. end
  967. else if getregtype(reg)=R_MMREGISTER then
  968. begin
  969. case getsupreg(reg) of
  970. RS_XMM0:
  971. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. else
  973. ;
  974. end;
  975. if result then
  976. exit;
  977. end
  978. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  979. begin
  980. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  981. exit(true);
  982. case getsubreg(reg) of
  983. R_SUBFLAGCARRY:
  984. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  985. R_SUBFLAGPARITY:
  986. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  987. R_SUBFLAGAUXILIARY:
  988. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  989. R_SUBFLAGZERO:
  990. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. R_SUBFLAGSIGN:
  992. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  993. R_SUBFLAGOVERFLOW:
  994. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  995. R_SUBFLAGINTERRUPT:
  996. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGDIRECTION:
  998. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBW,R_SUBD,R_SUBQ:
  1000. { Everything except the direction bits }
  1001. Result:=
  1002. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1003. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1004. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1005. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1006. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1007. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1008. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1009. else
  1010. ;
  1011. end;
  1012. if result then
  1013. exit;
  1014. end
  1015. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1016. exit(true);
  1017. Result:=inherited RegInInstruction(Reg, p1);
  1018. end;
  1019. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1020. const
  1021. WriteOps: array[0..3] of set of TInsChange =
  1022. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1023. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1024. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1025. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1026. var
  1027. OperIdx: Integer;
  1028. begin
  1029. Result := False;
  1030. if p1.typ <> ait_instruction then
  1031. exit;
  1032. with insprop[taicpu(p1).opcode] do
  1033. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1034. begin
  1035. case getsubreg(reg) of
  1036. R_SUBW,R_SUBD,R_SUBQ:
  1037. Result :=
  1038. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1039. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1040. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1041. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1042. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1043. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1044. R_SUBFLAGCARRY:
  1045. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1046. R_SUBFLAGPARITY:
  1047. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1048. R_SUBFLAGAUXILIARY:
  1049. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1050. R_SUBFLAGZERO:
  1051. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1052. R_SUBFLAGSIGN:
  1053. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1054. R_SUBFLAGOVERFLOW:
  1055. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGINTERRUPT:
  1057. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGDIRECTION:
  1059. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. else
  1061. internalerror(2017042602);
  1062. end;
  1063. exit;
  1064. end;
  1065. case taicpu(p1).opcode of
  1066. A_CALL:
  1067. { We could potentially set Result to False if the register in
  1068. question is non-volatile for the subroutine's calling convention,
  1069. but this would require detecting the calling convention in use and
  1070. also assuming that the routine doesn't contain malformed assembly
  1071. language, for example... so it could only be done under -O4 as it
  1072. would be considered a side-effect. [Kit] }
  1073. Result := True;
  1074. A_MOVSD:
  1075. { special handling for SSE MOVSD }
  1076. if (taicpu(p1).ops>0) then
  1077. begin
  1078. if taicpu(p1).ops<>2 then
  1079. internalerror(2017042703);
  1080. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1081. end;
  1082. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1083. so fix it here (FK)
  1084. }
  1085. A_VMOVSS,
  1086. A_VMOVSD:
  1087. begin
  1088. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1089. exit;
  1090. end;
  1091. A_MUL, A_DIV, A_IDIV:
  1092. begin
  1093. if taicpu(p1).opsize = S_B then
  1094. Result := (getsupreg(Reg) = RS_EAX)
  1095. else
  1096. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1097. end;
  1098. A_IMUL:
  1099. begin
  1100. if taicpu(p1).ops = 1 then
  1101. begin
  1102. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1103. end
  1104. else
  1105. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1106. Exit;
  1107. end;
  1108. else
  1109. ;
  1110. end;
  1111. if Result then
  1112. exit;
  1113. with insprop[taicpu(p1).opcode] do
  1114. begin
  1115. if getregtype(reg)=R_INTREGISTER then
  1116. begin
  1117. case getsupreg(reg) of
  1118. RS_EAX:
  1119. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1120. begin
  1121. Result := True;
  1122. exit
  1123. end;
  1124. RS_ECX:
  1125. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1126. begin
  1127. Result := True;
  1128. exit
  1129. end;
  1130. RS_EDX:
  1131. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_EBX:
  1137. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_ESP:
  1143. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. RS_EBP:
  1149. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1150. begin
  1151. Result := True;
  1152. exit
  1153. end;
  1154. RS_ESI:
  1155. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1156. begin
  1157. Result := True;
  1158. exit
  1159. end;
  1160. RS_EDI:
  1161. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1162. begin
  1163. Result := True;
  1164. exit
  1165. end;
  1166. end;
  1167. end;
  1168. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1169. if (WriteOps[OperIdx]*Ch<>[]) and
  1170. { The register doesn't get modified inside a reference }
  1171. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1172. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1173. begin
  1174. Result := true;
  1175. exit
  1176. end;
  1177. end;
  1178. end;
  1179. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1180. const
  1181. WriteOps: array[0..3] of set of TInsChange =
  1182. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1183. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1184. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1185. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1186. var
  1187. X: Integer;
  1188. CurrentP1Size: asizeint;
  1189. begin
  1190. Result := (
  1191. (Ref.base <> NR_NO) and
  1192. {$ifdef x86_64}
  1193. (Ref.base <> NR_RIP) and
  1194. {$endif x86_64}
  1195. RegModifiedBetween(Ref.base, p1, p2)
  1196. ) or
  1197. (
  1198. (Ref.index <> NR_NO) and
  1199. (Ref.index <> Ref.base) and
  1200. RegModifiedBetween(Ref.index, p1, p2)
  1201. );
  1202. { Now check to see if the memory itself is written to }
  1203. if not Result then
  1204. begin
  1205. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1206. if p1.typ = ait_instruction then
  1207. begin
  1208. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1209. with insprop[taicpu(p1).opcode] do
  1210. for X := 0 to taicpu(p1).ops - 1 do
  1211. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1212. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1213. { Catch any potential overlaps }
  1214. (
  1215. (RefSize = 0) or
  1216. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1217. ) and
  1218. (
  1219. (CurrentP1Size = 0) or
  1220. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1221. ) and
  1222. { Reference is used, but does the instruction write to it? }
  1223. (
  1224. (Ch_All in Ch) or
  1225. ((WriteOps[X] * Ch) <> [])
  1226. ) then
  1227. begin
  1228. Result := True;
  1229. Break;
  1230. end;
  1231. end;
  1232. end;
  1233. end;
  1234. {$ifdef DEBUG_AOPTCPU}
  1235. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1236. begin
  1237. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1238. end;
  1239. function debug_tostr(i: tcgint): string; inline;
  1240. begin
  1241. Result := tostr(i);
  1242. end;
  1243. function debug_hexstr(i: tcgint): string;
  1244. begin
  1245. Result := '0x';
  1246. case i of
  1247. 0..$FF:
  1248. Result := Result + hexstr(i, 2);
  1249. $100..$FFFF:
  1250. Result := Result + hexstr(i, 4);
  1251. $10000..$FFFFFF:
  1252. Result := Result + hexstr(i, 6);
  1253. $1000000..$FFFFFFFF:
  1254. Result := Result + hexstr(i, 8);
  1255. else
  1256. Result := Result + hexstr(i, 16);
  1257. end;
  1258. end;
  1259. function debug_regname(r: TRegister): string; inline;
  1260. begin
  1261. Result := '%' + std_regname(r);
  1262. end;
  1263. { Debug output function - creates a string representation of an operator }
  1264. function debug_operstr(oper: TOper): string;
  1265. begin
  1266. case oper.typ of
  1267. top_const:
  1268. Result := '$' + debug_tostr(oper.val);
  1269. top_reg:
  1270. Result := debug_regname(oper.reg);
  1271. top_ref:
  1272. begin
  1273. if oper.ref^.offset <> 0 then
  1274. Result := debug_tostr(oper.ref^.offset) + '('
  1275. else
  1276. Result := '(';
  1277. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1278. begin
  1279. Result := Result + debug_regname(oper.ref^.base);
  1280. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1281. Result := Result + ',' + debug_regname(oper.ref^.index);
  1282. end
  1283. else
  1284. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1285. Result := Result + debug_regname(oper.ref^.index);
  1286. if (oper.ref^.scalefactor > 1) then
  1287. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1288. else
  1289. Result := Result + ')';
  1290. end;
  1291. else
  1292. Result := '[UNKNOWN]';
  1293. end;
  1294. end;
  1295. function debug_op2str(opcode: tasmop): string; inline;
  1296. begin
  1297. Result := std_op2str[opcode];
  1298. end;
  1299. function debug_opsize2str(opsize: topsize): string; inline;
  1300. begin
  1301. Result := gas_opsize2str[opsize];
  1302. end;
  1303. {$else DEBUG_AOPTCPU}
  1304. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1305. begin
  1306. end;
  1307. function debug_tostr(i: tcgint): string; inline;
  1308. begin
  1309. Result := '';
  1310. end;
  1311. function debug_hexstr(i: tcgint): string; inline;
  1312. begin
  1313. Result := '';
  1314. end;
  1315. function debug_regname(r: TRegister): string; inline;
  1316. begin
  1317. Result := '';
  1318. end;
  1319. function debug_operstr(oper: TOper): string; inline;
  1320. begin
  1321. Result := '';
  1322. end;
  1323. function debug_op2str(opcode: tasmop): string; inline;
  1324. begin
  1325. Result := '';
  1326. end;
  1327. function debug_opsize2str(opsize: topsize): string; inline;
  1328. begin
  1329. Result := '';
  1330. end;
  1331. {$endif DEBUG_AOPTCPU}
  1332. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1333. begin
  1334. {$ifdef x86_64}
  1335. { Always fine on x86-64 }
  1336. Result := True;
  1337. {$else x86_64}
  1338. Result :=
  1339. {$ifdef i8086}
  1340. (current_settings.cputype >= cpu_386) and
  1341. {$endif i8086}
  1342. (
  1343. { Always accept if optimising for size }
  1344. (cs_opt_size in current_settings.optimizerswitches) or
  1345. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1346. (current_settings.optimizecputype >= cpu_Pentium2)
  1347. );
  1348. {$endif x86_64}
  1349. end;
  1350. { Attempts to allocate a volatile integer register for use between p and hp,
  1351. using AUsedRegs for the current register usage information. Returns NR_NO
  1352. if no free register could be found }
  1353. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1354. var
  1355. RegSet: TCPURegisterSet;
  1356. CurrentSuperReg: Integer;
  1357. CurrentReg: TRegister;
  1358. Currentp: tai;
  1359. Breakout: Boolean;
  1360. begin
  1361. Result := NR_NO;
  1362. RegSet :=
  1363. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1364. current_procinfo.saved_regs_int;
  1365. (*
  1366. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1367. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1368. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1369. *)
  1370. for CurrentSuperReg in RegSet do
  1371. begin
  1372. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1373. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1374. {$if defined(i386) or defined(i8086)}
  1375. { If the target size is 8-bit, make sure we can actually encode it }
  1376. and (
  1377. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1378. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1379. )
  1380. {$endif i386 or i8086}
  1381. then
  1382. begin
  1383. Currentp := p;
  1384. Breakout := False;
  1385. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1386. begin
  1387. case Currentp.typ of
  1388. ait_instruction:
  1389. begin
  1390. if RegInInstruction(CurrentReg, Currentp) then
  1391. begin
  1392. Breakout := True;
  1393. Break;
  1394. end;
  1395. { Cannot allocate across an unconditional jump }
  1396. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1397. Exit;
  1398. end;
  1399. ait_marker:
  1400. { Don't try anything more if a marker is hit }
  1401. Exit;
  1402. ait_regalloc:
  1403. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1404. begin
  1405. Breakout := True;
  1406. Break;
  1407. end;
  1408. else
  1409. ;
  1410. end;
  1411. end;
  1412. if Breakout then
  1413. { Try the next register }
  1414. Continue;
  1415. { We have a free register available }
  1416. Result := CurrentReg;
  1417. if not DontAlloc then
  1418. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1419. Exit;
  1420. end;
  1421. end;
  1422. end;
  1423. { Attempts to allocate a volatile MM register for use between p and hp,
  1424. using AUsedRegs for the current register usage information. Returns NR_NO
  1425. if no free register could be found }
  1426. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1427. var
  1428. RegSet: TCPURegisterSet;
  1429. CurrentSuperReg: Integer;
  1430. CurrentReg: TRegister;
  1431. Currentp: tai;
  1432. Breakout: Boolean;
  1433. begin
  1434. Result := NR_NO;
  1435. RegSet :=
  1436. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1437. current_procinfo.saved_regs_mm;
  1438. for CurrentSuperReg in RegSet do
  1439. begin
  1440. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1441. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1442. begin
  1443. Currentp := p;
  1444. Breakout := False;
  1445. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1446. begin
  1447. case Currentp.typ of
  1448. ait_instruction:
  1449. begin
  1450. if RegInInstruction(CurrentReg, Currentp) then
  1451. begin
  1452. Breakout := True;
  1453. Break;
  1454. end;
  1455. { Cannot allocate across an unconditional jump }
  1456. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1457. Exit;
  1458. end;
  1459. ait_marker:
  1460. { Don't try anything more if a marker is hit }
  1461. Exit;
  1462. ait_regalloc:
  1463. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1464. begin
  1465. Breakout := True;
  1466. Break;
  1467. end;
  1468. else
  1469. ;
  1470. end;
  1471. end;
  1472. if Breakout then
  1473. { Try the next register }
  1474. Continue;
  1475. { We have a free register available }
  1476. Result := CurrentReg;
  1477. if not DontAlloc then
  1478. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1479. Exit;
  1480. end;
  1481. end;
  1482. end;
  1483. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1484. begin
  1485. if not SuperRegistersEqual(reg1,reg2) then
  1486. exit(false);
  1487. if getregtype(reg1)<>R_INTREGISTER then
  1488. exit(true); {because SuperRegisterEqual is true}
  1489. case getsubreg(reg1) of
  1490. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1491. higher, it preserves the high bits, so the new value depends on
  1492. reg2's previous value. In other words, it is equivalent to doing:
  1493. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1494. R_SUBL:
  1495. exit(getsubreg(reg2)=R_SUBL);
  1496. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1497. higher, it actually does a:
  1498. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1499. R_SUBH:
  1500. exit(getsubreg(reg2)=R_SUBH);
  1501. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1502. bits of reg2:
  1503. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1504. R_SUBW:
  1505. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1506. { a write to R_SUBD always overwrites every other subregister,
  1507. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1508. R_SUBD,
  1509. R_SUBQ:
  1510. exit(true);
  1511. else
  1512. internalerror(2017042801);
  1513. end;
  1514. end;
  1515. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1516. begin
  1517. if not SuperRegistersEqual(reg1,reg2) then
  1518. exit(false);
  1519. if getregtype(reg1)<>R_INTREGISTER then
  1520. exit(true); {because SuperRegisterEqual is true}
  1521. case getsubreg(reg1) of
  1522. R_SUBL:
  1523. exit(getsubreg(reg2)<>R_SUBH);
  1524. R_SUBH:
  1525. exit(getsubreg(reg2)<>R_SUBL);
  1526. R_SUBW,
  1527. R_SUBD,
  1528. R_SUBQ:
  1529. exit(true);
  1530. else
  1531. internalerror(2017042802);
  1532. end;
  1533. end;
  1534. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1535. var
  1536. hp1 : tai;
  1537. l : TCGInt;
  1538. begin
  1539. result:=false;
  1540. if not(GetNextInstruction(p, hp1)) then
  1541. exit;
  1542. { changes the code sequence
  1543. shr/sar const1, x
  1544. shl const2, x
  1545. to
  1546. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1547. if (taicpu(p).oper[0]^.typ = top_const) and
  1548. MatchInstruction(hp1,A_SHL,[]) and
  1549. (taicpu(hp1).oper[0]^.typ = top_const) and
  1550. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1551. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1552. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1553. begin
  1554. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1555. not(cs_opt_size in current_settings.optimizerswitches) then
  1556. begin
  1557. { shr/sar const1, %reg
  1558. shl const2, %reg
  1559. with const1 > const2 }
  1560. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1561. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1562. taicpu(hp1).opcode := A_AND;
  1563. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1564. case taicpu(p).opsize Of
  1565. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1566. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1567. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1568. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1569. else
  1570. Internalerror(2017050703)
  1571. end;
  1572. end
  1573. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1574. not(cs_opt_size in current_settings.optimizerswitches) then
  1575. begin
  1576. { shr/sar const1, %reg
  1577. shl const2, %reg
  1578. with const1 < const2 }
  1579. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1580. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1581. taicpu(p).opcode := A_AND;
  1582. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1583. case taicpu(p).opsize Of
  1584. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1585. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1586. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1587. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1588. else
  1589. Internalerror(2017050702)
  1590. end;
  1591. end
  1592. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1593. begin
  1594. { shr/sar const1, %reg
  1595. shl const2, %reg
  1596. with const1 = const2 }
  1597. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1598. taicpu(p).opcode := A_AND;
  1599. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1600. case taicpu(p).opsize Of
  1601. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1602. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1603. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1604. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1605. else
  1606. Internalerror(2017050701)
  1607. end;
  1608. RemoveInstruction(hp1);
  1609. end;
  1610. end;
  1611. end;
  1612. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1613. var
  1614. opsize : topsize;
  1615. hp1, hp2 : tai;
  1616. tmpref : treference;
  1617. ShiftValue : Cardinal;
  1618. BaseValue : TCGInt;
  1619. begin
  1620. result:=false;
  1621. opsize:=taicpu(p).opsize;
  1622. { changes certain "imul const, %reg"'s to lea sequences }
  1623. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1624. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1625. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1626. if (taicpu(p).oper[0]^.val = 1) then
  1627. if (taicpu(p).ops = 2) then
  1628. { remove "imul $1, reg" }
  1629. begin
  1630. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1631. Result := RemoveCurrentP(p);
  1632. end
  1633. else
  1634. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1635. begin
  1636. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1637. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1638. asml.InsertAfter(hp1, p);
  1639. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1640. RemoveCurrentP(p, hp1);
  1641. Result := True;
  1642. end
  1643. else if ((taicpu(p).ops <= 2) or
  1644. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1645. not(cs_opt_size in current_settings.optimizerswitches) and
  1646. (not(GetNextInstruction(p, hp1)) or
  1647. not((tai(hp1).typ = ait_instruction) and
  1648. ((taicpu(hp1).opcode=A_Jcc) and
  1649. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1650. begin
  1651. {
  1652. imul X, reg1, reg2 to
  1653. lea (reg1,reg1,Y), reg2
  1654. shl ZZ,reg2
  1655. imul XX, reg1 to
  1656. lea (reg1,reg1,YY), reg1
  1657. shl ZZ,reg2
  1658. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1659. it does not exist as a separate optimization target in FPC though.
  1660. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1661. at most two zeros
  1662. }
  1663. reference_reset(tmpref,1,[]);
  1664. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1665. begin
  1666. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1667. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1668. TmpRef.base := taicpu(p).oper[1]^.reg;
  1669. TmpRef.index := taicpu(p).oper[1]^.reg;
  1670. if not(BaseValue in [3,5,9]) then
  1671. Internalerror(2018110101);
  1672. TmpRef.ScaleFactor := BaseValue-1;
  1673. if (taicpu(p).ops = 2) then
  1674. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1675. else
  1676. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1677. AsmL.InsertAfter(hp1,p);
  1678. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1679. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1680. RemoveCurrentP(p, hp1);
  1681. if ShiftValue>0 then
  1682. begin
  1683. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1684. AsmL.InsertAfter(hp2,hp1);
  1685. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1686. end;
  1687. Result := True;
  1688. end;
  1689. end;
  1690. end;
  1691. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1692. begin
  1693. Result := False;
  1694. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1695. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1696. begin
  1697. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1698. taicpu(p).opcode := A_MOV;
  1699. Result := True;
  1700. end;
  1701. end;
  1702. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1703. var
  1704. p: taicpu absolute hp; { Implicit typecast }
  1705. i: Integer;
  1706. begin
  1707. Result := False;
  1708. if not assigned(hp) or
  1709. (hp.typ <> ait_instruction) then
  1710. Exit;
  1711. Prefetch(insprop[p.opcode]);
  1712. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1713. with insprop[p.opcode] do
  1714. begin
  1715. case getsubreg(reg) of
  1716. R_SUBW,R_SUBD,R_SUBQ:
  1717. Result:=
  1718. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1719. uncommon flags are checked first }
  1720. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1721. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1725. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1726. R_SUBFLAGCARRY:
  1727. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1728. R_SUBFLAGPARITY:
  1729. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1730. R_SUBFLAGAUXILIARY:
  1731. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1732. R_SUBFLAGZERO:
  1733. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1734. R_SUBFLAGSIGN:
  1735. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1736. R_SUBFLAGOVERFLOW:
  1737. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1738. R_SUBFLAGINTERRUPT:
  1739. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1740. R_SUBFLAGDIRECTION:
  1741. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1742. else
  1743. internalerror(2017050501);
  1744. end;
  1745. exit;
  1746. end;
  1747. { Handle special cases first }
  1748. case p.opcode of
  1749. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1750. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1751. begin
  1752. Result :=
  1753. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1754. (p.oper[1]^.typ = top_reg) and
  1755. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1756. (
  1757. (p.oper[0]^.typ = top_const) or
  1758. (
  1759. (p.oper[0]^.typ = top_reg) and
  1760. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1761. ) or (
  1762. (p.oper[0]^.typ = top_ref) and
  1763. not RegInRef(reg,p.oper[0]^.ref^)
  1764. )
  1765. );
  1766. end;
  1767. A_MUL, A_IMUL:
  1768. Result :=
  1769. (
  1770. (p.ops=3) and { IMUL only }
  1771. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1772. (
  1773. (
  1774. (p.oper[1]^.typ=top_reg) and
  1775. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1776. ) or (
  1777. (p.oper[1]^.typ=top_ref) and
  1778. not RegInRef(reg,p.oper[1]^.ref^)
  1779. )
  1780. )
  1781. ) or (
  1782. (
  1783. (p.ops=1) and
  1784. (
  1785. (
  1786. (
  1787. (p.oper[0]^.typ=top_reg) and
  1788. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1789. )
  1790. ) or (
  1791. (p.oper[0]^.typ=top_ref) and
  1792. not RegInRef(reg,p.oper[0]^.ref^)
  1793. )
  1794. ) and (
  1795. (
  1796. (p.opsize=S_B) and
  1797. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1798. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1799. ) or (
  1800. (p.opsize=S_W) and
  1801. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1802. ) or (
  1803. (p.opsize=S_L) and
  1804. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1805. {$ifdef x86_64}
  1806. ) or (
  1807. (p.opsize=S_Q) and
  1808. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1809. {$endif x86_64}
  1810. )
  1811. )
  1812. )
  1813. );
  1814. A_CBW:
  1815. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1816. {$ifndef x86_64}
  1817. A_LDS:
  1818. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1819. A_LES:
  1820. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1821. {$endif not x86_64}
  1822. A_LFS:
  1823. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1824. A_LGS:
  1825. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1826. A_LSS:
  1827. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1828. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1829. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1830. A_LODSB:
  1831. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1832. A_LODSW:
  1833. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1834. {$ifdef x86_64}
  1835. A_LODSQ:
  1836. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1837. {$endif x86_64}
  1838. A_LODSD:
  1839. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1840. A_FSTSW, A_FNSTSW:
  1841. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1842. else
  1843. begin
  1844. with insprop[p.opcode] do
  1845. begin
  1846. if (
  1847. { xor %reg,%reg etc. is classed as a new value }
  1848. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1849. MatchOpType(p, top_reg, top_reg) and
  1850. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1851. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1852. ) then
  1853. begin
  1854. Result := True;
  1855. Exit;
  1856. end;
  1857. { Make sure the entire register is overwritten }
  1858. if (getregtype(reg) = R_INTREGISTER) then
  1859. begin
  1860. if (p.ops > 0) then
  1861. begin
  1862. if RegInOp(reg, p.oper[0]^) then
  1863. begin
  1864. if (p.oper[0]^.typ = top_ref) then
  1865. begin
  1866. if RegInRef(reg, p.oper[0]^.ref^) then
  1867. begin
  1868. Result := False;
  1869. Exit;
  1870. end;
  1871. end
  1872. else if (p.oper[0]^.typ = top_reg) then
  1873. begin
  1874. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1875. begin
  1876. Result := False;
  1877. Exit;
  1878. end
  1879. else if ([Ch_WOp1]*Ch<>[]) then
  1880. begin
  1881. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1882. Result := True
  1883. else
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end;
  1889. end;
  1890. end;
  1891. if (p.ops > 1) then
  1892. begin
  1893. if RegInOp(reg, p.oper[1]^) then
  1894. begin
  1895. if (p.oper[1]^.typ = top_ref) then
  1896. begin
  1897. if RegInRef(reg, p.oper[1]^.ref^) then
  1898. begin
  1899. Result := False;
  1900. Exit;
  1901. end;
  1902. end
  1903. else if (p.oper[1]^.typ = top_reg) then
  1904. begin
  1905. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1906. begin
  1907. Result := False;
  1908. Exit;
  1909. end
  1910. else if ([Ch_WOp2]*Ch<>[]) then
  1911. begin
  1912. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1913. Result := True
  1914. else
  1915. begin
  1916. Result := False;
  1917. Exit;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. if (p.ops > 2) then
  1923. begin
  1924. if RegInOp(reg, p.oper[2]^) then
  1925. begin
  1926. if (p.oper[2]^.typ = top_ref) then
  1927. begin
  1928. if RegInRef(reg, p.oper[2]^.ref^) then
  1929. begin
  1930. Result := False;
  1931. Exit;
  1932. end;
  1933. end
  1934. else if (p.oper[2]^.typ = top_reg) then
  1935. begin
  1936. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1937. begin
  1938. Result := False;
  1939. Exit;
  1940. end
  1941. else if ([Ch_WOp3]*Ch<>[]) then
  1942. begin
  1943. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1944. Result := True
  1945. else
  1946. begin
  1947. Result := False;
  1948. Exit;
  1949. end;
  1950. end;
  1951. end;
  1952. end;
  1953. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1954. begin
  1955. if (p.oper[3]^.typ = top_ref) then
  1956. begin
  1957. if RegInRef(reg, p.oper[3]^.ref^) then
  1958. begin
  1959. Result := False;
  1960. Exit;
  1961. end;
  1962. end
  1963. else if (p.oper[3]^.typ = top_reg) then
  1964. begin
  1965. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1966. begin
  1967. Result := False;
  1968. Exit;
  1969. end
  1970. else if ([Ch_WOp4]*Ch<>[]) then
  1971. begin
  1972. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1973. Result := True
  1974. else
  1975. begin
  1976. Result := False;
  1977. Exit;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. end;
  1985. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1986. case getsupreg(reg) of
  1987. RS_EAX:
  1988. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1989. begin
  1990. Result := True;
  1991. Exit;
  1992. end;
  1993. RS_ECX:
  1994. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1995. begin
  1996. Result := True;
  1997. Exit;
  1998. end;
  1999. RS_EDX:
  2000. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2001. begin
  2002. Result := True;
  2003. Exit;
  2004. end;
  2005. RS_EBX:
  2006. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2007. begin
  2008. Result := True;
  2009. Exit;
  2010. end;
  2011. RS_ESP:
  2012. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2013. begin
  2014. Result := True;
  2015. Exit;
  2016. end;
  2017. RS_EBP:
  2018. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2019. begin
  2020. Result := True;
  2021. Exit;
  2022. end;
  2023. RS_ESI:
  2024. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2025. begin
  2026. Result := True;
  2027. Exit;
  2028. end;
  2029. RS_EDI:
  2030. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2031. begin
  2032. Result := True;
  2033. Exit;
  2034. end;
  2035. else
  2036. ;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. end;
  2043. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2044. var
  2045. hp2,hp3 : tai;
  2046. begin
  2047. { some x86-64 issue a NOP before the real exit code }
  2048. if MatchInstruction(p,A_NOP,[]) then
  2049. GetNextInstruction(p,p);
  2050. result:=assigned(p) and (p.typ=ait_instruction) and
  2051. ((taicpu(p).opcode = A_RET) or
  2052. ((taicpu(p).opcode=A_LEAVE) and
  2053. GetNextInstruction(p,hp2) and
  2054. MatchInstruction(hp2,A_RET,[S_NO])
  2055. ) or
  2056. (((taicpu(p).opcode=A_LEA) and
  2057. MatchOpType(taicpu(p),top_ref,top_reg) and
  2058. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2059. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2060. ) and
  2061. GetNextInstruction(p,hp2) and
  2062. MatchInstruction(hp2,A_RET,[S_NO])
  2063. ) or
  2064. ((((taicpu(p).opcode=A_MOV) and
  2065. MatchOpType(taicpu(p),top_reg,top_reg) and
  2066. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2067. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2068. ((taicpu(p).opcode=A_LEA) and
  2069. MatchOpType(taicpu(p),top_ref,top_reg) and
  2070. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2071. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2072. )
  2073. ) and
  2074. GetNextInstruction(p,hp2) and
  2075. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2076. MatchOpType(taicpu(hp2),top_reg) and
  2077. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2078. GetNextInstruction(hp2,hp3) and
  2079. MatchInstruction(hp3,A_RET,[S_NO])
  2080. )
  2081. );
  2082. end;
  2083. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2084. begin
  2085. isFoldableArithOp := False;
  2086. case hp1.opcode of
  2087. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2088. isFoldableArithOp :=
  2089. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2090. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2091. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2092. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2093. (taicpu(hp1).oper[1]^.reg = reg);
  2094. A_INC,A_DEC,A_NEG,A_NOT:
  2095. isFoldableArithOp :=
  2096. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2097. (taicpu(hp1).oper[0]^.reg = reg);
  2098. else
  2099. ;
  2100. end;
  2101. end;
  2102. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2103. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2104. var
  2105. hp2: tai;
  2106. begin
  2107. hp2 := p;
  2108. repeat
  2109. hp2 := tai(hp2.previous);
  2110. if assigned(hp2) and
  2111. (hp2.typ = ait_regalloc) and
  2112. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2113. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2114. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2115. begin
  2116. RemoveInstruction(hp2);
  2117. break;
  2118. end;
  2119. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2120. end;
  2121. begin
  2122. case current_procinfo.procdef.returndef.typ of
  2123. arraydef,recorddef,pointerdef,
  2124. stringdef,enumdef,procdef,objectdef,errordef,
  2125. filedef,setdef,procvardef,
  2126. classrefdef,forwarddef:
  2127. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2128. orddef:
  2129. if current_procinfo.procdef.returndef.size <> 0 then
  2130. begin
  2131. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2132. { for int64/qword }
  2133. if current_procinfo.procdef.returndef.size = 8 then
  2134. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2135. end;
  2136. else
  2137. ;
  2138. end;
  2139. end;
  2140. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2141. var
  2142. hp1: tai;
  2143. operswap: poper;
  2144. begin
  2145. Result := False;
  2146. { Optimise:
  2147. cmov(c) %reg1,%reg2
  2148. mov %reg2,%reg1
  2149. (%reg2 dealloc.)
  2150. To:
  2151. cmov(~c) %reg2,%reg1
  2152. }
  2153. if (taicpu(p).oper[0]^.typ = top_reg) then
  2154. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2155. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2156. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2157. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2161. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2164. { Save time by swapping the pointers (they're both registers, so
  2165. we don't need to worry about reference counts) }
  2166. operswap := taicpu(p).oper[0];
  2167. taicpu(p).oper[0] := taicpu(p).oper[1];
  2168. taicpu(p).oper[1] := operswap;
  2169. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2170. RemoveInstruction(hp1);
  2171. { It's still a CMOV, so we can look further ahead }
  2172. Include(OptsToCheck, aoc_ForceNewIteration);
  2173. { But first, let's see if this will get optimised again
  2174. (probably won't happen, but best to be sure) }
  2175. Continue;
  2176. end;
  2177. Break;
  2178. end;
  2179. end;
  2180. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2181. var
  2182. hp1,hp2 : tai;
  2183. begin
  2184. result:=false;
  2185. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2186. begin
  2187. { vmova* reg1,reg1
  2188. =>
  2189. <nop> }
  2190. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2191. begin
  2192. RemoveCurrentP(p);
  2193. result:=true;
  2194. exit;
  2195. end;
  2196. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2197. (hp1.typ = ait_instruction) and
  2198. (
  2199. { Under -O2 and below, the instructions are always adjacent }
  2200. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2201. (taicpu(hp1).ops <= 1) or
  2202. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2203. { If reg1 = reg3, reg1 must not be modified in between }
  2204. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2205. ) then
  2206. begin
  2207. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2208. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2209. begin
  2210. { vmova* reg1,reg2
  2211. ...
  2212. vmova* reg2,reg3
  2213. dealloc reg2
  2214. =>
  2215. vmova* reg1,reg3 }
  2216. TransferUsedRegs(TmpUsedRegs);
  2217. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2218. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2219. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2220. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2221. begin
  2222. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2223. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2226. RemoveInstruction(hp1);
  2227. result:=true;
  2228. exit;
  2229. end;
  2230. { special case:
  2231. vmova* reg1,<op>
  2232. ...
  2233. vmova* <op>,reg1
  2234. =>
  2235. vmova* reg1,<op> }
  2236. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2237. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2238. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2239. ) then
  2240. begin
  2241. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2242. RemoveInstruction(hp1);
  2243. result:=true;
  2244. exit;
  2245. end
  2246. end
  2247. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2248. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2249. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2250. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2251. ) and
  2252. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2253. begin
  2254. { vmova* reg1,reg2
  2255. ...
  2256. vmovs* reg2,<op>
  2257. dealloc reg2
  2258. =>
  2259. vmovs* reg1,<op> }
  2260. TransferUsedRegs(TmpUsedRegs);
  2261. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2262. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2263. begin
  2264. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2265. taicpu(p).opcode:=taicpu(hp1).opcode;
  2266. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2267. TransferUsedRegs(TmpUsedRegs);
  2268. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2269. RemoveInstruction(hp1);
  2270. result:=true;
  2271. exit;
  2272. end
  2273. end;
  2274. if MatchInstruction(hp1,[A_VFMADDPD,
  2275. A_VFMADD132PD,
  2276. A_VFMADD132PS,
  2277. A_VFMADD132SD,
  2278. A_VFMADD132SS,
  2279. A_VFMADD213PD,
  2280. A_VFMADD213PS,
  2281. A_VFMADD213SD,
  2282. A_VFMADD213SS,
  2283. A_VFMADD231PD,
  2284. A_VFMADD231PS,
  2285. A_VFMADD231SD,
  2286. A_VFMADD231SS,
  2287. A_VFMADDSUB132PD,
  2288. A_VFMADDSUB132PS,
  2289. A_VFMADDSUB213PD,
  2290. A_VFMADDSUB213PS,
  2291. A_VFMADDSUB231PD,
  2292. A_VFMADDSUB231PS,
  2293. A_VFMSUB132PD,
  2294. A_VFMSUB132PS,
  2295. A_VFMSUB132SD,
  2296. A_VFMSUB132SS,
  2297. A_VFMSUB213PD,
  2298. A_VFMSUB213PS,
  2299. A_VFMSUB213SD,
  2300. A_VFMSUB213SS,
  2301. A_VFMSUB231PD,
  2302. A_VFMSUB231PS,
  2303. A_VFMSUB231SD,
  2304. A_VFMSUB231SS,
  2305. A_VFMSUBADD132PD,
  2306. A_VFMSUBADD132PS,
  2307. A_VFMSUBADD213PD,
  2308. A_VFMSUBADD213PS,
  2309. A_VFMSUBADD231PD,
  2310. A_VFMSUBADD231PS,
  2311. A_VFNMADD132PD,
  2312. A_VFNMADD132PS,
  2313. A_VFNMADD132SD,
  2314. A_VFNMADD132SS,
  2315. A_VFNMADD213PD,
  2316. A_VFNMADD213PS,
  2317. A_VFNMADD213SD,
  2318. A_VFNMADD213SS,
  2319. A_VFNMADD231PD,
  2320. A_VFNMADD231PS,
  2321. A_VFNMADD231SD,
  2322. A_VFNMADD231SS,
  2323. A_VFNMSUB132PD,
  2324. A_VFNMSUB132PS,
  2325. A_VFNMSUB132SD,
  2326. A_VFNMSUB132SS,
  2327. A_VFNMSUB213PD,
  2328. A_VFNMSUB213PS,
  2329. A_VFNMSUB213SD,
  2330. A_VFNMSUB213SS,
  2331. A_VFNMSUB231PD,
  2332. A_VFNMSUB231PS,
  2333. A_VFNMSUB231SD,
  2334. A_VFNMSUB231SS],[S_NO]) and
  2335. { we mix single and double opperations here because we assume that the compiler
  2336. generates vmovapd only after double operations and vmovaps only after single operations }
  2337. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2338. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2339. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2340. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2341. begin
  2342. TransferUsedRegs(TmpUsedRegs);
  2343. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2344. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2345. begin
  2346. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2347. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2348. RemoveCurrentP(p)
  2349. else
  2350. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2351. RemoveInstruction(hp2);
  2352. end;
  2353. end
  2354. else if (hp1.typ = ait_instruction) and
  2355. (((taicpu(p).opcode=A_MOVAPS) and
  2356. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2357. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2358. ((taicpu(p).opcode=A_MOVAPD) and
  2359. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2360. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2361. ) and
  2362. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2363. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2364. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2365. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2366. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2367. { change
  2368. movapX reg,reg2
  2369. addsX/subsX/... reg3, reg2
  2370. movapX reg2,reg
  2371. to
  2372. addsX/subsX/... reg3,reg
  2373. }
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2377. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2378. begin
  2379. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2380. debug_op2str(taicpu(p).opcode)+' '+
  2381. debug_op2str(taicpu(hp1).opcode)+' '+
  2382. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2383. { we cannot eliminate the first move if
  2384. the operations uses the same register for source and dest }
  2385. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2386. { Remember that hp1 is not necessarily the immediate
  2387. next instruction }
  2388. RemoveCurrentP(p);
  2389. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2390. RemoveInstruction(hp2);
  2391. result:=true;
  2392. end;
  2393. end
  2394. else if (hp1.typ = ait_instruction) and
  2395. (((taicpu(p).opcode=A_VMOVAPD) and
  2396. (taicpu(hp1).opcode=A_VCOMISD)) or
  2397. ((taicpu(p).opcode=A_VMOVAPS) and
  2398. ((taicpu(hp1).opcode=A_VCOMISS))
  2399. )
  2400. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2401. { change
  2402. movapX reg,reg1
  2403. vcomisX reg1,reg1
  2404. to
  2405. vcomisX reg,reg
  2406. }
  2407. begin
  2408. TransferUsedRegs(TmpUsedRegs);
  2409. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2411. begin
  2412. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2413. debug_op2str(taicpu(p).opcode)+' '+
  2414. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2415. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2416. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2417. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2418. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2419. RemoveCurrentP(p);
  2420. result:=true;
  2421. exit;
  2422. end;
  2423. end
  2424. end;
  2425. end;
  2426. end;
  2427. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2428. var
  2429. hp1 : tai;
  2430. begin
  2431. result:=false;
  2432. { replace
  2433. V<Op>X %mreg1,%mreg2,%mreg3
  2434. VMovX %mreg3,%mreg4
  2435. dealloc %mreg3
  2436. by
  2437. V<Op>X %mreg1,%mreg2,%mreg4
  2438. ?
  2439. }
  2440. if GetNextInstruction(p,hp1) and
  2441. { we mix single and double operations here because we assume that the compiler
  2442. generates vmovapd only after double operations and vmovaps only after single operations }
  2443. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2445. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2446. begin
  2447. TransferUsedRegs(TmpUsedRegs);
  2448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2450. begin
  2451. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2452. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2453. RemoveInstruction(hp1);
  2454. result:=true;
  2455. end;
  2456. end;
  2457. end;
  2458. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2459. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2460. begin
  2461. Result := False;
  2462. { For safety reasons, only check for exact register matches }
  2463. { Check base register }
  2464. if (ref.base = AOldReg) then
  2465. begin
  2466. ref.base := ANewReg;
  2467. Result := True;
  2468. end;
  2469. { Check index register }
  2470. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2471. begin
  2472. ref.index := ANewReg;
  2473. Result := True;
  2474. end;
  2475. end;
  2476. { Replaces all references to AOldReg in an operand to ANewReg }
  2477. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2478. var
  2479. OldSupReg, NewSupReg: TSuperRegister;
  2480. OldSubReg, NewSubReg: TSubRegister;
  2481. OldRegType: TRegisterType;
  2482. ThisOper: POper;
  2483. begin
  2484. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2485. Result := False;
  2486. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2487. InternalError(2020011801);
  2488. OldSupReg := getsupreg(AOldReg);
  2489. OldSubReg := getsubreg(AOldReg);
  2490. OldRegType := getregtype(AOldReg);
  2491. NewSupReg := getsupreg(ANewReg);
  2492. NewSubReg := getsubreg(ANewReg);
  2493. if OldRegType <> getregtype(ANewReg) then
  2494. InternalError(2020011802);
  2495. if OldSubReg <> NewSubReg then
  2496. InternalError(2020011803);
  2497. case ThisOper^.typ of
  2498. top_reg:
  2499. if (
  2500. (ThisOper^.reg = AOldReg) or
  2501. (
  2502. (OldRegType = R_INTREGISTER) and
  2503. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2504. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2505. (
  2506. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2507. {$ifndef x86_64}
  2508. and (
  2509. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2510. don't have an 8-bit representation }
  2511. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2512. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2513. )
  2514. {$endif x86_64}
  2515. )
  2516. )
  2517. ) then
  2518. begin
  2519. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2520. Result := True;
  2521. end;
  2522. top_ref:
  2523. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2524. Result := True;
  2525. else
  2526. ;
  2527. end;
  2528. end;
  2529. { Replaces all references to AOldReg in an instruction to ANewReg }
  2530. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2531. const
  2532. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2533. var
  2534. OperIdx: Integer;
  2535. begin
  2536. Result := False;
  2537. for OperIdx := 0 to p.ops - 1 do
  2538. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2539. begin
  2540. { The shift and rotate instructions can only use CL }
  2541. if not (
  2542. (OperIdx = 0) and
  2543. { This second condition just helps to avoid unnecessarily
  2544. calling MatchInstruction for 10 different opcodes }
  2545. (p.oper[0]^.reg = NR_CL) and
  2546. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2547. ) then
  2548. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2549. end
  2550. else if p.oper[OperIdx]^.typ = top_ref then
  2551. { It's okay to replace registers in references that get written to }
  2552. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2553. end;
  2554. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2555. begin
  2556. Result :=
  2557. (ref^.index = NR_NO) and
  2558. (
  2559. {$ifdef x86_64}
  2560. (
  2561. (ref^.base = NR_RIP) and
  2562. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2563. ) or
  2564. {$endif x86_64}
  2565. (ref^.refaddr = addr_full) or
  2566. (ref^.base = NR_STACK_POINTER_REG) or
  2567. (ref^.base = current_procinfo.framepointer)
  2568. );
  2569. end;
  2570. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2571. var
  2572. l: asizeint;
  2573. begin
  2574. Result := False;
  2575. { Should have been checked previously }
  2576. if p.opcode <> A_LEA then
  2577. InternalError(2020072501);
  2578. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2579. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2580. not(cs_opt_size in current_settings.optimizerswitches) then
  2581. exit;
  2582. with p.oper[0]^.ref^ do
  2583. begin
  2584. if (base <> p.oper[1]^.reg) or
  2585. (index <> NR_NO) or
  2586. assigned(symbol) then
  2587. exit;
  2588. l:=offset;
  2589. if (l=1) and UseIncDec then
  2590. begin
  2591. p.opcode:=A_INC;
  2592. p.loadreg(0,p.oper[1]^.reg);
  2593. p.ops:=1;
  2594. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2595. end
  2596. else if (l=-1) and UseIncDec then
  2597. begin
  2598. p.opcode:=A_DEC;
  2599. p.loadreg(0,p.oper[1]^.reg);
  2600. p.ops:=1;
  2601. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2602. end
  2603. else
  2604. begin
  2605. if (l<0) and (l<>-2147483648) then
  2606. begin
  2607. p.opcode:=A_SUB;
  2608. p.loadConst(0,-l);
  2609. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2610. end
  2611. else
  2612. begin
  2613. p.opcode:=A_ADD;
  2614. p.loadConst(0,l);
  2615. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2616. end;
  2617. end;
  2618. end;
  2619. Result := True;
  2620. end;
  2621. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2622. var
  2623. CurrentReg, ReplaceReg: TRegister;
  2624. begin
  2625. Result := False;
  2626. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2627. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2628. case hp.opcode of
  2629. A_FSTSW, A_FNSTSW,
  2630. A_IN, A_INS, A_OUT, A_OUTS,
  2631. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2632. { These routines have explicit operands, but they are restricted in
  2633. what they can be (e.g. IN and OUT can only read from AL, AX or
  2634. EAX. }
  2635. Exit;
  2636. A_IMUL:
  2637. begin
  2638. { The 1-operand version writes to implicit registers
  2639. The 2-operand version reads from the first operator, and reads
  2640. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2641. the 3-operand version reads from a register that it doesn't write to
  2642. }
  2643. case hp.ops of
  2644. 1:
  2645. if (
  2646. (
  2647. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2648. ) or
  2649. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2650. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2651. begin
  2652. Result := True;
  2653. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2654. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2655. end;
  2656. 2:
  2657. { Only modify the first parameter }
  2658. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2659. begin
  2660. Result := True;
  2661. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2662. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2663. end;
  2664. 3:
  2665. { Only modify the second parameter }
  2666. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2667. begin
  2668. Result := True;
  2669. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2670. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2671. end;
  2672. else
  2673. InternalError(2020012901);
  2674. end;
  2675. end;
  2676. else
  2677. if (hp.ops > 0) and
  2678. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2679. begin
  2680. Result := True;
  2681. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2682. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2683. end;
  2684. end;
  2685. end;
  2686. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2687. var
  2688. hp2, hp_regalloc: tai;
  2689. p_SourceReg, p_TargetReg: TRegister;
  2690. begin
  2691. Result := False;
  2692. { Backward optimisation. If we have:
  2693. func. %reg1,%reg2
  2694. mov %reg2,%reg3
  2695. (dealloc %reg2)
  2696. Change to:
  2697. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2698. Perform similar optimisations with 1, 3 and 4-operand instructions
  2699. that only have one output.
  2700. }
  2701. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2702. begin
  2703. p_SourceReg := taicpu(p).oper[0]^.reg;
  2704. p_TargetReg := taicpu(p).oper[1]^.reg;
  2705. TransferUsedRegs(TmpUsedRegs);
  2706. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2707. GetLastInstruction(p, hp2) and
  2708. (hp2.typ = ait_instruction) and
  2709. { Have to make sure it's an instruction that only reads from
  2710. the first operands and only writes (not reads or modifies) to
  2711. the last one; in essence, a pure function such as BSR, POPCNT
  2712. or ANDN }
  2713. (
  2714. (
  2715. (taicpu(hp2).ops = 1) and
  2716. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2717. ) or
  2718. (
  2719. (taicpu(hp2).ops = 2) and
  2720. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2721. ) or
  2722. (
  2723. (taicpu(hp2).ops = 3) and
  2724. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2725. ) or
  2726. (
  2727. (taicpu(hp2).ops = 4) and
  2728. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2729. )
  2730. ) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2732. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2733. begin
  2734. case taicpu(hp2).opcode of
  2735. A_FSTSW, A_FNSTSW,
  2736. A_IN, A_INS, A_OUT, A_OUTS,
  2737. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2738. { These routines have explicit operands, but they are restricted in
  2739. what they can be (e.g. IN and OUT can only read from AL, AX or
  2740. EAX. }
  2741. ;
  2742. else
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2745. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2746. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2747. if Assigned(hp_regalloc) then
  2748. begin
  2749. Asml.Remove(hp_regalloc);
  2750. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2751. begin
  2752. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2753. hp_regalloc.Free;
  2754. end
  2755. else
  2756. { If the register is not explicitly deallocated, it's
  2757. being reused, so move the allocation to after func. }
  2758. AsmL.InsertAfter(hp_regalloc, hp2);
  2759. end;
  2760. if not RegInInstruction(p_TargetReg, hp2) then
  2761. begin
  2762. TransferUsedRegs(TmpUsedRegs);
  2763. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2764. end;
  2765. { Actually make the changes }
  2766. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2767. RemoveCurrentp(p, hp1);
  2768. { If the Func was another MOV instruction, we might get
  2769. "mov %reg,%reg" that doesn't get removed in Pass 2
  2770. otherwise, so deal with it here (also do something
  2771. similar with lea (%reg),%reg}
  2772. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2773. begin
  2774. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2775. if p = hp2 then
  2776. RemoveCurrentp(p)
  2777. else
  2778. RemoveInstruction(hp2);
  2779. end;
  2780. Result := True;
  2781. Exit;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. end;
  2787. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2788. begin
  2789. Result := False;
  2790. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2791. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2792. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2793. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2794. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2795. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2797. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2800. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2801. Result := True;
  2802. Include(OptsToCheck, aoc_ForceNewIteration);
  2803. end;
  2804. end;
  2805. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2806. var
  2807. hp1, hp2, hp3, hp4: tai;
  2808. DoOptimisation, TempBool: Boolean;
  2809. {$ifdef x86_64}
  2810. NewConst: TCGInt;
  2811. {$endif x86_64}
  2812. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2813. begin
  2814. if taicpu(hp1).opcode = signed_movop then
  2815. begin
  2816. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2817. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2818. end
  2819. else
  2820. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2821. end;
  2822. function TryConstMerge(var p1, p2: tai): Boolean;
  2823. var
  2824. ThisRef: TReference;
  2825. begin
  2826. Result := False;
  2827. ThisRef := taicpu(p2).oper[1]^.ref^;
  2828. { Only permit writes to the stack, since we can guarantee alignment with that }
  2829. if (ThisRef.index = NR_NO) and
  2830. (
  2831. (ThisRef.base = NR_STACK_POINTER_REG) or
  2832. (ThisRef.base = current_procinfo.framepointer)
  2833. ) then
  2834. begin
  2835. case taicpu(p).opsize of
  2836. S_B:
  2837. begin
  2838. { Word writes must be on a 2-byte boundary }
  2839. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2840. begin
  2841. { Reduce offset of second reference to see if it is sequential with the first }
  2842. Dec(ThisRef.offset, 1);
  2843. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2844. begin
  2845. { Make sure the constants aren't represented as a
  2846. negative number, as these won't merge properly }
  2847. taicpu(p1).opsize := S_W;
  2848. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2849. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2850. RemoveInstruction(p2);
  2851. Result := True;
  2852. end;
  2853. end;
  2854. end;
  2855. S_W:
  2856. begin
  2857. { Longword writes must be on a 4-byte boundary }
  2858. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2859. begin
  2860. { Reduce offset of second reference to see if it is sequential with the first }
  2861. Dec(ThisRef.offset, 2);
  2862. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2863. begin
  2864. { Make sure the constants aren't represented as a
  2865. negative number, as these won't merge properly }
  2866. taicpu(p1).opsize := S_L;
  2867. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2868. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2869. RemoveInstruction(p2);
  2870. Result := True;
  2871. end;
  2872. end;
  2873. end;
  2874. {$ifdef x86_64}
  2875. S_L:
  2876. begin
  2877. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2878. see if the constants can be encoded this way. }
  2879. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2880. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2881. { Quadword writes must be on an 8-byte boundary }
  2882. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2883. begin
  2884. { Reduce offset of second reference to see if it is sequential with the first }
  2885. Dec(ThisRef.offset, 4);
  2886. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2887. begin
  2888. { Make sure the constants aren't represented as a
  2889. negative number, as these won't merge properly }
  2890. taicpu(p1).opsize := S_Q;
  2891. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2892. taicpu(p1).oper[0]^.val := NewConst;
  2893. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$endif x86_64}
  2900. else
  2901. ;
  2902. end;
  2903. end;
  2904. end;
  2905. var
  2906. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2907. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2908. NewSize: topsize; NewOffset: asizeint;
  2909. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2910. SourceRef, TargetRef: TReference;
  2911. MovAligned, MovUnaligned: TAsmOp;
  2912. ThisRef: TReference;
  2913. JumpTracking: TLinkedList;
  2914. begin
  2915. Result:=false;
  2916. { remove mov reg1,reg1? }
  2917. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2918. then
  2919. begin
  2920. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2921. { take care of the register (de)allocs following p }
  2922. RemoveCurrentP(p);
  2923. Result := True;
  2924. exit;
  2925. end;
  2926. { Prevent compiler warnings }
  2927. p_SourceReg := NR_NO;
  2928. p_TargetReg := NR_NO;
  2929. if taicpu(p).oper[1]^.typ = top_reg then
  2930. begin
  2931. { Saves on a large number of dereferences }
  2932. p_TargetReg := taicpu(p).oper[1]^.reg;
  2933. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2934. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2935. else
  2936. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2937. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2938. while True do
  2939. begin
  2940. if (taicpu(hp1).opcode = A_AND) and
  2941. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2942. begin
  2943. { A change has occurred, just not in p }
  2944. Include(OptsToCheck, aoc_ForceNewIteration);
  2945. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2946. begin
  2947. case taicpu(p).opsize of
  2948. S_L:
  2949. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2950. begin
  2951. { Optimize out:
  2952. mov x, %reg
  2953. and ffffffffh, %reg
  2954. }
  2955. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2956. RemoveInstruction(hp1);
  2957. Result:=true;
  2958. exit;
  2959. end;
  2960. S_Q: { TODO: Confirm if this is even possible }
  2961. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2962. begin
  2963. { Optimize out:
  2964. mov x, %reg
  2965. and ffffffffffffffffh, %reg
  2966. }
  2967. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2968. RemoveInstruction(hp1);
  2969. Result:=true;
  2970. exit;
  2971. end;
  2972. else
  2973. ;
  2974. end;
  2975. if (
  2976. { Make sure that if a reference is used, its registers
  2977. are not modified in between }
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_reg) and
  2980. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2981. ) or
  2982. (
  2983. (taicpu(p).oper[0]^.typ = top_ref) and
  2984. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2985. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2986. )
  2987. ) and
  2988. GetNextInstruction(hp1,hp2) and
  2989. MatchInstruction(hp2,A_TEST,[]) and
  2990. (
  2991. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2992. (
  2993. { If the register being tested is smaller than the one
  2994. that received a bitwise AND, permit it if the constant
  2995. fits into the smaller size }
  2996. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2997. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2998. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2999. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3000. (
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3003. (taicpu(hp1).oper[0]^.val <= $FF)
  3004. ) or
  3005. (
  3006. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3007. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3008. {$ifdef x86_64}
  3009. ) or
  3010. (
  3011. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3012. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3013. {$endif x86_64}
  3014. )
  3015. )
  3016. )
  3017. ) and
  3018. (
  3019. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3020. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3021. ) and
  3022. GetNextInstruction(hp2,hp3) and
  3023. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3024. (taicpu(hp3).condition in [C_E,C_NE]) then
  3025. begin
  3026. TransferUsedRegs(TmpUsedRegs);
  3027. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3028. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3029. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3030. begin
  3031. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3032. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3033. taicpu(hp1).opcode:=A_TEST;
  3034. { Shrink the TEST instruction down to the smallest possible size }
  3035. case taicpu(hp1).oper[0]^.val of
  3036. 0..255:
  3037. if (taicpu(hp1).opsize <> S_B)
  3038. {$ifndef x86_64}
  3039. and (
  3040. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3041. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3042. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3043. )
  3044. {$endif x86_64}
  3045. then
  3046. begin
  3047. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3048. { Only print debug message if the TEST instruction
  3049. is a different size before and after }
  3050. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3051. taicpu(hp1).opsize := S_B;
  3052. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3053. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3054. end;
  3055. 256..65535:
  3056. if (taicpu(hp1).opsize <> S_W) then
  3057. begin
  3058. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3059. { Only print debug message if the TEST instruction
  3060. is a different size before and after }
  3061. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3062. taicpu(hp1).opsize := S_W;
  3063. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3064. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3065. end;
  3066. {$ifdef x86_64}
  3067. 65536..$7FFFFFFF:
  3068. if (taicpu(hp1).opsize <> S_L) then
  3069. begin
  3070. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3071. { Only print debug message if the TEST instruction
  3072. is a different size before and after }
  3073. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3074. taicpu(hp1).opsize := S_L;
  3075. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3076. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3077. end;
  3078. {$endif x86_64}
  3079. else
  3080. ;
  3081. end;
  3082. RemoveInstruction(hp2);
  3083. RemoveCurrentP(p);
  3084. Result:=true;
  3085. exit;
  3086. end;
  3087. end;
  3088. end;
  3089. if IsMOVZXAcceptable and
  3090. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3091. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3092. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3093. then
  3094. begin
  3095. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3096. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3097. case taicpu(p).opsize of
  3098. S_B:
  3099. if (taicpu(hp1).oper[0]^.val = $ff) then
  3100. begin
  3101. { Convert:
  3102. movb x, %regl movb x, %regl
  3103. andw ffh, %regw andl ffh, %regd
  3104. To:
  3105. movzbw x, %regd movzbl x, %regd
  3106. (Identical registers, just different sizes)
  3107. }
  3108. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3109. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3110. case taicpu(hp1).opsize of
  3111. S_W: NewSize := S_BW;
  3112. S_L: NewSize := S_BL;
  3113. {$ifdef x86_64}
  3114. S_Q: NewSize := S_BQ;
  3115. {$endif x86_64}
  3116. else
  3117. InternalError(2018011510);
  3118. end;
  3119. end
  3120. else
  3121. NewSize := S_NO;
  3122. S_W:
  3123. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3124. begin
  3125. { Convert:
  3126. movw x, %regw
  3127. andl ffffh, %regd
  3128. To:
  3129. movzwl x, %regd
  3130. (Identical registers, just different sizes)
  3131. }
  3132. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3133. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3134. case taicpu(hp1).opsize of
  3135. S_L: NewSize := S_WL;
  3136. {$ifdef x86_64}
  3137. S_Q: NewSize := S_WQ;
  3138. {$endif x86_64}
  3139. else
  3140. InternalError(2018011511);
  3141. end;
  3142. end
  3143. else
  3144. NewSize := S_NO;
  3145. else
  3146. NewSize := S_NO;
  3147. end;
  3148. if NewSize <> S_NO then
  3149. begin
  3150. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3151. { The actual optimization }
  3152. taicpu(p).opcode := A_MOVZX;
  3153. taicpu(p).changeopsize(NewSize);
  3154. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3155. { Make sure we deal with any reference counts that were increased }
  3156. if taicpu(hp1).oper[1]^.typ = top_ref then
  3157. begin
  3158. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3159. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3160. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3161. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3162. end;
  3163. { Safeguard if "and" is followed by a conditional command }
  3164. TransferUsedRegs(TmpUsedRegs);
  3165. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3166. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3167. begin
  3168. { At this point, the "and" command is effectively equivalent to
  3169. "test %reg,%reg". This will be handled separately by the
  3170. Peephole Optimizer. [Kit] }
  3171. DebugMsg(SPeepholeOptimization + PreMessage +
  3172. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3173. end
  3174. else
  3175. begin
  3176. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3177. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3178. RemoveInstruction(hp1);
  3179. end;
  3180. Result := True;
  3181. Exit;
  3182. { Go through DeepMOVOpt again (jump to "while True do") }
  3183. Continue;
  3184. end;
  3185. end;
  3186. end;
  3187. if taicpu(p).oper[0]^.typ = top_reg then
  3188. begin
  3189. p_SourceReg := taicpu(p).oper[0]^.reg;
  3190. { Look for:
  3191. mov %reg1,%reg2
  3192. ??? %reg2,r/m
  3193. Change to:
  3194. mov %reg1,%reg2
  3195. ??? %reg1,r/m
  3196. }
  3197. if RegReadByInstruction(p_TargetReg, hp1) and
  3198. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3199. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3200. begin
  3201. { A change has occurred, just not in p }
  3202. Include(OptsToCheck, aoc_ForceNewIteration);
  3203. TransferUsedRegs(TmpUsedRegs);
  3204. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3205. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3206. { Just in case something didn't get modified (e.g. an
  3207. implicit register) }
  3208. not RegReadByInstruction(p_TargetReg, hp1) then
  3209. begin
  3210. { We can remove the original MOV }
  3211. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3212. RemoveCurrentP(p);
  3213. { UsedRegs got updated by RemoveCurrentp }
  3214. Result := True;
  3215. Exit;
  3216. end;
  3217. { If we know a MOV instruction has become a null operation, we might as well
  3218. get rid of it now to save time. }
  3219. if (taicpu(hp1).opcode = A_MOV) and
  3220. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3221. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3222. { Just being a register is enough to confirm it's a null operation }
  3223. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3224. begin
  3225. Result := True;
  3226. { Speed-up to reduce a pipeline stall... if we had something like...
  3227. movl %eax,%edx
  3228. movw %dx,%ax
  3229. ... the second instruction would change to movw %ax,%ax, but
  3230. given that it is now %ax that's active rather than %eax,
  3231. penalties might occur due to a partial register write, so instead,
  3232. change it to a MOVZX instruction when optimising for speed.
  3233. }
  3234. if not (cs_opt_size in current_settings.optimizerswitches) and
  3235. IsMOVZXAcceptable and
  3236. (taicpu(hp1).opsize < taicpu(p).opsize)
  3237. {$ifdef x86_64}
  3238. { operations already implicitly set the upper 64 bits to zero }
  3239. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3240. {$endif x86_64}
  3241. then
  3242. begin
  3243. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3244. case taicpu(p).opsize of
  3245. S_W:
  3246. if taicpu(hp1).opsize = S_B then
  3247. taicpu(hp1).opsize := S_BL
  3248. else
  3249. InternalError(2020012911);
  3250. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3251. case taicpu(hp1).opsize of
  3252. S_B:
  3253. taicpu(hp1).opsize := S_BL;
  3254. S_W:
  3255. taicpu(hp1).opsize := S_WL;
  3256. else
  3257. InternalError(2020012912);
  3258. end;
  3259. else
  3260. InternalError(2020012910);
  3261. end;
  3262. taicpu(hp1).opcode := A_MOVZX;
  3263. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3264. end
  3265. else
  3266. begin
  3267. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3268. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3269. RemoveInstruction(hp1);
  3270. { The instruction after what was hp1 is now the immediate next instruction,
  3271. so we can continue to make optimisations if it's present }
  3272. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3273. Exit;
  3274. hp1 := hp2;
  3275. end;
  3276. end;
  3277. end;
  3278. {$ifdef x86_64}
  3279. { Change:
  3280. movl %reg1l,%reg2l
  3281. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3282. To:
  3283. movl %reg1l,%reg2l
  3284. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3285. If %reg1 = %reg3, convert to:
  3286. movl %reg1l,%reg2l
  3287. andl %reg1l,%reg1l
  3288. }
  3289. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3290. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3291. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3292. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3293. begin
  3294. TransferUsedRegs(TmpUsedRegs);
  3295. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3296. taicpu(hp1).opsize := S_L;
  3297. taicpu(hp1).loadreg(0, p_SourceReg);
  3298. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3299. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3300. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3301. begin
  3302. { %reg1 = %reg3 }
  3303. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3304. taicpu(hp1).opcode := A_AND;
  3305. end
  3306. else
  3307. begin
  3308. { %reg1 <> %reg3 }
  3309. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3310. end;
  3311. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3312. begin
  3313. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3314. RemoveCurrentP(p);
  3315. Result := True;
  3316. Exit;
  3317. end
  3318. else
  3319. begin
  3320. { Initial instruction wasn't actually changed }
  3321. Include(OptsToCheck, aoc_ForceNewIteration);
  3322. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3323. appears below since %reg1 has technically changed }
  3324. if taicpu(hp1).opcode = A_AND then
  3325. Exit;
  3326. end;
  3327. end;
  3328. {$endif x86_64}
  3329. end
  3330. else if taicpu(p).oper[0]^.typ = top_const then
  3331. begin
  3332. if (taicpu(hp1).opcode = A_OR) and
  3333. (taicpu(p).oper[1]^.typ = top_reg) and
  3334. MatchOperand(taicpu(p).oper[0]^, 0) and
  3335. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3336. begin
  3337. { mov 0, %reg
  3338. or ###,%reg
  3339. Change to (only if the flags are not used):
  3340. mov ###,%reg
  3341. }
  3342. TransferUsedRegs(TmpUsedRegs);
  3343. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3344. DoOptimisation := True;
  3345. { Even if the flags are used, we might be able to do the optimisation
  3346. if the conditions are predictable }
  3347. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3348. begin
  3349. { Only perform if ### = %reg (the same register) or equal to 0,
  3350. so %reg is guaranteed to still have a value of zero }
  3351. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3352. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3353. begin
  3354. hp2 := hp1;
  3355. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3356. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3357. GetNextInstruction(hp2, hp3) do
  3358. begin
  3359. { Don't continue modifying if the flags state is getting changed }
  3360. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3361. Break;
  3362. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3363. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3364. begin
  3365. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3366. begin
  3367. { Condition is always true }
  3368. case taicpu(hp3).opcode of
  3369. A_Jcc:
  3370. begin
  3371. { Check for jump shortcuts before we destroy the condition }
  3372. hp4 := hp3;
  3373. DoJumpOptimizations(hp3, TempBool);
  3374. { Make sure hp3 hasn't changed }
  3375. if (hp4 = hp3) then
  3376. begin
  3377. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3378. MakeUnconditional(taicpu(hp3));
  3379. end;
  3380. Result := True;
  3381. end;
  3382. A_CMOVcc:
  3383. begin
  3384. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3385. taicpu(hp3).opcode := A_MOV;
  3386. taicpu(hp3).condition := C_None;
  3387. Result := True;
  3388. end;
  3389. A_SETcc:
  3390. begin
  3391. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3392. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3393. taicpu(hp3).opcode := A_MOV;
  3394. taicpu(hp3).ops := 2;
  3395. taicpu(hp3).condition := C_None;
  3396. taicpu(hp3).opsize := S_B;
  3397. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3398. taicpu(hp3).loadconst(0, 1);
  3399. Result := True;
  3400. end;
  3401. else
  3402. InternalError(2021090701);
  3403. end;
  3404. end
  3405. 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
  3406. begin
  3407. { Condition is always false }
  3408. case taicpu(hp3).opcode of
  3409. A_Jcc:
  3410. begin
  3411. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3412. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3413. RemoveInstruction(hp3);
  3414. Result := True;
  3415. { Since hp3 was deleted, hp2 must not be updated }
  3416. Continue;
  3417. end;
  3418. A_CMOVcc:
  3419. begin
  3420. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3421. RemoveInstruction(hp3);
  3422. Result := True;
  3423. { Since hp3 was deleted, hp2 must not be updated }
  3424. Continue;
  3425. end;
  3426. A_SETcc:
  3427. begin
  3428. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3429. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3430. taicpu(hp3).opcode := A_MOV;
  3431. taicpu(hp3).ops := 2;
  3432. taicpu(hp3).condition := C_None;
  3433. taicpu(hp3).opsize := S_B;
  3434. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3435. taicpu(hp3).loadconst(0, 0);
  3436. Result := True;
  3437. end;
  3438. else
  3439. InternalError(2021090702);
  3440. end;
  3441. end
  3442. else
  3443. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3444. DoOptimisation := False;
  3445. end;
  3446. hp2 := hp3;
  3447. end;
  3448. if DoOptimisation then
  3449. begin
  3450. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3451. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3452. { Flags are still in use - don't optimise }
  3453. DoOptimisation := False;
  3454. end;
  3455. end
  3456. else
  3457. DoOptimisation := False;
  3458. end;
  3459. if DoOptimisation then
  3460. begin
  3461. {$ifdef x86_64}
  3462. { OR only supports 32-bit sign-extended constants for 64-bit
  3463. instructions, so compensate for this if the constant is
  3464. encoded as a value greater than or equal to 2^31 }
  3465. if (taicpu(hp1).opsize = S_Q) and
  3466. (taicpu(hp1).oper[0]^.typ = top_const) and
  3467. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3468. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3469. {$endif x86_64}
  3470. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3471. taicpu(hp1).opcode := A_MOV;
  3472. RemoveCurrentP(p);
  3473. Result := True;
  3474. Exit;
  3475. end;
  3476. end;
  3477. end
  3478. else if
  3479. { oper[0] is a reference }
  3480. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3481. begin
  3482. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3483. begin
  3484. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3485. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3486. ) or
  3487. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3488. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3489. )
  3490. ) and
  3491. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3492. { mov ref,reg1
  3493. lea (reg1,reg2),reg2
  3494. to
  3495. add ref,reg2 }
  3496. begin
  3497. TransferUsedRegs(TmpUsedRegs);
  3498. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3499. { If the flags register is in use, don't change the instruction to an
  3500. ADD otherwise this will scramble the flags. [Kit] }
  3501. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3502. { reg1 may not be used afterwards }
  3503. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3504. begin
  3505. Taicpu(hp1).opcode:=A_ADD;
  3506. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3507. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3508. RemoveCurrentp(p);
  3509. result:=true;
  3510. exit;
  3511. end;
  3512. end;
  3513. { If the LEA instruction can be converted into an arithmetic instruction,
  3514. it may be possible to then fold it in the next optimisation. }
  3515. if ConvertLEA(taicpu(hp1)) then
  3516. Include(OptsToCheck, aoc_ForceNewIteration);
  3517. end;
  3518. {
  3519. mov ref,reg0
  3520. <op> reg0,reg1
  3521. dealloc reg0
  3522. to
  3523. <op> ref,reg1
  3524. }
  3525. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3526. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3527. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3528. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3529. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3530. begin
  3531. TransferUsedRegs(TmpUsedRegs);
  3532. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3533. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3534. begin
  3535. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3536. { loadref increases the reference count, so decrement it again }
  3537. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3538. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3539. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3540. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3541. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3542. { See if we can remove the allocation of reg0 }
  3543. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3544. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3545. RemoveCurrentp(p);
  3546. Result:=true;
  3547. exit;
  3548. end;
  3549. end;
  3550. end;
  3551. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3552. overwrites the original destination register. e.g.
  3553. movl ###,%reg2d
  3554. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3555. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3556. }
  3557. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3559. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3560. begin
  3561. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3562. begin
  3563. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3564. case taicpu(p).oper[0]^.typ of
  3565. top_const:
  3566. { We have something like:
  3567. movb $x, %regb
  3568. movzbl %regb,%regd
  3569. Change to:
  3570. movl $x, %regd
  3571. }
  3572. begin
  3573. case taicpu(hp1).opsize of
  3574. S_BW:
  3575. begin
  3576. convert_mov_value(A_MOVSX, $FF);
  3577. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3578. taicpu(p).opsize := S_W;
  3579. end;
  3580. S_BL:
  3581. begin
  3582. convert_mov_value(A_MOVSX, $FF);
  3583. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3584. taicpu(p).opsize := S_L;
  3585. end;
  3586. S_WL:
  3587. begin
  3588. convert_mov_value(A_MOVSX, $FFFF);
  3589. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3590. taicpu(p).opsize := S_L;
  3591. end;
  3592. {$ifdef x86_64}
  3593. S_BQ:
  3594. begin
  3595. convert_mov_value(A_MOVSX, $FF);
  3596. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3597. taicpu(p).opsize := S_Q;
  3598. end;
  3599. S_WQ:
  3600. begin
  3601. convert_mov_value(A_MOVSX, $FFFF);
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3603. taicpu(p).opsize := S_Q;
  3604. end;
  3605. S_LQ:
  3606. begin
  3607. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3608. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3609. taicpu(p).opsize := S_Q;
  3610. end;
  3611. {$endif x86_64}
  3612. else
  3613. { If hp1 was a MOV instruction, it should have been
  3614. optimised already }
  3615. InternalError(2020021001);
  3616. end;
  3617. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3618. RemoveInstruction(hp1);
  3619. Result := True;
  3620. Exit;
  3621. end;
  3622. top_ref:
  3623. begin
  3624. { We have something like:
  3625. movb mem, %regb
  3626. movzbl %regb,%regd
  3627. Change to:
  3628. movzbl mem, %regd
  3629. }
  3630. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3631. begin
  3632. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3633. taicpu(p).opcode := taicpu(hp1).opcode;
  3634. taicpu(p).opsize := taicpu(hp1).opsize;
  3635. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3636. RemoveInstruction(hp1);
  3637. Result := True;
  3638. Exit;
  3639. end;
  3640. end;
  3641. else
  3642. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3643. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3644. Exit;
  3645. end;
  3646. end
  3647. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3648. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3649. optimised }
  3650. else
  3651. begin
  3652. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3653. RemoveCurrentP(p);
  3654. Result := True;
  3655. Exit;
  3656. end;
  3657. end;
  3658. if (taicpu(hp1).opcode = A_MOV) and
  3659. (
  3660. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3661. {$ifdef x86_64}
  3662. or (
  3663. { Permit zero extension from 32- to 64-bit when writing
  3664. a constant (it will be checked to see if it fits into
  3665. a signed 32-bit integer) }
  3666. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3667. (
  3668. { Valid situations... writing an unsigned 32-bit
  3669. immediate, or the destination is a 64-bit register }
  3670. (taicpu(p).oper[0]^.typ = top_const) or
  3671. (taicpu(hp1).oper[1]^.typ = top_reg)
  3672. ) and
  3673. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3674. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3675. )
  3676. {$endif x86_64}
  3677. ) then
  3678. begin
  3679. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3680. TransferUsedRegs(TmpUsedRegs);
  3681. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3682. { we have
  3683. mov x, %treg
  3684. mov %treg, y
  3685. }
  3686. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3687. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3688. begin
  3689. { we've got
  3690. mov x, %treg
  3691. mov %treg, y
  3692. with %treg is not used after }
  3693. case taicpu(p).oper[0]^.typ Of
  3694. { top_reg is covered by DeepMOVOpt }
  3695. top_const:
  3696. begin
  3697. { change
  3698. mov const, %treg
  3699. mov %treg, y
  3700. to
  3701. mov const, y
  3702. }
  3703. {$ifdef x86_64}
  3704. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3705. (
  3706. { For 32-to-64-bit zero-extension, the immediate
  3707. must be between 0 and 2^31 - 1}
  3708. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3709. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3710. ) or
  3711. (
  3712. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3713. (
  3714. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3715. )
  3716. ) then
  3717. {$endif x86_64}
  3718. begin
  3719. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3720. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3721. RemoveCurrentP(p);
  3722. Result := True;
  3723. Exit;
  3724. end;
  3725. end;
  3726. top_ref:
  3727. case taicpu(hp1).oper[1]^.typ of
  3728. top_reg:
  3729. { change
  3730. mov mem, %treg
  3731. mov %treg, %reg
  3732. to
  3733. mov mem, %reg"
  3734. }
  3735. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3736. begin
  3737. {$ifdef x86_64}
  3738. { If zero extending from 32-bit to 64-bit,
  3739. we have to make sure the replaced
  3740. register is the right size }
  3741. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3742. {$else}
  3743. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3744. {$endif x86_64}
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3746. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3747. RemoveInstruction(hp1);
  3748. Result := True;
  3749. Exit;
  3750. end
  3751. else if
  3752. { Make sure that if a reference is used, its
  3753. registers are not modified in between }
  3754. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3755. begin
  3756. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3757. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3758. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3759. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3760. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3761. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3762. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3763. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3764. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3765. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3766. RemoveCurrentP(p);
  3767. Result := True;
  3768. Exit;
  3769. end;
  3770. top_ref:
  3771. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3772. begin
  3773. {$ifdef x86_64}
  3774. { Look for the following to simplify:
  3775. mov x(mem1), %reg
  3776. mov %reg, y(mem2)
  3777. mov x+8(mem1), %reg
  3778. mov %reg, y+8(mem2)
  3779. Change to:
  3780. movdqu x(mem1), %xmmreg
  3781. movdqu %xmmreg, y(mem2)
  3782. ...but only as long as the memory blocks don't overlap
  3783. }
  3784. SourceRef := taicpu(p).oper[0]^.ref^;
  3785. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3786. if (taicpu(p).opsize = S_Q) and
  3787. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3788. GetNextInstruction(hp1, hp2) and
  3789. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3790. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3791. begin
  3792. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3793. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3794. Inc(SourceRef.offset, 8);
  3795. if UseAVX then
  3796. begin
  3797. MovAligned := A_VMOVDQA;
  3798. MovUnaligned := A_VMOVDQU;
  3799. end
  3800. else
  3801. begin
  3802. MovAligned := A_MOVDQA;
  3803. MovUnaligned := A_MOVDQU;
  3804. end;
  3805. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3806. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3807. begin
  3808. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3809. Inc(TargetRef.offset, 8);
  3810. if GetNextInstruction(hp2, hp3) and
  3811. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3812. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3813. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3814. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3815. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3816. begin
  3817. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3818. if NewMMReg <> NR_NO then
  3819. begin
  3820. { Remember that the offsets are 8 ahead }
  3821. if ((SourceRef.offset mod 16) = 8) and
  3822. (
  3823. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3824. (SourceRef.base = current_procinfo.framepointer) or
  3825. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3826. ) then
  3827. taicpu(p).opcode := MovAligned
  3828. else
  3829. taicpu(p).opcode := MovUnaligned;
  3830. taicpu(p).opsize := S_XMM;
  3831. taicpu(p).oper[1]^.reg := NewMMReg;
  3832. if ((TargetRef.offset mod 16) = 8) and
  3833. (
  3834. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3835. (TargetRef.base = current_procinfo.framepointer) or
  3836. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3837. ) then
  3838. taicpu(hp1).opcode := MovAligned
  3839. else
  3840. taicpu(hp1).opcode := MovUnaligned;
  3841. taicpu(hp1).opsize := S_XMM;
  3842. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3843. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3844. RemoveInstruction(hp2);
  3845. RemoveInstruction(hp3);
  3846. Result := True;
  3847. Exit;
  3848. end;
  3849. end;
  3850. end
  3851. else
  3852. begin
  3853. { See if the next references are 8 less rather than 8 greater }
  3854. Dec(SourceRef.offset, 16); { -8 the other way }
  3855. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3856. begin
  3857. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3858. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3859. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3860. GetNextInstruction(hp2, hp3) and
  3861. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3862. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3863. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3864. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3865. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3866. begin
  3867. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3868. if NewMMReg <> NR_NO then
  3869. begin
  3870. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3871. if ((SourceRef.offset mod 16) = 0) and
  3872. (
  3873. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3874. (SourceRef.base = current_procinfo.framepointer) or
  3875. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3876. ) then
  3877. taicpu(hp2).opcode := MovAligned
  3878. else
  3879. taicpu(hp2).opcode := MovUnaligned;
  3880. taicpu(hp2).opsize := S_XMM;
  3881. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3882. if ((TargetRef.offset mod 16) = 0) and
  3883. (
  3884. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3885. (TargetRef.base = current_procinfo.framepointer) or
  3886. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3887. ) then
  3888. taicpu(hp3).opcode := MovAligned
  3889. else
  3890. taicpu(hp3).opcode := MovUnaligned;
  3891. taicpu(hp3).opsize := S_XMM;
  3892. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3893. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3894. RemoveInstruction(hp1);
  3895. RemoveCurrentP(p);
  3896. Result := True;
  3897. Exit;
  3898. end;
  3899. end;
  3900. end;
  3901. end;
  3902. end;
  3903. {$endif x86_64}
  3904. end;
  3905. else
  3906. { The write target should be a reg or a ref }
  3907. InternalError(2021091601);
  3908. end;
  3909. else
  3910. ;
  3911. end;
  3912. end
  3913. else if (taicpu(p).oper[0]^.typ = top_const) and
  3914. { %treg is used afterwards, but all eventualities other
  3915. than the first MOV instruction being a constant are
  3916. covered by DeepMOVOpt, so only check for that }
  3917. (
  3918. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3919. not (cs_opt_size in current_settings.optimizerswitches) or
  3920. (taicpu(hp1).opsize = S_B)
  3921. ) and
  3922. (
  3923. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3924. (
  3925. { For 32-to-64-bit zero-extension, the immediate
  3926. must be between 0 and 2^31 - 1}
  3927. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3928. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3929. ) or
  3930. (
  3931. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3932. (
  3933. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3934. )
  3935. )
  3936. ) then
  3937. begin
  3938. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3939. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3940. Include(OptsToCheck, aoc_ForceNewIteration);
  3941. end;
  3942. end;
  3943. Break;
  3944. end;
  3945. end;
  3946. if taicpu(p).oper[0]^.typ = top_reg then
  3947. begin
  3948. { oper[1] is a reference }
  3949. { Saves on a large number of dereferences }
  3950. p_SourceReg := taicpu(p).oper[0]^.reg;
  3951. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3952. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3953. else
  3954. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3955. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3956. begin
  3957. if taicpu(p).oper[1]^.typ = top_reg then
  3958. begin
  3959. p_TargetReg := taicpu(p).oper[1]^.reg;
  3960. { Change:
  3961. movl %reg1,%reg2
  3962. ...
  3963. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3964. ...
  3965. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3966. To:
  3967. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3968. ...
  3969. movl x(%reg1),%reg1
  3970. ...
  3971. movl %reg1,%regX
  3972. }
  3973. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3974. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3975. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3976. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3977. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3978. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3979. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3980. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3981. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3982. begin
  3983. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3984. if RegInRef(p_TargetReg, SourceRef) and
  3985. { If %reg1 also appears in the second reference, then it will
  3986. not refer to the same memory block as the first reference }
  3987. not RegInRef(p_SourceReg, SourceRef) then
  3988. begin
  3989. { Check to see if the references match if %reg2 is changed to %reg1 }
  3990. if SourceRef.base = p_TargetReg then
  3991. SourceRef.base := p_SourceReg;
  3992. if SourceRef.index = p_TargetReg then
  3993. SourceRef.index := p_SourceReg;
  3994. { RefsEqual also checks to ensure both references are non-volatile }
  3995. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3996. begin
  3997. taicpu(hp2).loadreg(0, p_SourceReg);
  3998. TransferUsedRegs(TmpUsedRegs);
  3999. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4000. { Make sure the register is allocated between these instructions
  4001. even though it doesn't change value, since it may cause
  4002. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4003. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4004. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4005. Result := True;
  4006. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4007. begin
  4008. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4009. RemoveCurrentP(p);
  4010. Exit;
  4011. end
  4012. else
  4013. begin
  4014. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4015. begin
  4016. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4017. RemoveCurrentP(p);
  4018. Exit;
  4019. end;
  4020. end;
  4021. { If we reach this point, p and hp1 weren't actually modified,
  4022. so we can do a bit more work on this pass }
  4023. end;
  4024. end;
  4025. end;
  4026. end;
  4027. end;
  4028. end;
  4029. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4030. { All the next optimisations require a next instruction }
  4031. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4032. Exit;
  4033. { Next instruction is also a MOV ? }
  4034. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4035. begin
  4036. if MatchOpType(taicpu(p), top_const, top_ref) and
  4037. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4038. TryConstMerge(p, hp1) then
  4039. begin
  4040. Result := True;
  4041. { In case we have four byte writes in a row, check for 2 more
  4042. right now so we don't have to wait for another iteration of
  4043. pass 1
  4044. }
  4045. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4046. case taicpu(p).opsize of
  4047. S_W:
  4048. begin
  4049. if GetNextInstruction(p, hp1) and
  4050. MatchInstruction(hp1, A_MOV, [S_B]) and
  4051. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4052. GetNextInstruction(hp1, hp2) and
  4053. MatchInstruction(hp2, A_MOV, [S_B]) and
  4054. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4055. { Try to merge the two bytes }
  4056. TryConstMerge(hp1, hp2) then
  4057. { Now try to merge the two words (hp2 will get deleted) }
  4058. TryConstMerge(p, hp1);
  4059. end;
  4060. S_L:
  4061. begin
  4062. { Though this only really benefits x86_64 and not i386, it
  4063. gets a potential optimisation done faster and hence
  4064. reduces the number of times OptPass1MOV is entered }
  4065. if GetNextInstruction(p, hp1) and
  4066. MatchInstruction(hp1, A_MOV, [S_W]) and
  4067. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4068. GetNextInstruction(hp1, hp2) and
  4069. MatchInstruction(hp2, A_MOV, [S_W]) and
  4070. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4071. { Try to merge the two words }
  4072. TryConstMerge(hp1, hp2) then
  4073. { This will always fail on i386, so don't bother
  4074. calling it unless we're doing x86_64 }
  4075. {$ifdef x86_64}
  4076. { Now try to merge the two longwords (hp2 will get deleted) }
  4077. TryConstMerge(p, hp1)
  4078. {$endif x86_64}
  4079. ;
  4080. end;
  4081. else
  4082. ;
  4083. end;
  4084. Exit;
  4085. end;
  4086. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4087. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4088. { mov reg1, mem1 or mov mem1, reg1
  4089. mov mem2, reg2 mov reg2, mem2}
  4090. begin
  4091. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4092. { mov reg1, mem1 or mov mem1, reg1
  4093. mov mem2, reg1 mov reg2, mem1}
  4094. begin
  4095. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4096. { Removes the second statement from
  4097. mov reg1, mem1/reg2
  4098. mov mem1/reg2, reg1 }
  4099. begin
  4100. if taicpu(p).oper[0]^.typ=top_reg then
  4101. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4102. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4103. RemoveInstruction(hp1);
  4104. Result:=true;
  4105. exit;
  4106. end
  4107. else
  4108. begin
  4109. TransferUsedRegs(TmpUsedRegs);
  4110. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4111. if (taicpu(p).oper[1]^.typ = top_ref) and
  4112. { mov reg1, mem1
  4113. mov mem2, reg1 }
  4114. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4115. GetNextInstruction(hp1, hp2) and
  4116. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4117. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4118. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4119. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4120. { change to
  4121. mov reg1, mem1 mov reg1, mem1
  4122. mov mem2, reg1 cmp reg1, mem2
  4123. cmp mem1, reg1
  4124. }
  4125. begin
  4126. RemoveInstruction(hp2);
  4127. taicpu(hp1).opcode := A_CMP;
  4128. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4129. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4130. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4131. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4132. end;
  4133. end;
  4134. end
  4135. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4136. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4137. begin
  4138. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4139. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4140. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4141. end
  4142. else
  4143. begin
  4144. TransferUsedRegs(TmpUsedRegs);
  4145. if GetNextInstruction(hp1, hp2) and
  4146. MatchOpType(taicpu(p),top_ref,top_reg) and
  4147. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4148. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4149. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4150. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4151. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4152. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4153. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4154. { mov mem1, %reg1
  4155. mov %reg1, mem2
  4156. mov mem2, reg2
  4157. to:
  4158. mov mem1, reg2
  4159. mov reg2, mem2}
  4160. begin
  4161. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4162. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4163. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4164. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4165. RemoveInstruction(hp2);
  4166. Result := True;
  4167. end
  4168. {$ifdef i386}
  4169. { this is enabled for i386 only, as the rules to create the reg sets below
  4170. are too complicated for x86-64, so this makes this code too error prone
  4171. on x86-64
  4172. }
  4173. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4174. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4175. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4176. { mov mem1, reg1 mov mem1, reg1
  4177. mov reg1, mem2 mov reg1, mem2
  4178. mov mem2, reg2 mov mem2, reg1
  4179. to: to:
  4180. mov mem1, reg1 mov mem1, reg1
  4181. mov mem1, reg2 mov reg1, mem2
  4182. mov reg1, mem2
  4183. or (if mem1 depends on reg1
  4184. and/or if mem2 depends on reg2)
  4185. to:
  4186. mov mem1, reg1
  4187. mov reg1, mem2
  4188. mov reg1, reg2
  4189. }
  4190. begin
  4191. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4192. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4193. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4194. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4195. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4196. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4197. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4198. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4199. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4200. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4201. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4202. end
  4203. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4204. begin
  4205. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4206. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4207. end
  4208. else
  4209. begin
  4210. RemoveInstruction(hp2);
  4211. end
  4212. {$endif i386}
  4213. ;
  4214. end;
  4215. end
  4216. { movl [mem1],reg1
  4217. movl [mem1],reg2
  4218. to
  4219. movl [mem1],reg1
  4220. movl reg1,reg2
  4221. }
  4222. else if not CheckMovMov2MovMov2(p, hp1) and
  4223. { movl const1,[mem1]
  4224. movl [mem1],reg1
  4225. to
  4226. movl const1,reg1
  4227. movl reg1,[mem1]
  4228. }
  4229. MatchOpType(Taicpu(p),top_const,top_ref) and
  4230. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4231. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4232. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4233. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4234. begin
  4235. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4236. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4237. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4238. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4239. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4240. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4241. Result:=true;
  4242. exit;
  4243. end;
  4244. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4245. end;
  4246. { search further than the next instruction for a mov (as long as it's not a jump) }
  4247. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4248. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4249. (taicpu(p).oper[1]^.typ = top_reg) and
  4250. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4251. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4252. begin
  4253. { we work with hp2 here, so hp1 can be still used later on when
  4254. checking for GetNextInstruction_p }
  4255. hp3 := hp1;
  4256. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4257. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4258. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4259. TransferUsedRegs(TmpUsedRegs);
  4260. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4261. if NotFirstIteration then
  4262. JumpTracking := TLinkedList.Create
  4263. else
  4264. JumpTracking := nil;
  4265. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4266. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4267. (hp2.typ=ait_instruction) do
  4268. begin
  4269. case taicpu(hp2).opcode of
  4270. A_POP:
  4271. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4272. begin
  4273. if not CrossJump and
  4274. not RegUsedBetween(p_TargetReg, p, hp2) then
  4275. begin
  4276. { We can remove the original MOV since the register
  4277. wasn't used between it and its popping from the stack }
  4278. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4279. RemoveCurrentp(p, hp1);
  4280. Result := True;
  4281. JumpTracking.Free;
  4282. Exit;
  4283. end;
  4284. { Can't go any further }
  4285. Break;
  4286. end;
  4287. A_MOV:
  4288. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4289. ((taicpu(p).oper[0]^.typ=top_const) or
  4290. ((taicpu(p).oper[0]^.typ=top_reg) and
  4291. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4292. )
  4293. ) then
  4294. begin
  4295. { we have
  4296. mov x, %treg
  4297. mov %treg, y
  4298. }
  4299. { We don't need to call UpdateUsedRegs for every instruction between
  4300. p and hp2 because the register we're concerned about will not
  4301. become deallocated (otherwise GetNextInstructionUsingReg would
  4302. have stopped at an earlier instruction). [Kit] }
  4303. TempRegUsed :=
  4304. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4305. RegReadByInstruction(p_TargetReg, hp3) or
  4306. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4307. case taicpu(p).oper[0]^.typ Of
  4308. top_reg:
  4309. begin
  4310. { change
  4311. mov %reg, %treg
  4312. mov %treg, y
  4313. to
  4314. mov %reg, y
  4315. }
  4316. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4317. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4318. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4319. begin
  4320. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4321. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4322. if TempRegUsed then
  4323. begin
  4324. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4325. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4326. { Set the start of the next GetNextInstructionUsingRegCond search
  4327. to start at the entry right before hp2 (which is about to be removed) }
  4328. hp3 := tai(hp2.Previous);
  4329. RemoveInstruction(hp2);
  4330. Include(OptsToCheck, aoc_ForceNewIteration);
  4331. { See if there's more we can optimise }
  4332. Continue;
  4333. end
  4334. else
  4335. begin
  4336. RemoveInstruction(hp2);
  4337. { We can remove the original MOV too }
  4338. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4339. RemoveCurrentP(p, hp1);
  4340. Result:=true;
  4341. JumpTracking.Free;
  4342. Exit;
  4343. end;
  4344. end
  4345. else
  4346. begin
  4347. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4348. taicpu(hp2).loadReg(0, p_SourceReg);
  4349. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4350. { Check to see if the register also appears in the reference }
  4351. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4352. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4353. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4354. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4355. begin
  4356. { Don't remove the first instruction if the temporary register is in use }
  4357. if not TempRegUsed then
  4358. begin
  4359. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4360. RemoveCurrentP(p, hp1);
  4361. Result:=true;
  4362. JumpTracking.Free;
  4363. Exit;
  4364. end;
  4365. { No need to set Result to True here. If there's another instruction later
  4366. on that can be optimised, it will be detected when the main Pass 1 loop
  4367. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4368. hp3 := hp2;
  4369. Continue;
  4370. end;
  4371. end;
  4372. end;
  4373. top_const:
  4374. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4375. begin
  4376. { change
  4377. mov const, %treg
  4378. mov %treg, y
  4379. to
  4380. mov const, y
  4381. }
  4382. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4383. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4384. begin
  4385. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4386. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4387. if TempRegUsed then
  4388. begin
  4389. { Don't remove the first instruction if the temporary register is in use }
  4390. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4391. { No need to set Result to True. If there's another instruction later on
  4392. that can be optimised, it will be detected when the main Pass 1 loop
  4393. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4394. end
  4395. else
  4396. begin
  4397. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4398. RemoveCurrentP(p, hp1);
  4399. Result:=true;
  4400. Exit;
  4401. end;
  4402. end;
  4403. end;
  4404. else
  4405. Internalerror(2019103001);
  4406. end;
  4407. end
  4408. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4409. begin
  4410. if not CrossJump and
  4411. not RegUsedBetween(p_TargetReg, p, hp2) and
  4412. not RegReadByInstruction(p_TargetReg, hp2) then
  4413. begin
  4414. { Register is not used before it is overwritten }
  4415. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4416. RemoveCurrentp(p, hp1);
  4417. Result := True;
  4418. Exit;
  4419. end;
  4420. if (taicpu(p).oper[0]^.typ = top_const) and
  4421. (taicpu(hp2).oper[0]^.typ = top_const) then
  4422. begin
  4423. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4424. begin
  4425. { Same value - register hasn't changed }
  4426. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4427. RemoveInstruction(hp2);
  4428. Include(OptsToCheck, aoc_ForceNewIteration);
  4429. { See if there's more we can optimise }
  4430. Continue;
  4431. end;
  4432. end;
  4433. {$ifdef x86_64}
  4434. end
  4435. { Change:
  4436. movl %reg1l,%reg2l
  4437. ...
  4438. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4439. To:
  4440. movl %reg1l,%reg2l
  4441. ...
  4442. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4443. If %reg1 = %reg3, convert to:
  4444. movl %reg1l,%reg2l
  4445. ...
  4446. andl %reg1l,%reg1l
  4447. }
  4448. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4449. (taicpu(p).oper[0]^.typ = top_reg) and
  4450. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4451. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4452. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4453. begin
  4454. TempRegUsed :=
  4455. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4456. RegReadByInstruction(p_TargetReg, hp3) or
  4457. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4458. taicpu(hp2).opsize := S_L;
  4459. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4460. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4461. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4462. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4463. begin
  4464. { %reg1 = %reg3 }
  4465. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4466. taicpu(hp2).opcode := A_AND;
  4467. end
  4468. else
  4469. begin
  4470. { %reg1 <> %reg3 }
  4471. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4472. end;
  4473. if not TempRegUsed then
  4474. begin
  4475. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4476. RemoveCurrentP(p, hp1);
  4477. Result := True;
  4478. Exit;
  4479. end
  4480. else
  4481. begin
  4482. { Initial instruction wasn't actually changed }
  4483. Include(OptsToCheck, aoc_ForceNewIteration);
  4484. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4485. appears below since %reg1 has technically changed }
  4486. if taicpu(hp2).opcode = A_AND then
  4487. Break;
  4488. end;
  4489. {$endif x86_64}
  4490. end
  4491. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4492. GetNextInstruction(hp2, hp4) and
  4493. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4494. { Optimise the following first:
  4495. movl [mem1],reg1
  4496. movl [mem1],reg2
  4497. to
  4498. movl [mem1],reg1
  4499. movl reg1,reg2
  4500. If [mem1] contains the target register and reg1 is the
  4501. the source register, this optimisation will get missed
  4502. and produce less efficient code later on.
  4503. }
  4504. if CheckMovMov2MovMov2(hp2, hp4) then
  4505. { Initial instruction wasn't actually changed }
  4506. Include(OptsToCheck, aoc_ForceNewIteration);
  4507. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4508. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4509. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4510. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4511. begin
  4512. {
  4513. Change from:
  4514. mov ###, %reg
  4515. ...
  4516. movs/z %reg,%reg (Same register, just different sizes)
  4517. To:
  4518. movs/z ###, %reg (Longer version)
  4519. ...
  4520. (remove)
  4521. }
  4522. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4523. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4524. { Keep the first instruction as mov if ### is a constant }
  4525. if taicpu(p).oper[0]^.typ = top_const then
  4526. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4527. else
  4528. begin
  4529. taicpu(p).opcode := taicpu(hp2).opcode;
  4530. taicpu(p).opsize := taicpu(hp2).opsize;
  4531. end;
  4532. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4533. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4534. RemoveInstruction(hp2);
  4535. Result := True;
  4536. JumpTracking.Free;
  4537. Exit;
  4538. end;
  4539. else
  4540. { Move down to the if-block below };
  4541. end;
  4542. { Also catches MOV/S/Z instructions that aren't modified }
  4543. if taicpu(p).oper[0]^.typ = top_reg then
  4544. begin
  4545. p_SourceReg := taicpu(p).oper[0]^.reg;
  4546. if
  4547. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4548. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4549. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4550. begin
  4551. Result := True;
  4552. { Just in case something didn't get modified (e.g. an
  4553. implicit register). Also, if it does read from this
  4554. register, then there's no longer an advantage to
  4555. changing the register on subsequent instructions.}
  4556. if not RegReadByInstruction(p_TargetReg, hp2) then
  4557. begin
  4558. { If a conditional jump was crossed, do not delete
  4559. the original MOV no matter what }
  4560. if not CrossJump and
  4561. { RegEndOfLife returns True if the register is
  4562. deallocated before the next instruction or has
  4563. been loaded with a new value }
  4564. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4565. begin
  4566. { We can remove the original MOV }
  4567. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4568. RemoveCurrentp(p, hp1);
  4569. JumpTracking.Free;
  4570. Result := True;
  4571. Exit;
  4572. end;
  4573. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4574. begin
  4575. { See if there's more we can optimise }
  4576. hp3 := hp2;
  4577. Continue;
  4578. end;
  4579. end;
  4580. end;
  4581. end;
  4582. { Break out of the while loop under normal circumstances }
  4583. Break;
  4584. end;
  4585. JumpTracking.Free;
  4586. end;
  4587. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4588. (taicpu(p).oper[1]^.typ = top_reg) and
  4589. (taicpu(p).opsize = S_L) and
  4590. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4591. (hp2.typ = ait_instruction) and
  4592. (taicpu(hp2).opcode = A_AND) and
  4593. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4594. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4595. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4596. ) then
  4597. begin
  4598. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4599. begin
  4600. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4601. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4602. begin
  4603. { Optimize out:
  4604. mov x, %reg
  4605. and ffffffffh, %reg
  4606. }
  4607. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4608. RemoveInstruction(hp2);
  4609. Result:=true;
  4610. exit;
  4611. end;
  4612. end;
  4613. end;
  4614. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4615. x >= RetOffset) as it doesn't do anything (it writes either to a
  4616. parameter or to the temporary storage room for the function
  4617. result)
  4618. }
  4619. if IsExitCode(hp1) and
  4620. (taicpu(p).oper[1]^.typ = top_ref) and
  4621. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4622. (
  4623. (
  4624. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4625. not (
  4626. assigned(current_procinfo.procdef.funcretsym) and
  4627. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4628. )
  4629. ) or
  4630. { Also discard writes to the stack that are below the base pointer,
  4631. as this is temporary storage rather than a function result on the
  4632. stack, say. }
  4633. (
  4634. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4635. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4636. )
  4637. ) then
  4638. begin
  4639. RemoveCurrentp(p, hp1);
  4640. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4641. RemoveLastDeallocForFuncRes(p);
  4642. Result:=true;
  4643. exit;
  4644. end;
  4645. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4646. begin
  4647. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4648. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4649. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4650. begin
  4651. { change
  4652. mov reg1, mem1
  4653. test/cmp x, mem1
  4654. to
  4655. mov reg1, mem1
  4656. test/cmp x, reg1
  4657. }
  4658. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4659. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4660. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4661. Result := True;
  4662. Exit;
  4663. end;
  4664. if DoMovCmpMemOpt(p, hp1) then
  4665. begin
  4666. Result := True;
  4667. Exit;
  4668. end;
  4669. end;
  4670. if (taicpu(p).oper[1]^.typ = top_reg) and
  4671. (hp1.typ = ait_instruction) and
  4672. GetNextInstruction(hp1, hp2) and
  4673. MatchInstruction(hp2,A_MOV,[]) and
  4674. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4675. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4676. (
  4677. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4678. {$ifdef x86_64}
  4679. or
  4680. (
  4681. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4682. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4683. )
  4684. {$endif x86_64}
  4685. ) then
  4686. begin
  4687. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4688. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4689. { change movsX/movzX reg/ref, reg2
  4690. add/sub/or/... reg3/$const, reg2
  4691. mov reg2 reg/ref
  4692. dealloc reg2
  4693. to
  4694. add/sub/or/... reg3/$const, reg/ref }
  4695. begin
  4696. TransferUsedRegs(TmpUsedRegs);
  4697. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4698. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4699. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4700. begin
  4701. { by example:
  4702. movswl %si,%eax movswl %si,%eax p
  4703. decl %eax addl %edx,%eax hp1
  4704. movw %ax,%si movw %ax,%si hp2
  4705. ->
  4706. movswl %si,%eax movswl %si,%eax p
  4707. decw %eax addw %edx,%eax hp1
  4708. movw %ax,%si movw %ax,%si hp2
  4709. }
  4710. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4711. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4712. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4713. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4714. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4715. {
  4716. ->
  4717. movswl %si,%eax movswl %si,%eax p
  4718. decw %si addw %dx,%si hp1
  4719. movw %ax,%si movw %ax,%si hp2
  4720. }
  4721. case taicpu(hp1).ops of
  4722. 1:
  4723. begin
  4724. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4725. if taicpu(hp1).oper[0]^.typ=top_reg then
  4726. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4727. end;
  4728. 2:
  4729. begin
  4730. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4731. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4732. (taicpu(hp1).opcode<>A_SHL) and
  4733. (taicpu(hp1).opcode<>A_SHR) and
  4734. (taicpu(hp1).opcode<>A_SAR) then
  4735. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4736. end;
  4737. else
  4738. internalerror(2008042701);
  4739. end;
  4740. {
  4741. ->
  4742. decw %si addw %dx,%si p
  4743. }
  4744. RemoveInstruction(hp2);
  4745. RemoveCurrentP(p, hp1);
  4746. Result:=True;
  4747. Exit;
  4748. end;
  4749. end;
  4750. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4751. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4752. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4753. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4754. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4755. )
  4756. {$ifdef i386}
  4757. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4758. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4759. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4760. {$endif i386}
  4761. then
  4762. { change movsX/movzX reg/ref, reg2
  4763. add/sub/or/... regX/$const, reg2
  4764. mov reg2, reg3
  4765. dealloc reg2
  4766. to
  4767. movsX/movzX reg/ref, reg3
  4768. add/sub/or/... reg3/$const, reg3
  4769. }
  4770. begin
  4771. TransferUsedRegs(TmpUsedRegs);
  4772. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4773. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4774. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4775. begin
  4776. { by example:
  4777. movswl %si,%eax movswl %si,%eax p
  4778. decl %eax addl %edx,%eax hp1
  4779. movw %ax,%si movw %ax,%si hp2
  4780. ->
  4781. movswl %si,%eax movswl %si,%eax p
  4782. decw %eax addw %edx,%eax hp1
  4783. movw %ax,%si movw %ax,%si hp2
  4784. }
  4785. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4786. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4787. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4788. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4789. { limit size of constants as well to avoid assembler errors, but
  4790. check opsize to avoid overflow when left shifting the 1 }
  4791. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4792. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4793. {$ifdef x86_64}
  4794. { Be careful of, for example:
  4795. movl %reg1,%reg2
  4796. addl %reg3,%reg2
  4797. movq %reg2,%reg4
  4798. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4799. }
  4800. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4801. begin
  4802. taicpu(hp2).changeopsize(S_L);
  4803. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4804. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4805. end;
  4806. {$endif x86_64}
  4807. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4808. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4809. if taicpu(p).oper[0]^.typ=top_reg then
  4810. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4811. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4812. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4813. {
  4814. ->
  4815. movswl %si,%eax movswl %si,%eax p
  4816. decw %si addw %dx,%si hp1
  4817. movw %ax,%si movw %ax,%si hp2
  4818. }
  4819. case taicpu(hp1).ops of
  4820. 1:
  4821. begin
  4822. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4823. if taicpu(hp1).oper[0]^.typ=top_reg then
  4824. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4825. end;
  4826. 2:
  4827. begin
  4828. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4829. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4830. (taicpu(hp1).opcode<>A_SHL) and
  4831. (taicpu(hp1).opcode<>A_SHR) and
  4832. (taicpu(hp1).opcode<>A_SAR) then
  4833. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4834. end;
  4835. else
  4836. internalerror(2018111801);
  4837. end;
  4838. {
  4839. ->
  4840. decw %si addw %dx,%si p
  4841. }
  4842. RemoveInstruction(hp2);
  4843. end;
  4844. end;
  4845. end;
  4846. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4847. GetNextInstruction(hp1, hp2) and
  4848. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4849. MatchOperand(Taicpu(p).oper[0]^,0) and
  4850. (Taicpu(p).oper[1]^.typ = top_reg) and
  4851. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4852. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4853. { mov reg1,0
  4854. bts reg1,operand1 --> mov reg1,operand2
  4855. or reg1,operand2 bts reg1,operand1}
  4856. begin
  4857. Taicpu(hp2).opcode:=A_MOV;
  4858. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4859. asml.remove(hp1);
  4860. insertllitem(hp2,hp2.next,hp1);
  4861. RemoveCurrentp(p, hp1);
  4862. Result:=true;
  4863. exit;
  4864. end;
  4865. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4866. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4867. GetNextInstruction(hp1, hp2) and
  4868. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4869. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4870. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4871. { change
  4872. mov reg1,reg2
  4873. sub reg3,reg2
  4874. cmp reg3,reg1
  4875. into
  4876. mov reg1,reg2
  4877. sub reg3,reg2
  4878. }
  4879. begin
  4880. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4881. RemoveInstruction(hp2);
  4882. Result:=true;
  4883. exit;
  4884. end;
  4885. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4886. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4887. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4888. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4889. begin
  4890. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4891. {$ifdef x86_64}
  4892. { Convert:
  4893. movq x(ref),%reg64
  4894. shrq y,%reg64
  4895. To:
  4896. movl x+4(ref),%reg32
  4897. shrl y-32,%reg32 (Remove if y = 32)
  4898. }
  4899. if (taicpu(p).opsize = S_Q) and
  4900. (taicpu(hp1).opcode = A_SHR) and
  4901. (taicpu(hp1).oper[0]^.val >= 32) then
  4902. begin
  4903. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4904. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4905. { Convert to 32-bit }
  4906. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4907. taicpu(p).opsize := S_L;
  4908. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4909. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4910. if (taicpu(hp1).oper[0]^.val = 32) then
  4911. begin
  4912. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4913. RemoveInstruction(hp1);
  4914. end
  4915. else
  4916. begin
  4917. { This will potentially open up more arithmetic operations since
  4918. the peephole optimizer now has a big hint that only the lower
  4919. 32 bits are currently in use (and opcodes are smaller in size) }
  4920. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4921. taicpu(hp1).opsize := S_L;
  4922. Dec(taicpu(hp1).oper[0]^.val, 32);
  4923. DebugMsg(SPeepholeOptimization + PreMessage +
  4924. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4925. end;
  4926. Result := True;
  4927. Exit;
  4928. end;
  4929. {$endif x86_64}
  4930. { Convert:
  4931. movl x(ref),%reg
  4932. shrl $24,%reg
  4933. To:
  4934. movzbl x+3(ref),%reg
  4935. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4936. Also accept sar instead of shr, but convert to movsx instead of movzx
  4937. }
  4938. if taicpu(hp1).opcode = A_SHR then
  4939. MovUnaligned := A_MOVZX
  4940. else
  4941. MovUnaligned := A_MOVSX;
  4942. NewSize := S_NO;
  4943. NewOffset := 0;
  4944. case taicpu(p).opsize of
  4945. S_B:
  4946. { No valid combinations };
  4947. S_W:
  4948. if (taicpu(hp1).oper[0]^.val = 8) then
  4949. begin
  4950. NewSize := S_BW;
  4951. NewOffset := 1;
  4952. end;
  4953. S_L:
  4954. case taicpu(hp1).oper[0]^.val of
  4955. 16:
  4956. begin
  4957. NewSize := S_WL;
  4958. NewOffset := 2;
  4959. end;
  4960. 24:
  4961. begin
  4962. NewSize := S_BL;
  4963. NewOffset := 3;
  4964. end;
  4965. else
  4966. ;
  4967. end;
  4968. {$ifdef x86_64}
  4969. S_Q:
  4970. case taicpu(hp1).oper[0]^.val of
  4971. 32:
  4972. begin
  4973. if taicpu(hp1).opcode = A_SAR then
  4974. begin
  4975. { 32-bit to 64-bit is a distinct instruction }
  4976. MovUnaligned := A_MOVSXD;
  4977. NewSize := S_LQ;
  4978. NewOffset := 4;
  4979. end
  4980. else
  4981. { Should have been handled by MovShr2Mov above }
  4982. InternalError(2022081811);
  4983. end;
  4984. 48:
  4985. begin
  4986. NewSize := S_WQ;
  4987. NewOffset := 6;
  4988. end;
  4989. 56:
  4990. begin
  4991. NewSize := S_BQ;
  4992. NewOffset := 7;
  4993. end;
  4994. else
  4995. ;
  4996. end;
  4997. {$endif x86_64}
  4998. else
  4999. InternalError(2022081810);
  5000. end;
  5001. if (NewSize <> S_NO) and
  5002. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5003. begin
  5004. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5005. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5006. debug_op2str(MovUnaligned);
  5007. {$ifdef x86_64}
  5008. if MovUnaligned <> A_MOVSXD then
  5009. { Don't add size suffix for MOVSXD }
  5010. {$endif x86_64}
  5011. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5012. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5013. taicpu(p).opcode := MovUnaligned;
  5014. taicpu(p).opsize := NewSize;
  5015. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5016. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5017. RemoveInstruction(hp1);
  5018. Result := True;
  5019. Exit;
  5020. end;
  5021. end;
  5022. { Backward optimisation shared with OptPass2MOV }
  5023. if FuncMov2Func(p, hp1) then
  5024. begin
  5025. Result := True;
  5026. Exit;
  5027. end;
  5028. end;
  5029. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5030. var
  5031. hp1 : tai;
  5032. begin
  5033. Result:=false;
  5034. if taicpu(p).ops <> 2 then
  5035. exit;
  5036. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5037. GetNextInstruction(p,hp1) then
  5038. begin
  5039. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5040. (taicpu(hp1).ops = 2) then
  5041. begin
  5042. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5043. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5044. { movXX reg1, mem1 or movXX mem1, reg1
  5045. movXX mem2, reg2 movXX reg2, mem2}
  5046. begin
  5047. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5048. { movXX reg1, mem1 or movXX mem1, reg1
  5049. movXX mem2, reg1 movXX reg2, mem1}
  5050. begin
  5051. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5052. begin
  5053. { Removes the second statement from
  5054. movXX reg1, mem1/reg2
  5055. movXX mem1/reg2, reg1
  5056. }
  5057. if taicpu(p).oper[0]^.typ=top_reg then
  5058. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5059. { Removes the second statement from
  5060. movXX mem1/reg1, reg2
  5061. movXX reg2, mem1/reg1
  5062. }
  5063. if (taicpu(p).oper[1]^.typ=top_reg) and
  5064. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5065. begin
  5066. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5067. RemoveInstruction(hp1);
  5068. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5069. Result:=true;
  5070. exit;
  5071. end
  5072. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5073. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5074. begin
  5075. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5076. RemoveInstruction(hp1);
  5077. Result:=true;
  5078. exit;
  5079. end;
  5080. end
  5081. end;
  5082. end;
  5083. end;
  5084. end;
  5085. end;
  5086. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5087. var
  5088. hp1 : tai;
  5089. begin
  5090. result:=false;
  5091. { replace
  5092. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5093. MovX %mreg2,%mreg1
  5094. dealloc %mreg2
  5095. by
  5096. <Op>X %mreg2,%mreg1
  5097. ?
  5098. }
  5099. if GetNextInstruction(p,hp1) and
  5100. { we mix single and double opperations here because we assume that the compiler
  5101. generates vmovapd only after double operations and vmovaps only after single operations }
  5102. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5103. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5104. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5105. (taicpu(p).oper[0]^.typ=top_reg) then
  5106. begin
  5107. TransferUsedRegs(TmpUsedRegs);
  5108. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5109. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5110. begin
  5111. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5112. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5113. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5114. RemoveInstruction(hp1);
  5115. result:=true;
  5116. end;
  5117. end;
  5118. end;
  5119. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5120. var
  5121. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5122. JumpLabel, JumpLabel_dist: TAsmLabel;
  5123. FirstValue, SecondValue: TCGInt;
  5124. function OptimizeJump(var InputP: tai): Boolean;
  5125. var
  5126. TempBool: Boolean;
  5127. begin
  5128. Result := False;
  5129. TempBool := True;
  5130. if DoJumpOptimizations(InputP, TempBool) or
  5131. not TempBool then
  5132. begin
  5133. Result := True;
  5134. if Assigned(InputP) then
  5135. begin
  5136. { CollapseZeroDistJump will be set to the label or an align
  5137. before it after the jump if it optimises, whether or not
  5138. the label is live or dead }
  5139. if (InputP.typ = ait_align) or
  5140. (
  5141. (InputP.typ = ait_label) and
  5142. not (tai_label(InputP).labsym.is_used)
  5143. ) then
  5144. GetNextInstruction(InputP, InputP);
  5145. end;
  5146. Exit;
  5147. end;
  5148. end;
  5149. begin
  5150. Result := False;
  5151. if (taicpu(p).oper[0]^.typ = top_const) and
  5152. (taicpu(p).oper[0]^.val <> -1) then
  5153. begin
  5154. { Convert unsigned maximum constants to -1 to aid optimisation }
  5155. case taicpu(p).opsize of
  5156. S_B:
  5157. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5158. begin
  5159. taicpu(p).oper[0]^.val := -1;
  5160. Result := True;
  5161. Exit;
  5162. end;
  5163. S_W:
  5164. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5165. begin
  5166. taicpu(p).oper[0]^.val := -1;
  5167. Result := True;
  5168. Exit;
  5169. end;
  5170. S_L:
  5171. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5172. begin
  5173. taicpu(p).oper[0]^.val := -1;
  5174. Result := True;
  5175. Exit;
  5176. end;
  5177. {$ifdef x86_64}
  5178. S_Q:
  5179. { Storing anything greater than $7FFFFFFF is not possible so do
  5180. nothing };
  5181. {$endif x86_64}
  5182. else
  5183. InternalError(2021121001);
  5184. end;
  5185. end;
  5186. if GetNextInstruction(p, hp1) and
  5187. TrySwapMovCmp(p, hp1) then
  5188. begin
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. p_label := nil;
  5193. JumpLabel := nil;
  5194. if MatchInstruction(hp1, A_Jcc, []) then
  5195. begin
  5196. if OptimizeJump(hp1) then
  5197. begin
  5198. Result := True;
  5199. if Assigned(hp1) then
  5200. begin
  5201. { CollapseZeroDistJump will be set to the label or an align
  5202. before it after the jump if it optimises, whether or not
  5203. the label is live or dead }
  5204. if (hp1.typ = ait_align) or
  5205. (
  5206. (hp1.typ = ait_label) and
  5207. not (tai_label(hp1).labsym.is_used)
  5208. ) then
  5209. GetNextInstruction(hp1, hp1);
  5210. end;
  5211. TransferUsedRegs(TmpUsedRegs);
  5212. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5213. if not Assigned(hp1) or
  5214. (
  5215. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5216. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5217. ) then
  5218. begin
  5219. { No more conditional jumps; conditional statement is no longer required }
  5220. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5221. RemoveCurrentP(p);
  5222. end;
  5223. Exit;
  5224. end;
  5225. if IsJumpToLabel(taicpu(hp1)) then
  5226. begin
  5227. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5228. if Assigned(JumpLabel) then
  5229. p_label := getlabelwithsym(JumpLabel);
  5230. end;
  5231. end;
  5232. { Search for:
  5233. test $x,(reg/ref)
  5234. jne @lbl1
  5235. test $y,(reg/ref) (same register or reference)
  5236. jne @lbl1
  5237. Change to:
  5238. test $(x or y),(reg/ref)
  5239. jne @lbl1
  5240. (Note, this doesn't work with je instead of jne)
  5241. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5242. Also search for:
  5243. test $x,(reg/ref)
  5244. je @lbl1
  5245. ...
  5246. test $y,(reg/ref)
  5247. je/jne @lbl2
  5248. If (x or y) = x, then the second jump is deterministic
  5249. }
  5250. if (
  5251. (
  5252. (taicpu(p).oper[0]^.typ = top_const) or
  5253. (
  5254. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5255. (taicpu(p).oper[0]^.typ = top_reg) and
  5256. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5257. )
  5258. ) and
  5259. MatchInstruction(hp1, A_JCC, [])
  5260. ) then
  5261. begin
  5262. if (taicpu(p).oper[0]^.typ = top_reg) and
  5263. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5264. FirstValue := -1
  5265. else
  5266. FirstValue := taicpu(p).oper[0]^.val;
  5267. { If we have several test/jne's in a row, it might be the case that
  5268. the second label doesn't go to the same location, but the one
  5269. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5270. so accommodate for this with a while loop.
  5271. }
  5272. hp1_last := hp1;
  5273. while (
  5274. (
  5275. (taicpu(p).oper[1]^.typ = top_reg) and
  5276. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5277. ) or GetNextInstruction(hp1_last, p_dist)
  5278. ) and (p_dist.typ = ait_instruction) do
  5279. begin
  5280. if (
  5281. (
  5282. (taicpu(p_dist).opcode = A_TEST) and
  5283. (
  5284. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5285. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5286. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5287. )
  5288. ) or
  5289. (
  5290. { cmp 0,%reg = test %reg,%reg }
  5291. (taicpu(p_dist).opcode = A_CMP) and
  5292. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5293. )
  5294. ) and
  5295. { Make sure the destination operands are actually the same }
  5296. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5297. GetNextInstruction(p_dist, hp1_dist) and
  5298. MatchInstruction(hp1_dist, A_JCC, []) then
  5299. begin
  5300. if OptimizeJump(hp1_dist) then
  5301. begin
  5302. Result := True;
  5303. Exit;
  5304. end;
  5305. if
  5306. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5307. (
  5308. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5309. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5310. ) then
  5311. SecondValue := -1
  5312. else
  5313. SecondValue := taicpu(p_dist).oper[0]^.val;
  5314. { If both of the TEST constants are identical, delete the
  5315. second TEST that is unnecessary (be careful though, just
  5316. in case the flags are modified in between) }
  5317. if (FirstValue = SecondValue) then
  5318. begin
  5319. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5320. begin
  5321. { Since the second jump's condition is a subset of the first, we
  5322. know it will never branch because the first jump dominates it.
  5323. Get it out of the way now rather than wait for the jump
  5324. optimisations for a speed boost. }
  5325. if IsJumpToLabel(taicpu(hp1_dist)) then
  5326. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5327. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5328. RemoveInstruction(hp1_dist);
  5329. Result := True;
  5330. end
  5331. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5332. begin
  5333. { If the inverse of the first condition is a subset of the second,
  5334. the second one will definitely branch if the first one doesn't }
  5335. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5336. { We can remove the TEST instruction too }
  5337. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5338. RemoveInstruction(p_dist);
  5339. MakeUnconditional(taicpu(hp1_dist));
  5340. RemoveDeadCodeAfterJump(hp1_dist);
  5341. { Since the jump is now unconditional, we can't
  5342. continue any further with this particular
  5343. optimisation. The original TEST is still intact
  5344. though, so there might be something else we can
  5345. do }
  5346. Include(OptsToCheck, aoc_ForceNewIteration);
  5347. Break;
  5348. end;
  5349. if Result or
  5350. { If a jump wasn't removed or made unconditional, only
  5351. remove the identical TEST instruction if the flags
  5352. weren't modified }
  5353. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5354. begin
  5355. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5356. RemoveInstruction(p_dist);
  5357. { If the jump was removed or made unconditional, we
  5358. don't need to allocate NR_DEFAULTFLAGS over the
  5359. entire range }
  5360. if not Result then
  5361. begin
  5362. { Mark the flags as 'in use' over the entire range }
  5363. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5364. { Speed gain - continue search from the Jcc instruction }
  5365. hp1_last := hp1_dist;
  5366. { Only the TEST instruction was removed, and the
  5367. original was unchanged, so we can safely do
  5368. another iteration of the while loop }
  5369. Include(OptsToCheck, aoc_ForceNewIteration);
  5370. Continue;
  5371. end;
  5372. Exit;
  5373. end;
  5374. end;
  5375. hp1_last := nil;
  5376. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5377. (
  5378. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5379. { Always adjacent under -O2 and under }
  5380. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5381. (
  5382. GetNextInstruction(hp1, hp1_last) and
  5383. (hp1_last = p_dist)
  5384. )
  5385. ) and
  5386. (
  5387. (
  5388. { Test the following variant:
  5389. test $x,(reg/ref)
  5390. jne @lbl1
  5391. test $y,(reg/ref)
  5392. je @lbl2
  5393. @lbl1:
  5394. Becomes:
  5395. test $(x or y),(reg/ref)
  5396. je @lbl2
  5397. @lbl1: (may become a dead label)
  5398. }
  5399. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5400. GetNextInstruction(hp1_dist, hp1_last) and
  5401. (hp1_last = p_label)
  5402. ) or
  5403. (
  5404. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5405. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5406. then the second jump will never branch, so it can also be
  5407. removed regardless of where it goes }
  5408. (
  5409. (FirstValue = -1) or
  5410. (SecondValue = -1) or
  5411. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5412. )
  5413. )
  5414. ) then
  5415. begin
  5416. { Same jump location... can be a register since nothing's changed }
  5417. { If any of the entries are equivalent to test %reg,%reg, then the
  5418. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5419. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5420. if (hp1_last = p_label) then
  5421. begin
  5422. { Variant }
  5423. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5424. RemoveInstruction(p_dist);
  5425. if Assigned(JumpLabel) then
  5426. JumpLabel.decrefs;
  5427. RemoveInstruction(hp1);
  5428. end
  5429. else
  5430. begin
  5431. { Only remove the second test if no jumps or other conditional instructions follow }
  5432. TransferUsedRegs(TmpUsedRegs);
  5433. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5434. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5435. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5436. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5437. begin
  5438. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5439. RemoveInstruction(p_dist);
  5440. { Remove the first jump, not the second, to keep
  5441. any register deallocations between the second
  5442. TEST/JNE pair in the same place. Aids future
  5443. optimisation. }
  5444. if Assigned(JumpLabel) then
  5445. JumpLabel.decrefs;
  5446. RemoveInstruction(hp1);
  5447. end
  5448. else
  5449. begin
  5450. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5451. if IsJumpToLabel(taicpu(hp1_dist)) then
  5452. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5453. { Remove second jump in this instance }
  5454. RemoveInstruction(hp1_dist);
  5455. end;
  5456. end;
  5457. Result := True;
  5458. Exit;
  5459. end;
  5460. end;
  5461. if { If -O2 and under, it may stop on any old instruction }
  5462. (cs_opt_level3 in current_settings.optimizerswitches) and
  5463. (taicpu(p).oper[1]^.typ = top_reg) and
  5464. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5465. begin
  5466. hp1_last := p_dist;
  5467. Continue;
  5468. end;
  5469. Break;
  5470. end;
  5471. end;
  5472. { Search for:
  5473. test %reg,%reg
  5474. j(c1) @lbl1
  5475. ...
  5476. @lbl:
  5477. test %reg,%reg (same register)
  5478. j(c2) @lbl2
  5479. If c2 is a subset of c1, change to:
  5480. test %reg,%reg
  5481. j(c1) @lbl2
  5482. (@lbl1 may become a dead label as a result)
  5483. }
  5484. if (taicpu(p).oper[1]^.typ = top_reg) and
  5485. (taicpu(p).oper[0]^.typ = top_reg) and
  5486. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5487. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5488. Assigned(p_label) and
  5489. GetNextInstruction(p_label, p_dist) and
  5490. MatchInstruction(p_dist, A_TEST, []) and
  5491. { It's fine if the second test uses smaller sub-registers }
  5492. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5493. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5494. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5495. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5496. GetNextInstruction(p_dist, hp1_dist) and
  5497. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5498. begin
  5499. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5500. if JumpLabel = JumpLabel_dist then
  5501. { This is an infinite loop }
  5502. Exit;
  5503. { Best optimisation when the first condition is a subset (or equal) of the second }
  5504. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5505. begin
  5506. { Any registers used here will already be allocated }
  5507. if Assigned(JumpLabel) then
  5508. JumpLabel.DecRefs;
  5509. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5510. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5511. Result := True;
  5512. Exit;
  5513. end;
  5514. end;
  5515. end;
  5516. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5517. var
  5518. hp1, hp2: tai;
  5519. ActiveReg: TRegister;
  5520. OldOffset: asizeint;
  5521. ThisConst: TCGInt;
  5522. function RegDeallocated: Boolean;
  5523. begin
  5524. TransferUsedRegs(TmpUsedRegs);
  5525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5526. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5527. end;
  5528. begin
  5529. result:=false;
  5530. hp1 := nil;
  5531. { replace
  5532. addX const,%reg1
  5533. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5534. dealloc %reg1
  5535. by
  5536. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5537. }
  5538. if MatchOpType(taicpu(p),top_const,top_reg) then
  5539. begin
  5540. ActiveReg := taicpu(p).oper[1]^.reg;
  5541. { Ensures the entire register was updated }
  5542. if (taicpu(p).opsize >= S_L) and
  5543. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5544. MatchInstruction(hp1,A_LEA,[]) and
  5545. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5546. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5547. (
  5548. { Cover the case where the register in the reference is also the destination register }
  5549. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5550. (
  5551. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5552. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5553. RegDeallocated
  5554. )
  5555. ) then
  5556. begin
  5557. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5558. {$push}
  5559. {$R-}{$Q-}
  5560. { Explicitly disable overflow checking for these offset calculation
  5561. as those do not matter for the final result }
  5562. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5563. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5564. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5565. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5566. {$pop}
  5567. {$ifdef x86_64}
  5568. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5569. begin
  5570. { Overflow; abort }
  5571. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5572. end
  5573. else
  5574. {$endif x86_64}
  5575. begin
  5576. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5577. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5578. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5579. RemoveCurrentP(p, hp1)
  5580. else
  5581. RemoveCurrentP(p);
  5582. result:=true;
  5583. Exit;
  5584. end;
  5585. end;
  5586. if (
  5587. { Save calling GetNextInstructionUsingReg again }
  5588. Assigned(hp1) or
  5589. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5590. ) and
  5591. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5592. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5593. begin
  5594. if taicpu(hp1).oper[0]^.typ = top_const then
  5595. begin
  5596. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5597. if taicpu(hp1).opcode = A_ADD then
  5598. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5599. else
  5600. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5601. Result := True;
  5602. { Handle any overflows }
  5603. case taicpu(p).opsize of
  5604. S_B:
  5605. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5606. S_W:
  5607. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5608. S_L:
  5609. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5610. {$ifdef x86_64}
  5611. S_Q:
  5612. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5613. { Overflow; abort }
  5614. Result := False
  5615. else
  5616. taicpu(p).oper[0]^.val := ThisConst;
  5617. {$endif x86_64}
  5618. else
  5619. InternalError(2021102610);
  5620. end;
  5621. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5622. if Result then
  5623. begin
  5624. if (taicpu(p).oper[0]^.val < 0) and
  5625. (
  5626. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5627. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5628. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5629. ) then
  5630. begin
  5631. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5632. taicpu(p).opcode := A_SUB;
  5633. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5634. end
  5635. else
  5636. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5637. RemoveInstruction(hp1);
  5638. end;
  5639. end
  5640. else
  5641. begin
  5642. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5643. TransferUsedRegs(TmpUsedRegs);
  5644. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5645. hp2 := p;
  5646. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5647. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5648. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5649. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5650. begin
  5651. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5652. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5653. Asml.Remove(p);
  5654. Asml.InsertAfter(p, hp1);
  5655. p := hp1;
  5656. Result := True;
  5657. Exit;
  5658. end;
  5659. end;
  5660. end;
  5661. if DoArithCombineOpt(p) then
  5662. Result:=true;
  5663. end;
  5664. end;
  5665. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5666. var
  5667. hp1, hp2: tai;
  5668. ref: Integer;
  5669. saveref: treference;
  5670. offsetcalc: Int64;
  5671. TempReg: TRegister;
  5672. Multiple: TCGInt;
  5673. Adjacent, IntermediateRegDiscarded: Boolean;
  5674. begin
  5675. Result:=false;
  5676. { play save and throw an error if LEA uses a seg register prefix,
  5677. this is most likely an error somewhere else }
  5678. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5679. internalerror(2022022001);
  5680. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5681. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5682. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5683. (
  5684. { do not mess with leas accessing the stack pointer
  5685. unless it's a null operation }
  5686. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5687. (
  5688. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5689. (taicpu(p).oper[0]^.ref^.offset = 0)
  5690. )
  5691. ) and
  5692. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5693. begin
  5694. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5695. begin
  5696. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5697. begin
  5698. taicpu(p).opcode := A_MOV;
  5699. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5700. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5701. end
  5702. else
  5703. begin
  5704. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5705. RemoveCurrentP(p);
  5706. end;
  5707. Result:=true;
  5708. exit;
  5709. end
  5710. else if (
  5711. { continue to use lea to adjust the stack pointer,
  5712. it is the recommended way, but only if not optimizing for size }
  5713. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5714. (cs_opt_size in current_settings.optimizerswitches)
  5715. ) and
  5716. { If the flags register is in use, don't change the instruction
  5717. to an ADD otherwise this will scramble the flags. [Kit] }
  5718. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5719. ConvertLEA(taicpu(p)) then
  5720. begin
  5721. Result:=true;
  5722. exit;
  5723. end;
  5724. end;
  5725. { Don't optimise if the stack or frame pointer is the destination register }
  5726. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5727. Exit;
  5728. if GetNextInstruction(p,hp1) and
  5729. (hp1.typ=ait_instruction) then
  5730. begin
  5731. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5732. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5733. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5734. begin
  5735. TransferUsedRegs(TmpUsedRegs);
  5736. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5737. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5738. begin
  5739. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5740. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5741. RemoveInstruction(hp1);
  5742. result:=true;
  5743. exit;
  5744. end;
  5745. end;
  5746. { changes
  5747. lea <ref1>, reg1
  5748. <op> ...,<ref. with reg1>,...
  5749. to
  5750. <op> ...,<ref1>,... }
  5751. { find a reference which uses reg1 }
  5752. 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
  5753. ref:=0
  5754. 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
  5755. ref:=1
  5756. else
  5757. ref:=-1;
  5758. if (ref<>-1) and
  5759. { reg1 must be either the base or the index }
  5760. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5761. begin
  5762. { reg1 can be removed from the reference }
  5763. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5764. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5765. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5766. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5767. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5768. else
  5769. Internalerror(2019111201);
  5770. { check if the can insert all data of the lea into the second instruction }
  5771. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5772. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5773. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5774. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5775. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5776. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5777. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5778. {$ifdef x86_64}
  5779. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5780. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5781. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5782. )
  5783. {$endif x86_64}
  5784. then
  5785. begin
  5786. { reg1 might not used by the second instruction after it is remove from the reference }
  5787. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5788. begin
  5789. TransferUsedRegs(TmpUsedRegs);
  5790. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5791. { reg1 is not updated so it might not be used afterwards }
  5792. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5793. begin
  5794. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5795. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5796. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5797. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5798. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5799. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5800. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5801. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5802. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5803. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5804. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5805. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5806. RemoveCurrentP(p, hp1);
  5807. result:=true;
  5808. exit;
  5809. end
  5810. end;
  5811. end;
  5812. { recover }
  5813. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5814. end;
  5815. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5816. if Adjacent or
  5817. { Check further ahead (up to 2 instructions ahead for -O2) }
  5818. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5819. begin
  5820. { Check common LEA/LEA conditions }
  5821. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5822. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5823. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5824. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5825. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5826. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5827. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5828. (
  5829. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5830. calling it (since it calls GetNextInstruction) }
  5831. Adjacent or
  5832. (
  5833. (
  5834. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5835. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5836. ) and (
  5837. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5838. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5839. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5840. )
  5841. )
  5842. ) then
  5843. begin
  5844. TransferUsedRegs(TmpUsedRegs);
  5845. hp2 := p;
  5846. repeat
  5847. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5848. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5849. IntermediateRegDiscarded :=
  5850. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5851. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5852. { changes
  5853. lea offset1(regX,scale), reg1
  5854. lea offset2(reg1,reg1), reg2
  5855. to
  5856. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5857. and
  5858. lea offset1(regX,scale1), reg1
  5859. lea offset2(reg1,scale2), reg2
  5860. to
  5861. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5862. and
  5863. lea offset1(regX,scale1), reg1
  5864. lea offset2(reg3,reg1,scale2), reg2
  5865. to
  5866. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5867. ... so long as the final scale does not exceed 8
  5868. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5869. }
  5870. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5871. (
  5872. { Don't optimise if size is a concern and the intermediate register remains in use }
  5873. IntermediateRegDiscarded or
  5874. (
  5875. not (cs_opt_size in current_settings.optimizerswitches) and
  5876. { If the intermediate register is not discarded, it must not
  5877. appear in the first LEA's reference. (Fixes #41166) }
  5878. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5879. )
  5880. ) and
  5881. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5882. (
  5883. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5884. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5885. ) and (
  5886. (
  5887. { lea (reg1,scale2), reg2 variant }
  5888. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5889. (
  5890. Adjacent or
  5891. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5892. ) and
  5893. (
  5894. (
  5895. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5896. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5897. ) or (
  5898. { lea (regX,regX), reg1 variant }
  5899. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5900. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5901. )
  5902. )
  5903. ) or (
  5904. { lea (reg1,reg1), reg1 variant }
  5905. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5906. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5907. )
  5908. ) then
  5909. begin
  5910. { Make everything homogeneous to make calculations easier }
  5911. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5912. begin
  5913. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5914. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5915. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5916. else
  5917. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5918. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5919. end;
  5920. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5921. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5922. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5923. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5924. begin
  5925. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5926. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5927. begin
  5928. { Put the register to change in the index register }
  5929. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5930. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5931. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5932. end;
  5933. { Change lea (reg,reg) to lea(,reg,2) }
  5934. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5935. begin
  5936. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5937. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5938. end;
  5939. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5940. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5941. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5942. { Just to prevent miscalculations }
  5943. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5944. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5945. else
  5946. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5947. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5948. if IntermediateRegDiscarded then
  5949. begin
  5950. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5951. RemoveCurrentP(p);
  5952. end
  5953. else
  5954. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5955. result:=true;
  5956. exit;
  5957. end;
  5958. end;
  5959. { changes
  5960. lea offset1(regX), reg1
  5961. lea offset2(reg1), reg2
  5962. to
  5963. lea offset1+offset2(regX), reg2 }
  5964. if (
  5965. { Don't optimise if size is a concern and the intermediate register remains in use }
  5966. IntermediateRegDiscarded or
  5967. (
  5968. not (cs_opt_size in current_settings.optimizerswitches) and
  5969. { If the intermediate register is not discarded, it must not
  5970. appear in the first LEA's reference. (Fixes #41166) }
  5971. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5972. )
  5973. ) and
  5974. (
  5975. (
  5976. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5977. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5978. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5979. ) or (
  5980. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5981. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5982. (
  5983. (
  5984. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5985. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5986. ) or (
  5987. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5988. (
  5989. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5990. (
  5991. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5992. (
  5993. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5994. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5995. )
  5996. )
  5997. )
  5998. )
  5999. )
  6000. )
  6001. ) then
  6002. begin
  6003. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6004. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6005. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6006. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6007. begin
  6008. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6009. begin
  6010. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6011. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6012. { if the register is used as index and base, we have to increase for base as well
  6013. and adapt base }
  6014. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6015. begin
  6016. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6017. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6018. end;
  6019. end
  6020. else
  6021. begin
  6022. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6023. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6024. end;
  6025. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6026. begin
  6027. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6028. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6029. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6030. { Catch the situation where the base = index
  6031. and treat this as *2. The scalefactor of
  6032. p will be 0 or 1 due to the conditional
  6033. checks above. Fixes i40647 }
  6034. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6035. else
  6036. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6037. end;
  6038. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6039. if IntermediateRegDiscarded then
  6040. begin
  6041. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6042. RemoveCurrentP(p);
  6043. end
  6044. else
  6045. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6046. result:=true;
  6047. exit;
  6048. end;
  6049. end;
  6050. end;
  6051. { Change:
  6052. leal/q $x(%reg1),%reg2
  6053. ...
  6054. shll/q $y,%reg2
  6055. To:
  6056. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6057. }
  6058. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6059. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6060. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6061. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6062. (taicpu(hp1).oper[0]^.val <= 3) then
  6063. begin
  6064. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6065. TransferUsedRegs(TmpUsedRegs);
  6066. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6067. if
  6068. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6069. (this works even if scalefactor is zero) }
  6070. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6071. { Ensure offset doesn't go out of bounds }
  6072. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6073. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6074. (
  6075. (
  6076. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6077. (
  6078. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6079. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6080. (
  6081. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6082. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6083. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6084. )
  6085. )
  6086. ) or (
  6087. (
  6088. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6089. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6090. ) and
  6091. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6092. )
  6093. ) then
  6094. begin
  6095. repeat
  6096. with taicpu(p).oper[0]^.ref^ do
  6097. begin
  6098. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6099. if index = base then
  6100. begin
  6101. if Multiple > 4 then
  6102. { Optimisation will no longer work because resultant
  6103. scale factor will exceed 8 }
  6104. Break;
  6105. base := NR_NO;
  6106. scalefactor := 2;
  6107. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6108. end
  6109. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6110. begin
  6111. { Scale factor only works on the index register }
  6112. index := base;
  6113. base := NR_NO;
  6114. end;
  6115. { For safety }
  6116. if scalefactor <= 1 then
  6117. begin
  6118. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6119. scalefactor := Multiple;
  6120. end
  6121. else
  6122. begin
  6123. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6124. scalefactor := scalefactor * Multiple;
  6125. end;
  6126. offset := offset * Multiple;
  6127. end;
  6128. RemoveInstruction(hp1);
  6129. Result := True;
  6130. Exit;
  6131. { This repeat..until loop exists for the benefit of Break }
  6132. until True;
  6133. end;
  6134. end;
  6135. end;
  6136. end;
  6137. end;
  6138. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6139. var
  6140. hp1 : tai;
  6141. SubInstr: Boolean;
  6142. ThisConst: TCGInt;
  6143. const
  6144. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6145. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6146. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6147. begin
  6148. Result := False;
  6149. if taicpu(p).oper[0]^.typ <> top_const then
  6150. { Should have been confirmed before calling }
  6151. InternalError(2021102601);
  6152. SubInstr := (taicpu(p).opcode = A_SUB);
  6153. if GetLastInstruction(p, hp1) and
  6154. (hp1.typ = ait_instruction) and
  6155. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6156. begin
  6157. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6158. { Bad size }
  6159. InternalError(2022042001);
  6160. case taicpu(hp1).opcode Of
  6161. A_INC:
  6162. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6163. begin
  6164. if SubInstr then
  6165. ThisConst := taicpu(p).oper[0]^.val - 1
  6166. else
  6167. ThisConst := taicpu(p).oper[0]^.val + 1;
  6168. end
  6169. else
  6170. Exit;
  6171. A_DEC:
  6172. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6173. begin
  6174. if SubInstr then
  6175. ThisConst := taicpu(p).oper[0]^.val + 1
  6176. else
  6177. ThisConst := taicpu(p).oper[0]^.val - 1;
  6178. end
  6179. else
  6180. Exit;
  6181. A_SUB:
  6182. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6183. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6184. begin
  6185. if SubInstr then
  6186. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6187. else
  6188. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6189. end
  6190. else
  6191. Exit;
  6192. A_ADD:
  6193. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6194. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6195. begin
  6196. if SubInstr then
  6197. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6198. else
  6199. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6200. end
  6201. else
  6202. Exit;
  6203. else
  6204. Exit;
  6205. end;
  6206. { Check that the values are in range }
  6207. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6208. { Overflow; abort }
  6209. Exit;
  6210. if (ThisConst = 0) then
  6211. begin
  6212. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6213. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6214. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6215. RemoveInstruction(hp1);
  6216. hp1 := tai(p.next);
  6217. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6218. if not GetLastInstruction(hp1, p) then
  6219. p := hp1;
  6220. end
  6221. else
  6222. begin
  6223. if taicpu(hp1).opercnt=1 then
  6224. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6225. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6226. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6227. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6228. else
  6229. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6230. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6231. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6232. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6233. RemoveInstruction(hp1);
  6234. taicpu(p).loadconst(0, ThisConst);
  6235. end;
  6236. Result := True;
  6237. end;
  6238. end;
  6239. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6240. begin
  6241. Result := False;
  6242. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6243. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6244. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6245. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6246. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6247. (
  6248. (
  6249. (taicpu(hp1).opcode = A_TEST)
  6250. ) or (
  6251. (taicpu(hp1).opcode = A_CMP) and
  6252. { A sanity check more than anything }
  6253. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6254. )
  6255. ) then
  6256. begin
  6257. { change
  6258. mov mem, %reg
  6259. ...
  6260. cmp/test x, %reg / test %reg,%reg
  6261. (reg deallocated)
  6262. to
  6263. cmp/test x, mem / cmp 0, mem
  6264. }
  6265. TransferUsedRegs(TmpUsedRegs);
  6266. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6267. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6268. begin
  6269. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6270. if (taicpu(hp1).opcode = A_TEST) and
  6271. (
  6272. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6273. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6274. ) then
  6275. begin
  6276. taicpu(hp1).opcode := A_CMP;
  6277. taicpu(hp1).loadconst(0, 0);
  6278. end;
  6279. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6280. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6281. RemoveCurrentP(p);
  6282. if (p <> hp1) then
  6283. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6284. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6285. { Make sure the flags are allocated across the CMP instruction }
  6286. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6287. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6288. Result := True;
  6289. Exit;
  6290. end;
  6291. end;
  6292. end;
  6293. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6294. var
  6295. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6296. ThisReg, SecondReg: TRegister;
  6297. JumpLoc: TAsmLabel;
  6298. NewSize: TOpSize;
  6299. begin
  6300. Result := False;
  6301. {
  6302. Convert:
  6303. j<c> .L1
  6304. .L2:
  6305. mov 1,reg
  6306. jmp .L3 (or ret, although it might not be a RET yet)
  6307. .L1:
  6308. mov 0,reg
  6309. jmp .L3 (or ret)
  6310. ( As long as .L3 <> .L1 or .L2)
  6311. To:
  6312. mov 0,reg
  6313. set<not(c)> reg
  6314. jmp .L3 (or ret)
  6315. .L2:
  6316. mov 1,reg
  6317. jmp .L3 (or ret)
  6318. .L1:
  6319. mov 0,reg
  6320. jmp .L3 (or ret)
  6321. }
  6322. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6323. Exit;
  6324. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6325. if GetNextInstruction(hp_label, hp2) and
  6326. MatchInstruction(hp2,A_MOV,[]) and
  6327. (taicpu(hp2).oper[0]^.typ = top_const) and
  6328. (
  6329. (
  6330. (taicpu(hp2).oper[1]^.typ = top_reg)
  6331. {$ifdef i386}
  6332. { Under i386, ESI, EDI, EBP and ESP
  6333. don't have an 8-bit representation }
  6334. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6335. {$endif i386}
  6336. ) or (
  6337. {$ifdef i386}
  6338. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6339. {$endif i386}
  6340. (taicpu(hp2).opsize = S_B)
  6341. )
  6342. ) and
  6343. GetNextInstruction(hp2, hp3) and
  6344. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6345. (
  6346. (taicpu(hp3).opcode=A_RET) or
  6347. (
  6348. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6349. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6350. )
  6351. ) and
  6352. GetNextInstruction(hp3, hp4) and
  6353. FindLabel(JumpLoc, hp4) and
  6354. (
  6355. not (cs_opt_size in current_settings.optimizerswitches) or
  6356. { If the initial jump is the label's only reference, then it will
  6357. become a dead label if the other conditions are met and hence
  6358. remove at least 2 instructions, including a jump }
  6359. (JumpLoc.getrefs = 1)
  6360. ) and
  6361. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6362. that will be optimised out }
  6363. GetNextInstruction(hp4, hp5) and
  6364. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6365. (taicpu(hp5).oper[0]^.typ = top_const) and
  6366. (
  6367. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6368. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6369. ) and
  6370. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6371. GetNextInstruction(hp5,hp6) and
  6372. (
  6373. not (hp6.typ in [ait_align, ait_label]) or
  6374. SkipLabels(hp6, hp6)
  6375. ) and
  6376. (hp6.typ=ait_instruction) then
  6377. begin
  6378. { First, let's look at the two jumps that are hp3 and hp6 }
  6379. if not
  6380. (
  6381. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6382. (
  6383. (taicpu(hp6).opcode=A_RET) or
  6384. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6385. )
  6386. ) then
  6387. { If condition is False, then the JMP/RET instructions matched conventionally }
  6388. begin
  6389. { See if one of the jumps can be instantly converted into a RET }
  6390. if (taicpu(hp3).opcode=A_JMP) then
  6391. begin
  6392. { Reuse hp5 }
  6393. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6394. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6395. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6396. Exit;
  6397. if MatchInstruction(hp5, A_RET, []) then
  6398. begin
  6399. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6400. ConvertJumpToRET(hp3, hp5);
  6401. Result := True;
  6402. end
  6403. else
  6404. Exit;
  6405. end;
  6406. if (taicpu(hp6).opcode=A_JMP) then
  6407. begin
  6408. { Reuse hp5 }
  6409. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6410. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6411. Exit;
  6412. if MatchInstruction(hp5, A_RET, []) then
  6413. begin
  6414. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6415. ConvertJumpToRET(hp6, hp5);
  6416. Result := True;
  6417. end
  6418. else
  6419. Exit;
  6420. end;
  6421. if not
  6422. (
  6423. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6424. (
  6425. (taicpu(hp6).opcode=A_RET) or
  6426. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6427. )
  6428. ) then
  6429. { Still doesn't match }
  6430. Exit;
  6431. end;
  6432. if (taicpu(hp2).oper[0]^.val = 1) then
  6433. begin
  6434. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6435. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6436. end
  6437. else
  6438. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6439. if taicpu(hp2).opsize=S_B then
  6440. begin
  6441. if taicpu(hp2).oper[1]^.typ = top_reg then
  6442. begin
  6443. SecondReg := taicpu(hp2).oper[1]^.reg;
  6444. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6445. end
  6446. else
  6447. begin
  6448. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6449. SecondReg := NR_NO;
  6450. end;
  6451. hp_pos := p;
  6452. hp_allocstart := hp4;
  6453. end
  6454. else
  6455. begin
  6456. { Will be a register because the size can't be S_B otherwise }
  6457. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6458. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6459. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6460. if (cs_opt_size in current_settings.optimizerswitches) then
  6461. begin
  6462. { Favour using MOVZX when optimising for size }
  6463. case taicpu(hp2).opsize of
  6464. S_W:
  6465. NewSize := S_BW;
  6466. S_L:
  6467. NewSize := S_BL;
  6468. {$ifdef x86_64}
  6469. S_Q:
  6470. begin
  6471. NewSize := S_BL;
  6472. { Will implicitly zero-extend to 64-bit }
  6473. setsubreg(SecondReg, R_SUBD);
  6474. end;
  6475. {$endif x86_64}
  6476. else
  6477. InternalError(2022101301);
  6478. end;
  6479. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6480. { Inserting it right before p will guarantee that the flags are also tracked }
  6481. Asml.InsertBefore(hp5, p);
  6482. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6483. hp_pos := hp5;
  6484. hp_allocstart := hp4;
  6485. end
  6486. else
  6487. begin
  6488. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6489. { Inserting it right before p will guarantee that the flags are also tracked }
  6490. Asml.InsertBefore(hp5, p);
  6491. hp_pos := p;
  6492. hp_allocstart := hp5;
  6493. end;
  6494. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6495. end;
  6496. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6497. taicpu(hp4).condition := taicpu(p).condition;
  6498. asml.InsertBefore(hp4, hp_pos);
  6499. if taicpu(hp3).is_jmp then
  6500. begin
  6501. JumpLoc.decrefs;
  6502. MakeUnconditional(taicpu(p));
  6503. { This also increases the reference count }
  6504. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6505. end
  6506. else
  6507. ConvertJumpToRET(p, hp3);
  6508. if SecondReg <> NR_NO then
  6509. { Ensure the destination register is allocated over this region }
  6510. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6511. if (JumpLoc.getrefs = 0) then
  6512. RemoveDeadCodeAfterJump(hp3);
  6513. Result:=true;
  6514. exit;
  6515. end;
  6516. end;
  6517. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6518. var
  6519. hp1, hp2: tai;
  6520. ActiveReg: TRegister;
  6521. OldOffset: asizeint;
  6522. ThisConst: TCGInt;
  6523. function RegDeallocated: Boolean;
  6524. begin
  6525. TransferUsedRegs(TmpUsedRegs);
  6526. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6527. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6528. end;
  6529. begin
  6530. Result:=false;
  6531. hp1 := nil;
  6532. { replace
  6533. subX const,%reg1
  6534. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6535. dealloc %reg1
  6536. by
  6537. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6538. }
  6539. if MatchOpType(taicpu(p),top_const,top_reg) then
  6540. begin
  6541. ActiveReg := taicpu(p).oper[1]^.reg;
  6542. { Ensures the entire register was updated }
  6543. if (taicpu(p).opsize >= S_L) and
  6544. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6545. MatchInstruction(hp1,A_LEA,[]) and
  6546. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6547. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6548. (
  6549. { Cover the case where the register in the reference is also the destination register }
  6550. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6551. (
  6552. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6553. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6554. RegDeallocated
  6555. )
  6556. ) then
  6557. begin
  6558. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6559. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6560. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6561. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6562. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6563. {$ifdef x86_64}
  6564. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6565. begin
  6566. { Overflow; abort }
  6567. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6568. end
  6569. else
  6570. {$endif x86_64}
  6571. begin
  6572. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6573. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6574. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6575. RemoveCurrentP(p, hp1)
  6576. else
  6577. RemoveCurrentP(p);
  6578. result:=true;
  6579. Exit;
  6580. end;
  6581. end;
  6582. if (
  6583. { Save calling GetNextInstructionUsingReg again }
  6584. Assigned(hp1) or
  6585. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6586. ) and
  6587. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6588. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6589. begin
  6590. if taicpu(hp1).oper[0]^.typ = top_const then
  6591. begin
  6592. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6593. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6594. Result := True;
  6595. { Handle any overflows }
  6596. case taicpu(p).opsize of
  6597. S_B:
  6598. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6599. S_W:
  6600. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6601. S_L:
  6602. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6603. {$ifdef x86_64}
  6604. S_Q:
  6605. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6606. { Overflow; abort }
  6607. Result := False
  6608. else
  6609. taicpu(p).oper[0]^.val := ThisConst;
  6610. {$endif x86_64}
  6611. else
  6612. InternalError(2021102611);
  6613. end;
  6614. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6615. if Result then
  6616. begin
  6617. if (taicpu(p).oper[0]^.val < 0) and
  6618. (
  6619. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6620. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6621. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6622. ) then
  6623. begin
  6624. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6625. taicpu(p).opcode := A_SUB;
  6626. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6627. end
  6628. else
  6629. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6630. RemoveInstruction(hp1);
  6631. end;
  6632. end
  6633. else
  6634. begin
  6635. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6636. TransferUsedRegs(TmpUsedRegs);
  6637. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6638. hp2 := p;
  6639. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6640. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6641. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6642. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6643. begin
  6644. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6645. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6646. Asml.Remove(p);
  6647. Asml.InsertAfter(p, hp1);
  6648. p := hp1;
  6649. Result := True;
  6650. Exit;
  6651. end;
  6652. end;
  6653. end;
  6654. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6655. { * change "sub/add const1, reg" or "dec reg" followed by
  6656. "sub const2, reg" to one "sub ..., reg" }
  6657. {$ifdef i386}
  6658. if (taicpu(p).oper[0]^.val = 2) and
  6659. (ActiveReg = NR_ESP) and
  6660. { Don't do the sub/push optimization if the sub }
  6661. { comes from setting up the stack frame (JM) }
  6662. (not(GetLastInstruction(p,hp1)) or
  6663. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6664. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6665. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6666. begin
  6667. hp1 := tai(p.next);
  6668. while Assigned(hp1) and
  6669. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6670. not RegReadByInstruction(NR_ESP,hp1) and
  6671. not RegModifiedByInstruction(NR_ESP,hp1) do
  6672. hp1 := tai(hp1.next);
  6673. if Assigned(hp1) and
  6674. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6675. begin
  6676. taicpu(hp1).changeopsize(S_L);
  6677. if taicpu(hp1).oper[0]^.typ=top_reg then
  6678. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6679. hp1 := tai(p.next);
  6680. RemoveCurrentp(p, hp1);
  6681. Result:=true;
  6682. exit;
  6683. end;
  6684. end;
  6685. {$endif i386}
  6686. if DoArithCombineOpt(p) then
  6687. Result:=true;
  6688. end;
  6689. end;
  6690. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6691. var
  6692. TmpBool1,TmpBool2 : Boolean;
  6693. tmpref : treference;
  6694. hp1,hp2: tai;
  6695. mask, shiftval: tcgint;
  6696. begin
  6697. Result:=false;
  6698. { All these optimisations work on "shl/sal const,%reg" }
  6699. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6700. Exit;
  6701. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6702. (taicpu(p).oper[0]^.val <= 3) then
  6703. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6704. begin
  6705. { should we check the next instruction? }
  6706. TmpBool1 := True;
  6707. { have we found an add/sub which could be
  6708. integrated in the lea? }
  6709. TmpBool2 := False;
  6710. reference_reset(tmpref,2,[]);
  6711. TmpRef.index := taicpu(p).oper[1]^.reg;
  6712. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6713. while TmpBool1 and
  6714. GetNextInstruction(p, hp1) and
  6715. (tai(hp1).typ = ait_instruction) and
  6716. ((((taicpu(hp1).opcode = A_ADD) or
  6717. (taicpu(hp1).opcode = A_SUB)) and
  6718. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6719. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6720. (((taicpu(hp1).opcode = A_INC) or
  6721. (taicpu(hp1).opcode = A_DEC)) and
  6722. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6723. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6724. ((taicpu(hp1).opcode = A_LEA) and
  6725. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6726. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6727. (not GetNextInstruction(hp1,hp2) or
  6728. not instrReadsFlags(hp2)) Do
  6729. begin
  6730. TmpBool1 := False;
  6731. if taicpu(hp1).opcode=A_LEA then
  6732. begin
  6733. if (TmpRef.base = NR_NO) and
  6734. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6735. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6736. { Segment register isn't a concern here }
  6737. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6738. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6739. begin
  6740. TmpBool1 := True;
  6741. TmpBool2 := True;
  6742. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6743. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6744. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6745. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6746. RemoveInstruction(hp1);
  6747. end
  6748. end
  6749. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6750. begin
  6751. TmpBool1 := True;
  6752. TmpBool2 := True;
  6753. case taicpu(hp1).opcode of
  6754. A_ADD:
  6755. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6756. A_SUB:
  6757. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6758. else
  6759. internalerror(2019050536);
  6760. end;
  6761. RemoveInstruction(hp1);
  6762. end
  6763. else
  6764. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6765. (((taicpu(hp1).opcode = A_ADD) and
  6766. (TmpRef.base = NR_NO)) or
  6767. (taicpu(hp1).opcode = A_INC) or
  6768. (taicpu(hp1).opcode = A_DEC)) then
  6769. begin
  6770. TmpBool1 := True;
  6771. TmpBool2 := True;
  6772. case taicpu(hp1).opcode of
  6773. A_ADD:
  6774. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6775. A_INC:
  6776. inc(TmpRef.offset);
  6777. A_DEC:
  6778. dec(TmpRef.offset);
  6779. else
  6780. internalerror(2019050535);
  6781. end;
  6782. RemoveInstruction(hp1);
  6783. end;
  6784. end;
  6785. if TmpBool2
  6786. {$ifndef x86_64}
  6787. or
  6788. ((current_settings.optimizecputype < cpu_Pentium2) and
  6789. (taicpu(p).oper[0]^.val <= 3) and
  6790. not(cs_opt_size in current_settings.optimizerswitches))
  6791. {$endif x86_64}
  6792. then
  6793. begin
  6794. if not(TmpBool2) and
  6795. (taicpu(p).oper[0]^.val=1) then
  6796. begin
  6797. taicpu(p).opcode := A_ADD;
  6798. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6799. end
  6800. else
  6801. begin
  6802. taicpu(p).opcode := A_LEA;
  6803. taicpu(p).loadref(0, TmpRef);
  6804. end;
  6805. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6806. Result := True;
  6807. end;
  6808. end
  6809. {$ifndef x86_64}
  6810. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6811. begin
  6812. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6813. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6814. (unlike shl, which is only Tairable in the U pipe) }
  6815. if taicpu(p).oper[0]^.val=1 then
  6816. begin
  6817. taicpu(p).opcode := A_ADD;
  6818. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6819. Result := True;
  6820. end
  6821. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6822. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6823. else if (taicpu(p).opsize = S_L) and
  6824. (taicpu(p).oper[0]^.val<= 3) then
  6825. begin
  6826. reference_reset(tmpref,2,[]);
  6827. TmpRef.index := taicpu(p).oper[1]^.reg;
  6828. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6829. taicpu(p).opcode := A_LEA;
  6830. taicpu(p).loadref(0, TmpRef);
  6831. Result := True;
  6832. end;
  6833. end
  6834. {$endif x86_64}
  6835. else if
  6836. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6837. (
  6838. (
  6839. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6840. SetAndTest(hp1, hp2)
  6841. {$ifdef x86_64}
  6842. ) or
  6843. (
  6844. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6845. GetNextInstruction(hp1, hp2) and
  6846. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6847. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6848. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6849. {$endif x86_64}
  6850. )
  6851. ) and
  6852. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6853. begin
  6854. { Change:
  6855. shl x, %reg1
  6856. mov -(1<<x), %reg2
  6857. and %reg2, %reg1
  6858. Or:
  6859. shl x, %reg1
  6860. and -(1<<x), %reg1
  6861. To just:
  6862. shl x, %reg1
  6863. Since the and operation only zeroes bits that are already zero from the shl operation
  6864. }
  6865. case taicpu(p).oper[0]^.val of
  6866. 8:
  6867. mask:=$FFFFFFFFFFFFFF00;
  6868. 16:
  6869. mask:=$FFFFFFFFFFFF0000;
  6870. 32:
  6871. mask:=$FFFFFFFF00000000;
  6872. 63:
  6873. { Constant pre-calculated to prevent overflow errors with Int64 }
  6874. mask:=$8000000000000000;
  6875. else
  6876. begin
  6877. if taicpu(p).oper[0]^.val >= 64 then
  6878. { Shouldn't happen realistically, since the register
  6879. is guaranteed to be set to zero at this point }
  6880. mask := 0
  6881. else
  6882. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6883. end;
  6884. end;
  6885. if taicpu(hp1).oper[0]^.val = mask then
  6886. begin
  6887. { Everything checks out, perform the optimisation, as long as
  6888. the FLAGS register isn't being used}
  6889. TransferUsedRegs(TmpUsedRegs);
  6890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6891. {$ifdef x86_64}
  6892. if (hp1 <> hp2) then
  6893. begin
  6894. { "shl/mov/and" version }
  6895. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6896. { Don't do the optimisation if the FLAGS register is in use }
  6897. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6898. begin
  6899. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6900. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6901. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6902. begin
  6903. RemoveInstruction(hp1);
  6904. Result := True;
  6905. end;
  6906. { Only set Result to True if the 'mov' instruction was removed }
  6907. RemoveInstruction(hp2);
  6908. end;
  6909. end
  6910. else
  6911. {$endif x86_64}
  6912. begin
  6913. { "shl/and" version }
  6914. { Don't do the optimisation if the FLAGS register is in use }
  6915. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6916. begin
  6917. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6918. RemoveInstruction(hp1);
  6919. Result := True;
  6920. end;
  6921. end;
  6922. Exit;
  6923. end
  6924. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6925. begin
  6926. { Even if the mask doesn't allow for its removal, we might be
  6927. able to optimise the mask for the "shl/and" version, which
  6928. may permit other peephole optimisations }
  6929. {$ifdef DEBUG_AOPTCPU}
  6930. mask := taicpu(hp1).oper[0]^.val and mask;
  6931. if taicpu(hp1).oper[0]^.val <> mask then
  6932. begin
  6933. DebugMsg(
  6934. SPeepholeOptimization +
  6935. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6936. ' to $' + debug_tostr(mask) +
  6937. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6938. taicpu(hp1).oper[0]^.val := mask;
  6939. end;
  6940. {$else DEBUG_AOPTCPU}
  6941. { If debugging is off, just set the operand even if it's the same }
  6942. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6943. {$endif DEBUG_AOPTCPU}
  6944. end;
  6945. end;
  6946. {
  6947. change
  6948. shl/sal const,reg
  6949. <op> ...(...,reg,1),...
  6950. into
  6951. <op> ...(...,reg,1 shl const),...
  6952. if const in 1..3
  6953. }
  6954. if MatchOpType(taicpu(p), top_const, top_reg) and
  6955. (taicpu(p).oper[0]^.val in [1..3]) and
  6956. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6957. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6958. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6959. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6960. MatchOpType(taicpu(hp1),top_ref))
  6961. ) and
  6962. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6963. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6964. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6965. begin
  6966. TransferUsedRegs(TmpUsedRegs);
  6967. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6968. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6969. begin
  6970. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6971. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6972. RemoveCurrentP(p);
  6973. Result:=true;
  6974. exit;
  6975. end;
  6976. end;
  6977. if MatchOpType(taicpu(p), top_const, top_reg) and
  6978. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6979. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6980. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6981. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6982. begin
  6983. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6984. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6985. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6986. {$ifdef x86_64}
  6987. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6988. {$endif x86_64}
  6989. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6990. begin
  6991. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6992. taicpu(hp1).opcode:=A_MOV;
  6993. taicpu(hp1).oper[0]^.val:=0;
  6994. end
  6995. else
  6996. begin
  6997. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6998. taicpu(hp1).oper[0]^.val:=shiftval;
  6999. end;
  7000. RemoveCurrentP(p);
  7001. Result:=true;
  7002. exit;
  7003. end;
  7004. end;
  7005. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7006. begin
  7007. case shr_size of
  7008. S_B:
  7009. { No valid combinations }
  7010. Result := False;
  7011. S_W:
  7012. Result := (Shift >= 8) and (movz_size = S_BW);
  7013. S_L:
  7014. Result :=
  7015. (Shift >= 24) { Any opsize is valid for this shift } or
  7016. ((Shift >= 16) and (movz_size = S_WL));
  7017. {$ifdef x86_64}
  7018. S_Q:
  7019. Result :=
  7020. (Shift >= 56) { Any opsize is valid for this shift } or
  7021. ((Shift >= 48) and (movz_size = S_WL));
  7022. {$endif x86_64}
  7023. else
  7024. InternalError(2022081510);
  7025. end;
  7026. end;
  7027. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7028. var
  7029. hp1, hp2: tai;
  7030. Shift: TCGInt;
  7031. LimitSize: Topsize;
  7032. DoNotMerge: Boolean;
  7033. begin
  7034. Result := False;
  7035. { All these optimisations work on "shr const,%reg" }
  7036. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7037. Exit;
  7038. DoNotMerge := False;
  7039. Shift := taicpu(p).oper[0]^.val;
  7040. LimitSize := taicpu(p).opsize;
  7041. hp1 := p;
  7042. repeat
  7043. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7044. Exit;
  7045. case taicpu(hp1).opcode of
  7046. A_TEST, A_CMP, A_Jcc:
  7047. { Skip over conditional jumps and relevant comparisons }
  7048. Continue;
  7049. A_MOVZX:
  7050. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7051. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7052. begin
  7053. { Since the original register is being read as is, subsequent
  7054. SHRs must not be merged at this point }
  7055. DoNotMerge := True;
  7056. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7057. begin
  7058. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  7059. begin
  7060. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7061. taicpu(hp1).opcode := A_MOV;
  7062. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7063. case taicpu(hp1).opsize of
  7064. S_BW:
  7065. taicpu(hp1).opsize := S_W;
  7066. S_BL, S_WL:
  7067. taicpu(hp1).opsize := S_L;
  7068. else
  7069. InternalError(2022081503);
  7070. end;
  7071. { p itself hasn't changed, so no need to set Result to True }
  7072. Include(OptsToCheck, aoc_ForceNewIteration);
  7073. { See if there's anything afterwards that can be
  7074. optimised, since the input register hasn't changed }
  7075. Continue;
  7076. end;
  7077. { NOTE: If the MOVZX instruction reads and writes the same
  7078. register, defer this to the post-peephole optimisation stage }
  7079. Exit;
  7080. end;
  7081. end;
  7082. A_SHL, A_SAL, A_SHR:
  7083. if (taicpu(hp1).opsize <= LimitSize) and
  7084. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7085. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7086. begin
  7087. { Make sure the sizes don't exceed the register size limit
  7088. (measured by the shift value falling below the limit) }
  7089. if taicpu(hp1).opsize < LimitSize then
  7090. LimitSize := taicpu(hp1).opsize;
  7091. if taicpu(hp1).opcode = A_SHR then
  7092. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7093. else
  7094. begin
  7095. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7096. DoNotMerge := True;
  7097. end;
  7098. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7099. Exit;
  7100. { Since we've established that the combined shift is within
  7101. limits, we can actually combine the adjacent SHR
  7102. instructions even if they're different sizes }
  7103. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7104. begin
  7105. hp2 := tai(hp1.Previous);
  7106. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7107. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7108. RemoveInstruction(hp1);
  7109. hp1 := hp2;
  7110. { Though p has changed, only the constant has, and its
  7111. effects can still be detected on the next iteration of
  7112. the repeat..until loop }
  7113. Include(OptsToCheck, aoc_ForceNewIteration);
  7114. end;
  7115. { Move onto the next instruction }
  7116. Continue;
  7117. end;
  7118. else
  7119. ;
  7120. end;
  7121. Break;
  7122. until False;
  7123. end;
  7124. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7125. var
  7126. CurrentRef: TReference;
  7127. FullReg: TRegister;
  7128. hp1, hp2: tai;
  7129. begin
  7130. Result := False;
  7131. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7132. Exit;
  7133. { We assume you've checked if the operand is actually a reference by
  7134. this point. If it isn't, you'll most likely get an access violation }
  7135. CurrentRef := first_mov.oper[1]^.ref^;
  7136. { Memory must be aligned }
  7137. if (CurrentRef.offset mod 4) <> 0 then
  7138. Exit;
  7139. Inc(CurrentRef.offset);
  7140. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7141. if MatchOperand(second_mov.oper[0]^, 0) and
  7142. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7143. GetNextInstruction(second_mov, hp1) and
  7144. (hp1.typ = ait_instruction) and
  7145. (taicpu(hp1).opcode = A_MOV) and
  7146. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7147. (taicpu(hp1).oper[0]^.val = 0) then
  7148. begin
  7149. Inc(CurrentRef.offset);
  7150. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7151. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7152. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7153. begin
  7154. case taicpu(hp1).opsize of
  7155. S_B:
  7156. if GetNextInstruction(hp1, hp2) and
  7157. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7158. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7159. (taicpu(hp2).oper[0]^.val = 0) then
  7160. begin
  7161. Inc(CurrentRef.offset);
  7162. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7163. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7164. (taicpu(hp2).opsize = S_B) then
  7165. begin
  7166. RemoveInstruction(hp1);
  7167. RemoveInstruction(hp2);
  7168. first_mov.opsize := S_L;
  7169. if first_mov.oper[0]^.typ = top_reg then
  7170. begin
  7171. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7172. { Reuse second_mov as a MOVZX instruction }
  7173. second_mov.opcode := A_MOVZX;
  7174. second_mov.opsize := S_BL;
  7175. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7176. second_mov.loadreg(1, FullReg);
  7177. first_mov.oper[0]^.reg := FullReg;
  7178. asml.Remove(second_mov);
  7179. asml.InsertBefore(second_mov, first_mov);
  7180. end
  7181. else
  7182. { It's a value }
  7183. begin
  7184. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7185. RemoveInstruction(second_mov);
  7186. end;
  7187. Result := True;
  7188. Exit;
  7189. end;
  7190. end;
  7191. S_W:
  7192. begin
  7193. RemoveInstruction(hp1);
  7194. first_mov.opsize := S_L;
  7195. if first_mov.oper[0]^.typ = top_reg then
  7196. begin
  7197. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7198. { Reuse second_mov as a MOVZX instruction }
  7199. second_mov.opcode := A_MOVZX;
  7200. second_mov.opsize := S_BL;
  7201. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7202. second_mov.loadreg(1, FullReg);
  7203. first_mov.oper[0]^.reg := FullReg;
  7204. asml.Remove(second_mov);
  7205. asml.InsertBefore(second_mov, first_mov);
  7206. end
  7207. else
  7208. { It's a value }
  7209. begin
  7210. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7211. RemoveInstruction(second_mov);
  7212. end;
  7213. Result := True;
  7214. Exit;
  7215. end;
  7216. else
  7217. ;
  7218. end;
  7219. end;
  7220. end;
  7221. end;
  7222. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7223. { returns true if a "continue" should be done after this optimization }
  7224. var
  7225. hp1, hp2, hp3: tai;
  7226. begin
  7227. Result := false;
  7228. hp3 := nil;
  7229. if MatchOpType(taicpu(p),top_ref) and
  7230. GetNextInstruction(p, hp1) and
  7231. (hp1.typ = ait_instruction) and
  7232. (((taicpu(hp1).opcode = A_FLD) and
  7233. (taicpu(p).opcode = A_FSTP)) or
  7234. ((taicpu(p).opcode = A_FISTP) and
  7235. (taicpu(hp1).opcode = A_FILD))) and
  7236. MatchOpType(taicpu(hp1),top_ref) and
  7237. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7238. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7239. begin
  7240. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7241. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7242. GetNextInstruction(hp1, hp2) and
  7243. (((hp2.typ = ait_instruction) and
  7244. IsExitCode(hp2) and
  7245. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7246. not(assigned(current_procinfo.procdef.funcretsym) and
  7247. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7248. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7249. { fstp <temp>
  7250. fld <temp>
  7251. <dealloc> <temp>
  7252. }
  7253. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7254. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7255. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7256. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7257. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7258. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7259. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7260. )
  7261. )
  7262. ) then
  7263. begin
  7264. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7265. RemoveInstruction(hp1);
  7266. RemoveCurrentP(p, hp2);
  7267. { first case: exit code }
  7268. if hp2.typ = ait_instruction then
  7269. RemoveLastDeallocForFuncRes(p);
  7270. Result := true;
  7271. end
  7272. else
  7273. { we can do this only in fast math mode as fstp is rounding ...
  7274. ... still disabled as it breaks the compiler and/or rtl }
  7275. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7276. { ... or if another fstp equal to the first one follows }
  7277. GetNextInstruction(hp1,hp2) and
  7278. (hp2.typ = ait_instruction) and
  7279. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7280. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7281. begin
  7282. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7283. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7284. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7285. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7286. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7287. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7288. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7289. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7290. ) then
  7291. begin
  7292. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7293. RemoveCurrentP(p,hp2);
  7294. RemoveInstruction(hp1);
  7295. Result := true;
  7296. end
  7297. else if { fst can't store an extended/comp value }
  7298. (taicpu(p).opsize <> S_FX) and
  7299. (taicpu(p).opsize <> S_IQ) then
  7300. begin
  7301. if (taicpu(p).opcode = A_FSTP) then
  7302. taicpu(p).opcode := A_FST
  7303. else
  7304. taicpu(p).opcode := A_FIST;
  7305. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7306. RemoveInstruction(hp1);
  7307. Result := true;
  7308. end;
  7309. end;
  7310. end;
  7311. end;
  7312. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7313. var
  7314. hp1, hp2, hp3: tai;
  7315. begin
  7316. result:=false;
  7317. if MatchOpType(taicpu(p),top_reg) and
  7318. GetNextInstruction(p, hp1) and
  7319. (hp1.typ = Ait_Instruction) and
  7320. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7321. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7322. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7323. { change to
  7324. fld reg fxxx reg,st
  7325. fxxxp st, st1 (hp1)
  7326. Remark: non commutative operations must be reversed!
  7327. }
  7328. begin
  7329. case taicpu(hp1).opcode Of
  7330. A_FMULP,A_FADDP,
  7331. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7332. begin
  7333. case taicpu(hp1).opcode Of
  7334. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7335. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7336. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7337. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7338. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7339. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7340. else
  7341. internalerror(2019050534);
  7342. end;
  7343. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7344. taicpu(hp1).oper[1]^.reg := NR_ST;
  7345. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7346. RemoveCurrentP(p, hp1);
  7347. Result:=true;
  7348. exit;
  7349. end;
  7350. else
  7351. ;
  7352. end;
  7353. end
  7354. else
  7355. if MatchOpType(taicpu(p),top_ref) and
  7356. GetNextInstruction(p, hp2) and
  7357. (hp2.typ = Ait_Instruction) and
  7358. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7359. (taicpu(p).opsize in [S_FS, S_FL]) and
  7360. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7361. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7362. if GetLastInstruction(p, hp1) and
  7363. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7364. MatchOpType(taicpu(hp1),top_ref) and
  7365. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7366. if ((taicpu(hp2).opcode = A_FMULP) or
  7367. (taicpu(hp2).opcode = A_FADDP)) then
  7368. { change to
  7369. fld/fst mem1 (hp1) fld/fst mem1
  7370. fld mem1 (p) fadd/
  7371. faddp/ fmul st, st
  7372. fmulp st, st1 (hp2) }
  7373. begin
  7374. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7375. RemoveCurrentP(p, hp1);
  7376. if (taicpu(hp2).opcode = A_FADDP) then
  7377. taicpu(hp2).opcode := A_FADD
  7378. else
  7379. taicpu(hp2).opcode := A_FMUL;
  7380. taicpu(hp2).oper[1]^.reg := NR_ST;
  7381. end
  7382. else
  7383. { change to
  7384. fld/fst mem1 (hp1) fld/fst mem1
  7385. fld mem1 (p) fld st
  7386. }
  7387. begin
  7388. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7389. taicpu(p).changeopsize(S_FL);
  7390. taicpu(p).loadreg(0,NR_ST);
  7391. end
  7392. else
  7393. begin
  7394. case taicpu(hp2).opcode Of
  7395. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7396. { change to
  7397. fld/fst mem1 (hp1) fld/fst mem1
  7398. fld mem2 (p) fxxx mem2
  7399. fxxxp st, st1 (hp2) }
  7400. begin
  7401. case taicpu(hp2).opcode Of
  7402. A_FADDP: taicpu(p).opcode := A_FADD;
  7403. A_FMULP: taicpu(p).opcode := A_FMUL;
  7404. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7405. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7406. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7407. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7408. else
  7409. internalerror(2019050533);
  7410. end;
  7411. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7412. RemoveInstruction(hp2);
  7413. end
  7414. else
  7415. ;
  7416. end
  7417. end
  7418. end;
  7419. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7420. begin
  7421. Result := condition_in(cond1, cond2) or
  7422. { Not strictly subsets due to the actual flags checked, but because we're
  7423. comparing integers, E is a subset of AE and GE and their aliases }
  7424. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7425. end;
  7426. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7427. var
  7428. v: TCGInt;
  7429. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7430. FirstMatch, TempBool: Boolean;
  7431. NewReg: TRegister;
  7432. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7433. begin
  7434. Result:=false;
  7435. { All these optimisations need a next instruction }
  7436. if not GetNextInstruction(p, hp1) then
  7437. Exit;
  7438. true_hp1 := hp1;
  7439. { Search for:
  7440. cmp ###,###
  7441. j(c1) @lbl1
  7442. ...
  7443. @lbl:
  7444. cmp ###,### (same comparison as above)
  7445. j(c2) @lbl2
  7446. If c1 is a subset of c2, change to:
  7447. cmp ###,###
  7448. j(c1) @lbl2
  7449. (@lbl1 may become a dead label as a result)
  7450. }
  7451. { Also handle cases where there are multiple jumps in a row }
  7452. p_jump := hp1;
  7453. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7454. begin
  7455. Prefetch(p_jump.Next);
  7456. if IsJumpToLabel(taicpu(p_jump)) then
  7457. begin
  7458. { Do jump optimisations first in case the condition becomes
  7459. unnecessary }
  7460. TempBool := True;
  7461. if DoJumpOptimizations(p_jump, TempBool) or
  7462. not TempBool then
  7463. begin
  7464. if Assigned(p_jump) then
  7465. begin
  7466. { CollapseZeroDistJump will be set to the label or an align
  7467. before it after the jump if it optimises, whether or not
  7468. the label is live or dead }
  7469. if (p_jump.typ = ait_align) or
  7470. (
  7471. (p_jump.typ = ait_label) and
  7472. not (tai_label(p_jump).labsym.is_used)
  7473. ) then
  7474. GetNextInstruction(p_jump, p_jump);
  7475. end;
  7476. TransferUsedRegs(TmpUsedRegs);
  7477. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7478. if not Assigned(p_jump) or
  7479. (
  7480. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7481. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7482. ) then
  7483. begin
  7484. { No more conditional jumps; conditional statement is no longer required }
  7485. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7486. RemoveCurrentP(p);
  7487. Result := True;
  7488. Exit;
  7489. end;
  7490. hp1 := p_jump;
  7491. Include(OptsToCheck, aoc_ForceNewIteration);
  7492. Continue;
  7493. end;
  7494. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7495. if GetNextInstruction(p_jump, hp2) and
  7496. (
  7497. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7498. not TempBool
  7499. ) then
  7500. begin
  7501. hp1 := p_jump;
  7502. Include(OptsToCheck, aoc_ForceNewIteration);
  7503. Continue;
  7504. end;
  7505. p_label := nil;
  7506. if Assigned(JumpLabel) then
  7507. p_label := getlabelwithsym(JumpLabel);
  7508. if Assigned(p_label) and
  7509. GetNextInstruction(p_label, p_dist) and
  7510. MatchInstruction(p_dist, A_CMP, []) and
  7511. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7512. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7513. GetNextInstruction(p_dist, hp1_dist) and
  7514. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7515. begin
  7516. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7517. if JumpLabel = JumpLabel_dist then
  7518. { This is an infinite loop }
  7519. Exit;
  7520. { Best optimisation when the first condition is a subset (or equal) of the second }
  7521. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7522. begin
  7523. { Any registers used here will already be allocated }
  7524. if Assigned(JumpLabel) then
  7525. JumpLabel.DecRefs;
  7526. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7527. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7528. Include(OptsToCheck, aoc_ForceNewIteration);
  7529. { Don't exit yet. Since p and p_jump haven't actually been
  7530. removed, we can check for more on this iteration }
  7531. end
  7532. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7533. GetNextInstruction(hp1_dist, hp1_label) and
  7534. (hp1_label.typ = ait_label) then
  7535. begin
  7536. JumpLabel_far := tai_label(hp1_label).labsym;
  7537. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7538. { This is an infinite loop }
  7539. Exit;
  7540. if Assigned(JumpLabel_far) then
  7541. begin
  7542. { In this situation, if the first jump branches, the second one will never,
  7543. branch so change the destination label to after the second jump }
  7544. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7545. if Assigned(JumpLabel) then
  7546. JumpLabel.DecRefs;
  7547. JumpLabel_far.IncRefs;
  7548. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7549. Result := True;
  7550. { Don't exit yet. Since p and p_jump haven't actually been
  7551. removed, we can check for more on this iteration }
  7552. Continue;
  7553. end;
  7554. end;
  7555. end;
  7556. end;
  7557. { Search for:
  7558. cmp ###,###
  7559. j(c1) @lbl1
  7560. cmp ###,### (same as first)
  7561. Remove second cmp
  7562. }
  7563. if GetNextInstruction(p_jump, hp2) and
  7564. (
  7565. (
  7566. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7567. (
  7568. (
  7569. MatchOpType(taicpu(p), top_const, top_reg) and
  7570. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7571. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7572. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7573. ) or (
  7574. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7575. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7576. )
  7577. )
  7578. ) or (
  7579. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7580. MatchOperand(taicpu(p).oper[0]^, 0) and
  7581. (taicpu(p).oper[1]^.typ = top_reg) and
  7582. MatchInstruction(hp2, A_TEST, []) and
  7583. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7584. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7585. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7586. )
  7587. ) then
  7588. begin
  7589. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7590. TransferUsedRegs(TmpUsedRegs);
  7591. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7592. RemoveInstruction(hp2);
  7593. Result := True;
  7594. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7595. end
  7596. else
  7597. begin
  7598. { hp2 is the next instruction, so save time and just set p_jump
  7599. to it instead of calling GetNextInstruction below }
  7600. p_jump := hp2;
  7601. Continue;
  7602. end;
  7603. GetNextInstruction(p_jump, p_jump);
  7604. end;
  7605. if (
  7606. { Don't call GetNextInstruction again if we already have it }
  7607. (true_hp1 = p_jump) or
  7608. GetNextInstruction(p, hp1)
  7609. ) and
  7610. MatchInstruction(hp1, A_Jcc, []) and
  7611. IsJumpToLabel(taicpu(hp1)) and
  7612. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7613. GetNextInstruction(hp1, hp2) then
  7614. begin
  7615. {
  7616. cmp x, y (or "cmp y, x")
  7617. je @lbl
  7618. mov x, y
  7619. @lbl:
  7620. (x and y can be constants, registers or references)
  7621. Change to:
  7622. mov x, y (x and y will always be equal in the end)
  7623. @lbl: (may beceome a dead label)
  7624. Also:
  7625. cmp x, y (or "cmp y, x")
  7626. jne @lbl
  7627. mov x, y
  7628. @lbl:
  7629. (x and y can be constants, registers or references)
  7630. Change to:
  7631. Absolutely nothing! (Except @lbl if it's still live)
  7632. }
  7633. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7634. (
  7635. (
  7636. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7637. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7638. ) or (
  7639. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7640. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7641. )
  7642. ) and
  7643. GetNextInstruction(hp2, hp1_label) and
  7644. (hp1_label.typ = ait_label) and
  7645. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7646. begin
  7647. tai_label(hp1_label).labsym.DecRefs;
  7648. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7649. begin
  7650. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7651. RemoveInstruction(hp2);
  7652. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7653. end
  7654. else
  7655. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7656. RemoveInstruction(hp1);
  7657. RemoveCurrentp(p, hp2);
  7658. Result := True;
  7659. Exit;
  7660. end;
  7661. {
  7662. Try to optimise the following:
  7663. cmp $x,### ($x and $y can be registers or constants)
  7664. je @lbl1 (only reference)
  7665. cmp $y,### (### are identical)
  7666. @Lbl:
  7667. sete %reg1
  7668. Change to:
  7669. cmp $x,###
  7670. sete %reg2 (allocate new %reg2)
  7671. cmp $y,###
  7672. sete %reg1
  7673. orb %reg2,%reg1
  7674. (dealloc %reg2)
  7675. This adds an instruction (so don't perform under -Os), but it removes
  7676. a conditional branch.
  7677. }
  7678. if not (cs_opt_size in current_settings.optimizerswitches) and
  7679. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7680. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7681. { The first operand of CMP instructions can only be a register or
  7682. immediate anyway, so no need to check }
  7683. GetNextInstruction(hp2, p_label) and
  7684. (p_label.typ = ait_label) and
  7685. (tai_label(p_label).labsym.getrefs = 1) and
  7686. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7687. GetNextInstruction(p_label, p_dist) and
  7688. MatchInstruction(p_dist, A_SETcc, []) and
  7689. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7690. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7691. begin
  7692. TransferUsedRegs(TmpUsedRegs);
  7693. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7694. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7695. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7696. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7697. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7698. { Get the instruction after the SETcc instruction so we can
  7699. allocate a new register over the entire range }
  7700. GetNextInstruction(p_dist, hp1_dist) then
  7701. begin
  7702. { Register can appear in p if it's not used afterwards, so only
  7703. allocate between hp1 and hp1_dist }
  7704. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7705. if NewReg <> NR_NO then
  7706. begin
  7707. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7708. { Change the jump instruction into a SETcc instruction }
  7709. taicpu(hp1).opcode := A_SETcc;
  7710. taicpu(hp1).opsize := S_B;
  7711. taicpu(hp1).loadreg(0, NewReg);
  7712. { This is now a dead label }
  7713. tai_label(p_label).labsym.decrefs;
  7714. { Prefer adding before the next instruction so the FLAGS
  7715. register is deallicated first }
  7716. AsmL.InsertBefore(
  7717. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7718. hp1_dist
  7719. );
  7720. Result := True;
  7721. { Don't exit yet, as p wasn't changed and hp1, while
  7722. modified, is still intact and might be optimised by the
  7723. SETcc optimisation below }
  7724. end;
  7725. end;
  7726. end;
  7727. end;
  7728. if (taicpu(p).oper[0]^.typ = top_const) and
  7729. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7730. begin
  7731. if (taicpu(p).oper[0]^.val = 0) and
  7732. (taicpu(p).oper[1]^.typ = top_reg) then
  7733. begin
  7734. hp2 := p;
  7735. FirstMatch := True;
  7736. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7737. anything meaningful once it's converted to "test %reg,%reg";
  7738. additionally, some jumps will always (or never) branch, so
  7739. evaluate every jump immediately following the
  7740. comparison, optimising the conditions if possible.
  7741. Similarly with SETcc... those that are always set to 0 or 1
  7742. are changed to MOV instructions }
  7743. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7744. (
  7745. GetNextInstruction(hp2, hp1) and
  7746. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7747. ) do
  7748. begin
  7749. Prefetch(hp1.Next);
  7750. FirstMatch := False;
  7751. case taicpu(hp1).condition of
  7752. C_B, C_C, C_NAE, C_O:
  7753. { For B/NAE:
  7754. Will never branch since an unsigned integer can never be below zero
  7755. For C/O:
  7756. Result cannot overflow because 0 is being subtracted
  7757. }
  7758. begin
  7759. if taicpu(hp1).opcode = A_Jcc then
  7760. begin
  7761. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7762. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7763. RemoveInstruction(hp1);
  7764. { Since hp1 was deleted, hp2 must not be updated }
  7765. Continue;
  7766. end
  7767. else
  7768. begin
  7769. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7770. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7771. taicpu(hp1).opcode := A_MOV;
  7772. taicpu(hp1).ops := 2;
  7773. taicpu(hp1).condition := C_None;
  7774. taicpu(hp1).opsize := S_B;
  7775. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7776. taicpu(hp1).loadconst(0, 0);
  7777. end;
  7778. end;
  7779. C_BE, C_NA:
  7780. begin
  7781. { Will only branch if equal to zero }
  7782. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7783. taicpu(hp1).condition := C_E;
  7784. end;
  7785. C_A, C_NBE:
  7786. begin
  7787. { Will only branch if not equal to zero }
  7788. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7789. taicpu(hp1).condition := C_NE;
  7790. end;
  7791. C_AE, C_NB, C_NC, C_NO:
  7792. begin
  7793. { Will always branch }
  7794. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7795. if taicpu(hp1).opcode = A_Jcc then
  7796. begin
  7797. MakeUnconditional(taicpu(hp1));
  7798. { Any jumps/set that follow will now be dead code }
  7799. RemoveDeadCodeAfterJump(taicpu(hp1));
  7800. Break;
  7801. end
  7802. else
  7803. begin
  7804. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7805. taicpu(hp1).opcode := A_MOV;
  7806. taicpu(hp1).ops := 2;
  7807. taicpu(hp1).condition := C_None;
  7808. taicpu(hp1).opsize := S_B;
  7809. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7810. taicpu(hp1).loadconst(0, 1);
  7811. end;
  7812. end;
  7813. C_None:
  7814. InternalError(2020012201);
  7815. C_P, C_PE, C_NP, C_PO:
  7816. { We can't handle parity checks and they should never be generated
  7817. after a general-purpose CMP (it's used in some floating-point
  7818. comparisons that don't use CMP) }
  7819. InternalError(2020012202);
  7820. else
  7821. { Zero/Equality, Sign, their complements and all of the
  7822. signed comparisons do not need to be converted };
  7823. end;
  7824. hp2 := hp1;
  7825. end;
  7826. { Convert the instruction to a TEST }
  7827. taicpu(p).opcode := A_TEST;
  7828. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7829. Result := True;
  7830. Exit;
  7831. end
  7832. else
  7833. begin
  7834. TransferUsedRegs(TmpUsedRegs);
  7835. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7836. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7837. begin
  7838. if (taicpu(p).oper[0]^.val = 1) and
  7839. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7840. begin
  7841. { Convert; To:
  7842. cmp $1,r/m cmp $0,r/m
  7843. jl @lbl jle @lbl
  7844. (Also do inverted conditions)
  7845. }
  7846. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7847. taicpu(p).oper[0]^.val := 0;
  7848. if taicpu(hp1).condition in [C_L, C_NGE] then
  7849. taicpu(hp1).condition := C_LE
  7850. else
  7851. taicpu(hp1).condition := C_NLE;
  7852. { If the instruction is now "cmp $0,%reg", convert it to a
  7853. TEST (and effectively do the work of the "cmp $0,%reg" in
  7854. the block above)
  7855. }
  7856. if (taicpu(p).oper[1]^.typ = top_reg) then
  7857. begin
  7858. taicpu(p).opcode := A_TEST;
  7859. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7860. end;
  7861. Result := True;
  7862. Exit;
  7863. end
  7864. else if (taicpu(p).oper[1]^.typ = top_reg)
  7865. {$ifdef x86_64}
  7866. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7867. {$endif x86_64}
  7868. then
  7869. begin
  7870. { cmp register,$8000 neg register
  7871. je target --> jo target
  7872. .... only if register is deallocated before jump.}
  7873. case Taicpu(p).opsize of
  7874. S_B: v:=$80;
  7875. S_W: v:=$8000;
  7876. S_L: v:=qword($80000000);
  7877. else
  7878. internalerror(2013112905);
  7879. end;
  7880. if (taicpu(p).oper[0]^.val=v) and
  7881. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7882. begin
  7883. TransferUsedRegs(TmpUsedRegs);
  7884. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7885. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7886. begin
  7887. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7888. Taicpu(p).opcode:=A_NEG;
  7889. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7890. Taicpu(p).clearop(1);
  7891. Taicpu(p).ops:=1;
  7892. if Taicpu(hp1).condition=C_E then
  7893. Taicpu(hp1).condition:=C_O
  7894. else
  7895. Taicpu(hp1).condition:=C_NO;
  7896. Result:=true;
  7897. exit;
  7898. end;
  7899. end;
  7900. end;
  7901. end;
  7902. end;
  7903. end;
  7904. if TrySwapMovCmp(p, hp1) then
  7905. begin
  7906. Result := True;
  7907. Exit;
  7908. end;
  7909. end;
  7910. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7911. var
  7912. hp1: tai;
  7913. begin
  7914. {
  7915. remove the second (v)pxor from
  7916. pxor reg,reg
  7917. ...
  7918. pxor reg,reg
  7919. }
  7920. Result:=false;
  7921. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7922. MatchOpType(taicpu(p),top_reg,top_reg) and
  7923. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7924. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7925. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7926. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7927. begin
  7928. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7929. RemoveInstruction(hp1);
  7930. Result:=true;
  7931. Exit;
  7932. end
  7933. {
  7934. replace
  7935. pxor reg1,reg1
  7936. movapd/s reg1,reg2
  7937. dealloc reg1
  7938. by
  7939. pxor reg2,reg2
  7940. }
  7941. else if GetNextInstruction(p,hp1) and
  7942. { we mix single and double opperations here because we assume that the compiler
  7943. generates vmovapd only after double operations and vmovaps only after single operations }
  7944. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7945. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7946. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7947. (taicpu(p).oper[0]^.typ=top_reg) then
  7948. begin
  7949. TransferUsedRegs(TmpUsedRegs);
  7950. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7951. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7952. begin
  7953. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7954. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7955. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7956. RemoveInstruction(hp1);
  7957. result:=true;
  7958. end;
  7959. end;
  7960. end;
  7961. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7962. var
  7963. hp1: tai;
  7964. begin
  7965. {
  7966. remove the second (v)pxor from
  7967. (v)pxor reg,reg
  7968. ...
  7969. (v)pxor reg,reg
  7970. }
  7971. Result:=false;
  7972. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7973. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7974. begin
  7975. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7976. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7977. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7978. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7979. begin
  7980. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7981. RemoveInstruction(hp1);
  7982. Result:=true;
  7983. Exit;
  7984. end;
  7985. {$ifdef x86_64}
  7986. {
  7987. replace
  7988. vpxor reg1,reg1,reg1
  7989. vmov reg,mem
  7990. by
  7991. movq $0,mem
  7992. }
  7993. if GetNextInstruction(p,hp1) and
  7994. MatchInstruction(hp1,A_VMOVSD,[]) and
  7995. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7996. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7997. begin
  7998. TransferUsedRegs(TmpUsedRegs);
  7999. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8000. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8001. begin
  8002. taicpu(hp1).loadconst(0,0);
  8003. taicpu(hp1).opcode:=A_MOV;
  8004. taicpu(hp1).opsize:=S_Q;
  8005. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8006. RemoveCurrentP(p);
  8007. result:=true;
  8008. Exit;
  8009. end;
  8010. end;
  8011. {$endif x86_64}
  8012. end
  8013. {
  8014. replace
  8015. vpxor reg1,reg1,reg2
  8016. by
  8017. vpxor reg2,reg2,reg2
  8018. to avoid unncessary data dependencies
  8019. }
  8020. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8021. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8022. begin
  8023. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8024. { avoid unncessary data dependency }
  8025. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8026. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8027. result:=true;
  8028. exit;
  8029. end;
  8030. Result:=OptPass1VOP(p);
  8031. end;
  8032. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8033. var
  8034. hp1 : tai;
  8035. begin
  8036. result:=false;
  8037. { replace
  8038. IMul const,%mreg1,%mreg2
  8039. Mov %reg2,%mreg3
  8040. dealloc %mreg3
  8041. by
  8042. Imul const,%mreg1,%mreg23
  8043. }
  8044. if (taicpu(p).ops=3) and
  8045. GetNextInstruction(p,hp1) and
  8046. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8047. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8048. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8049. begin
  8050. TransferUsedRegs(TmpUsedRegs);
  8051. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8052. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8053. begin
  8054. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8055. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8056. RemoveInstruction(hp1);
  8057. result:=true;
  8058. end;
  8059. end;
  8060. end;
  8061. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8062. var
  8063. hp1 : tai;
  8064. begin
  8065. result:=false;
  8066. { replace
  8067. IMul %reg0,%reg1,%reg2
  8068. Mov %reg2,%reg3
  8069. dealloc %reg2
  8070. by
  8071. Imul %reg0,%reg1,%reg3
  8072. }
  8073. if GetNextInstruction(p,hp1) and
  8074. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8075. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8076. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8077. begin
  8078. TransferUsedRegs(TmpUsedRegs);
  8079. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8080. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8081. begin
  8082. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8083. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8084. RemoveInstruction(hp1);
  8085. result:=true;
  8086. end;
  8087. end;
  8088. end;
  8089. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8090. var
  8091. hp1: tai;
  8092. begin
  8093. Result:=false;
  8094. { get rid of
  8095. (v)cvtss2sd reg0,<reg1,>reg2
  8096. (v)cvtss2sd reg2,<reg2,>reg0
  8097. }
  8098. if GetNextInstruction(p,hp1) and
  8099. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8100. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8101. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8102. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8103. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8104. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8105. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8106. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8107. )
  8108. ) then
  8109. begin
  8110. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8111. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8112. begin
  8113. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8114. RemoveCurrentP(p);
  8115. RemoveInstruction(hp1);
  8116. end
  8117. else
  8118. begin
  8119. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8120. if taicpu(hp1).opcode=A_CVTSD2SS then
  8121. begin
  8122. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8123. taicpu(p).opcode:=A_MOVAPS;
  8124. end
  8125. else
  8126. begin
  8127. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8128. taicpu(p).opcode:=A_VMOVAPS;
  8129. end;
  8130. taicpu(p).ops:=2;
  8131. RemoveInstruction(hp1);
  8132. end;
  8133. Result:=true;
  8134. Exit;
  8135. end;
  8136. end;
  8137. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8138. var
  8139. hp1, hp2, hp3, hp4, hp5: tai;
  8140. ThisReg: TRegister;
  8141. begin
  8142. Result := False;
  8143. if not GetNextInstruction(p,hp1) then
  8144. Exit;
  8145. {
  8146. convert
  8147. j<c> .L1
  8148. mov 1,reg
  8149. jmp .L2
  8150. .L1
  8151. mov 0,reg
  8152. .L2
  8153. into
  8154. mov 0,reg
  8155. set<not(c)> reg
  8156. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8157. would destroy the flag contents
  8158. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8159. executed at the same time as a previous comparison.
  8160. set<not(c)> reg
  8161. movzx reg, reg
  8162. }
  8163. if MatchInstruction(hp1,A_MOV,[]) and
  8164. (taicpu(hp1).oper[0]^.typ = top_const) and
  8165. (
  8166. (
  8167. (taicpu(hp1).oper[1]^.typ = top_reg)
  8168. {$ifdef i386}
  8169. { Under i386, ESI, EDI, EBP and ESP
  8170. don't have an 8-bit representation }
  8171. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8172. {$endif i386}
  8173. ) or (
  8174. {$ifdef i386}
  8175. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8176. {$endif i386}
  8177. (taicpu(hp1).opsize = S_B)
  8178. )
  8179. ) and
  8180. GetNextInstruction(hp1,hp2) and
  8181. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8182. GetNextInstruction(hp2,hp3) and
  8183. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8184. GetNextInstruction(hp3,hp4) and
  8185. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8186. (taicpu(hp4).oper[0]^.typ = top_const) and
  8187. (
  8188. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8189. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8190. ) and
  8191. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8192. GetNextInstruction(hp4,hp5) and
  8193. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8194. begin
  8195. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8196. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8197. tai_label(hp3).labsym.DecRefs;
  8198. { If this isn't the only reference to the middle label, we can
  8199. still make a saving - only that the first jump and everything
  8200. that follows will remain. }
  8201. if (tai_label(hp3).labsym.getrefs = 0) then
  8202. begin
  8203. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8204. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8205. else
  8206. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8207. { remove jump, first label and second MOV (also catching any aligns) }
  8208. repeat
  8209. if not GetNextInstruction(hp2, hp3) then
  8210. InternalError(2021040810);
  8211. RemoveInstruction(hp2);
  8212. hp2 := hp3;
  8213. until hp2 = hp5;
  8214. { Don't decrement reference count before the removal loop
  8215. above, otherwise GetNextInstruction won't stop on the
  8216. the label }
  8217. tai_label(hp5).labsym.DecRefs;
  8218. end
  8219. else
  8220. begin
  8221. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8222. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8223. else
  8224. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8225. end;
  8226. taicpu(p).opcode:=A_SETcc;
  8227. taicpu(p).opsize:=S_B;
  8228. taicpu(p).is_jmp:=False;
  8229. if taicpu(hp1).opsize=S_B then
  8230. begin
  8231. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8232. if taicpu(hp1).oper[1]^.typ = top_reg then
  8233. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8234. RemoveInstruction(hp1);
  8235. end
  8236. else
  8237. begin
  8238. { Will be a register because the size can't be S_B otherwise }
  8239. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8240. taicpu(p).loadreg(0, ThisReg);
  8241. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8242. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8243. begin
  8244. case taicpu(hp1).opsize of
  8245. S_W:
  8246. taicpu(hp1).opsize := S_BW;
  8247. S_L:
  8248. taicpu(hp1).opsize := S_BL;
  8249. {$ifdef x86_64}
  8250. S_Q:
  8251. begin
  8252. taicpu(hp1).opsize := S_BL;
  8253. { Change the destination register to 32-bit }
  8254. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8255. end;
  8256. {$endif x86_64}
  8257. else
  8258. InternalError(2021040820);
  8259. end;
  8260. taicpu(hp1).opcode := A_MOVZX;
  8261. taicpu(hp1).loadreg(0, ThisReg);
  8262. end
  8263. else
  8264. begin
  8265. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8266. { hp1 is already a MOV instruction with the correct register }
  8267. taicpu(hp1).loadconst(0, 0);
  8268. { Inserting it right before p will guarantee that the flags are also tracked }
  8269. asml.Remove(hp1);
  8270. asml.InsertBefore(hp1, p);
  8271. end;
  8272. end;
  8273. Result:=true;
  8274. exit;
  8275. end
  8276. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8277. Result := TryJccStcClcOpt(p, hp1)
  8278. else if (hp1.typ = ait_label) then
  8279. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8280. end;
  8281. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8282. var
  8283. hp1, hp2, hp3: tai;
  8284. SourceRef, TargetRef: TReference;
  8285. CurrentReg: TRegister;
  8286. begin
  8287. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8288. if not UseAVX then
  8289. InternalError(2021100501);
  8290. Result := False;
  8291. { Look for the following to simplify:
  8292. vmovdqa/u x(mem1), %xmmreg
  8293. vmovdqa/u %xmmreg, y(mem2)
  8294. vmovdqa/u x+16(mem1), %xmmreg
  8295. vmovdqa/u %xmmreg, y+16(mem2)
  8296. Change to:
  8297. vmovdqa/u x(mem1), %ymmreg
  8298. vmovdqa/u %ymmreg, y(mem2)
  8299. vpxor %ymmreg, %ymmreg, %ymmreg
  8300. ( The VPXOR instruction is to zero the upper half, thus removing the
  8301. need to call the potentially expensive VZEROUPPER instruction. Other
  8302. peephole optimisations can remove VPXOR if it's unnecessary )
  8303. }
  8304. TransferUsedRegs(TmpUsedRegs);
  8305. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8306. { NOTE: In the optimisations below, if the references dictate that an
  8307. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8308. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8309. if (taicpu(p).opsize = S_XMM) and
  8310. MatchOpType(taicpu(p), top_ref, top_reg) and
  8311. GetNextInstruction(p, hp1) and
  8312. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8313. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8314. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8315. begin
  8316. SourceRef := taicpu(p).oper[0]^.ref^;
  8317. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8318. if GetNextInstruction(hp1, hp2) and
  8319. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8320. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8321. begin
  8322. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8323. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8324. Inc(SourceRef.offset, 16);
  8325. { Reuse the register in the first block move }
  8326. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8327. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8328. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8329. begin
  8330. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8331. Inc(TargetRef.offset, 16);
  8332. if GetNextInstruction(hp2, hp3) and
  8333. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8334. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8335. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8336. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8337. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8338. begin
  8339. { Update the register tracking to the new size }
  8340. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8341. { Remember that the offsets are 16 ahead }
  8342. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8343. if not (
  8344. ((SourceRef.offset mod 32) = 16) and
  8345. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8346. ) then
  8347. taicpu(p).opcode := A_VMOVDQU;
  8348. taicpu(p).opsize := S_YMM;
  8349. taicpu(p).oper[1]^.reg := CurrentReg;
  8350. if not (
  8351. ((TargetRef.offset mod 32) = 16) and
  8352. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8353. ) then
  8354. taicpu(hp1).opcode := A_VMOVDQU;
  8355. taicpu(hp1).opsize := S_YMM;
  8356. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8357. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8358. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8359. if (pi_uses_ymm in current_procinfo.flags) then
  8360. RemoveInstruction(hp2)
  8361. else
  8362. begin
  8363. taicpu(hp2).opcode := A_VPXOR;
  8364. taicpu(hp2).opsize := S_YMM;
  8365. taicpu(hp2).loadreg(0, CurrentReg);
  8366. taicpu(hp2).loadreg(1, CurrentReg);
  8367. taicpu(hp2).loadreg(2, CurrentReg);
  8368. taicpu(hp2).ops := 3;
  8369. end;
  8370. RemoveInstruction(hp3);
  8371. Result := True;
  8372. Exit;
  8373. end;
  8374. end
  8375. else
  8376. begin
  8377. { See if the next references are 16 less rather than 16 greater }
  8378. Dec(SourceRef.offset, 32); { -16 the other way }
  8379. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8380. begin
  8381. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8382. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8383. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8384. GetNextInstruction(hp2, hp3) and
  8385. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8386. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8387. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8388. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8389. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8390. begin
  8391. { Update the register tracking to the new size }
  8392. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8393. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8394. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8395. if not(
  8396. ((SourceRef.offset mod 32) = 0) and
  8397. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8398. ) then
  8399. taicpu(hp2).opcode := A_VMOVDQU;
  8400. taicpu(hp2).opsize := S_YMM;
  8401. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8402. if not (
  8403. ((TargetRef.offset mod 32) = 0) and
  8404. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8405. ) then
  8406. taicpu(hp3).opcode := A_VMOVDQU;
  8407. taicpu(hp3).opsize := S_YMM;
  8408. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8409. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8410. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8411. if (pi_uses_ymm in current_procinfo.flags) then
  8412. RemoveInstruction(hp1)
  8413. else
  8414. begin
  8415. taicpu(hp1).opcode := A_VPXOR;
  8416. taicpu(hp1).opsize := S_YMM;
  8417. taicpu(hp1).loadreg(0, CurrentReg);
  8418. taicpu(hp1).loadreg(1, CurrentReg);
  8419. taicpu(hp1).loadreg(2, CurrentReg);
  8420. taicpu(hp1).ops := 3;
  8421. Asml.Remove(hp1);
  8422. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8423. end;
  8424. RemoveCurrentP(p, hp2);
  8425. Result := True;
  8426. Exit;
  8427. end;
  8428. end;
  8429. end;
  8430. end;
  8431. end;
  8432. end;
  8433. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8434. var
  8435. hp2, hp3, first_assignment: tai;
  8436. IncCount, OperIdx: Integer;
  8437. OrigLabel: TAsmLabel;
  8438. begin
  8439. Count := 0;
  8440. Result := False;
  8441. first_assignment := nil;
  8442. if (LoopCount >= 20) then
  8443. begin
  8444. { Guard against infinite loops }
  8445. Exit;
  8446. end;
  8447. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8448. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8449. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8450. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8451. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8452. Exit;
  8453. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8454. {
  8455. change
  8456. jmp .L1
  8457. ...
  8458. .L1:
  8459. mov ##, ## ( multiple movs possible )
  8460. jmp/ret
  8461. into
  8462. mov ##, ##
  8463. jmp/ret
  8464. }
  8465. if not Assigned(hp1) then
  8466. begin
  8467. hp1 := GetLabelWithSym(OrigLabel);
  8468. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8469. Exit;
  8470. end;
  8471. hp2 := hp1;
  8472. while Assigned(hp2) do
  8473. begin
  8474. if Assigned(hp2) and (hp2.typ = ait_label) then
  8475. SkipLabels(hp2,hp2);
  8476. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8477. Break;
  8478. case taicpu(hp2).opcode of
  8479. A_MOVSD:
  8480. begin
  8481. if taicpu(hp2).ops = 0 then
  8482. { Wrong MOVSD }
  8483. Break;
  8484. Inc(Count);
  8485. if Count >= 5 then
  8486. { Too many to be worthwhile }
  8487. Break;
  8488. GetNextInstruction(hp2, hp2);
  8489. Continue;
  8490. end;
  8491. A_MOV,
  8492. A_MOVD,
  8493. A_MOVQ,
  8494. A_MOVSX,
  8495. {$ifdef x86_64}
  8496. A_MOVSXD,
  8497. {$endif x86_64}
  8498. A_MOVZX,
  8499. A_MOVAPS,
  8500. A_MOVUPS,
  8501. A_MOVSS,
  8502. A_MOVAPD,
  8503. A_MOVUPD,
  8504. A_MOVDQA,
  8505. A_MOVDQU,
  8506. A_VMOVSS,
  8507. A_VMOVAPS,
  8508. A_VMOVUPS,
  8509. A_VMOVSD,
  8510. A_VMOVAPD,
  8511. A_VMOVUPD,
  8512. A_VMOVDQA,
  8513. A_VMOVDQU:
  8514. begin
  8515. Inc(Count);
  8516. if Count >= 5 then
  8517. { Too many to be worthwhile }
  8518. Break;
  8519. GetNextInstruction(hp2, hp2);
  8520. Continue;
  8521. end;
  8522. A_JMP:
  8523. begin
  8524. { Guard against infinite loops }
  8525. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8526. Exit;
  8527. { Analyse this jump first in case it also duplicates assignments }
  8528. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8529. begin
  8530. { Something did change! }
  8531. Result := True;
  8532. Inc(Count, IncCount);
  8533. if Count >= 5 then
  8534. begin
  8535. { Too many to be worthwhile }
  8536. Exit;
  8537. end;
  8538. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8539. Break;
  8540. end;
  8541. Result := True;
  8542. Break;
  8543. end;
  8544. A_RET:
  8545. begin
  8546. Result := True;
  8547. Break;
  8548. end;
  8549. else
  8550. Break;
  8551. end;
  8552. end;
  8553. if Result then
  8554. begin
  8555. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8556. if Count = 0 then
  8557. begin
  8558. Result := False;
  8559. Exit;
  8560. end;
  8561. TransferUsedRegs(TmpUsedRegs);
  8562. hp3 := p;
  8563. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8564. while True do
  8565. begin
  8566. if Assigned(hp1) and (hp1.typ = ait_label) then
  8567. SkipLabels(hp1,hp1);
  8568. case hp1.typ of
  8569. ait_regalloc:
  8570. if tai_regalloc(hp1).ratype = ra_dealloc then
  8571. begin
  8572. { Duplicate the register deallocation... }
  8573. hp3:=tai(hp1.getcopy);
  8574. if first_assignment = nil then
  8575. first_assignment := hp3;
  8576. asml.InsertBefore(hp3, p);
  8577. { ... but also reallocate it after the jump }
  8578. hp3:=tai(hp1.getcopy);
  8579. tai_regalloc(hp3).ratype := ra_alloc;
  8580. asml.InsertAfter(hp3, p);
  8581. end;
  8582. ait_instruction:
  8583. case taicpu(hp1).opcode of
  8584. A_JMP:
  8585. begin
  8586. { Change the original jump to the new destination }
  8587. OrigLabel.decrefs;
  8588. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8589. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8590. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8591. if not Assigned(first_assignment) then
  8592. InternalError(2021040810)
  8593. else
  8594. p := first_assignment;
  8595. Exit;
  8596. end;
  8597. A_RET:
  8598. begin
  8599. { Now change the jump into a RET instruction }
  8600. ConvertJumpToRET(p, hp1);
  8601. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8602. if not Assigned(first_assignment) then
  8603. InternalError(2021040811)
  8604. else
  8605. p := first_assignment;
  8606. Exit;
  8607. end;
  8608. else
  8609. begin
  8610. { Duplicate the MOV instruction }
  8611. hp3:=tai(hp1.getcopy);
  8612. if first_assignment = nil then
  8613. first_assignment := hp3;
  8614. asml.InsertBefore(hp3, p);
  8615. { Make sure the compiler knows about any final registers written here }
  8616. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8617. with taicpu(hp3).oper[OperIdx]^ do
  8618. begin
  8619. case typ of
  8620. top_ref:
  8621. begin
  8622. if (ref^.base <> NR_NO) and
  8623. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8624. (
  8625. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8626. (
  8627. { Allow the frame pointer if it's not being used by the procedure as such }
  8628. Assigned(current_procinfo) and
  8629. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8630. )
  8631. )
  8632. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8633. then
  8634. begin
  8635. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8636. if not Assigned(first_assignment) then
  8637. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8638. end;
  8639. if (ref^.index <> NR_NO) and
  8640. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8641. (
  8642. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8643. (
  8644. { Allow the frame pointer if it's not being used by the procedure as such }
  8645. Assigned(current_procinfo) and
  8646. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8647. )
  8648. )
  8649. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8650. (ref^.index <> ref^.base) then
  8651. begin
  8652. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8653. if not Assigned(first_assignment) then
  8654. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8655. end;
  8656. end;
  8657. top_reg:
  8658. begin
  8659. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8660. if not Assigned(first_assignment) then
  8661. IncludeRegInUsedRegs(reg, UsedRegs);
  8662. end;
  8663. else
  8664. ;
  8665. end;
  8666. end;
  8667. end;
  8668. end;
  8669. else
  8670. InternalError(2021040720);
  8671. end;
  8672. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8673. { Should have dropped out earlier }
  8674. InternalError(2021040710);
  8675. end;
  8676. end;
  8677. end;
  8678. const
  8679. WriteOp: array[0..3] of set of TInsChange = (
  8680. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8681. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8682. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8683. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8684. RegWriteFlags: array[0..7] of set of TInsChange = (
  8685. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8686. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8687. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8688. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8689. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8690. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8691. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8692. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8693. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8694. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8695. var
  8696. hp2: tai;
  8697. X: Integer;
  8698. begin
  8699. { If we have something like:
  8700. op ###,###
  8701. mov ###,###
  8702. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8703. interfere in regards to what they write to.
  8704. NOTE: p must be a 2-operand instruction
  8705. }
  8706. Result := False;
  8707. if (hp1.typ <> ait_instruction) or
  8708. taicpu(hp1).is_jmp or
  8709. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8710. Exit;
  8711. { NOP is a pipeline fence, likely marking the beginning of the function
  8712. epilogue, so drop out. Similarly, drop out if POP or RET are
  8713. encountered }
  8714. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8715. Exit;
  8716. if (taicpu(hp1).opcode = A_MOVSD) and
  8717. (taicpu(hp1).ops = 0) then
  8718. { Wrong MOVSD }
  8719. Exit;
  8720. { Check for writes to specific registers first }
  8721. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8722. for X := 0 to 7 do
  8723. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8724. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8725. Exit;
  8726. for X := 0 to taicpu(hp1).ops - 1 do
  8727. begin
  8728. { Check to see if this operand writes to something }
  8729. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8730. { And matches something in the CMP/TEST instruction }
  8731. (
  8732. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8733. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8734. (
  8735. { If it's a register, make sure the register written to doesn't
  8736. appear in the cmp instruction as part of a reference }
  8737. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8738. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8739. )
  8740. ) then
  8741. Exit;
  8742. end;
  8743. { Check p to make sure it doesn't write to something that affects hp1 }
  8744. { Check for writes to specific registers first }
  8745. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8746. for X := 0 to 7 do
  8747. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8748. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8749. Exit;
  8750. for X := 0 to taicpu(p).ops - 1 do
  8751. begin
  8752. { Check to see if this operand writes to something }
  8753. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8754. { And matches something in hp1 }
  8755. (taicpu(p).oper[X]^.typ = top_reg) and
  8756. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8757. Exit;
  8758. end;
  8759. { The instruction can be safely moved }
  8760. asml.Remove(hp1);
  8761. { Try to insert after the last instructions where the FLAGS register is not
  8762. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8763. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8764. asml.InsertBefore(hp1, hp2)
  8765. { Failing that, try to insert after the last instructions where the
  8766. FLAGS register is not yet in use }
  8767. else if GetLastInstruction(p, hp2) and
  8768. (
  8769. (hp2.typ <> ait_instruction) or
  8770. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8771. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8772. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8773. ) then
  8774. asml.InsertAfter(hp1, hp2)
  8775. else
  8776. { Note, if p.Previous is nil (even if it should logically never be the
  8777. case), FindRegAllocBackward immediately exits with False and so we
  8778. safely land here (we can't just pass p because FindRegAllocBackward
  8779. immediately exits on an instruction). [Kit] }
  8780. asml.InsertBefore(hp1, p);
  8781. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8782. { We can't trust UsedRegs because we're looking backwards, although we
  8783. know the registers are allocated after p at the very least, so manually
  8784. create tai_regalloc objects if needed }
  8785. for X := 0 to taicpu(hp1).ops - 1 do
  8786. case taicpu(hp1).oper[X]^.typ of
  8787. top_reg:
  8788. begin
  8789. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8790. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8791. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8792. end;
  8793. top_ref:
  8794. begin
  8795. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8796. begin
  8797. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8798. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8799. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8800. end;
  8801. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8802. begin
  8803. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8804. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8805. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8806. end;
  8807. end;
  8808. else
  8809. ;
  8810. end;
  8811. Result := True;
  8812. end;
  8813. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8814. var
  8815. hp2: tai;
  8816. X: Integer;
  8817. begin
  8818. { If we have something like:
  8819. cmp ###,%reg1
  8820. mov 0,%reg2
  8821. And no modified registers are shared, move the instruction to before
  8822. the comparison as this means it can be optimised without worrying
  8823. about the FLAGS register. (CMP/MOV is generated by
  8824. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8825. As long as the second instruction doesn't use the flags or one of the
  8826. registers used by CMP or TEST (also check any references that use the
  8827. registers), then it can be moved prior to the comparison.
  8828. }
  8829. Result := False;
  8830. if not TrySwapMovOp(p, hp1) then
  8831. Exit;
  8832. if taicpu(hp1).opcode = A_LEA then
  8833. { The flags will be overwritten by the CMP/TEST instruction }
  8834. ConvertLEA(taicpu(hp1));
  8835. Result := True;
  8836. { Can we move it one further back? }
  8837. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8838. { Check to see if CMP/TEST is a comparison against zero }
  8839. (
  8840. (
  8841. (taicpu(p).opcode = A_CMP) and
  8842. MatchOperand(taicpu(p).oper[0]^, 0)
  8843. ) or
  8844. (
  8845. (taicpu(p).opcode = A_TEST) and
  8846. (
  8847. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8848. MatchOperand(taicpu(p).oper[0]^, -1)
  8849. )
  8850. )
  8851. ) and
  8852. { These instructions set the zero flag if the result is zero }
  8853. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8854. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8855. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8856. TrySwapMovOp(hp2, hp1);
  8857. end;
  8858. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8859. var
  8860. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8861. JumpLabel: TAsmLabel;
  8862. TmpBool: Boolean;
  8863. begin
  8864. Result := False;
  8865. { Look for:
  8866. stc/clc
  8867. j(c) .L1
  8868. ...
  8869. .L1:
  8870. set(n)cb %reg
  8871. (flags deallocated)
  8872. j(c) .L2
  8873. Change to:
  8874. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8875. j(c) .L2
  8876. }
  8877. p_last := p;
  8878. while GetNextInstruction(p_last, hp1) and
  8879. (hp1.typ = ait_instruction) and
  8880. IsJumpToLabel(taicpu(hp1)) do
  8881. begin
  8882. if DoJumpOptimizations(hp1, TmpBool) then
  8883. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8884. Continue;
  8885. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8886. if not Assigned(JumpLabel) then
  8887. InternalError(2024012801);
  8888. { Optimise the J(c); stc/clc optimisation first since this will
  8889. get missed if the main optimisation takes place }
  8890. if (taicpu(hp1).opcode = A_JCC) then
  8891. begin
  8892. if GetNextInstruction(hp1, hp2) and
  8893. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8894. TryJccStcClcOpt(hp1, hp2) then
  8895. begin
  8896. Result := True;
  8897. Exit;
  8898. end;
  8899. hp2 := nil; { Suppress compiler warning }
  8900. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8901. { Make sure the flags aren't used again }
  8902. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8903. begin
  8904. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8905. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8906. begin
  8907. if (taicpu(p).opcode = A_STC) then
  8908. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8909. else
  8910. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8911. MakeUnconditional(taicpu(hp1));
  8912. { Move the jump to after the flag deallocations }
  8913. Asml.Remove(hp1);
  8914. Asml.InsertAfter(hp1, hp2);
  8915. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8916. Result := True;
  8917. Exit;
  8918. end
  8919. else
  8920. begin
  8921. if (taicpu(p).opcode = A_STC) then
  8922. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8923. else
  8924. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8925. { In this case, the jump is deterministic in that it will never be taken }
  8926. JumpLabel.DecRefs;
  8927. RemoveInstruction(hp1);
  8928. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8929. Result := True;
  8930. Exit;
  8931. end;
  8932. end;
  8933. end;
  8934. hp2 := nil; { Suppress compiler warning }
  8935. if
  8936. { Make sure the carry flag doesn't appear in the jump conditions }
  8937. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8938. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8939. GetNextInstruction(hp2, p_dist) and
  8940. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8941. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8942. begin
  8943. case taicpu(p_dist).opcode of
  8944. A_Jcc:
  8945. begin
  8946. if DoJumpOptimizations(p_dist, TmpBool) then
  8947. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8948. Continue;
  8949. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8950. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8951. begin
  8952. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8953. JumpLabel.decrefs;
  8954. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8955. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8956. Result := True;
  8957. Exit;
  8958. end
  8959. else if GetNextInstruction(p_dist, hp1_dist) and
  8960. (hp1_dist.typ = ait_label) then
  8961. begin
  8962. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8963. JumpLabel.decrefs;
  8964. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8965. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8966. Result := True;
  8967. Exit;
  8968. end;
  8969. end;
  8970. A_SETcc:
  8971. if { Make sure the flags aren't used again }
  8972. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8973. GetNextInstruction(hp2, hp1_dist) and
  8974. (hp1_dist.typ = ait_instruction) and
  8975. IsJumpToLabel(taicpu(hp1_dist)) and
  8976. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8977. { This works if hp1_dist or both are regular JMP instructions }
  8978. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8979. (
  8980. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8981. { Make sure the register isn't still in use, otherwise it
  8982. may get corrupted (fixes #40659) }
  8983. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8984. ) then
  8985. begin
  8986. taicpu(p).allocate_oper(2);
  8987. taicpu(p).ops := 2;
  8988. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8989. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8990. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8991. taicpu(p).opcode := A_MOV;
  8992. taicpu(p).opsize := S_B;
  8993. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8994. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8995. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8996. JumpLabel.decrefs;
  8997. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8998. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8999. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9000. (tai_regalloc(hp2).ratype = ra_alloc) then
  9001. begin
  9002. Asml.Remove(hp2);
  9003. Asml.InsertAfter(hp2, p);
  9004. end;
  9005. Result := True;
  9006. Exit;
  9007. end;
  9008. else
  9009. ;
  9010. end;
  9011. end;
  9012. p_last := hp1;
  9013. end;
  9014. end;
  9015. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9016. var
  9017. hp2, hp3: tai;
  9018. TempBool: Boolean;
  9019. begin
  9020. Result := False;
  9021. {
  9022. j(c) .L1
  9023. stc/clc
  9024. .L1:
  9025. jc/jnc .L2
  9026. (Flags deallocated)
  9027. Change to:
  9028. j)c) .L1
  9029. jmp .L2
  9030. .L1:
  9031. jc/jnc .L2
  9032. Then call DoJumpOptimizations to convert to:
  9033. j(nc) .L2
  9034. .L1: (may become a dead label)
  9035. jc/jnc .L2
  9036. }
  9037. if GetNextInstruction(hp1, hp2) and
  9038. (hp2.typ = ait_label) and
  9039. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9040. GetNextInstruction(hp2, hp3) and
  9041. MatchInstruction(hp3, A_Jcc, []) and
  9042. (
  9043. (
  9044. (taicpu(hp3).condition = C_C) and
  9045. (taicpu(hp1).opcode = A_STC)
  9046. ) or (
  9047. (taicpu(hp3).condition = C_NC) and
  9048. (taicpu(hp1).opcode = A_CLC)
  9049. )
  9050. ) and
  9051. { Make sure the flags aren't used again }
  9052. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9053. begin
  9054. taicpu(hp1).allocate_oper(1);
  9055. taicpu(hp1).ops := 1;
  9056. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9057. taicpu(hp1).opcode := A_JMP;
  9058. taicpu(hp1).is_jmp := True;
  9059. TempBool := True; { Prevent compiler warnings }
  9060. if DoJumpOptimizations(p, TempBool) then
  9061. Result := True
  9062. else
  9063. Include(OptsToCheck, aoc_ForceNewIteration);
  9064. end;
  9065. end;
  9066. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9067. begin
  9068. { This generally only executes under -O3 and above }
  9069. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9070. end;
  9071. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9072. var
  9073. hp1, hp2: tai;
  9074. FoundComparison: Boolean;
  9075. begin
  9076. { Run the pass 1 optimisations as well, since they may have some effect
  9077. after the CMOV blocks are created in OptPass2Jcc }
  9078. Result := False;
  9079. { Result := OptPass1CMOVcc(p);
  9080. if Result then
  9081. Exit;}
  9082. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9083. and make a slightly inefficent result on branching-type blocks, notably
  9084. when setting a function result then jumping to the function epilogue.
  9085. In this case, change:
  9086. cmov(c) %reg1,%reg2
  9087. j(c) @lbl
  9088. (%reg2 deallocated)
  9089. To:
  9090. mov %reg11,%reg2
  9091. j(c) @lbl
  9092. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9093. jump because if it's not present, we may end up with a jump that's
  9094. completely unrelated.
  9095. }
  9096. hp1 := p;
  9097. while GetNextInstruction(hp1, hp1) and
  9098. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9099. if (hp1.typ = ait_instruction) and
  9100. (taicpu(hp1).opcode = A_Jcc) and
  9101. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9102. begin
  9103. TransferUsedRegs(TmpUsedRegs);
  9104. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9105. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9106. (
  9107. { See if we can find a more distant instruction that overwrites
  9108. the destination register }
  9109. (cs_opt_level3 in current_settings.optimizerswitches) and
  9110. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9111. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9112. ) then
  9113. begin
  9114. if (taicpu(p).oper[0]^.typ = top_reg) then
  9115. begin
  9116. { Search backwards to see if the source register is set to a
  9117. constant }
  9118. FoundComparison := False;
  9119. hp1 := p;
  9120. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9121. begin
  9122. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9123. begin
  9124. FoundComparison := True;
  9125. Continue;
  9126. end;
  9127. { Once we find the CMP, TEST or similar instruction, we
  9128. have to stop if we find anything other than a MOV }
  9129. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9130. Break;
  9131. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9132. { Destination register was modified }
  9133. Break;
  9134. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9135. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9136. begin
  9137. { Found a constant! }
  9138. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9139. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9140. { The source register is no longer in use }
  9141. RemoveInstruction(hp1);
  9142. Break;
  9143. end;
  9144. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9145. { Some other instruction has modified the source register }
  9146. Break;
  9147. end;
  9148. end;
  9149. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9150. taicpu(p).opcode := A_MOV;
  9151. taicpu(p).condition := C_None;
  9152. { Rely on the post peephole stage to put the MOV before the
  9153. CMP/TEST instruction that appears prior }
  9154. Result := True;
  9155. Exit;
  9156. end;
  9157. end;
  9158. end;
  9159. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9160. function IsXCHGAcceptable: Boolean; inline;
  9161. begin
  9162. { Always accept if optimising for size }
  9163. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9164. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9165. than 3, so it becomes a saving compared to three MOVs with two of
  9166. them able to execute simultaneously. [Kit] }
  9167. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9168. end;
  9169. var
  9170. NewRef: TReference;
  9171. hp1, hp2, hp3, hp4: Tai;
  9172. {$ifndef x86_64}
  9173. OperIdx: Integer;
  9174. {$endif x86_64}
  9175. NewInstr : Taicpu;
  9176. NewAligh : Tai_align;
  9177. DestLabel: TAsmLabel;
  9178. TempTracking: TAllUsedRegs;
  9179. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9180. var
  9181. NextInstr: tai;
  9182. begin
  9183. Result := False;
  9184. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9185. if not GetNextInstruction(InputInstr, NextInstr) or
  9186. (
  9187. { The FLAGS register isn't always tracked properly, so do not
  9188. perform this optimisation if a conditional statement follows }
  9189. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9190. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9191. ) then
  9192. begin
  9193. reference_reset(NewRef, 1, []);
  9194. NewRef.base := taicpu(p).oper[0]^.reg;
  9195. NewRef.scalefactor := 1;
  9196. if taicpu(InputInstr).opcode = A_ADD then
  9197. begin
  9198. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9199. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9200. end
  9201. else
  9202. begin
  9203. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9204. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9205. end;
  9206. taicpu(p).opcode := A_LEA;
  9207. taicpu(p).loadref(0, NewRef);
  9208. { For the sake of debugging, have the line info match the
  9209. arithmetic instruction rather than the MOV instruction }
  9210. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9211. RemoveInstruction(InputInstr);
  9212. Result := True;
  9213. end;
  9214. end;
  9215. begin
  9216. Result:=false;
  9217. { This optimisation adds an instruction, so only do it for speed }
  9218. if not (cs_opt_size in current_settings.optimizerswitches) and
  9219. MatchOpType(taicpu(p), top_const, top_reg) and
  9220. (taicpu(p).oper[0]^.val = 0) then
  9221. begin
  9222. { To avoid compiler warning }
  9223. DestLabel := nil;
  9224. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9225. InternalError(2021040750);
  9226. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9227. Exit;
  9228. case hp1.typ of
  9229. ait_label:
  9230. begin
  9231. { Change:
  9232. mov $0,%reg mov $0,%reg
  9233. @Lbl1: @Lbl1:
  9234. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9235. je @Lbl2 jne @Lbl2
  9236. To: To:
  9237. mov $0,%reg mov $0,%reg
  9238. jmp @Lbl2 jmp @Lbl3
  9239. (align) (align)
  9240. @Lbl1: @Lbl1:
  9241. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9242. je @Lbl2 je @Lbl2
  9243. @Lbl3: <-- Only if label exists
  9244. (Not if it's optimised for size)
  9245. }
  9246. if not GetNextInstruction(hp1, hp2) then
  9247. Exit;
  9248. if (hp2.typ = ait_instruction) and
  9249. (
  9250. { Register sizes must exactly match }
  9251. (
  9252. (taicpu(hp2).opcode = A_CMP) and
  9253. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9254. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9255. ) or (
  9256. (taicpu(hp2).opcode = A_TEST) and
  9257. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9258. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9259. )
  9260. ) and GetNextInstruction(hp2, hp3) and
  9261. (hp3.typ = ait_instruction) and
  9262. (taicpu(hp3).opcode = A_JCC) and
  9263. (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
  9264. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9265. begin
  9266. { Check condition of jump }
  9267. { Always true? }
  9268. if condition_in(C_E, taicpu(hp3).condition) then
  9269. begin
  9270. { Copy label symbol and obtain matching label entry for the
  9271. conditional jump, as this will be our destination}
  9272. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9273. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9274. Result := True;
  9275. end
  9276. { Always false? }
  9277. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9278. begin
  9279. { This is only worth it if there's a jump to take }
  9280. case hp2.typ of
  9281. ait_instruction:
  9282. begin
  9283. if taicpu(hp2).opcode = A_JMP then
  9284. begin
  9285. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9286. { An unconditional jump follows the conditional jump which will always be false,
  9287. so use this jump's destination for the new jump }
  9288. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9289. Result := True;
  9290. end
  9291. else if taicpu(hp2).opcode = A_JCC then
  9292. begin
  9293. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9294. if condition_in(C_E, taicpu(hp2).condition) then
  9295. begin
  9296. { A second conditional jump follows the conditional jump which will always be false,
  9297. while the second jump is always True, so use this jump's destination for the new jump }
  9298. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9299. Result := True;
  9300. end;
  9301. { Don't risk it if the jump isn't always true (Result remains False) }
  9302. end;
  9303. end;
  9304. else
  9305. { If anything else don't optimise };
  9306. end;
  9307. end;
  9308. if Result then
  9309. begin
  9310. { Just so we have something to insert as a paremeter}
  9311. reference_reset(NewRef, 1, []);
  9312. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9313. { Now actually load the correct parameter (this also
  9314. increases the reference count) }
  9315. NewInstr.loadsymbol(0, DestLabel, 0);
  9316. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9317. begin
  9318. { Get instruction before original label (may not be p under -O3) }
  9319. if not GetLastInstruction(hp1, hp2) then
  9320. { Shouldn't fail here }
  9321. InternalError(2021040701);
  9322. end
  9323. else
  9324. hp2 := p;
  9325. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9326. AsmL.InsertAfter(NewInstr, hp2);
  9327. { Add new alignment field }
  9328. (* AsmL.InsertAfter(
  9329. cai_align.create_max(
  9330. current_settings.alignment.jumpalign,
  9331. current_settings.alignment.jumpalignskipmax
  9332. ),
  9333. NewInstr
  9334. ); *)
  9335. end;
  9336. Exit;
  9337. end;
  9338. end;
  9339. else
  9340. ;
  9341. end;
  9342. end;
  9343. if not GetNextInstruction(p, hp1) then
  9344. Exit;
  9345. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9346. begin
  9347. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9348. begin
  9349. Result := True;
  9350. Exit;
  9351. end;
  9352. { This optimisation is only effective on a second run of Pass 2,
  9353. hence -O3 or above.
  9354. Change:
  9355. mov %reg1,%reg2
  9356. cmp/test (contains %reg1)
  9357. mov x, %reg1
  9358. (another mov or a j(c))
  9359. To:
  9360. mov %reg1,%reg2
  9361. mov x, %reg1
  9362. cmp (%reg1 replaced with %reg2)
  9363. (another mov or a j(c))
  9364. The requirement of an additional MOV or a jump ensures there
  9365. isn't performance loss, since a j(c) will permit macro-fusion
  9366. with the cmp instruction, while another MOV likely means it's
  9367. not all being executed in a single cycle due to parallelisation.
  9368. }
  9369. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9370. MatchOpType(taicpu(p), top_reg, top_reg) and
  9371. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9372. GetNextInstruction(hp1, hp2) and
  9373. MatchInstruction(hp2, A_MOV, []) and
  9374. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9375. { Registers don't have to be the same size in this case }
  9376. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9377. GetNextInstruction(hp2, hp3) and
  9378. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9379. { Make sure the operands in the camparison can be safely replaced }
  9380. (
  9381. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9382. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9383. ) and
  9384. (
  9385. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9386. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9387. ) then
  9388. begin
  9389. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9390. AsmL.Remove(hp2);
  9391. AsmL.InsertAfter(hp2, p);
  9392. Result := True;
  9393. Exit;
  9394. end;
  9395. end;
  9396. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9397. begin
  9398. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9399. further, but we can't just put this jump optimisation in pass 1
  9400. because it tends to perform worse when conditional jumps are
  9401. nearby (e.g. when converting CMOV instructions). [Kit] }
  9402. CopyUsedRegs(TempTracking);
  9403. UpdateUsedRegs(tai(p.Next));
  9404. if OptPass2JMP(hp1) then
  9405. begin
  9406. { Restore register state }
  9407. RestoreUsedRegs(TempTracking);
  9408. ReleaseUsedRegs(TempTracking);
  9409. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9410. OptPass1MOV(p);
  9411. Result := True;
  9412. Exit;
  9413. end;
  9414. { If OptPass2JMP returned False, no optimisations were done to
  9415. the jump and there are no further optimisations that can be done
  9416. to the MOV instruction on this pass other than FuncMov2Func }
  9417. { Restore register state }
  9418. RestoreUsedRegs(TempTracking);
  9419. ReleaseUsedRegs(TempTracking);
  9420. Result := FuncMov2Func(p, hp1);
  9421. Exit;
  9422. end;
  9423. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9424. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9425. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9426. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9427. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9428. begin
  9429. { Change:
  9430. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9431. addl/q $x,%reg2 subl/q $x,%reg2
  9432. To:
  9433. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9434. }
  9435. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9436. { be lazy, checking separately for sub would be slightly better }
  9437. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9438. begin
  9439. TransferUsedRegs(TmpUsedRegs);
  9440. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9441. if TryMovArith2Lea(hp1) then
  9442. begin
  9443. Result := True;
  9444. Exit;
  9445. end
  9446. end
  9447. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9448. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9449. { Same as above, but also adds or subtracts to %reg2 in between.
  9450. It's still valid as long as the flags aren't in use }
  9451. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9452. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9453. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9454. { be lazy, checking separately for sub would be slightly better }
  9455. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9456. begin
  9457. TransferUsedRegs(TmpUsedRegs);
  9458. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9459. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9460. if TryMovArith2Lea(hp2) then
  9461. begin
  9462. Result := True;
  9463. Exit;
  9464. end;
  9465. end;
  9466. end;
  9467. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9468. {$ifdef x86_64}
  9469. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9470. {$else x86_64}
  9471. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9472. {$endif x86_64}
  9473. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9474. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9475. { mov reg1, reg2 mov reg1, reg2
  9476. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9477. begin
  9478. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9479. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9480. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9481. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9482. TransferUsedRegs(TmpUsedRegs);
  9483. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9484. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9485. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9486. then
  9487. begin
  9488. RemoveCurrentP(p, hp1);
  9489. Result:=true;
  9490. end;
  9491. Exit;
  9492. end;
  9493. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9494. IsXCHGAcceptable and
  9495. { XCHG doesn't support 8-bit registers }
  9496. (taicpu(p).opsize <> S_B) and
  9497. MatchInstruction(hp1, A_MOV, []) and
  9498. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9499. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9500. GetNextInstruction(hp1, hp2) and
  9501. MatchInstruction(hp2, A_MOV, []) and
  9502. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9503. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9504. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9505. begin
  9506. { mov %reg1,%reg2
  9507. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9508. mov %reg2,%reg3
  9509. (%reg2 not used afterwards)
  9510. Note that xchg takes 3 cycles to execute, and generally mov's take
  9511. only one cycle apiece, but the first two mov's can be executed in
  9512. parallel, only taking 2 cycles overall. Older processors should
  9513. therefore only optimise for size. [Kit]
  9514. }
  9515. TransferUsedRegs(TmpUsedRegs);
  9516. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9517. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9518. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9519. begin
  9520. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9521. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9522. taicpu(hp1).opcode := A_XCHG;
  9523. RemoveCurrentP(p, hp1);
  9524. RemoveInstruction(hp2);
  9525. Result := True;
  9526. Exit;
  9527. end;
  9528. end;
  9529. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9530. MatchInstruction(hp1, A_SAR, []) then
  9531. begin
  9532. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9533. begin
  9534. { the use of %edx also covers the opsize being S_L }
  9535. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9536. begin
  9537. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9538. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9539. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9540. begin
  9541. { Change:
  9542. movl %eax,%edx
  9543. sarl $31,%edx
  9544. To:
  9545. cltd
  9546. }
  9547. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9548. RemoveInstruction(hp1);
  9549. taicpu(p).opcode := A_CDQ;
  9550. taicpu(p).opsize := S_NO;
  9551. taicpu(p).clearop(1);
  9552. taicpu(p).clearop(0);
  9553. taicpu(p).ops:=0;
  9554. Result := True;
  9555. Exit;
  9556. end
  9557. else if (cs_opt_size in current_settings.optimizerswitches) and
  9558. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9559. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9560. begin
  9561. { Change:
  9562. movl %edx,%eax
  9563. sarl $31,%edx
  9564. To:
  9565. movl %edx,%eax
  9566. cltd
  9567. Note that this creates a dependency between the two instructions,
  9568. so only perform if optimising for size.
  9569. }
  9570. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9571. taicpu(hp1).opcode := A_CDQ;
  9572. taicpu(hp1).opsize := S_NO;
  9573. taicpu(hp1).clearop(1);
  9574. taicpu(hp1).clearop(0);
  9575. taicpu(hp1).ops:=0;
  9576. Include(OptsToCheck, aoc_ForceNewIteration);
  9577. Exit;
  9578. end;
  9579. {$ifndef x86_64}
  9580. end
  9581. { Don't bother if CMOV is supported, because a more optimal
  9582. sequence would have been generated for the Abs() intrinsic }
  9583. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9584. { the use of %eax also covers the opsize being S_L }
  9585. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9586. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9587. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9588. GetNextInstruction(hp1, hp2) and
  9589. MatchInstruction(hp2, A_XOR, [S_L]) and
  9590. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9591. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9592. GetNextInstruction(hp2, hp3) and
  9593. MatchInstruction(hp3, A_SUB, [S_L]) and
  9594. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9595. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9596. begin
  9597. { Change:
  9598. movl %eax,%edx
  9599. sarl $31,%eax
  9600. xorl %eax,%edx
  9601. subl %eax,%edx
  9602. (Instruction that uses %edx)
  9603. (%eax deallocated)
  9604. (%edx deallocated)
  9605. To:
  9606. cltd
  9607. xorl %edx,%eax <-- Note the registers have swapped
  9608. subl %edx,%eax
  9609. (Instruction that uses %eax) <-- %eax rather than %edx
  9610. }
  9611. TransferUsedRegs(TmpUsedRegs);
  9612. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9613. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9614. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9615. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9616. begin
  9617. if GetNextInstruction(hp3, hp4) and
  9618. not RegModifiedByInstruction(NR_EDX, hp4) and
  9619. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9620. begin
  9621. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9622. taicpu(p).opcode := A_CDQ;
  9623. taicpu(p).clearop(1);
  9624. taicpu(p).clearop(0);
  9625. taicpu(p).ops:=0;
  9626. RemoveInstruction(hp1);
  9627. taicpu(hp2).loadreg(0, NR_EDX);
  9628. taicpu(hp2).loadreg(1, NR_EAX);
  9629. taicpu(hp3).loadreg(0, NR_EDX);
  9630. taicpu(hp3).loadreg(1, NR_EAX);
  9631. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9632. { Convert references in the following instruction (hp4) from %edx to %eax }
  9633. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9634. with taicpu(hp4).oper[OperIdx]^ do
  9635. case typ of
  9636. top_reg:
  9637. if getsupreg(reg) = RS_EDX then
  9638. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9639. top_ref:
  9640. begin
  9641. if getsupreg(reg) = RS_EDX then
  9642. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9643. if getsupreg(reg) = RS_EDX then
  9644. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9645. end;
  9646. else
  9647. ;
  9648. end;
  9649. Result := True;
  9650. Exit;
  9651. end;
  9652. end;
  9653. {$else x86_64}
  9654. end;
  9655. end
  9656. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9657. { the use of %rdx also covers the opsize being S_Q }
  9658. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9659. begin
  9660. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9661. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9662. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9663. begin
  9664. { Change:
  9665. movq %rax,%rdx
  9666. sarq $63,%rdx
  9667. To:
  9668. cqto
  9669. }
  9670. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9671. RemoveInstruction(hp1);
  9672. taicpu(p).opcode := A_CQO;
  9673. taicpu(p).opsize := S_NO;
  9674. taicpu(p).clearop(1);
  9675. taicpu(p).clearop(0);
  9676. taicpu(p).ops:=0;
  9677. Result := True;
  9678. Exit;
  9679. end
  9680. else if (cs_opt_size in current_settings.optimizerswitches) and
  9681. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9682. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9683. begin
  9684. { Change:
  9685. movq %rdx,%rax
  9686. sarq $63,%rdx
  9687. To:
  9688. movq %rdx,%rax
  9689. cqto
  9690. Note that this creates a dependency between the two instructions,
  9691. so only perform if optimising for size.
  9692. }
  9693. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9694. taicpu(hp1).opcode := A_CQO;
  9695. taicpu(hp1).opsize := S_NO;
  9696. taicpu(hp1).clearop(1);
  9697. taicpu(hp1).clearop(0);
  9698. taicpu(hp1).ops:=0;
  9699. Include(OptsToCheck, aoc_ForceNewIteration);
  9700. Exit;
  9701. {$endif x86_64}
  9702. end;
  9703. end;
  9704. end;
  9705. if MatchInstruction(hp1, A_MOV, []) and
  9706. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9707. { Though "GetNextInstruction" could be factored out, along with
  9708. the instructions that depend on hp2, it is an expensive call that
  9709. should be delayed for as long as possible, hence we do cheaper
  9710. checks first that are likely to be False. [Kit] }
  9711. begin
  9712. if (
  9713. (
  9714. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9715. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9716. (
  9717. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9718. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9719. )
  9720. ) or
  9721. (
  9722. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9723. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9724. (
  9725. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9726. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9727. )
  9728. )
  9729. ) and
  9730. GetNextInstruction(hp1, hp2) and
  9731. MatchInstruction(hp2, A_SAR, []) and
  9732. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9733. begin
  9734. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9735. begin
  9736. { Change:
  9737. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9738. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9739. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9740. To:
  9741. movl r/m,%eax <- Note the change in register
  9742. cltd
  9743. }
  9744. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9745. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9746. taicpu(p).loadreg(1, NR_EAX);
  9747. taicpu(hp1).opcode := A_CDQ;
  9748. taicpu(hp1).clearop(1);
  9749. taicpu(hp1).clearop(0);
  9750. taicpu(hp1).ops:=0;
  9751. RemoveInstruction(hp2);
  9752. Include(OptsToCheck, aoc_ForceNewIteration);
  9753. (*
  9754. {$ifdef x86_64}
  9755. end
  9756. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9757. { This code sequence does not get generated - however it might become useful
  9758. if and when 128-bit signed integer types make an appearance, so the code
  9759. is kept here for when it is eventually needed. [Kit] }
  9760. (
  9761. (
  9762. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9763. (
  9764. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9765. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9766. )
  9767. ) or
  9768. (
  9769. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9770. (
  9771. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9772. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9773. )
  9774. )
  9775. ) and
  9776. GetNextInstruction(hp1, hp2) and
  9777. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9778. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9779. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9780. begin
  9781. { Change:
  9782. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9783. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9784. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9785. To:
  9786. movq r/m,%rax <- Note the change in register
  9787. cqto
  9788. }
  9789. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9790. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9791. taicpu(p).loadreg(1, NR_RAX);
  9792. taicpu(hp1).opcode := A_CQO;
  9793. taicpu(hp1).clearop(1);
  9794. taicpu(hp1).clearop(0);
  9795. taicpu(hp1).ops:=0;
  9796. RemoveInstruction(hp2);
  9797. Include(OptsToCheck, aoc_ForceNewIteration);
  9798. {$endif x86_64}
  9799. *)
  9800. end;
  9801. end;
  9802. {$ifdef x86_64}
  9803. end;
  9804. if (taicpu(p).opsize = S_L) and
  9805. (taicpu(p).oper[1]^.typ = top_reg) and
  9806. (
  9807. MatchInstruction(hp1, A_MOV,[]) and
  9808. (taicpu(hp1).opsize = S_L) and
  9809. (taicpu(hp1).oper[1]^.typ = top_reg)
  9810. ) and (
  9811. GetNextInstruction(hp1, hp2) and
  9812. (tai(hp2).typ=ait_instruction) and
  9813. (taicpu(hp2).opsize = S_Q) and
  9814. (
  9815. (
  9816. MatchInstruction(hp2, A_ADD,[]) and
  9817. (taicpu(hp2).opsize = S_Q) and
  9818. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9819. (
  9820. (
  9821. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9822. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9823. ) or (
  9824. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9825. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9826. )
  9827. )
  9828. ) or (
  9829. MatchInstruction(hp2, A_LEA,[]) and
  9830. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9831. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9832. (
  9833. (
  9834. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9835. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9836. ) or (
  9837. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9838. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9839. )
  9840. ) and (
  9841. (
  9842. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9843. ) or (
  9844. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9845. )
  9846. )
  9847. )
  9848. )
  9849. ) and (
  9850. GetNextInstruction(hp2, hp3) and
  9851. MatchInstruction(hp3, A_SHR,[]) and
  9852. (taicpu(hp3).opsize = S_Q) and
  9853. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9854. (taicpu(hp3).oper[0]^.val = 1) and
  9855. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9856. ) then
  9857. begin
  9858. { Change movl x, reg1d movl x, reg1d
  9859. movl y, reg2d movl y, reg2d
  9860. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9861. shrq $1, reg1q shrq $1, reg1q
  9862. ( reg1d and reg2d can be switched around in the first two instructions )
  9863. To movl x, reg1d
  9864. addl y, reg1d
  9865. rcrl $1, reg1d
  9866. This corresponds to the common expression (x + y) shr 1, where
  9867. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9868. smaller code, but won't account for x + y causing an overflow). [Kit]
  9869. }
  9870. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9871. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9872. begin
  9873. { Change first MOV command to have the same register as the final output }
  9874. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9875. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9876. Result := True;
  9877. end
  9878. else
  9879. begin
  9880. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9881. Include(OptsToCheck, aoc_ForceNewIteration);
  9882. end;
  9883. { Change second MOV command to an ADD command. This is easier than
  9884. converting the existing command because it means we don't have to
  9885. touch 'y', which might be a complicated reference, and also the
  9886. fact that the third command might either be ADD or LEA. [Kit] }
  9887. taicpu(hp1).opcode := A_ADD;
  9888. { Delete old ADD/LEA instruction }
  9889. RemoveInstruction(hp2);
  9890. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9891. taicpu(hp3).opcode := A_RCR;
  9892. taicpu(hp3).changeopsize(S_L);
  9893. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9894. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9895. called, so FuncMov2Func below is safe to call }
  9896. {$endif x86_64}
  9897. end;
  9898. if FuncMov2Func(p, hp1) then
  9899. begin
  9900. Result := True;
  9901. Exit;
  9902. end;
  9903. end;
  9904. {$push}
  9905. {$q-}{$r-}
  9906. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9907. var
  9908. ThisReg: TRegister;
  9909. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9910. TargetSubReg: TSubRegister;
  9911. hp1, hp2: tai;
  9912. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9913. { Store list of found instructions so we don't have to call
  9914. GetNextInstructionUsingReg multiple times }
  9915. InstrList: array of taicpu;
  9916. InstrMax, Index: Integer;
  9917. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9918. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9919. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9920. WorkingValue: TCgInt;
  9921. PreMessage: string;
  9922. { Data flow analysis }
  9923. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9924. BitwiseOnly, OrXorUsed,
  9925. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9926. function CheckOverflowConditions: Boolean;
  9927. begin
  9928. Result := True;
  9929. if (TestValSignedMax > SignedUpperLimit) then
  9930. UpperSignedOverflow := True;
  9931. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9932. LowerSignedOverflow := True;
  9933. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9934. LowerUnsignedOverflow := True;
  9935. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9936. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9937. begin
  9938. { Absolute overflow }
  9939. Result := False;
  9940. Exit;
  9941. end;
  9942. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9943. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9944. ShiftDownOverflow := True;
  9945. if (TestValMin < 0) or (TestValMax < 0) then
  9946. begin
  9947. LowerUnsignedOverflow := True;
  9948. UpperUnsignedOverflow := True;
  9949. end;
  9950. end;
  9951. function AdjustInitialLoadAndSize: Boolean;
  9952. begin
  9953. Result := False;
  9954. if not p_removed then
  9955. begin
  9956. if TargetSize = MinSize then
  9957. begin
  9958. { Convert the input MOVZX to a MOV }
  9959. if (taicpu(p).oper[0]^.typ = top_reg) and
  9960. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9961. begin
  9962. { Or remove it completely! }
  9963. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9964. RemoveCurrentP(p);
  9965. p_removed := True;
  9966. end
  9967. else
  9968. begin
  9969. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9970. taicpu(p).opcode := A_MOV;
  9971. taicpu(p).oper[1]^.reg := ThisReg;
  9972. taicpu(p).opsize := TargetSize;
  9973. end;
  9974. Result := True;
  9975. end
  9976. else if TargetSize <> MaxSize then
  9977. begin
  9978. case MaxSize of
  9979. S_L:
  9980. if TargetSize = S_W then
  9981. begin
  9982. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9983. taicpu(p).opsize := S_BW;
  9984. taicpu(p).oper[1]^.reg := ThisReg;
  9985. Result := True;
  9986. end
  9987. else
  9988. InternalError(2020112341);
  9989. S_W:
  9990. if TargetSize = S_L then
  9991. begin
  9992. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9993. taicpu(p).opsize := S_BL;
  9994. taicpu(p).oper[1]^.reg := ThisReg;
  9995. Result := True;
  9996. end
  9997. else
  9998. InternalError(2020112342);
  9999. else
  10000. ;
  10001. end;
  10002. end
  10003. else if not hp1_removed and not RegInUse then
  10004. begin
  10005. { If we have something like:
  10006. movzbl (oper),%regd
  10007. add x, %regd
  10008. movzbl %regb, %regd
  10009. We can reduce the register size to the input of the final
  10010. movzbl instruction. Overflows won't have any effect.
  10011. }
  10012. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10013. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10014. begin
  10015. TargetSize := S_B;
  10016. setsubreg(ThisReg, R_SUBL);
  10017. Result := True;
  10018. end
  10019. else if (taicpu(p).opsize = S_WL) and
  10020. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10021. begin
  10022. TargetSize := S_W;
  10023. setsubreg(ThisReg, R_SUBW);
  10024. Result := True;
  10025. end;
  10026. if Result then
  10027. begin
  10028. { Convert the input MOVZX to a MOV }
  10029. if (taicpu(p).oper[0]^.typ = top_reg) and
  10030. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10031. begin
  10032. { Or remove it completely! }
  10033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10034. RemoveCurrentP(p);
  10035. p_removed := True;
  10036. end
  10037. else
  10038. begin
  10039. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10040. taicpu(p).opcode := A_MOV;
  10041. taicpu(p).oper[1]^.reg := ThisReg;
  10042. taicpu(p).opsize := TargetSize;
  10043. end;
  10044. end;
  10045. end;
  10046. end;
  10047. end;
  10048. procedure AdjustFinalLoad;
  10049. begin
  10050. if not LowerUnsignedOverflow then
  10051. begin
  10052. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10053. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10054. begin
  10055. { Convert the output MOVZX to a MOV }
  10056. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10057. begin
  10058. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10059. if (MinSize = S_B) or
  10060. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10061. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10062. begin
  10063. { Remove it completely! }
  10064. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10065. { Be careful; if p = hp1 and p was also removed, p
  10066. will become a dangling pointer }
  10067. if p = hp1 then
  10068. begin
  10069. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10070. p_removed := True;
  10071. end
  10072. else
  10073. RemoveInstruction(hp1);
  10074. hp1_removed := True;
  10075. end;
  10076. end
  10077. else
  10078. begin
  10079. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10080. taicpu(hp1).opcode := A_MOV;
  10081. taicpu(hp1).oper[0]^.reg := ThisReg;
  10082. taicpu(hp1).opsize := TargetSize;
  10083. end;
  10084. end
  10085. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10086. begin
  10087. { Need to change the size of the output }
  10088. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10089. taicpu(hp1).oper[0]^.reg := ThisReg;
  10090. taicpu(hp1).opsize := S_BL;
  10091. end;
  10092. end;
  10093. end;
  10094. function CompressInstructions: Boolean;
  10095. var
  10096. LocalIndex: Integer;
  10097. begin
  10098. Result := False;
  10099. { The objective here is to try to find a combination that
  10100. removes one of the MOV/Z instructions. }
  10101. if (
  10102. (taicpu(p).oper[0]^.typ <> top_reg) or
  10103. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10104. ) and
  10105. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10106. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10107. begin
  10108. { Make a preference to remove the second MOVZX instruction }
  10109. case taicpu(hp1).opsize of
  10110. S_BL, S_WL:
  10111. begin
  10112. TargetSize := S_L;
  10113. TargetSubReg := R_SUBD;
  10114. end;
  10115. S_BW:
  10116. begin
  10117. TargetSize := S_W;
  10118. TargetSubReg := R_SUBW;
  10119. end;
  10120. else
  10121. InternalError(2020112302);
  10122. end;
  10123. end
  10124. else
  10125. begin
  10126. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10127. begin
  10128. { Exceeded lower bound but not upper bound }
  10129. TargetSize := MaxSize;
  10130. end
  10131. else if not LowerUnsignedOverflow then
  10132. begin
  10133. { Size didn't exceed lower bound }
  10134. TargetSize := MinSize;
  10135. end
  10136. else
  10137. Exit;
  10138. end;
  10139. case TargetSize of
  10140. S_B:
  10141. TargetSubReg := R_SUBL;
  10142. S_W:
  10143. TargetSubReg := R_SUBW;
  10144. S_L:
  10145. TargetSubReg := R_SUBD;
  10146. else
  10147. InternalError(2020112350);
  10148. end;
  10149. { Update the register to its new size }
  10150. setsubreg(ThisReg, TargetSubReg);
  10151. RegInUse := False;
  10152. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10153. begin
  10154. { Check to see if the active register is used afterwards;
  10155. if not, we can change it and make a saving. }
  10156. TransferUsedRegs(TmpUsedRegs);
  10157. { The target register may be marked as in use to cross
  10158. a jump to a distant label, so exclude it }
  10159. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10160. hp2 := p;
  10161. repeat
  10162. { Explicitly check for the excluded register (don't include the first
  10163. instruction as it may be reading from here }
  10164. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10165. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10166. begin
  10167. RegInUse := True;
  10168. Break;
  10169. end;
  10170. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10171. if not GetNextInstruction(hp2, hp2) then
  10172. InternalError(2020112340);
  10173. until (hp2 = hp1);
  10174. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10175. { We might still be able to get away with this }
  10176. RegInUse := not
  10177. (
  10178. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10179. (hp2.typ = ait_instruction) and
  10180. (
  10181. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10182. instruction that doesn't actually contain ThisReg }
  10183. (cs_opt_level3 in current_settings.optimizerswitches) or
  10184. RegInInstruction(ThisReg, hp2)
  10185. ) and
  10186. RegLoadedWithNewValue(ThisReg, hp2)
  10187. );
  10188. if not RegInUse then
  10189. begin
  10190. { Force the register size to the same as this instruction so it can be removed}
  10191. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10192. begin
  10193. TargetSize := S_L;
  10194. TargetSubReg := R_SUBD;
  10195. end
  10196. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10197. begin
  10198. TargetSize := S_W;
  10199. TargetSubReg := R_SUBW;
  10200. end;
  10201. ThisReg := taicpu(hp1).oper[1]^.reg;
  10202. setsubreg(ThisReg, TargetSubReg);
  10203. RegChanged := True;
  10204. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10205. TransferUsedRegs(TmpUsedRegs);
  10206. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10207. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10208. if p = hp1 then
  10209. begin
  10210. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10211. p_removed := True;
  10212. end
  10213. else
  10214. RemoveInstruction(hp1);
  10215. hp1_removed := True;
  10216. { Instruction will become "mov %reg,%reg" }
  10217. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10218. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10219. begin
  10220. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10221. RemoveCurrentP(p);
  10222. p_removed := True;
  10223. end
  10224. else
  10225. taicpu(p).oper[1]^.reg := ThisReg;
  10226. Result := True;
  10227. end
  10228. else
  10229. begin
  10230. if TargetSize <> MaxSize then
  10231. begin
  10232. { Since the register is in use, we have to force it to
  10233. MaxSize otherwise part of it may become undefined later on }
  10234. TargetSize := MaxSize;
  10235. case TargetSize of
  10236. S_B:
  10237. TargetSubReg := R_SUBL;
  10238. S_W:
  10239. TargetSubReg := R_SUBW;
  10240. S_L:
  10241. TargetSubReg := R_SUBD;
  10242. else
  10243. InternalError(2020112351);
  10244. end;
  10245. setsubreg(ThisReg, TargetSubReg);
  10246. end;
  10247. AdjustFinalLoad;
  10248. end;
  10249. end
  10250. else
  10251. AdjustFinalLoad;
  10252. Result := AdjustInitialLoadAndSize or Result;
  10253. { Now go through every instruction we found and change the
  10254. size. If TargetSize = MaxSize, then almost no changes are
  10255. needed and Result can remain False if it hasn't been set
  10256. yet.
  10257. If RegChanged is True, then the register requires changing
  10258. and so the point about TargetSize = MaxSize doesn't apply. }
  10259. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10260. begin
  10261. for LocalIndex := 0 to InstrMax do
  10262. begin
  10263. { If p_removed is true, then the original MOV/Z was removed
  10264. and removing the AND instruction may not be safe if it
  10265. appears first }
  10266. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10267. InternalError(2020112310);
  10268. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10269. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10270. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10271. InstrList[LocalIndex].opsize := TargetSize;
  10272. end;
  10273. Result := True;
  10274. end;
  10275. end;
  10276. begin
  10277. Result := False;
  10278. p_removed := False;
  10279. hp1_removed := False;
  10280. ThisReg := taicpu(p).oper[1]^.reg;
  10281. { Check for:
  10282. movs/z ###,%ecx (or %cx or %rcx)
  10283. ...
  10284. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10285. (dealloc %ecx)
  10286. Change to:
  10287. mov ###,%cl (if ### = %cl, then remove completely)
  10288. ...
  10289. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10290. }
  10291. if (getsupreg(ThisReg) = RS_ECX) and
  10292. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10293. (hp1.typ = ait_instruction) and
  10294. (
  10295. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10296. instruction that doesn't actually contain ECX }
  10297. (cs_opt_level3 in current_settings.optimizerswitches) or
  10298. RegInInstruction(NR_ECX, hp1) or
  10299. (
  10300. { It's common for the shift/rotate's read/write register to be
  10301. initialised in between, so under -O2 and under, search ahead
  10302. one more instruction
  10303. }
  10304. GetNextInstruction(hp1, hp1) and
  10305. (hp1.typ = ait_instruction) and
  10306. RegInInstruction(NR_ECX, hp1)
  10307. )
  10308. ) and
  10309. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10310. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10311. begin
  10312. TransferUsedRegs(TmpUsedRegs);
  10313. hp2 := p;
  10314. repeat
  10315. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10316. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10317. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10318. begin
  10319. case taicpu(p).opsize of
  10320. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10321. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10322. begin
  10323. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10324. RemoveCurrentP(p);
  10325. end
  10326. else
  10327. begin
  10328. taicpu(p).opcode := A_MOV;
  10329. taicpu(p).opsize := S_B;
  10330. taicpu(p).oper[1]^.reg := NR_CL;
  10331. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10332. end;
  10333. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10334. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10335. begin
  10336. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10337. RemoveCurrentP(p);
  10338. end
  10339. else
  10340. begin
  10341. taicpu(p).opcode := A_MOV;
  10342. taicpu(p).opsize := S_W;
  10343. taicpu(p).oper[1]^.reg := NR_CX;
  10344. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10345. end;
  10346. {$ifdef x86_64}
  10347. S_LQ:
  10348. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10349. begin
  10350. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10351. RemoveCurrentP(p);
  10352. end
  10353. else
  10354. begin
  10355. taicpu(p).opcode := A_MOV;
  10356. taicpu(p).opsize := S_L;
  10357. taicpu(p).oper[1]^.reg := NR_ECX;
  10358. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10359. end;
  10360. {$endif x86_64}
  10361. else
  10362. InternalError(2021120401);
  10363. end;
  10364. Result := True;
  10365. Exit;
  10366. end;
  10367. end;
  10368. { This is anything but quick! }
  10369. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10370. Exit;
  10371. SetLength(InstrList, 0);
  10372. InstrMax := -1;
  10373. case taicpu(p).opsize of
  10374. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10375. begin
  10376. {$if defined(i386) or defined(i8086)}
  10377. { If the target size is 8-bit, make sure we can actually encode it }
  10378. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10379. Exit;
  10380. {$endif i386 or i8086}
  10381. LowerLimit := $FF;
  10382. SignedLowerLimit := $7F;
  10383. SignedLowerLimitBottom := -128;
  10384. MinSize := S_B;
  10385. if taicpu(p).opsize = S_BW then
  10386. begin
  10387. MaxSize := S_W;
  10388. UpperLimit := $FFFF;
  10389. SignedUpperLimit := $7FFF;
  10390. SignedUpperLimitBottom := -32768;
  10391. end
  10392. else
  10393. begin
  10394. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10395. MaxSize := S_L;
  10396. UpperLimit := $FFFFFFFF;
  10397. SignedUpperLimit := $7FFFFFFF;
  10398. SignedUpperLimitBottom := -2147483648;
  10399. end;
  10400. end;
  10401. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10402. begin
  10403. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10404. LowerLimit := $FFFF;
  10405. SignedLowerLimit := $7FFF;
  10406. SignedLowerLimitBottom := -32768;
  10407. UpperLimit := $FFFFFFFF;
  10408. SignedUpperLimit := $7FFFFFFF;
  10409. SignedUpperLimitBottom := -2147483648;
  10410. MinSize := S_W;
  10411. MaxSize := S_L;
  10412. end;
  10413. {$ifdef x86_64}
  10414. S_LQ:
  10415. begin
  10416. { Both the lower and upper limits are set to 32-bit. If a limit
  10417. is breached, then optimisation is impossible }
  10418. LowerLimit := $FFFFFFFF;
  10419. SignedLowerLimit := $7FFFFFFF;
  10420. SignedLowerLimitBottom := -2147483648;
  10421. UpperLimit := $FFFFFFFF;
  10422. SignedUpperLimit := $7FFFFFFF;
  10423. SignedUpperLimitBottom := -2147483648;
  10424. MinSize := S_L;
  10425. MaxSize := S_L;
  10426. end;
  10427. {$endif x86_64}
  10428. else
  10429. InternalError(2020112301);
  10430. end;
  10431. TestValMin := 0;
  10432. TestValMax := LowerLimit;
  10433. TestValSignedMax := SignedLowerLimit;
  10434. TryShiftDownLimit := LowerLimit;
  10435. TryShiftDown := S_NO;
  10436. ShiftDownOverflow := False;
  10437. RegChanged := False;
  10438. BitwiseOnly := True;
  10439. OrXorUsed := False;
  10440. UpperSignedOverflow := False;
  10441. LowerSignedOverflow := False;
  10442. UpperUnsignedOverflow := False;
  10443. LowerUnsignedOverflow := False;
  10444. hp1 := p;
  10445. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10446. (hp1.typ = ait_instruction) and
  10447. (
  10448. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10449. instruction that doesn't actually contain ThisReg }
  10450. (cs_opt_level3 in current_settings.optimizerswitches) or
  10451. { This allows this Movx optimisation to work through the SETcc instructions
  10452. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10453. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10454. skip over these SETcc instructions). }
  10455. (taicpu(hp1).opcode = A_SETcc) or
  10456. RegInInstruction(ThisReg, hp1)
  10457. ) do
  10458. begin
  10459. case taicpu(hp1).opcode of
  10460. A_INC,A_DEC:
  10461. begin
  10462. { Has to be an exact match on the register }
  10463. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10464. Break;
  10465. if taicpu(hp1).opcode = A_INC then
  10466. begin
  10467. Inc(TestValMin);
  10468. Inc(TestValMax);
  10469. Inc(TestValSignedMax);
  10470. end
  10471. else
  10472. begin
  10473. Dec(TestValMin);
  10474. Dec(TestValMax);
  10475. Dec(TestValSignedMax);
  10476. end;
  10477. end;
  10478. A_TEST, A_CMP:
  10479. begin
  10480. if (
  10481. { Too high a risk of non-linear behaviour that breaks DFA
  10482. here, unless it's cmp $0,%reg, which is equivalent to
  10483. test %reg,%reg }
  10484. OrXorUsed and
  10485. (taicpu(hp1).opcode = A_CMP) and
  10486. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10487. ) or
  10488. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10489. { Has to be an exact match on the register }
  10490. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10491. (
  10492. { Permit "test %reg,%reg" }
  10493. (taicpu(hp1).opcode = A_TEST) and
  10494. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10495. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10496. ) or
  10497. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10498. { Make sure the comparison value is not smaller than the
  10499. smallest allowed signed value for the minimum size (e.g.
  10500. -128 for 8-bit) }
  10501. not (
  10502. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10503. { Is it in the negative range? }
  10504. (
  10505. (taicpu(hp1).oper[0]^.val < 0) and
  10506. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10507. )
  10508. ) then
  10509. Break;
  10510. { Check to see if the active register is used afterwards }
  10511. TransferUsedRegs(TmpUsedRegs);
  10512. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10513. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10514. begin
  10515. { Make sure the comparison or any previous instructions
  10516. hasn't pushed the test values outside of the range of
  10517. MinSize }
  10518. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10519. begin
  10520. { Exceeded lower bound but not upper bound }
  10521. Exit;
  10522. end
  10523. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10524. begin
  10525. { Size didn't exceed lower bound }
  10526. TargetSize := MinSize;
  10527. end
  10528. else
  10529. Break;
  10530. case TargetSize of
  10531. S_B:
  10532. TargetSubReg := R_SUBL;
  10533. S_W:
  10534. TargetSubReg := R_SUBW;
  10535. S_L:
  10536. TargetSubReg := R_SUBD;
  10537. else
  10538. InternalError(2021051002);
  10539. end;
  10540. if TargetSize <> MaxSize then
  10541. begin
  10542. { Update the register to its new size }
  10543. setsubreg(ThisReg, TargetSubReg);
  10544. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10545. taicpu(hp1).oper[1]^.reg := ThisReg;
  10546. taicpu(hp1).opsize := TargetSize;
  10547. { Convert the input MOVZX to a MOV if necessary }
  10548. AdjustInitialLoadAndSize;
  10549. if (InstrMax >= 0) then
  10550. begin
  10551. for Index := 0 to InstrMax do
  10552. begin
  10553. { If p_removed is true, then the original MOV/Z was removed
  10554. and removing the AND instruction may not be safe if it
  10555. appears first }
  10556. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10557. InternalError(2020112311);
  10558. if InstrList[Index].oper[0]^.typ = top_reg then
  10559. InstrList[Index].oper[0]^.reg := ThisReg;
  10560. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10561. InstrList[Index].opsize := MinSize;
  10562. end;
  10563. end;
  10564. Result := True;
  10565. end;
  10566. Exit;
  10567. end;
  10568. end;
  10569. A_SETcc:
  10570. begin
  10571. { This allows this Movx optimisation to work through the SETcc instructions
  10572. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10573. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10574. skip over these SETcc instructions). }
  10575. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10576. { Of course, break out if the current register is used }
  10577. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10578. Break
  10579. else
  10580. { We must use Continue so the instruction doesn't get added
  10581. to InstrList }
  10582. Continue;
  10583. end;
  10584. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10585. begin
  10586. if
  10587. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10588. { Has to be an exact match on the register }
  10589. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10590. (
  10591. (
  10592. (taicpu(hp1).oper[0]^.typ = top_const) and
  10593. (
  10594. (
  10595. (taicpu(hp1).opcode = A_SHL) and
  10596. (
  10597. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10598. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10599. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10600. )
  10601. ) or (
  10602. (taicpu(hp1).opcode <> A_SHL) and
  10603. (
  10604. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10605. { Is it in the negative range? }
  10606. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10607. )
  10608. )
  10609. )
  10610. ) or (
  10611. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10612. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10613. )
  10614. ) then
  10615. Break;
  10616. { Only process OR and XOR if there are only bitwise operations,
  10617. since otherwise they can too easily fool the data flow
  10618. analysis (they can cause non-linear behaviour) }
  10619. case taicpu(hp1).opcode of
  10620. A_ADD:
  10621. begin
  10622. if OrXorUsed then
  10623. { Too high a risk of non-linear behaviour that breaks DFA here }
  10624. Break
  10625. else
  10626. BitwiseOnly := False;
  10627. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10628. begin
  10629. TestValMin := TestValMin * 2;
  10630. TestValMax := TestValMax * 2;
  10631. TestValSignedMax := TestValSignedMax * 2;
  10632. end
  10633. else
  10634. begin
  10635. WorkingValue := taicpu(hp1).oper[0]^.val;
  10636. TestValMin := TestValMin + WorkingValue;
  10637. TestValMax := TestValMax + WorkingValue;
  10638. TestValSignedMax := TestValSignedMax + WorkingValue;
  10639. end;
  10640. end;
  10641. A_SUB:
  10642. begin
  10643. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10644. begin
  10645. TestValMin := 0;
  10646. TestValMax := 0;
  10647. TestValSignedMax := 0;
  10648. end
  10649. else
  10650. begin
  10651. if OrXorUsed then
  10652. { Too high a risk of non-linear behaviour that breaks DFA here }
  10653. Break
  10654. else
  10655. BitwiseOnly := False;
  10656. WorkingValue := taicpu(hp1).oper[0]^.val;
  10657. TestValMin := TestValMin - WorkingValue;
  10658. TestValMax := TestValMax - WorkingValue;
  10659. TestValSignedMax := TestValSignedMax - WorkingValue;
  10660. end;
  10661. end;
  10662. A_AND:
  10663. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10664. begin
  10665. { we might be able to go smaller if AND appears first }
  10666. if InstrMax = -1 then
  10667. case MinSize of
  10668. S_B:
  10669. ;
  10670. S_W:
  10671. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10672. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10673. begin
  10674. TryShiftDown := S_B;
  10675. TryShiftDownLimit := $FF;
  10676. end;
  10677. S_L:
  10678. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10679. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10680. begin
  10681. TryShiftDown := S_B;
  10682. TryShiftDownLimit := $FF;
  10683. end
  10684. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10685. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10686. begin
  10687. TryShiftDown := S_W;
  10688. TryShiftDownLimit := $FFFF;
  10689. end;
  10690. else
  10691. InternalError(2020112320);
  10692. end;
  10693. WorkingValue := taicpu(hp1).oper[0]^.val;
  10694. TestValMin := TestValMin and WorkingValue;
  10695. TestValMax := TestValMax and WorkingValue;
  10696. TestValSignedMax := TestValSignedMax and WorkingValue;
  10697. end;
  10698. A_OR:
  10699. begin
  10700. if not BitwiseOnly then
  10701. Break;
  10702. OrXorUsed := True;
  10703. WorkingValue := taicpu(hp1).oper[0]^.val;
  10704. TestValMin := TestValMin or WorkingValue;
  10705. TestValMax := TestValMax or WorkingValue;
  10706. TestValSignedMax := TestValSignedMax or WorkingValue;
  10707. end;
  10708. A_XOR:
  10709. begin
  10710. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10711. begin
  10712. TestValMin := 0;
  10713. TestValMax := 0;
  10714. TestValSignedMax := 0;
  10715. end
  10716. else
  10717. begin
  10718. if not BitwiseOnly then
  10719. Break;
  10720. OrXorUsed := True;
  10721. WorkingValue := taicpu(hp1).oper[0]^.val;
  10722. TestValMin := TestValMin xor WorkingValue;
  10723. TestValMax := TestValMax xor WorkingValue;
  10724. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10725. end;
  10726. end;
  10727. A_SHL:
  10728. begin
  10729. BitwiseOnly := False;
  10730. WorkingValue := taicpu(hp1).oper[0]^.val;
  10731. TestValMin := TestValMin shl WorkingValue;
  10732. TestValMax := TestValMax shl WorkingValue;
  10733. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10734. end;
  10735. A_SHR,
  10736. { The first instruction was MOVZX, so the value won't be negative }
  10737. A_SAR:
  10738. begin
  10739. if InstrMax <> -1 then
  10740. BitwiseOnly := False
  10741. else
  10742. { we might be able to go smaller if SHR appears first }
  10743. case MinSize of
  10744. S_B:
  10745. ;
  10746. S_W:
  10747. if (taicpu(hp1).oper[0]^.val >= 8) then
  10748. begin
  10749. TryShiftDown := S_B;
  10750. TryShiftDownLimit := $FF;
  10751. TryShiftDownSignedLimit := $7F;
  10752. TryShiftDownSignedLimitLower := -128;
  10753. end;
  10754. S_L:
  10755. if (taicpu(hp1).oper[0]^.val >= 24) then
  10756. begin
  10757. TryShiftDown := S_B;
  10758. TryShiftDownLimit := $FF;
  10759. TryShiftDownSignedLimit := $7F;
  10760. TryShiftDownSignedLimitLower := -128;
  10761. end
  10762. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10763. begin
  10764. TryShiftDown := S_W;
  10765. TryShiftDownLimit := $FFFF;
  10766. TryShiftDownSignedLimit := $7FFF;
  10767. TryShiftDownSignedLimitLower := -32768;
  10768. end;
  10769. else
  10770. InternalError(2020112321);
  10771. end;
  10772. WorkingValue := taicpu(hp1).oper[0]^.val;
  10773. if taicpu(hp1).opcode = A_SAR then
  10774. begin
  10775. TestValMin := SarInt64(TestValMin, WorkingValue);
  10776. TestValMax := SarInt64(TestValMax, WorkingValue);
  10777. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10778. end
  10779. else
  10780. begin
  10781. TestValMin := TestValMin shr WorkingValue;
  10782. TestValMax := TestValMax shr WorkingValue;
  10783. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10784. end;
  10785. end;
  10786. else
  10787. InternalError(2020112303);
  10788. end;
  10789. end;
  10790. (*
  10791. A_IMUL:
  10792. case taicpu(hp1).ops of
  10793. 2:
  10794. begin
  10795. if not MatchOpType(hp1, top_reg, top_reg) or
  10796. { Has to be an exact match on the register }
  10797. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10798. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10799. Break;
  10800. TestValMin := TestValMin * TestValMin;
  10801. TestValMax := TestValMax * TestValMax;
  10802. TestValSignedMax := TestValSignedMax * TestValMax;
  10803. end;
  10804. 3:
  10805. begin
  10806. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10807. { Has to be an exact match on the register }
  10808. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10809. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10810. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10811. { Is it in the negative range? }
  10812. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10813. Break;
  10814. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10815. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10816. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10817. end;
  10818. else
  10819. Break;
  10820. end;
  10821. A_IDIV:
  10822. case taicpu(hp1).ops of
  10823. 3:
  10824. begin
  10825. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10826. { Has to be an exact match on the register }
  10827. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10828. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10829. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10830. { Is it in the negative range? }
  10831. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10832. Break;
  10833. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10834. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10835. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10836. end;
  10837. else
  10838. Break;
  10839. end;
  10840. *)
  10841. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10842. begin
  10843. { If there are no instructions in between, then we might be able to make a saving }
  10844. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10845. Break;
  10846. { We have something like:
  10847. movzbw %dl,%dx
  10848. ...
  10849. movswl %dx,%edx
  10850. Change the latter to a zero-extension then enter the
  10851. A_MOVZX case branch.
  10852. }
  10853. {$ifdef x86_64}
  10854. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10855. begin
  10856. { this becomes a zero extension from 32-bit to 64-bit, but
  10857. the upper 32 bits are already zero, so just delete the
  10858. instruction }
  10859. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10860. RemoveInstruction(hp1);
  10861. Result := True;
  10862. Exit;
  10863. end
  10864. else
  10865. {$endif x86_64}
  10866. begin
  10867. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10868. taicpu(hp1).opcode := A_MOVZX;
  10869. {$ifdef x86_64}
  10870. case taicpu(hp1).opsize of
  10871. S_BQ:
  10872. begin
  10873. taicpu(hp1).opsize := S_BL;
  10874. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10875. end;
  10876. S_WQ:
  10877. begin
  10878. taicpu(hp1).opsize := S_WL;
  10879. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10880. end;
  10881. S_LQ:
  10882. begin
  10883. taicpu(hp1).opcode := A_MOV;
  10884. taicpu(hp1).opsize := S_L;
  10885. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10886. { In this instance, we need to break out because the
  10887. instruction is no longer MOVZX or MOVSXD }
  10888. Result := True;
  10889. Exit;
  10890. end;
  10891. else
  10892. ;
  10893. end;
  10894. {$endif x86_64}
  10895. Result := CompressInstructions;
  10896. Exit;
  10897. end;
  10898. end;
  10899. A_MOVZX:
  10900. begin
  10901. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10902. Break;
  10903. if (InstrMax = -1) then
  10904. begin
  10905. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10906. begin
  10907. { Optimise around i40003 }
  10908. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10909. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10910. {$ifndef x86_64}
  10911. and (
  10912. (taicpu(p).oper[0]^.typ <> top_reg) or
  10913. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10914. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10915. )
  10916. {$endif not x86_64}
  10917. then
  10918. begin
  10919. if (taicpu(p).oper[0]^.typ = top_reg) then
  10920. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10921. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10922. taicpu(p).opsize := S_BL;
  10923. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10924. RemoveInstruction(hp1);
  10925. Result := True;
  10926. Exit;
  10927. end;
  10928. end
  10929. else
  10930. begin
  10931. { Will return false if the second parameter isn't ThisReg
  10932. (can happen on -O2 and under) }
  10933. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10934. begin
  10935. { The two MOVZX instructions are adjacent, so remove the first one }
  10936. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10937. RemoveCurrentP(p);
  10938. Result := True;
  10939. Exit;
  10940. end;
  10941. Break;
  10942. end;
  10943. end;
  10944. Result := CompressInstructions;
  10945. Exit;
  10946. end;
  10947. else
  10948. { This includes ADC, SBB and IDIV }
  10949. Break;
  10950. end;
  10951. if not CheckOverflowConditions then
  10952. Break;
  10953. { Contains highest index (so instruction count - 1) }
  10954. Inc(InstrMax);
  10955. if InstrMax > High(InstrList) then
  10956. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10957. InstrList[InstrMax] := taicpu(hp1);
  10958. end;
  10959. end;
  10960. {$pop}
  10961. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10962. var
  10963. hp1 : tai;
  10964. begin
  10965. Result:=false;
  10966. if (taicpu(p).ops >= 2) and
  10967. ((taicpu(p).oper[0]^.typ = top_const) or
  10968. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10969. (taicpu(p).oper[1]^.typ = top_reg) and
  10970. ((taicpu(p).ops = 2) or
  10971. ((taicpu(p).oper[2]^.typ = top_reg) and
  10972. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10973. GetLastInstruction(p,hp1) and
  10974. MatchInstruction(hp1,A_MOV,[]) and
  10975. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10976. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10977. begin
  10978. TransferUsedRegs(TmpUsedRegs);
  10979. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10980. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10981. { change
  10982. mov reg1,reg2
  10983. imul y,reg2 to imul y,reg1,reg2 }
  10984. begin
  10985. taicpu(p).ops := 3;
  10986. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10987. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10988. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10989. RemoveInstruction(hp1);
  10990. result:=true;
  10991. end;
  10992. end;
  10993. end;
  10994. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10995. var
  10996. ThisLabel: TAsmLabel;
  10997. begin
  10998. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10999. ThisLabel.decrefs;
  11000. taicpu(p).condition := C_None;
  11001. taicpu(p).opcode := A_RET;
  11002. taicpu(p).is_jmp := false;
  11003. taicpu(p).ops := taicpu(ret_p).ops;
  11004. case taicpu(ret_p).ops of
  11005. 0:
  11006. taicpu(p).clearop(0);
  11007. 1:
  11008. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11009. else
  11010. internalerror(2016041301);
  11011. end;
  11012. { If the original label is now dead, it might turn out that the label
  11013. immediately follows p. As a result, everything beyond it, which will
  11014. be just some final register configuration and a RET instruction, is
  11015. now dead code. [Kit] }
  11016. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11017. running RemoveDeadCodeAfterJump for each RET instruction, because
  11018. this optimisation rarely happens and most RETs appear at the end of
  11019. routines where there is nothing that can be stripped. [Kit] }
  11020. if not ThisLabel.is_used then
  11021. RemoveDeadCodeAfterJump(p);
  11022. end;
  11023. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11024. var
  11025. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11026. Unconditional, PotentialModified: Boolean;
  11027. OperPtr: POper;
  11028. NewRef: TReference;
  11029. InstrList: array of taicpu;
  11030. InstrMax, Index: Integer;
  11031. const
  11032. {$ifdef DEBUG_AOPTCPU}
  11033. SNoFlags: shortstring = ' so the flags aren''t modified';
  11034. {$else DEBUG_AOPTCPU}
  11035. SNoFlags = '';
  11036. {$endif DEBUG_AOPTCPU}
  11037. begin
  11038. Result:=false;
  11039. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11040. begin
  11041. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11042. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11043. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11044. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11045. GetNextInstruction(hp1, hp2) and
  11046. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11047. { Change from: To:
  11048. set(C) %reg j(~C) label
  11049. test %reg,%reg/cmp $0,%reg
  11050. je label
  11051. set(C) %reg j(C) label
  11052. test %reg,%reg/cmp $0,%reg
  11053. jne label
  11054. (Also do something similar with sete/setne instead of je/jne)
  11055. }
  11056. begin
  11057. { Before we do anything else, we need to check the instructions
  11058. in between SETcc and TEST to make sure they don't modify the
  11059. FLAGS register - if -O2 or under, there won't be any
  11060. instructions between SET and TEST }
  11061. TransferUsedRegs(TmpUsedRegs);
  11062. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11063. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11064. begin
  11065. next := p;
  11066. SetLength(InstrList, 0);
  11067. InstrMax := -1;
  11068. PotentialModified := False;
  11069. { Make a note of every instruction that modifies the FLAGS
  11070. register }
  11071. while GetNextInstruction(next, next) and (next <> hp1) do
  11072. begin
  11073. if next.typ <> ait_instruction then
  11074. { GetNextInstructionUsingReg should have returned False }
  11075. InternalError(2021051701);
  11076. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11077. begin
  11078. case taicpu(next).opcode of
  11079. A_SETcc,
  11080. A_CMOVcc,
  11081. A_Jcc:
  11082. begin
  11083. if PotentialModified then
  11084. { Not safe because the flags were modified earlier }
  11085. Exit
  11086. else
  11087. { Condition is the same as the initial SETcc, so this is safe
  11088. (don't add to instruction list though) }
  11089. Continue;
  11090. end;
  11091. A_ADD:
  11092. begin
  11093. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11094. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11095. (taicpu(next).oper[1]^.typ <> top_reg) or
  11096. { Must write to a register }
  11097. (taicpu(next).oper[0]^.typ = top_ref) then
  11098. { Require a constant or a register }
  11099. Exit;
  11100. PotentialModified := True;
  11101. end;
  11102. A_SUB:
  11103. begin
  11104. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11105. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11106. (taicpu(next).oper[1]^.typ <> top_reg) or
  11107. { Must write to a register }
  11108. (taicpu(next).oper[0]^.typ <> top_const) or
  11109. (taicpu(next).oper[0]^.val = $80000000) then
  11110. { Can't subtract a register with LEA - also
  11111. check that the value isn't -2^31, as this
  11112. can't be negated }
  11113. Exit;
  11114. PotentialModified := True;
  11115. end;
  11116. A_SAL,
  11117. A_SHL:
  11118. begin
  11119. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11120. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11121. (taicpu(next).oper[1]^.typ <> top_reg) or
  11122. { Must write to a register }
  11123. (taicpu(next).oper[0]^.typ <> top_const) or
  11124. (taicpu(next).oper[0]^.val < 0) or
  11125. (taicpu(next).oper[0]^.val > 3) then
  11126. Exit;
  11127. PotentialModified := True;
  11128. end;
  11129. A_IMUL:
  11130. begin
  11131. if (taicpu(next).ops <> 3) or
  11132. (taicpu(next).oper[1]^.typ <> top_reg) or
  11133. { Must write to a register }
  11134. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11135. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11136. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11137. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11138. Exit
  11139. else
  11140. PotentialModified := True;
  11141. end;
  11142. else
  11143. { Don't know how to change this, so abort }
  11144. Exit;
  11145. end;
  11146. { Contains highest index (so instruction count - 1) }
  11147. Inc(InstrMax);
  11148. if InstrMax > High(InstrList) then
  11149. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11150. InstrList[InstrMax] := taicpu(next);
  11151. end;
  11152. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11153. end;
  11154. if not Assigned(next) or (next <> hp1) then
  11155. { It should be equal to hp1 }
  11156. InternalError(2021051702);
  11157. { Cycle through each instruction and check to see if we can
  11158. change them to versions that don't modify the flags }
  11159. if (InstrMax >= 0) then
  11160. begin
  11161. for Index := 0 to InstrMax do
  11162. case InstrList[Index].opcode of
  11163. A_ADD:
  11164. begin
  11165. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11166. InstrList[Index].opcode := A_LEA;
  11167. reference_reset(NewRef, 1, []);
  11168. NewRef.base := InstrList[Index].oper[1]^.reg;
  11169. if InstrList[Index].oper[0]^.typ = top_reg then
  11170. begin
  11171. NewRef.index := InstrList[Index].oper[0]^.reg;
  11172. NewRef.scalefactor := 1;
  11173. end
  11174. else
  11175. NewRef.offset := InstrList[Index].oper[0]^.val;
  11176. InstrList[Index].loadref(0, NewRef);
  11177. end;
  11178. A_SUB:
  11179. begin
  11180. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11181. InstrList[Index].opcode := A_LEA;
  11182. reference_reset(NewRef, 1, []);
  11183. NewRef.base := InstrList[Index].oper[1]^.reg;
  11184. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11185. InstrList[Index].loadref(0, NewRef);
  11186. end;
  11187. A_SHL,
  11188. A_SAL:
  11189. begin
  11190. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11191. InstrList[Index].opcode := A_LEA;
  11192. reference_reset(NewRef, 1, []);
  11193. NewRef.index := InstrList[Index].oper[1]^.reg;
  11194. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11195. InstrList[Index].loadref(0, NewRef);
  11196. end;
  11197. A_IMUL:
  11198. begin
  11199. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11200. InstrList[Index].opcode := A_LEA;
  11201. reference_reset(NewRef, 1, []);
  11202. NewRef.index := InstrList[Index].oper[1]^.reg;
  11203. case InstrList[Index].oper[0]^.val of
  11204. 2, 4, 8:
  11205. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11206. else {3, 5 and 9}
  11207. begin
  11208. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11209. NewRef.base := InstrList[Index].oper[1]^.reg;
  11210. end;
  11211. end;
  11212. InstrList[Index].loadref(0, NewRef);
  11213. end;
  11214. else
  11215. InternalError(2021051710);
  11216. end;
  11217. end;
  11218. { Mark the FLAGS register as used across this whole block }
  11219. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11220. end;
  11221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11222. JumpC := taicpu(hp2).condition;
  11223. Unconditional := False;
  11224. if conditions_equal(JumpC, C_E) then
  11225. SetC := inverse_cond(taicpu(p).condition)
  11226. else if conditions_equal(JumpC, C_NE) then
  11227. SetC := taicpu(p).condition
  11228. else
  11229. { We've got something weird here (and inefficent) }
  11230. begin
  11231. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11232. SetC := C_NONE;
  11233. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11234. if condition_in(C_AE, JumpC) then
  11235. Unconditional := True
  11236. else
  11237. { Not sure what to do with this jump - drop out }
  11238. Exit;
  11239. end;
  11240. RemoveInstruction(hp1);
  11241. if Unconditional then
  11242. MakeUnconditional(taicpu(hp2))
  11243. else
  11244. begin
  11245. if SetC = C_NONE then
  11246. InternalError(2018061402);
  11247. taicpu(hp2).SetCondition(SetC);
  11248. end;
  11249. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11250. TmpUsedRegs }
  11251. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11252. begin
  11253. RemoveCurrentp(p, hp2);
  11254. if taicpu(hp2).opcode = A_SETcc then
  11255. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11256. else
  11257. begin
  11258. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11259. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11260. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11261. end;
  11262. end
  11263. else
  11264. if taicpu(hp2).opcode = A_SETcc then
  11265. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11266. else
  11267. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11268. Result := True;
  11269. end
  11270. else if
  11271. { Make sure the instructions are adjacent }
  11272. (
  11273. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11274. GetNextInstruction(p, hp1)
  11275. ) and
  11276. MatchInstruction(hp1, A_MOV, [S_B]) and
  11277. { Writing to memory is allowed }
  11278. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11279. begin
  11280. {
  11281. Watch out for sequences such as:
  11282. set(c)b %regb
  11283. movb %regb,(ref)
  11284. movb $0,1(ref)
  11285. movb $0,2(ref)
  11286. movb $0,3(ref)
  11287. Much more efficient to turn it into:
  11288. movl $0,%regl
  11289. set(c)b %regb
  11290. movl %regl,(ref)
  11291. Or:
  11292. set(c)b %regb
  11293. movzbl %regb,%regl
  11294. movl %regl,(ref)
  11295. }
  11296. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11297. GetNextInstruction(hp1, hp2) and
  11298. MatchInstruction(hp2, A_MOV, [S_B]) and
  11299. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11300. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11301. begin
  11302. { Don't do anything else except set Result to True }
  11303. end
  11304. else
  11305. begin
  11306. if taicpu(p).oper[0]^.typ = top_reg then
  11307. begin
  11308. TransferUsedRegs(TmpUsedRegs);
  11309. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11310. end;
  11311. { If it's not a register, it's a memory address }
  11312. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11313. begin
  11314. { Even if the register is still in use, we can minimise the
  11315. pipeline stall by changing the MOV into another SETcc. }
  11316. taicpu(hp1).opcode := A_SETcc;
  11317. taicpu(hp1).condition := taicpu(p).condition;
  11318. if taicpu(hp1).oper[1]^.typ = top_ref then
  11319. begin
  11320. { Swapping the operand pointers like this is probably a
  11321. bit naughty, but it is far faster than using loadoper
  11322. to transfer the reference from oper[1] to oper[0] if
  11323. you take into account the extra procedure calls and
  11324. the memory allocation and deallocation required }
  11325. OperPtr := taicpu(hp1).oper[1];
  11326. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11327. taicpu(hp1).oper[0] := OperPtr;
  11328. end
  11329. else
  11330. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11331. taicpu(hp1).clearop(1);
  11332. taicpu(hp1).ops := 1;
  11333. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11334. end
  11335. else
  11336. begin
  11337. if taicpu(hp1).oper[1]^.typ = top_reg then
  11338. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11339. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11340. RemoveInstruction(hp1);
  11341. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11342. end
  11343. end;
  11344. Result := True;
  11345. end;
  11346. end;
  11347. end;
  11348. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11349. var
  11350. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11351. TargetReg: TRegister;
  11352. condition, inverted_condition: TAsmCond;
  11353. FoundMOV: Boolean;
  11354. begin
  11355. Result := False;
  11356. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11357. create the most optimial instructions possible due to limited
  11358. register availability, and there are situations where two
  11359. complementary "simple" CMOV blocks are created which, after the fact
  11360. can be merged into a "double" block. For example:
  11361. movw $257,%ax
  11362. movw $2,%r8w
  11363. xorl r9d,%r9d
  11364. testw $16,18(%rcx)
  11365. cmovew %ax,%dx
  11366. cmovew %r8w,%bx
  11367. cmovel %r9d,%r14d
  11368. movw $1283,%ax
  11369. movw $4,%r8w
  11370. movl $9,%r9d
  11371. cmovnew %ax,%dx
  11372. cmovnew %r8w,%bx
  11373. cmovnel %r9d,%r14d
  11374. The CMOVNE instructions at the end can be removed, and the
  11375. destination registers copied into the MOV instructions directly
  11376. above them, before finally being moved to before the first CMOVE
  11377. instructions, to produce:
  11378. movw $257,%ax
  11379. movw $2,%r8w
  11380. xorl r9d,%r9d
  11381. testw $16,18(%rcx)
  11382. movw $1283,%dx
  11383. movw $4,%bx
  11384. movl $9,%r14d
  11385. cmovew %ax,%dx
  11386. cmovew %r8w,%bx
  11387. cmovel %r9d,%r14d
  11388. Which can then be later optimised to:
  11389. movw $257,%ax
  11390. movw $2,%r8w
  11391. xorl r9d,%r9d
  11392. movw $1283,%dx
  11393. movw $4,%bx
  11394. movl $9,%r14d
  11395. testw $16,18(%rcx)
  11396. cmovew %ax,%dx
  11397. cmovew %r8w,%bx
  11398. cmovel %r9d,%r14d
  11399. }
  11400. TargetReg := taicpu(hp1).oper[1]^.reg;
  11401. condition := taicpu(hp1).condition;
  11402. inverted_condition := inverse_cond(condition);
  11403. pFirstMov := nil;
  11404. pLastMov := nil;
  11405. pCMOV := nil;
  11406. if (p.typ = ait_instruction) then
  11407. pCond := p
  11408. else if not GetNextInstruction(p, pCond) then
  11409. InternalError(2024012501);
  11410. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11411. { We should get the CMP or TEST instructeion }
  11412. InternalError(2024012502);
  11413. if (
  11414. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11415. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11416. ) then
  11417. begin
  11418. { We have to tread carefully here, hence why we're not using
  11419. GetNextInstructionUsingReg... we can only accept MOV and other
  11420. CMOV instructions. Anything else and we must drop out}
  11421. hp2 := hp1;
  11422. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11423. begin
  11424. if (hp2.typ <> ait_instruction) then
  11425. Exit;
  11426. case taicpu(hp2).opcode of
  11427. A_MOV:
  11428. begin
  11429. if not Assigned(pFirstMov) then
  11430. pFirstMov := hp2;
  11431. pLastMOV := hp2;
  11432. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11433. { Something different - drop out }
  11434. Exit;
  11435. { Otherwise, leave it for now }
  11436. end;
  11437. A_CMOVcc:
  11438. begin
  11439. if taicpu(hp2).condition = inverted_condition then
  11440. begin
  11441. { We found what we're looking for }
  11442. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11443. begin
  11444. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11445. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11446. begin
  11447. pCMOV := hp2;
  11448. Break;
  11449. end
  11450. else
  11451. { Unsafe reference - drop out }
  11452. Exit;
  11453. end;
  11454. end
  11455. else if taicpu(hp2).condition <> condition then
  11456. { Something weird - drop out }
  11457. Exit;
  11458. end;
  11459. else
  11460. { Invalid }
  11461. Exit;
  11462. end;
  11463. end;
  11464. if not Assigned(pCMOV) then
  11465. { No complementary CMOV found }
  11466. Exit;
  11467. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11468. begin
  11469. { Don't need to do anything special or search for a matching MOV }
  11470. Asml.Remove(pCMOV);
  11471. if RegInInstruction(TargetReg, pCond) then
  11472. { Make sure we don't overwrite the register if it's being used in the condition }
  11473. Asml.InsertAfter(pCMOV, pCond)
  11474. else
  11475. Asml.InsertBefore(pCMOV, pCond);
  11476. taicpu(pCMOV).opcode := A_MOV;
  11477. taicpu(pCMOV).condition := C_None;
  11478. { Don't need to worry about allocating new registers in these cases }
  11479. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11480. Result := True;
  11481. Exit;
  11482. end
  11483. else
  11484. begin
  11485. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11486. FoundMOV := False;
  11487. { Search for the MOV that sets the target register }
  11488. hp2 := pFirstMov;
  11489. repeat
  11490. if (taicpu(hp2).opcode = A_MOV) and
  11491. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11492. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11493. begin
  11494. { Change the destination }
  11495. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11496. if not FoundMOV then
  11497. begin
  11498. FoundMOV := True;
  11499. { Make sure the register is allocated }
  11500. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11501. end;
  11502. hp1 := tai(hp2.Previous);
  11503. Asml.Remove(hp2);
  11504. if RegInInstruction(TargetReg, pCond) then
  11505. { Make sure we don't overwrite the register if it's being used in the condition }
  11506. Asml.InsertAfter(hp2, pCond)
  11507. else
  11508. Asml.InsertBefore(hp2, pCond);
  11509. if (hp2 = pLastMov) then
  11510. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11511. Break;
  11512. hp2 := hp1;
  11513. end;
  11514. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11515. if FoundMOV then
  11516. { Delete the CMOV }
  11517. RemoveInstruction(pCMOV)
  11518. else
  11519. begin
  11520. { If no MOV was found, we have to actually move and transmute the CMOV }
  11521. Asml.Remove(pCMOV);
  11522. if RegInInstruction(TargetReg, pCond) then
  11523. { Make sure we don't overwrite the register if it's being used in the condition }
  11524. Asml.InsertAfter(pCMOV, pCond)
  11525. else
  11526. Asml.InsertBefore(pCMOV, pCond);
  11527. taicpu(pCMOV).opcode := A_MOV;
  11528. taicpu(pCMOV).condition := C_None;
  11529. end;
  11530. Result := True;
  11531. Exit;
  11532. end;
  11533. end;
  11534. end;
  11535. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11536. var
  11537. hp1, hp2, pCond: tai;
  11538. begin
  11539. Result := False;
  11540. { Search ahead for CMOV instructions }
  11541. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11542. begin
  11543. hp1 := p;
  11544. hp2 := p;
  11545. pCond := nil; { To prevent compiler warnings }
  11546. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11547. DEFAULTFLAGS }
  11548. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11549. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11550. pCond := p;
  11551. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11552. begin
  11553. if (hp1.typ <> ait_instruction) then
  11554. { Break out on markers and labels etc. }
  11555. Break;
  11556. case taicpu(hp1).opcode of
  11557. A_MOV:
  11558. { Ignore regular MOVs unless they are obviously not related
  11559. to a CMOV block }
  11560. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11561. Break;
  11562. A_CMOVcc:
  11563. if TryCmpCMovOpts(pCond, hp1) then
  11564. begin
  11565. hp1 := hp2;
  11566. { p itself isn't changed, and we're still inside a
  11567. while loop to catch subsequent CMOVs, so just flag
  11568. a new iteration }
  11569. Include(OptsToCheck, aoc_ForceNewIteration);
  11570. Continue;
  11571. end;
  11572. else
  11573. { Drop out if we find anything else }
  11574. Break;
  11575. end;
  11576. hp2 := hp1;
  11577. end;
  11578. end;
  11579. end;
  11580. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11581. var
  11582. hp1, hp2, pCond: tai;
  11583. SourceReg, TargetReg: TRegister;
  11584. begin
  11585. Result := False;
  11586. { In some situations, we end up with an inefficient arrangement of
  11587. instructions in the form of:
  11588. or %reg1,%reg2
  11589. (%reg1 deallocated)
  11590. test %reg2,%reg2
  11591. mov x,%reg2
  11592. we may be able to swap and rearrange the registers to produce:
  11593. or %reg2,%reg1
  11594. mov x,%reg2
  11595. test %reg1,%reg1
  11596. (%reg1 deallocated)
  11597. }
  11598. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11599. (taicpu(p).oper[1]^.typ = top_reg) and
  11600. (
  11601. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11602. MatchOperand(taicpu(p).oper[0]^, -1)
  11603. ) and
  11604. GetNextInstruction(p, hp1) and
  11605. MatchInstruction(hp1, A_MOV, []) and
  11606. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11607. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11608. begin
  11609. TargetReg := taicpu(p).oper[1]^.reg;
  11610. { Now look backwards to find a simple commutative operation: ADD,
  11611. IMUL (2-register version), OR, AND or XOR - whose destination
  11612. register is the same as TEST }
  11613. hp2 := p;
  11614. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11615. if RegInInstruction(TargetReg, hp2) then
  11616. begin
  11617. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11618. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11619. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11620. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11621. begin
  11622. SourceReg := taicpu(hp2).oper[0]^.reg;
  11623. if
  11624. { Make sure the MOV doesn't use the other register }
  11625. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11626. { And make sure the source register is not used afterwards }
  11627. not RegInUsedRegs(SourceReg, UsedRegs) then
  11628. begin
  11629. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11630. taicpu(hp2).oper[0]^.reg := TargetReg;
  11631. taicpu(hp2).oper[1]^.reg := SourceReg;
  11632. if taicpu(p).oper[0]^.typ = top_reg then
  11633. taicpu(p).oper[0]^.reg := SourceReg;
  11634. taicpu(p).oper[1]^.reg := SourceReg;
  11635. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11636. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11637. Include(OptsToCheck, aoc_ForceNewIteration);
  11638. { We can still check the following optimisations since
  11639. the instruction is still a TEST }
  11640. end;
  11641. end;
  11642. Break;
  11643. end;
  11644. end;
  11645. { Search ahead3 for CMOV instructions }
  11646. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11647. begin
  11648. hp1 := p;
  11649. hp2 := p;
  11650. pCond := nil; { To prevent compiler warnings }
  11651. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11652. DEFAULTFLAGS }
  11653. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11654. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11655. pCond := p;
  11656. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11657. begin
  11658. if (hp1.typ <> ait_instruction) then
  11659. { Break out on markers and labels etc. }
  11660. Break;
  11661. case taicpu(hp1).opcode of
  11662. A_MOV:
  11663. { Ignore regular MOVs unless they are obviously not related
  11664. to a CMOV block }
  11665. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11666. Break;
  11667. A_CMOVcc:
  11668. if TryCmpCMovOpts(pCond, hp1) then
  11669. begin
  11670. hp1 := hp2;
  11671. { p itself isn't changed, and we're still inside a
  11672. while loop to catch subsequent CMOVs, so just flag
  11673. a new iteration }
  11674. Include(OptsToCheck, aoc_ForceNewIteration);
  11675. Continue;
  11676. end;
  11677. else
  11678. { Drop out if we find anything else }
  11679. Break;
  11680. end;
  11681. hp2 := hp1;
  11682. end;
  11683. end;
  11684. end;
  11685. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11686. var
  11687. hp1: tai;
  11688. Count: Integer;
  11689. OrigLabel: TAsmLabel;
  11690. begin
  11691. result := False;
  11692. { Sometimes, the optimisations below can permit this }
  11693. RemoveDeadCodeAfterJump(p);
  11694. 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
  11695. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11696. begin
  11697. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11698. { Also a side-effect of optimisations }
  11699. if CollapseZeroDistJump(p, OrigLabel) then
  11700. begin
  11701. Result := True;
  11702. Exit;
  11703. end;
  11704. hp1 := GetLabelWithSym(OrigLabel);
  11705. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11706. begin
  11707. if taicpu(hp1).opcode = A_RET then
  11708. begin
  11709. {
  11710. change
  11711. jmp .L1
  11712. ...
  11713. .L1:
  11714. ret
  11715. into
  11716. ret
  11717. }
  11718. begin
  11719. ConvertJumpToRET(p, hp1);
  11720. result:=true;
  11721. end;
  11722. end
  11723. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11724. not (cs_opt_size in current_settings.optimizerswitches) and
  11725. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11726. begin
  11727. Result := True;
  11728. Exit;
  11729. end;
  11730. end;
  11731. end;
  11732. end;
  11733. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11734. begin
  11735. Result := assigned(p) and
  11736. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11737. (taicpu(p).oper[1]^.typ = top_reg) and
  11738. (
  11739. (taicpu(p).oper[0]^.typ = top_reg) or
  11740. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11741. it is not expected that this can cause a seg. violation }
  11742. (
  11743. (taicpu(p).oper[0]^.typ = top_ref) and
  11744. { TODO: Can we detect which references become constants at this
  11745. stage so we don't have to do a blanket ban? }
  11746. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11747. (
  11748. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11749. (
  11750. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11751. not RefModified and
  11752. { If the reference also appears in the condition, then we know it's safe, otherwise
  11753. any kind of access violation would have occurred already }
  11754. Assigned(cond_p) and
  11755. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11756. (cond_p.typ = ait_instruction) and
  11757. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11758. { Just consider 2-operand comparison instructions for now to be safe }
  11759. (taicpu(cond_p).ops = 2) and
  11760. (
  11761. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11762. (
  11763. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11764. { Don't risk identical registers but different offsets, as we may have constructs
  11765. such as buffer streams with things like length fields that indicate whether
  11766. any more data follows. And there are probably some contrived examples where
  11767. writing to offsets behind the one being read also lead to access violations }
  11768. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11769. (
  11770. { Check that we're not modifying a register that appears in the reference }
  11771. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11772. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11773. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11774. )
  11775. )
  11776. )
  11777. )
  11778. )
  11779. )
  11780. );
  11781. end;
  11782. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11783. begin
  11784. { Update integer registers, ignoring deallocations }
  11785. repeat
  11786. while assigned(p) and
  11787. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11788. (p.typ = ait_label) or
  11789. ((p.typ = ait_marker) and
  11790. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11791. p := tai(p.next);
  11792. while assigned(p) and
  11793. (p.typ=ait_RegAlloc) Do
  11794. begin
  11795. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11796. begin
  11797. case tai_regalloc(p).ratype of
  11798. ra_alloc :
  11799. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11800. else
  11801. ;
  11802. end;
  11803. end;
  11804. p := tai(p.next);
  11805. end;
  11806. until not(assigned(p)) or
  11807. (not(p.typ in SkipInstr) and
  11808. not((p.typ = ait_label) and
  11809. labelCanBeSkipped(tai_label(p))));
  11810. end;
  11811. {$ifndef 8086}
  11812. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11813. begin
  11814. Result := False;
  11815. EndJump := nil;
  11816. BlockStop := nil;
  11817. while (BlockStart <> fOptimizer.BlockEnd) and
  11818. { stop on labels }
  11819. (BlockStart.typ <> ait_label) do
  11820. begin
  11821. { Keep track of all integer registers that are used }
  11822. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11823. if BlockStart.typ = ait_instruction then
  11824. begin
  11825. if (taicpu(BlockStart).opcode = A_JMP) then
  11826. begin
  11827. if not IsJumpToLabel(taicpu(BlockStart)) or
  11828. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11829. Exit;
  11830. EndJump := BlockStart;
  11831. Break;
  11832. end
  11833. { Check to see if we have a valid MOV instruction instead }
  11834. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11835. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11836. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11837. begin
  11838. Exit;
  11839. end
  11840. else
  11841. { This will be a valid MOV }
  11842. fAllocationRange := BlockStart;
  11843. end;
  11844. OneBeforeBlock := BlockStart;
  11845. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11846. end;
  11847. if (BlockStart = fOptimizer.BlockEnd) then
  11848. Exit;
  11849. BlockStop := BlockStart;
  11850. Result := True;
  11851. end;
  11852. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11853. var
  11854. hp1: tai;
  11855. RefModified: Boolean;
  11856. begin
  11857. Result := 0;
  11858. hp1 := BlockStart;
  11859. RefModified := False; { As long as the condition is inverted, this can be reset }
  11860. while assigned(hp1) and
  11861. (hp1 <> BlockStop) do
  11862. begin
  11863. case hp1.typ of
  11864. ait_instruction:
  11865. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11866. begin
  11867. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11868. begin
  11869. Inc(Result);
  11870. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11871. Assigned(fCondition) and
  11872. { Will have 2 operands }
  11873. (
  11874. (
  11875. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11876. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11877. ) or
  11878. (
  11879. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11880. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11881. )
  11882. ) then
  11883. { It is no longer safe to use the reference in the condition.
  11884. this prevents problems such as:
  11885. mov (%reg),%reg
  11886. mov (%reg),...
  11887. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11888. (fixes #40165)
  11889. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11890. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11891. }
  11892. RefModified := True;
  11893. end
  11894. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11895. { CMOV with constants grows the code size }
  11896. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11897. begin
  11898. { Register was reserved by TryCMOVConst and
  11899. stored on ConstRegs }
  11900. end
  11901. else
  11902. begin
  11903. Result := -1;
  11904. Exit;
  11905. end;
  11906. end
  11907. else
  11908. begin
  11909. Result := -1;
  11910. Exit;
  11911. end;
  11912. else
  11913. { Most likely an align };
  11914. end;
  11915. fOptimizer.GetNextInstruction(hp1, hp1);
  11916. end;
  11917. end;
  11918. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11919. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11920. (this is done as a separate stage because the double types are extensions of the branching type,
  11921. but we can't discount the conditional jump until the last step) }
  11922. procedure EvaluateBranchingType;
  11923. begin
  11924. Inc(CMOVScore);
  11925. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11926. { Too many instructions to be worthwhile }
  11927. fState := tsInvalid;
  11928. end;
  11929. var
  11930. hp1: tai;
  11931. Count: Integer;
  11932. begin
  11933. { Table of valid CMOV block types
  11934. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11935. ---------- --------- --------- --------- --------- ---------
  11936. tsSimple X Yes X X X
  11937. tsDetour = 1st X X X X
  11938. tsBranching <> Mid Yes X X X
  11939. tsDouble End-label Yes * Yes X Yes
  11940. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11941. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11942. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11943. * Only one reference allowed
  11944. }
  11945. hp1 := nil; { To prevent compiler warnings }
  11946. Optimizer.CopyUsedRegs(RegisterTracking);
  11947. fOptimizer := Optimizer;
  11948. fLabel := AFirstLabel;
  11949. CMOVScore := 0;
  11950. ConstCount := 0;
  11951. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11952. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11953. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11954. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11955. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11956. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11957. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11958. fInsertionPoint := p_initialjump;
  11959. fCondition := nil;
  11960. fInitialJump := p_initialjump;
  11961. fFirstMovBlock := p_initialmov;
  11962. fFirstMovBlockStop := nil;
  11963. fSecondJump := nil;
  11964. fSecondMovBlock := nil;
  11965. fSecondMovBlockStop := nil;
  11966. fMidLabel := nil;
  11967. fSecondJump := nil;
  11968. fSecondMovBlock := nil;
  11969. fEndLabel := nil;
  11970. fAllocationRange := nil;
  11971. { Assume it all goes horribly wrong! }
  11972. fState := tsInvalid;
  11973. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11974. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11975. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11976. begin
  11977. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11978. for Count := 0 to 1 do
  11979. with taicpu(fCondition).oper[Count]^ do
  11980. case typ of
  11981. top_reg:
  11982. if getregtype(reg) = R_INTREGISTER then
  11983. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11984. top_ref:
  11985. begin
  11986. if
  11987. {$ifdef x86_64}
  11988. (ref^.base <> NR_RIP) and
  11989. {$endif x86_64}
  11990. (ref^.base <> NR_NO) then
  11991. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11992. if (ref^.index <> NR_NO) then
  11993. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11994. end
  11995. else
  11996. ;
  11997. end;
  11998. { When inserting instructions before hp_prev, try to insert them
  11999. before the allocation of the FLAGS register }
  12000. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12001. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12002. { If not found, set it equal to the condition so it's something sensible }
  12003. fInsertionPoint := fCondition;
  12004. { When dealing with a comparison against zero, take note of the
  12005. instruction before it to see if we can move instructions further
  12006. back in order to benefit PostPeepholeOptTestOr.
  12007. }
  12008. if (
  12009. (
  12010. (taicpu(fCondition).opcode = A_CMP) and
  12011. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12012. ) or
  12013. (
  12014. (taicpu(fCondition).opcode = A_TEST) and
  12015. (
  12016. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12017. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12018. )
  12019. )
  12020. ) and
  12021. Optimizer.GetLastInstruction(fCondition, hp1) then
  12022. begin
  12023. { These instructions set the zero flag if the result is zero }
  12024. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12025. begin
  12026. fInsertionPoint := hp1;
  12027. { Also mark all the registers in this previous instruction
  12028. as 'in use', even if they've just been deallocated }
  12029. for Count := 0 to 1 do
  12030. with taicpu(hp1).oper[Count]^ do
  12031. case typ of
  12032. top_reg:
  12033. if getregtype(reg) = R_INTREGISTER then
  12034. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12035. top_ref:
  12036. begin
  12037. if
  12038. {$ifdef x86_64}
  12039. (ref^.base <> NR_RIP) and
  12040. {$endif x86_64}
  12041. (ref^.base <> NR_NO) then
  12042. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12043. if (ref^.index <> NR_NO) then
  12044. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12045. end
  12046. else
  12047. ;
  12048. end;
  12049. end;
  12050. end;
  12051. end
  12052. else
  12053. fCondition := nil;
  12054. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12055. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12056. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12057. { If not found, set it equal to p so it's something sensible }
  12058. fInsertionPoint := hp1;
  12059. hp1 := p_initialmov;
  12060. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12061. Exit;
  12062. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12063. if (hp1.typ <> ait_label) then { should be on a jump }
  12064. begin
  12065. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12066. { Need a label afterwards }
  12067. Exit;
  12068. end
  12069. else
  12070. fMidLabel := hp1;
  12071. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12072. { Not the correct label }
  12073. fMidLabel := nil;
  12074. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12075. { If there's neither a 2nd jump nor correct label, then it's invalid
  12076. (see above table) }
  12077. Exit;
  12078. { Analyse the first block of MOVs more closely }
  12079. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12080. if Assigned(fSecondJump) then
  12081. begin
  12082. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12083. begin
  12084. fState := tsDetour
  12085. end
  12086. else
  12087. begin
  12088. { Need the correct mid-label for this one }
  12089. if not Assigned(fMidLabel) then
  12090. Exit;
  12091. fState := tsBranching;
  12092. end;
  12093. end
  12094. else
  12095. { No jump. but mid-label is present }
  12096. fState := tsSimple;
  12097. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12098. begin
  12099. { Invalid or too many instructions to be worthwhile }
  12100. fState := tsInvalid;
  12101. Exit;
  12102. end;
  12103. { check further for
  12104. jCC xxx
  12105. <several movs 1>
  12106. jmp yyy
  12107. xxx:
  12108. <several movs 2>
  12109. yyy:
  12110. etc.
  12111. }
  12112. if (fState = tsBranching) and
  12113. { Estimate for required savings for extra jump }
  12114. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12115. { Only one reference is allowed for double blocks }
  12116. (AFirstLabel.getrefs = 1) then
  12117. begin
  12118. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12119. fSecondMovBlock := hp1;
  12120. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12121. begin
  12122. EvaluateBranchingType;
  12123. Exit;
  12124. end;
  12125. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12126. if (hp1.typ <> ait_label) then { should be on a jump }
  12127. begin
  12128. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12129. begin
  12130. { Need a label afterwards }
  12131. EvaluateBranchingType;
  12132. Exit;
  12133. end;
  12134. end
  12135. else
  12136. fEndLabel := hp1;
  12137. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12138. { Second jump doesn't go to the end }
  12139. fEndLabel := nil;
  12140. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12141. begin
  12142. { If there's neither a 3rd jump nor correct end label, then it's
  12143. not a invalid double block, but is a valid single branching
  12144. block (see above table) }
  12145. EvaluateBranchingType;
  12146. Exit;
  12147. end;
  12148. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12149. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12150. { Invalid or too many instructions to be worthwhile }
  12151. Exit;
  12152. Inc(CMOVScore, Count);
  12153. if Assigned(fThirdJump) then
  12154. begin
  12155. if not Assigned(fSecondJump) then
  12156. fState := tsDoubleSecondBranching
  12157. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12158. fState := tsDoubleBranchSame
  12159. else
  12160. fState := tsDoubleBranchDifferent;
  12161. end
  12162. else
  12163. fState := tsDouble;
  12164. end;
  12165. if fState = tsBranching then
  12166. EvaluateBranchingType;
  12167. end;
  12168. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12169. new register to store the constant }
  12170. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12171. var
  12172. RegSize: TSubRegister;
  12173. CurrentVal: TCGInt;
  12174. ANewReg: TRegister;
  12175. X: ShortInt;
  12176. begin
  12177. Result := False;
  12178. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12179. Exit;
  12180. if ConstCount >= MAX_CMOV_REGISTERS then
  12181. { Arrays are full }
  12182. Exit;
  12183. { Remember that CMOV can't encode 8-bit registers }
  12184. case taicpu(p).opsize of
  12185. S_W:
  12186. RegSize := R_SUBW;
  12187. S_L:
  12188. RegSize := R_SUBD;
  12189. {$ifdef x86_64}
  12190. S_Q:
  12191. RegSize := R_SUBQ;
  12192. {$endif x86_64}
  12193. else
  12194. InternalError(2021100401);
  12195. end;
  12196. { See if the value has already been reserved for another CMOV instruction }
  12197. CurrentVal := taicpu(p).oper[0]^.val;
  12198. for X := 0 to ConstCount - 1 do
  12199. if ConstVals[X] = CurrentVal then
  12200. begin
  12201. ConstRegs[ConstCount] := ConstRegs[X];
  12202. ConstSizes[ConstCount] := RegSize;
  12203. ConstVals[ConstCount] := CurrentVal;
  12204. Inc(ConstCount);
  12205. Inc(Count);
  12206. Result := True;
  12207. Exit;
  12208. end;
  12209. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12210. if ANewReg = NR_NO then
  12211. { No free registers }
  12212. Exit;
  12213. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12214. up vying for the same register }
  12215. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12216. ConstRegs[ConstCount] := ANewReg;
  12217. ConstSizes[ConstCount] := RegSize;
  12218. ConstVals[ConstCount] := CurrentVal;
  12219. Inc(ConstCount);
  12220. Inc(Count);
  12221. Result := True;
  12222. end;
  12223. destructor TCMOVTracking.Done;
  12224. begin
  12225. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12226. end;
  12227. procedure TCMOVTracking.Process(out new_p: tai);
  12228. var
  12229. Count, Writes: LongInt;
  12230. RegMatch: Boolean;
  12231. hp1, hp_new: tai;
  12232. inverted_condition, condition: TAsmCond;
  12233. begin
  12234. if (fState in [tsInvalid, tsProcessed]) then
  12235. InternalError(2023110701);
  12236. { Repurpose RegisterTracking to mark registers that we've defined }
  12237. RegisterTracking[R_INTREGISTER].Clear;
  12238. Count := 0;
  12239. Writes := 0;
  12240. condition := taicpu(fInitialJump).condition;
  12241. inverted_condition := inverse_cond(condition);
  12242. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12243. doesn't get CMOVs in this case }
  12244. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12245. begin
  12246. { Include the jump in the flag tracking }
  12247. if Assigned(fThirdJump) then
  12248. begin
  12249. if (fState = tsDoubleBranchSame) then
  12250. begin
  12251. { Will be an unconditional jump, so track to the instruction before it }
  12252. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12253. InternalError(2023110710);
  12254. end
  12255. else
  12256. hp1 := fThirdJump;
  12257. end
  12258. else
  12259. hp1 := fSecondMovBlockStop;
  12260. end
  12261. else
  12262. begin
  12263. { Include a conditional jump in the flag tracking }
  12264. if Assigned(fSecondJump) then
  12265. begin
  12266. if (fState = tsDetour) then
  12267. begin
  12268. { Will be an unconditional jump, so track to the instruction before it }
  12269. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12270. InternalError(2023110711);
  12271. end
  12272. else
  12273. hp1 := fSecondJump;
  12274. end
  12275. else
  12276. hp1 := fFirstMovBlockStop;
  12277. end;
  12278. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12279. { Process the second set of MOVs first, because if a destination
  12280. register is shared between the first and second MOV sets, it is more
  12281. efficient to turn the first one into a MOV instruction and place it
  12282. before the CMP if possible, but we won't know which registers are
  12283. shared until we've processed at least one list, so we might as well
  12284. make it the second one since that won't be modified again. }
  12285. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12286. begin
  12287. hp1 := fSecondMovBlock;
  12288. repeat
  12289. if not Assigned(hp1) then
  12290. InternalError(2018062902);
  12291. if (hp1.typ = ait_instruction) then
  12292. begin
  12293. { Extra safeguard }
  12294. if (taicpu(hp1).opcode <> A_MOV) then
  12295. InternalError(2018062903);
  12296. { Note: tsDoubleBranchDifferent is essentially identical to
  12297. tsBranching and the 2nd block is best left largely
  12298. untouched, but we need to evaluate which registers the MOVs
  12299. write to in order to track what would be complementary CMOV
  12300. pairs that can be further optimised. [Kit] }
  12301. if fState <> tsDoubleBranchDifferent then
  12302. begin
  12303. if taicpu(hp1).oper[0]^.typ = top_const then
  12304. begin
  12305. RegMatch := False;
  12306. for Count := 0 to ConstCount - 1 do
  12307. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12308. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12309. begin
  12310. RegMatch := True;
  12311. { If it's in RegisterTracking, then this register
  12312. is being used more than once and hence has
  12313. already had its value defined (it gets added to
  12314. UsedRegs through AllocRegBetween below) }
  12315. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12316. begin
  12317. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12318. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12319. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12320. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12321. ConstMovs[Count] := hp_new;
  12322. end
  12323. else
  12324. { We just need an instruction between hp_prev and hp1
  12325. where we know the register is marked as in use }
  12326. hp_new := fSecondMovBlock;
  12327. { Keep track of largest write for this register so it can be optimised later }
  12328. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12329. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12330. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12331. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12332. Break;
  12333. end;
  12334. if not RegMatch then
  12335. InternalError(2021100411);
  12336. end;
  12337. taicpu(hp1).opcode := A_CMOVcc;
  12338. taicpu(hp1).condition := condition;
  12339. end;
  12340. { Store these writes to search for duplicates later on }
  12341. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12342. Inc(Writes);
  12343. end;
  12344. fOptimizer.GetNextInstruction(hp1, hp1);
  12345. until (hp1 = fSecondMovBlockStop);
  12346. end;
  12347. { Now do the first set of MOVs }
  12348. hp1 := fFirstMovBlock;
  12349. repeat
  12350. if not Assigned(hp1) then
  12351. InternalError(2018062904);
  12352. if (hp1.typ = ait_instruction) then
  12353. begin
  12354. RegMatch := False;
  12355. { Extra safeguard }
  12356. if (taicpu(hp1).opcode <> A_MOV) then
  12357. InternalError(2018062905);
  12358. { Search through the RegWrites list to see if there are any
  12359. opposing CMOV pairs that write to the same register }
  12360. for Count := 0 to Writes - 1 do
  12361. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12362. begin
  12363. { We have a match. Keep this as a MOV }
  12364. { Move ahead in preparation }
  12365. fOptimizer.GetNextInstruction(hp1, hp1);
  12366. RegMatch := True;
  12367. Break;
  12368. end;
  12369. if RegMatch then
  12370. Continue;
  12371. if taicpu(hp1).oper[0]^.typ = top_const then
  12372. begin
  12373. for Count := 0 to ConstCount - 1 do
  12374. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12375. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12376. begin
  12377. RegMatch := True;
  12378. { If it's in RegisterTracking, then this register is
  12379. being used more than once and hence has already had
  12380. its value defined (it gets added to UsedRegs through
  12381. AllocRegBetween below) }
  12382. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12383. begin
  12384. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12385. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12386. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12387. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12388. ConstMovs[Count] := hp_new;
  12389. end
  12390. else
  12391. { We just need an instruction between hp_prev and hp1
  12392. where we know the register is marked as in use }
  12393. hp_new := fFirstMovBlock;
  12394. { Keep track of largest write for this register so it can be optimised later }
  12395. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12396. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12397. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12398. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12399. Break;
  12400. end;
  12401. if not RegMatch then
  12402. InternalError(2021100412);
  12403. end;
  12404. taicpu(hp1).opcode := A_CMOVcc;
  12405. taicpu(hp1).condition := inverted_condition;
  12406. if (fState = tsDoubleBranchDifferent) then
  12407. begin
  12408. { Store these writes to search for duplicates later on }
  12409. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12410. Inc(Writes);
  12411. end;
  12412. end;
  12413. fOptimizer.GetNextInstruction(hp1, hp1);
  12414. until (hp1 = fFirstMovBlockStop);
  12415. { Update initialisation MOVs to the smallest possible size }
  12416. for Count := 0 to ConstCount - 1 do
  12417. if Assigned(ConstMovs[Count]) then
  12418. begin
  12419. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12420. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12421. end;
  12422. case fState of
  12423. tsSimple:
  12424. begin
  12425. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12426. { No branch to delete }
  12427. end;
  12428. tsDetour:
  12429. begin
  12430. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12431. { Preserve jump }
  12432. end;
  12433. tsBranching, tsDoubleBranchDifferent:
  12434. begin
  12435. if (fState = tsBranching) then
  12436. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12437. else
  12438. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12439. taicpu(fSecondJump).opcode := A_JCC;
  12440. taicpu(fSecondJump).condition := inverted_condition;
  12441. end;
  12442. tsDouble, tsDoubleBranchSame:
  12443. begin
  12444. if (fState = tsDouble) then
  12445. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12446. else
  12447. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12448. { Delete second jump }
  12449. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12450. fOptimizer.RemoveInstruction(fSecondJump);
  12451. end;
  12452. tsDoubleSecondBranching:
  12453. begin
  12454. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12455. { Delete second jump, preserve third jump as conditional }
  12456. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12457. fOptimizer.RemoveInstruction(fSecondJump);
  12458. taicpu(fThirdJump).opcode := A_JCC;
  12459. taicpu(fThirdJump).condition := condition;
  12460. end;
  12461. else
  12462. InternalError(2023110720);
  12463. end;
  12464. { Now we can safely decrement the reference count }
  12465. tasmlabel(fLabel).decrefs;
  12466. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12467. { Remove the original jump }
  12468. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12469. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12470. fState := tsProcessed;
  12471. end;
  12472. {$endif 8086}
  12473. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12474. var
  12475. hp1,hp2: tai;
  12476. carryadd_opcode : TAsmOp;
  12477. symbol: TAsmSymbol;
  12478. increg, tmpreg: TRegister;
  12479. {$ifndef i8086}
  12480. CMOVTracking: PCMOVTracking;
  12481. hp3,hp4,hp5: tai;
  12482. {$endif i8086}
  12483. TempBool: Boolean;
  12484. begin
  12485. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12486. DoJumpOptimizations(p, TempBool) then
  12487. Exit(True);
  12488. result:=false;
  12489. if GetNextInstruction(p,hp1) then
  12490. begin
  12491. if (hp1.typ=ait_label) then
  12492. begin
  12493. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12494. Exit;
  12495. end
  12496. else if (hp1.typ<>ait_instruction) then
  12497. Exit;
  12498. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12499. if (
  12500. (
  12501. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12502. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12503. (Taicpu(hp1).oper[0]^.val=1)
  12504. ) or
  12505. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12506. ) and
  12507. GetNextInstruction(hp1,hp2) and
  12508. FindLabel(TAsmLabel(symbol), hp2) then
  12509. { jb @@1 cmc
  12510. inc/dec operand --> adc/sbb operand,0
  12511. @@1:
  12512. ... and ...
  12513. jnb @@1
  12514. inc/dec operand --> adc/sbb operand,0
  12515. @@1: }
  12516. begin
  12517. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12518. begin
  12519. case taicpu(hp1).opcode of
  12520. A_INC,
  12521. A_ADD:
  12522. carryadd_opcode:=A_ADC;
  12523. A_DEC,
  12524. A_SUB:
  12525. carryadd_opcode:=A_SBB;
  12526. else
  12527. InternalError(2021011001);
  12528. end;
  12529. Taicpu(p).clearop(0);
  12530. Taicpu(p).ops:=0;
  12531. Taicpu(p).is_jmp:=false;
  12532. Taicpu(p).opcode:=A_CMC;
  12533. Taicpu(p).condition:=C_NONE;
  12534. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12535. Taicpu(hp1).ops:=2;
  12536. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12537. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12538. else
  12539. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12540. Taicpu(hp1).loadconst(0,0);
  12541. Taicpu(hp1).opcode:=carryadd_opcode;
  12542. result:=true;
  12543. exit;
  12544. end
  12545. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12546. begin
  12547. case taicpu(hp1).opcode of
  12548. A_INC,
  12549. A_ADD:
  12550. carryadd_opcode:=A_ADC;
  12551. A_DEC,
  12552. A_SUB:
  12553. carryadd_opcode:=A_SBB;
  12554. else
  12555. InternalError(2021011002);
  12556. end;
  12557. Taicpu(hp1).ops:=2;
  12558. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12559. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12560. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12561. else
  12562. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12563. Taicpu(hp1).loadconst(0,0);
  12564. Taicpu(hp1).opcode:=carryadd_opcode;
  12565. RemoveCurrentP(p, hp1);
  12566. result:=true;
  12567. exit;
  12568. end
  12569. {
  12570. jcc @@1 setcc tmpreg
  12571. inc/dec/add/sub operand -> (movzx tmpreg)
  12572. @@1: add/sub tmpreg,operand
  12573. While this increases code size slightly, it makes the code much faster if the
  12574. jump is unpredictable
  12575. }
  12576. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12577. begin
  12578. { search for an available register which is volatile }
  12579. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12580. if increg <> NR_NO then
  12581. begin
  12582. { We don't need to check if tmpreg is in hp1 or not, because
  12583. it will be marked as in use at p (if not, this is
  12584. indictive of a compiler bug). }
  12585. TAsmLabel(symbol).decrefs;
  12586. Taicpu(p).clearop(0);
  12587. Taicpu(p).ops:=1;
  12588. Taicpu(p).is_jmp:=false;
  12589. Taicpu(p).opcode:=A_SETcc;
  12590. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12591. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12592. Taicpu(p).loadreg(0,increg);
  12593. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12594. begin
  12595. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12596. R_SUBW:
  12597. begin
  12598. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12599. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12600. end;
  12601. R_SUBD:
  12602. begin
  12603. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12604. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12605. end;
  12606. {$ifdef x86_64}
  12607. R_SUBQ:
  12608. begin
  12609. { MOVZX doesn't have a 64-bit variant, because
  12610. the 32-bit version implicitly zeroes the
  12611. upper 32-bits of the destination register }
  12612. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12613. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12614. setsubreg(tmpreg, R_SUBQ);
  12615. end;
  12616. {$endif x86_64}
  12617. else
  12618. Internalerror(2020030601);
  12619. end;
  12620. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12621. asml.InsertAfter(hp2,p);
  12622. end
  12623. else
  12624. tmpreg := increg;
  12625. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12626. begin
  12627. Taicpu(hp1).ops:=2;
  12628. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12629. end;
  12630. Taicpu(hp1).loadreg(0,tmpreg);
  12631. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12632. Result := True;
  12633. { p is no longer a Jcc instruction, so exit }
  12634. Exit;
  12635. end;
  12636. end;
  12637. end;
  12638. { Detect the following:
  12639. jmp<cond> @Lbl1
  12640. jmp @Lbl2
  12641. ...
  12642. @Lbl1:
  12643. ret
  12644. Change to:
  12645. jmp<inv_cond> @Lbl2
  12646. ret
  12647. }
  12648. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12649. begin
  12650. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12651. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12652. MatchInstruction(hp2,A_RET,[S_NO]) then
  12653. begin
  12654. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12655. { Change label address to that of the unconditional jump }
  12656. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12657. TAsmLabel(symbol).DecRefs;
  12658. taicpu(hp1).opcode := A_RET;
  12659. taicpu(hp1).is_jmp := false;
  12660. taicpu(hp1).ops := taicpu(hp2).ops;
  12661. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12662. case taicpu(hp2).ops of
  12663. 0:
  12664. taicpu(hp1).clearop(0);
  12665. 1:
  12666. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12667. else
  12668. internalerror(2016041302);
  12669. end;
  12670. end;
  12671. {$ifndef i8086}
  12672. end
  12673. {
  12674. convert
  12675. j<c> .L1
  12676. mov 1,reg
  12677. jmp .L2
  12678. .L1
  12679. mov 0,reg
  12680. .L2
  12681. into
  12682. mov 0,reg
  12683. set<not(c)> reg
  12684. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12685. would destroy the flag contents
  12686. }
  12687. else if MatchInstruction(hp1,A_MOV,[]) and
  12688. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12689. {$ifdef i386}
  12690. (
  12691. { Under i386, ESI, EDI, EBP and ESP
  12692. don't have an 8-bit representation }
  12693. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12694. ) and
  12695. {$endif i386}
  12696. (taicpu(hp1).oper[0]^.val=1) and
  12697. GetNextInstruction(hp1,hp2) and
  12698. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12699. GetNextInstruction(hp2,hp3) and
  12700. (hp3.typ=ait_label) and
  12701. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12702. (tai_label(hp3).labsym.getrefs=1) and
  12703. GetNextInstruction(hp3,hp4) and
  12704. MatchInstruction(hp4,A_MOV,[]) and
  12705. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12706. (taicpu(hp4).oper[0]^.val=0) and
  12707. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12708. GetNextInstruction(hp4,hp5) and
  12709. (hp5.typ=ait_label) and
  12710. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12711. (tai_label(hp5).labsym.getrefs=1) then
  12712. begin
  12713. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12714. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12715. { remove last label }
  12716. RemoveInstruction(hp5);
  12717. { remove second label }
  12718. RemoveInstruction(hp3);
  12719. { remove jmp }
  12720. RemoveInstruction(hp2);
  12721. if taicpu(hp1).opsize=S_B then
  12722. RemoveInstruction(hp1)
  12723. else
  12724. taicpu(hp1).loadconst(0,0);
  12725. taicpu(hp4).opcode:=A_SETcc;
  12726. taicpu(hp4).opsize:=S_B;
  12727. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12728. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12729. taicpu(hp4).opercnt:=1;
  12730. taicpu(hp4).ops:=1;
  12731. taicpu(hp4).freeop(1);
  12732. RemoveCurrentP(p);
  12733. Result:=true;
  12734. exit;
  12735. end
  12736. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12737. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12738. begin
  12739. { check for
  12740. jCC xxx
  12741. <several movs>
  12742. xxx:
  12743. Also spot:
  12744. Jcc xxx
  12745. <several movs>
  12746. jmp xxx
  12747. Change to:
  12748. <several cmovs with inverted condition>
  12749. jmp xxx (only for the 2nd case)
  12750. }
  12751. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12752. if CMOVTracking^.State <> tsInvalid then
  12753. begin
  12754. CMovTracking^.Process(p);
  12755. Result := True;
  12756. end;
  12757. CMOVTracking^.Done;
  12758. {$endif i8086}
  12759. end;
  12760. end;
  12761. end;
  12762. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12763. var
  12764. hp1,hp2,hp3: tai;
  12765. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12766. NewSize: TOpSize;
  12767. NewRegSize: TSubRegister;
  12768. Limit: TCgInt;
  12769. SwapOper: POper;
  12770. begin
  12771. result:=false;
  12772. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12773. GetNextInstruction(p,hp1) and
  12774. (hp1.typ = ait_instruction);
  12775. if reg_and_hp1_is_instr and
  12776. (
  12777. (taicpu(hp1).opcode <> A_LEA) or
  12778. { If the LEA instruction can be converted into an arithmetic instruction,
  12779. it may be possible to then fold it. }
  12780. (
  12781. { If the flags register is in use, don't change the instruction
  12782. to an ADD otherwise this will scramble the flags. [Kit] }
  12783. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12784. ConvertLEA(taicpu(hp1))
  12785. )
  12786. ) and
  12787. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12788. GetNextInstruction(hp1,hp2) and
  12789. MatchInstruction(hp2,A_MOV,[]) and
  12790. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12791. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12792. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12793. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12794. {$ifdef i386}
  12795. { not all registers have byte size sub registers on i386 }
  12796. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12797. {$endif i386}
  12798. (((taicpu(hp1).ops=2) and
  12799. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12800. ((taicpu(hp1).ops=1) and
  12801. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12802. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12803. begin
  12804. { change movsX/movzX reg/ref, reg2
  12805. add/sub/or/... reg3/$const, reg2
  12806. mov reg2 reg/ref
  12807. to add/sub/or/... reg3/$const, reg/ref }
  12808. { by example:
  12809. movswl %si,%eax movswl %si,%eax p
  12810. decl %eax addl %edx,%eax hp1
  12811. movw %ax,%si movw %ax,%si hp2
  12812. ->
  12813. movswl %si,%eax movswl %si,%eax p
  12814. decw %eax addw %edx,%eax hp1
  12815. movw %ax,%si movw %ax,%si hp2
  12816. }
  12817. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12818. {
  12819. ->
  12820. movswl %si,%eax movswl %si,%eax p
  12821. decw %si addw %dx,%si hp1
  12822. movw %ax,%si movw %ax,%si hp2
  12823. }
  12824. case taicpu(hp1).ops of
  12825. 1:
  12826. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12827. 2:
  12828. begin
  12829. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12830. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12831. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12832. end;
  12833. else
  12834. internalerror(2008042702);
  12835. end;
  12836. {
  12837. ->
  12838. decw %si addw %dx,%si p
  12839. }
  12840. DebugMsg(SPeepholeOptimization + 'var3',p);
  12841. RemoveCurrentP(p, hp1);
  12842. RemoveInstruction(hp2);
  12843. Result := True;
  12844. Exit;
  12845. end;
  12846. if reg_and_hp1_is_instr and
  12847. (taicpu(hp1).opcode = A_MOV) and
  12848. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12849. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12850. {$ifdef x86_64}
  12851. { check for implicit extension to 64 bit }
  12852. or
  12853. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12854. (taicpu(hp1).opsize=S_Q) and
  12855. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12856. )
  12857. {$endif x86_64}
  12858. )
  12859. then
  12860. begin
  12861. { change
  12862. movx %reg1,%reg2
  12863. mov %reg2,%reg3
  12864. dealloc %reg2
  12865. into
  12866. movx %reg,%reg3
  12867. }
  12868. TransferUsedRegs(TmpUsedRegs);
  12869. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12870. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12871. begin
  12872. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12873. {$ifdef x86_64}
  12874. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12875. (taicpu(hp1).opsize=S_Q) then
  12876. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12877. else
  12878. {$endif x86_64}
  12879. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12880. RemoveInstruction(hp1);
  12881. Result := True;
  12882. Exit;
  12883. end;
  12884. end;
  12885. if reg_and_hp1_is_instr and
  12886. ((taicpu(hp1).opcode=A_MOV) or
  12887. (taicpu(hp1).opcode=A_ADD) or
  12888. (taicpu(hp1).opcode=A_SUB) or
  12889. (taicpu(hp1).opcode=A_CMP) or
  12890. (taicpu(hp1).opcode=A_OR) or
  12891. (taicpu(hp1).opcode=A_XOR) or
  12892. (taicpu(hp1).opcode=A_AND)
  12893. ) and
  12894. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12895. begin
  12896. AndTest := (taicpu(hp1).opcode=A_AND) and
  12897. GetNextInstruction(hp1, hp2) and
  12898. (hp2.typ = ait_instruction) and
  12899. (
  12900. (
  12901. (taicpu(hp2).opcode=A_TEST) and
  12902. (
  12903. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12904. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12905. (
  12906. { If the AND and TEST instructions share a constant, this is also valid }
  12907. (taicpu(hp1).oper[0]^.typ = top_const) and
  12908. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12909. )
  12910. ) and
  12911. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12912. ) or
  12913. (
  12914. (taicpu(hp2).opcode=A_CMP) and
  12915. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12916. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12917. )
  12918. );
  12919. { change
  12920. movx (oper),%reg2
  12921. and $x,%reg2
  12922. test %reg2,%reg2
  12923. dealloc %reg2
  12924. into
  12925. op %reg1,%reg3
  12926. if the second op accesses only the bits stored in reg1
  12927. }
  12928. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12929. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12930. (taicpu(hp1).oper[0]^.typ = top_const) and
  12931. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12932. AndTest then
  12933. begin
  12934. { Check if the AND constant is in range }
  12935. case taicpu(p).opsize of
  12936. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12937. begin
  12938. NewSize := S_B;
  12939. Limit := $FF;
  12940. end;
  12941. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12942. begin
  12943. NewSize := S_W;
  12944. Limit := $FFFF;
  12945. end;
  12946. {$ifdef x86_64}
  12947. S_LQ:
  12948. begin
  12949. NewSize := S_L;
  12950. Limit := $FFFFFFFF;
  12951. end;
  12952. {$endif x86_64}
  12953. else
  12954. InternalError(2021120303);
  12955. end;
  12956. if (
  12957. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12958. { Check for negative operands }
  12959. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12960. ) and
  12961. GetNextInstruction(hp2,hp3) and
  12962. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12963. (taicpu(hp3).condition in [C_E,C_NE]) then
  12964. begin
  12965. TransferUsedRegs(TmpUsedRegs);
  12966. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12967. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12968. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12969. begin
  12970. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12971. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12972. taicpu(hp1).opcode := A_TEST;
  12973. taicpu(hp1).opsize := NewSize;
  12974. RemoveInstruction(hp2);
  12975. RemoveCurrentP(p, hp1);
  12976. Result:=true;
  12977. exit;
  12978. end;
  12979. end;
  12980. end;
  12981. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12982. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12983. (taicpu(hp1).opsize=S_B)) or
  12984. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12985. (taicpu(hp1).opsize=S_W))
  12986. {$ifdef x86_64}
  12987. or ((taicpu(p).opsize=S_LQ) and
  12988. (taicpu(hp1).opsize=S_L))
  12989. {$endif x86_64}
  12990. ) and
  12991. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12992. begin
  12993. { change
  12994. movx %reg1,%reg2
  12995. op %reg2,%reg3
  12996. dealloc %reg2
  12997. into
  12998. op %reg1,%reg3
  12999. if the second op accesses only the bits stored in reg1
  13000. }
  13001. TransferUsedRegs(TmpUsedRegs);
  13002. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13003. if AndTest then
  13004. begin
  13005. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13006. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13007. end
  13008. else
  13009. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13010. if not RegUsed then
  13011. begin
  13012. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13013. if taicpu(p).oper[0]^.typ=top_reg then
  13014. begin
  13015. case taicpu(hp1).opsize of
  13016. S_B:
  13017. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13018. S_W:
  13019. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13020. S_L:
  13021. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13022. else
  13023. Internalerror(2020102301);
  13024. end;
  13025. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13026. end
  13027. else
  13028. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13029. RemoveCurrentP(p);
  13030. if AndTest then
  13031. RemoveInstruction(hp2);
  13032. result:=true;
  13033. exit;
  13034. end;
  13035. end
  13036. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13037. (
  13038. { Bitwise operations only }
  13039. (taicpu(hp1).opcode=A_AND) or
  13040. (taicpu(hp1).opcode=A_TEST) or
  13041. (
  13042. (taicpu(hp1).oper[0]^.typ = top_const) and
  13043. (
  13044. (taicpu(hp1).opcode=A_OR) or
  13045. (taicpu(hp1).opcode=A_XOR)
  13046. )
  13047. )
  13048. ) and
  13049. (
  13050. (taicpu(hp1).oper[0]^.typ = top_const) or
  13051. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13052. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13053. ) then
  13054. begin
  13055. { change
  13056. movx %reg2,%reg2
  13057. op const,%reg2
  13058. into
  13059. op const,%reg2 (smaller version)
  13060. movx %reg2,%reg2
  13061. also change
  13062. movx %reg1,%reg2
  13063. and/test (oper),%reg2
  13064. dealloc %reg2
  13065. into
  13066. and/test (oper),%reg1
  13067. }
  13068. case taicpu(p).opsize of
  13069. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13070. begin
  13071. NewSize := S_B;
  13072. NewRegSize := R_SUBL;
  13073. Limit := $FF;
  13074. end;
  13075. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13076. begin
  13077. NewSize := S_W;
  13078. NewRegSize := R_SUBW;
  13079. Limit := $FFFF;
  13080. end;
  13081. {$ifdef x86_64}
  13082. S_LQ:
  13083. begin
  13084. NewSize := S_L;
  13085. NewRegSize := R_SUBD;
  13086. Limit := $FFFFFFFF;
  13087. end;
  13088. {$endif x86_64}
  13089. else
  13090. Internalerror(2021120302);
  13091. end;
  13092. TransferUsedRegs(TmpUsedRegs);
  13093. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13094. if AndTest then
  13095. begin
  13096. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13097. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13098. end
  13099. else
  13100. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13101. if
  13102. (
  13103. (taicpu(p).opcode = A_MOVZX) and
  13104. (
  13105. (taicpu(hp1).opcode=A_AND) or
  13106. (taicpu(hp1).opcode=A_TEST)
  13107. ) and
  13108. not (
  13109. { If both are references, then the final instruction will have
  13110. both operands as references, which is not allowed }
  13111. (taicpu(p).oper[0]^.typ = top_ref) and
  13112. (taicpu(hp1).oper[0]^.typ = top_ref)
  13113. ) and
  13114. not RegUsed
  13115. ) or
  13116. (
  13117. (
  13118. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13119. not RegUsed
  13120. ) and
  13121. (taicpu(p).oper[0]^.typ = top_reg) and
  13122. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13123. (taicpu(hp1).oper[0]^.typ = top_const) and
  13124. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13125. ) then
  13126. begin
  13127. {$if defined(i386) or defined(i8086)}
  13128. { If the target size is 8-bit, make sure we can actually encode it }
  13129. 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
  13130. Exit;
  13131. {$endif i386 or i8086}
  13132. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13133. taicpu(hp1).opsize := NewSize;
  13134. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13135. if AndTest then
  13136. begin
  13137. RemoveInstruction(hp2);
  13138. if not RegUsed then
  13139. begin
  13140. taicpu(hp1).opcode := A_TEST;
  13141. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13142. begin
  13143. { Make sure the reference is the second operand }
  13144. SwapOper := taicpu(hp1).oper[0];
  13145. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13146. taicpu(hp1).oper[1] := SwapOper;
  13147. end;
  13148. end;
  13149. end;
  13150. case taicpu(hp1).oper[0]^.typ of
  13151. top_reg:
  13152. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13153. top_const:
  13154. { For the AND/TEST case }
  13155. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13156. else
  13157. ;
  13158. end;
  13159. if RegUsed then
  13160. begin
  13161. AsmL.Remove(p);
  13162. AsmL.InsertAfter(p, hp1);
  13163. p := hp1;
  13164. end
  13165. else
  13166. RemoveCurrentP(p, hp1);
  13167. result:=true;
  13168. exit;
  13169. end;
  13170. end;
  13171. end;
  13172. if reg_and_hp1_is_instr and
  13173. (taicpu(p).oper[0]^.typ = top_reg) and
  13174. (
  13175. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13176. ) and
  13177. (taicpu(hp1).oper[0]^.typ = top_const) and
  13178. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13179. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13180. { Minimum shift value allowed is the bit difference between the sizes }
  13181. (taicpu(hp1).oper[0]^.val >=
  13182. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13183. 8 * (
  13184. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13185. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13186. )
  13187. ) then
  13188. begin
  13189. { For:
  13190. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13191. shl/sal ##, %reg1
  13192. Remove the movsx/movzx instruction if the shift overwrites the
  13193. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13194. }
  13195. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13196. RemoveCurrentP(p, hp1);
  13197. Result := True;
  13198. Exit;
  13199. end
  13200. else if reg_and_hp1_is_instr and
  13201. (taicpu(p).oper[0]^.typ = top_reg) and
  13202. (
  13203. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13204. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13205. ) and
  13206. (taicpu(hp1).oper[0]^.typ = top_const) and
  13207. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13208. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13209. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13210. (taicpu(hp1).oper[0]^.val <
  13211. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13212. 8 * (
  13213. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13214. )
  13215. ) then
  13216. begin
  13217. { For:
  13218. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13219. sar ##, %reg1 shr ##, %reg1
  13220. Move the shift to before the movx instruction if the shift value
  13221. is not too large.
  13222. }
  13223. asml.Remove(hp1);
  13224. asml.InsertBefore(hp1, p);
  13225. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13226. case taicpu(p).opsize of
  13227. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13228. taicpu(hp1).opsize := S_B;
  13229. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13230. taicpu(hp1).opsize := S_W;
  13231. {$ifdef x86_64}
  13232. S_LQ:
  13233. taicpu(hp1).opsize := S_L;
  13234. {$endif}
  13235. else
  13236. InternalError(2020112401);
  13237. end;
  13238. if (taicpu(hp1).opcode = A_SHR) then
  13239. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13240. else
  13241. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13242. Result := True;
  13243. end;
  13244. if reg_and_hp1_is_instr and
  13245. (taicpu(p).oper[0]^.typ = top_reg) and
  13246. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13247. (
  13248. (taicpu(hp1).opcode = taicpu(p).opcode)
  13249. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13250. {$ifdef x86_64}
  13251. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13252. {$endif x86_64}
  13253. ) then
  13254. begin
  13255. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13256. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13257. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13258. begin
  13259. {
  13260. For example:
  13261. movzbw %al,%ax
  13262. movzwl %ax,%eax
  13263. Compress into:
  13264. movzbl %al,%eax
  13265. }
  13266. RegUsed := False;
  13267. case taicpu(p).opsize of
  13268. S_BW:
  13269. case taicpu(hp1).opsize of
  13270. S_WL:
  13271. begin
  13272. taicpu(p).opsize := S_BL;
  13273. RegUsed := True;
  13274. end;
  13275. {$ifdef x86_64}
  13276. S_WQ:
  13277. begin
  13278. if taicpu(p).opcode = A_MOVZX then
  13279. begin
  13280. taicpu(p).opsize := S_BL;
  13281. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13282. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13283. end
  13284. else
  13285. taicpu(p).opsize := S_BQ;
  13286. RegUsed := True;
  13287. end;
  13288. {$endif x86_64}
  13289. else
  13290. ;
  13291. end;
  13292. {$ifdef x86_64}
  13293. S_BL:
  13294. case taicpu(hp1).opsize of
  13295. S_LQ:
  13296. begin
  13297. if taicpu(p).opcode = A_MOVZX then
  13298. begin
  13299. taicpu(p).opsize := S_BL;
  13300. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13301. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13302. end
  13303. else
  13304. taicpu(p).opsize := S_BQ;
  13305. RegUsed := True;
  13306. end;
  13307. else
  13308. ;
  13309. end;
  13310. S_WL:
  13311. case taicpu(hp1).opsize of
  13312. S_LQ:
  13313. begin
  13314. if taicpu(p).opcode = A_MOVZX then
  13315. begin
  13316. taicpu(p).opsize := S_WL;
  13317. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13318. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13319. end
  13320. else
  13321. taicpu(p).opsize := S_WQ;
  13322. RegUsed := True;
  13323. end;
  13324. else
  13325. ;
  13326. end;
  13327. {$endif x86_64}
  13328. else
  13329. ;
  13330. end;
  13331. if RegUsed then
  13332. begin
  13333. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13334. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13335. RemoveInstruction(hp1);
  13336. Result := True;
  13337. Exit;
  13338. end;
  13339. end;
  13340. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13341. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13342. GetNextInstruction(hp1, hp2) and
  13343. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13344. (
  13345. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13346. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13347. {$ifdef x86_64}
  13348. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13349. {$endif x86_64}
  13350. ) and
  13351. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13352. (
  13353. (
  13354. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13355. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13356. ) or
  13357. (
  13358. { Only allow the operands in reverse order for TEST instructions }
  13359. (taicpu(hp2).opcode = A_TEST) and
  13360. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13361. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13362. )
  13363. ) then
  13364. begin
  13365. {
  13366. For example:
  13367. movzbl %al,%eax
  13368. movzbl (ref),%edx
  13369. andl %edx,%eax
  13370. (%edx deallocated)
  13371. Change to:
  13372. andb (ref),%al
  13373. movzbl %al,%eax
  13374. Rules are:
  13375. - First two instructions have the same opcode and opsize
  13376. - First instruction's operands are the same super-register
  13377. - Second instruction operates on a different register
  13378. - Third instruction is AND, OR, XOR or TEST
  13379. - Third instruction's operands are the destination registers of the first two instructions
  13380. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13381. - Second instruction's destination register is deallocated afterwards
  13382. }
  13383. TransferUsedRegs(TmpUsedRegs);
  13384. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13385. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13386. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13387. begin
  13388. case taicpu(p).opsize of
  13389. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13390. NewSize := S_B;
  13391. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13392. NewSize := S_W;
  13393. {$ifdef x86_64}
  13394. S_LQ:
  13395. NewSize := S_L;
  13396. {$endif x86_64}
  13397. else
  13398. InternalError(2021120301);
  13399. end;
  13400. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13401. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13402. taicpu(hp2).opsize := NewSize;
  13403. RemoveInstruction(hp1);
  13404. { With TEST, it's best to keep the MOVX instruction at the top }
  13405. if (taicpu(hp2).opcode <> A_TEST) then
  13406. begin
  13407. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13408. asml.Remove(p);
  13409. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13410. asml.InsertAfter(p, hp2);
  13411. p := hp2;
  13412. end
  13413. else
  13414. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13415. Result := True;
  13416. Exit;
  13417. end;
  13418. end;
  13419. end;
  13420. if taicpu(p).opcode=A_MOVZX then
  13421. begin
  13422. { removes superfluous And's after movzx's }
  13423. if reg_and_hp1_is_instr and
  13424. (taicpu(hp1).opcode = A_AND) and
  13425. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13426. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13427. {$ifdef x86_64}
  13428. { check for implicit extension to 64 bit }
  13429. or
  13430. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13431. (taicpu(hp1).opsize=S_Q) and
  13432. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13433. )
  13434. {$endif x86_64}
  13435. )
  13436. then
  13437. begin
  13438. case taicpu(p).opsize Of
  13439. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13440. if (taicpu(hp1).oper[0]^.val = $ff) then
  13441. begin
  13442. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13443. RemoveInstruction(hp1);
  13444. Result:=true;
  13445. exit;
  13446. end;
  13447. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13448. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13449. begin
  13450. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13451. RemoveInstruction(hp1);
  13452. Result:=true;
  13453. exit;
  13454. end;
  13455. {$ifdef x86_64}
  13456. S_LQ:
  13457. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13458. begin
  13459. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13460. RemoveInstruction(hp1);
  13461. Result:=true;
  13462. exit;
  13463. end;
  13464. {$endif x86_64}
  13465. else
  13466. ;
  13467. end;
  13468. { we cannot get rid of the and, but can we get rid of the movz ?}
  13469. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13470. begin
  13471. case taicpu(p).opsize Of
  13472. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13473. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13474. begin
  13475. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13476. RemoveCurrentP(p,hp1);
  13477. Result:=true;
  13478. exit;
  13479. end;
  13480. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13481. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13482. begin
  13483. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13484. RemoveCurrentP(p,hp1);
  13485. Result:=true;
  13486. exit;
  13487. end;
  13488. {$ifdef x86_64}
  13489. S_LQ:
  13490. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13491. begin
  13492. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13493. RemoveCurrentP(p,hp1);
  13494. Result:=true;
  13495. exit;
  13496. end;
  13497. {$endif x86_64}
  13498. else
  13499. ;
  13500. end;
  13501. end;
  13502. end;
  13503. { changes some movzx constructs to faster synonyms (all examples
  13504. are given with eax/ax, but are also valid for other registers)}
  13505. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13506. begin
  13507. case taicpu(p).opsize of
  13508. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13509. (the machine code is equivalent to movzbl %al,%eax), but the
  13510. code generator still generates that assembler instruction and
  13511. it is silently converted. This should probably be checked.
  13512. [Kit] }
  13513. S_BW:
  13514. begin
  13515. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13516. (
  13517. not IsMOVZXAcceptable
  13518. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13519. or (
  13520. (cs_opt_size in current_settings.optimizerswitches) and
  13521. (taicpu(p).oper[1]^.reg = NR_AX)
  13522. )
  13523. ) then
  13524. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13525. begin
  13526. DebugMsg(SPeepholeOptimization + 'var7',p);
  13527. taicpu(p).opcode := A_AND;
  13528. taicpu(p).changeopsize(S_W);
  13529. taicpu(p).loadConst(0,$ff);
  13530. Result := True;
  13531. end
  13532. else if not IsMOVZXAcceptable and
  13533. GetNextInstruction(p, hp1) and
  13534. (tai(hp1).typ = ait_instruction) and
  13535. (taicpu(hp1).opcode = A_AND) and
  13536. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13537. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13538. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13539. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13540. begin
  13541. DebugMsg(SPeepholeOptimization + 'var8',p);
  13542. taicpu(p).opcode := A_MOV;
  13543. taicpu(p).changeopsize(S_W);
  13544. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13545. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13546. Result := True;
  13547. end;
  13548. end;
  13549. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13550. S_BL:
  13551. if not IsMOVZXAcceptable then
  13552. begin
  13553. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13554. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13555. begin
  13556. DebugMsg(SPeepholeOptimization + 'var9',p);
  13557. taicpu(p).opcode := A_AND;
  13558. taicpu(p).changeopsize(S_L);
  13559. taicpu(p).loadConst(0,$ff);
  13560. Result := True;
  13561. end
  13562. else if GetNextInstruction(p, hp1) and
  13563. (tai(hp1).typ = ait_instruction) and
  13564. (taicpu(hp1).opcode = A_AND) and
  13565. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13567. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13568. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13569. begin
  13570. DebugMsg(SPeepholeOptimization + 'var10',p);
  13571. taicpu(p).opcode := A_MOV;
  13572. taicpu(p).changeopsize(S_L);
  13573. { do not use R_SUBWHOLE
  13574. as movl %rdx,%eax
  13575. is invalid in assembler PM }
  13576. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13577. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13578. Result := True;
  13579. end;
  13580. end;
  13581. {$endif i8086}
  13582. S_WL:
  13583. if not IsMOVZXAcceptable then
  13584. begin
  13585. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13586. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13587. begin
  13588. DebugMsg(SPeepholeOptimization + 'var11',p);
  13589. taicpu(p).opcode := A_AND;
  13590. taicpu(p).changeopsize(S_L);
  13591. taicpu(p).loadConst(0,$ffff);
  13592. Result := True;
  13593. end
  13594. else if GetNextInstruction(p, hp1) and
  13595. (tai(hp1).typ = ait_instruction) and
  13596. (taicpu(hp1).opcode = A_AND) and
  13597. (taicpu(hp1).oper[0]^.typ = top_const) and
  13598. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13599. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13600. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13601. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13602. begin
  13603. DebugMsg(SPeepholeOptimization + 'var12',p);
  13604. taicpu(p).opcode := A_MOV;
  13605. taicpu(p).changeopsize(S_L);
  13606. { do not use R_SUBWHOLE
  13607. as movl %rdx,%eax
  13608. is invalid in assembler PM }
  13609. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13610. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13611. Result := True;
  13612. end;
  13613. end;
  13614. else
  13615. InternalError(2017050705);
  13616. end;
  13617. end
  13618. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13619. begin
  13620. if GetNextInstruction(p, hp1) and
  13621. (tai(hp1).typ = ait_instruction) and
  13622. (taicpu(hp1).opcode = A_AND) and
  13623. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13624. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13625. begin
  13626. case taicpu(p).opsize Of
  13627. S_BL:
  13628. if (taicpu(hp1).opsize <> S_L) or
  13629. (taicpu(hp1).oper[0]^.val > $FF) then
  13630. begin
  13631. DebugMsg(SPeepholeOptimization + 'var13',p);
  13632. taicpu(hp1).changeopsize(S_L);
  13633. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13634. Include(OptsToCheck, aoc_ForceNewIteration);
  13635. end;
  13636. S_WL:
  13637. if (taicpu(hp1).opsize <> S_L) or
  13638. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13639. begin
  13640. DebugMsg(SPeepholeOptimization + 'var14',p);
  13641. taicpu(hp1).changeopsize(S_L);
  13642. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13643. Include(OptsToCheck, aoc_ForceNewIteration);
  13644. end;
  13645. S_BW:
  13646. if (taicpu(hp1).opsize <> S_W) or
  13647. (taicpu(hp1).oper[0]^.val > $FF) then
  13648. begin
  13649. DebugMsg(SPeepholeOptimization + 'var15',p);
  13650. taicpu(hp1).changeopsize(S_W);
  13651. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13652. Include(OptsToCheck, aoc_ForceNewIteration);
  13653. end;
  13654. else
  13655. Internalerror(2017050704)
  13656. end;
  13657. end;
  13658. end;
  13659. end;
  13660. end;
  13661. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13662. var
  13663. hp1, hp2 : tai;
  13664. MaskLength : Cardinal;
  13665. MaskedBits : TCgInt;
  13666. ActiveReg : TRegister;
  13667. begin
  13668. Result:=false;
  13669. { There are no optimisations for reference targets }
  13670. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13671. Exit;
  13672. while GetNextInstruction(p, hp1) and
  13673. (hp1.typ = ait_instruction) do
  13674. begin
  13675. if (taicpu(p).oper[0]^.typ = top_const) then
  13676. begin
  13677. case taicpu(hp1).opcode of
  13678. A_AND:
  13679. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13680. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13681. { the second register must contain the first one, so compare their subreg types }
  13682. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13683. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13684. { change
  13685. and const1, reg
  13686. and const2, reg
  13687. to
  13688. and (const1 and const2), reg
  13689. }
  13690. begin
  13691. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13692. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13693. RemoveCurrentP(p, hp1);
  13694. Result:=true;
  13695. exit;
  13696. end;
  13697. A_CMP:
  13698. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13699. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13700. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13701. { Just check that the condition on the next instruction is compatible }
  13702. GetNextInstruction(hp1, hp2) and
  13703. (hp2.typ = ait_instruction) and
  13704. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13705. then
  13706. { change
  13707. and 2^n, reg
  13708. cmp 2^n, reg
  13709. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13710. to
  13711. and 2^n, reg
  13712. test reg, reg
  13713. j(~c) / set(~c) / cmov(~c)
  13714. }
  13715. begin
  13716. { Keep TEST instruction in, rather than remove it, because
  13717. it may trigger other optimisations such as MovAndTest2Test }
  13718. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13719. taicpu(hp1).opcode := A_TEST;
  13720. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13721. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13722. Result := True;
  13723. Exit;
  13724. end
  13725. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13726. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13727. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13728. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13729. { change
  13730. and $ff/$ff/$ffff, reg
  13731. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13732. dealloc reg
  13733. to
  13734. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13735. }
  13736. begin
  13737. TransferUsedRegs(TmpUsedRegs);
  13738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13739. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13740. begin
  13741. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13742. case taicpu(p).oper[0]^.val of
  13743. $ff:
  13744. begin
  13745. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13746. taicpu(hp1).opsize:=S_B;
  13747. end;
  13748. $ffff:
  13749. begin
  13750. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13751. taicpu(hp1).opsize:=S_W;
  13752. end;
  13753. $ffffffff:
  13754. begin
  13755. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13756. taicpu(hp1).opsize:=S_L;
  13757. end;
  13758. else
  13759. Internalerror(2023030401);
  13760. end;
  13761. RemoveCurrentP(p);
  13762. Result := True;
  13763. Exit;
  13764. end;
  13765. end;
  13766. A_MOVZX:
  13767. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13768. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13769. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13770. (
  13771. (
  13772. (taicpu(p).opsize=S_W) and
  13773. (taicpu(hp1).opsize=S_BW)
  13774. ) or
  13775. (
  13776. (taicpu(p).opsize=S_L) and
  13777. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13778. )
  13779. {$ifdef x86_64}
  13780. or
  13781. (
  13782. (taicpu(p).opsize=S_Q) and
  13783. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13784. )
  13785. {$endif x86_64}
  13786. ) then
  13787. begin
  13788. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13789. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13790. ) or
  13791. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13792. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13793. then
  13794. begin
  13795. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13796. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13797. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13798. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13799. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13800. }
  13801. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13802. RemoveInstruction(hp1);
  13803. { See if there are other optimisations possible }
  13804. Continue;
  13805. end;
  13806. end;
  13807. A_SHL:
  13808. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13809. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13810. begin
  13811. {$ifopt R+}
  13812. {$define RANGE_WAS_ON}
  13813. {$R-}
  13814. {$endif}
  13815. { get length of potential and mask }
  13816. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13817. { really a mask? }
  13818. {$ifdef RANGE_WAS_ON}
  13819. {$R+}
  13820. {$endif}
  13821. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13822. { unmasked part shifted out? }
  13823. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13824. begin
  13825. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13826. RemoveCurrentP(p, hp1);
  13827. Result:=true;
  13828. exit;
  13829. end;
  13830. end;
  13831. A_SHR:
  13832. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13833. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13834. (taicpu(hp1).oper[0]^.val <= 63) then
  13835. begin
  13836. { Does SHR combined with the AND cover all the bits?
  13837. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13838. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13839. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13840. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13841. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13842. begin
  13843. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13844. RemoveCurrentP(p, hp1);
  13845. Result := True;
  13846. Exit;
  13847. end;
  13848. end;
  13849. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13850. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13851. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13852. begin
  13853. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13854. (
  13855. (
  13856. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13857. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13858. ) or (
  13859. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13860. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13861. {$ifdef x86_64}
  13862. ) or (
  13863. (taicpu(hp1).opsize = S_LQ) and
  13864. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13865. {$endif x86_64}
  13866. )
  13867. ) then
  13868. begin
  13869. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13870. begin
  13871. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13872. RemoveInstruction(hp1);
  13873. { See if there are other optimisations possible }
  13874. Continue;
  13875. end;
  13876. { The super-registers are the same though.
  13877. Note that this change by itself doesn't improve
  13878. code speed, but it opens up other optimisations. }
  13879. {$ifdef x86_64}
  13880. { Convert 64-bit register to 32-bit }
  13881. case taicpu(hp1).opsize of
  13882. S_BQ:
  13883. begin
  13884. taicpu(hp1).opsize := S_BL;
  13885. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13886. end;
  13887. S_WQ:
  13888. begin
  13889. taicpu(hp1).opsize := S_WL;
  13890. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13891. end
  13892. else
  13893. ;
  13894. end;
  13895. {$endif x86_64}
  13896. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13897. taicpu(hp1).opcode := A_MOVZX;
  13898. { See if there are other optimisations possible }
  13899. Continue;
  13900. end;
  13901. end;
  13902. else
  13903. ;
  13904. end;
  13905. end
  13906. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13907. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13908. begin
  13909. {$ifdef x86_64}
  13910. if (taicpu(p).opsize = S_Q) then
  13911. begin
  13912. { Never necessary }
  13913. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13914. RemoveCurrentP(p, hp1);
  13915. Result := True;
  13916. Exit;
  13917. end;
  13918. {$endif x86_64}
  13919. { Forward check to determine necessity of and %reg,%reg }
  13920. TransferUsedRegs(TmpUsedRegs);
  13921. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13922. { Saves on a bunch of dereferences }
  13923. ActiveReg := taicpu(p).oper[1]^.reg;
  13924. case taicpu(hp1).opcode of
  13925. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13926. if (
  13927. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13928. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13929. ) and
  13930. (
  13931. (taicpu(hp1).opcode <> A_MOV) or
  13932. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13933. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13934. ) and
  13935. not (
  13936. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13937. (taicpu(hp1).opcode = A_MOV) and
  13938. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13939. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13940. ) and
  13941. (
  13942. (
  13943. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13944. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13945. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13946. ) or
  13947. (
  13948. {$ifdef x86_64}
  13949. (
  13950. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13951. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13952. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13953. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13954. ) and
  13955. {$endif x86_64}
  13956. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13957. )
  13958. ) then
  13959. begin
  13960. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13961. RemoveCurrentP(p, hp1);
  13962. Result := True;
  13963. Exit;
  13964. end;
  13965. A_ADD,
  13966. A_AND,
  13967. A_BSF,
  13968. A_BSR,
  13969. A_BTC,
  13970. A_BTR,
  13971. A_BTS,
  13972. A_OR,
  13973. A_SUB,
  13974. A_XOR:
  13975. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13976. if (
  13977. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13978. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13979. ) and
  13980. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13981. begin
  13982. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13983. RemoveCurrentP(p, hp1);
  13984. Result := True;
  13985. Exit;
  13986. end;
  13987. A_CMP,
  13988. A_TEST:
  13989. if (
  13990. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13991. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13992. ) and
  13993. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13994. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13995. begin
  13996. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13997. RemoveCurrentP(p, hp1);
  13998. Result := True;
  13999. Exit;
  14000. end;
  14001. A_BSWAP,
  14002. A_NEG,
  14003. A_NOT:
  14004. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14005. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14006. begin
  14007. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14008. RemoveCurrentP(p, hp1);
  14009. Result := True;
  14010. Exit;
  14011. end;
  14012. else
  14013. ;
  14014. end;
  14015. end;
  14016. if (taicpu(hp1).is_jmp) and
  14017. (taicpu(hp1).opcode<>A_JMP) and
  14018. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14019. begin
  14020. { change
  14021. and x, reg
  14022. jxx
  14023. to
  14024. test x, reg
  14025. jxx
  14026. if reg is deallocated before the
  14027. jump, but only if it's a conditional jump (PFV)
  14028. }
  14029. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14030. taicpu(p).opcode := A_TEST;
  14031. Exit;
  14032. end;
  14033. Break;
  14034. end;
  14035. { Lone AND tests }
  14036. if (taicpu(p).oper[0]^.typ = top_const) then
  14037. begin
  14038. {
  14039. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14040. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14041. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14042. }
  14043. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14044. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14045. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14046. begin
  14047. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14048. if taicpu(p).opsize = S_L then
  14049. begin
  14050. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14051. Result := True;
  14052. end;
  14053. end;
  14054. end;
  14055. { Backward check to determine necessity of and %reg,%reg }
  14056. if (taicpu(p).oper[0]^.typ = top_reg) and
  14057. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14058. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14059. GetLastInstruction(p, hp2) and
  14060. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14061. { Check size of adjacent instruction to determine if the AND is
  14062. effectively a null operation }
  14063. (
  14064. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14065. { Note: Don't include S_Q }
  14066. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14067. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14068. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14069. ) then
  14070. begin
  14071. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14072. { If GetNextInstruction returned False, hp1 will be nil }
  14073. RemoveCurrentP(p, hp1);
  14074. Result := True;
  14075. Exit;
  14076. end;
  14077. end;
  14078. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14079. var
  14080. hp1, hp2: tai;
  14081. NewRef: TReference;
  14082. Distance: Cardinal;
  14083. TempTracking: TAllUsedRegs;
  14084. DoAddMov2Lea: Boolean;
  14085. { This entire nested function is used in an if-statement below, but we
  14086. want to avoid all the used reg transfers and GetNextInstruction calls
  14087. until we really have to check }
  14088. function MemRegisterNotUsedLater: Boolean; inline;
  14089. var
  14090. hp2: tai;
  14091. begin
  14092. TransferUsedRegs(TmpUsedRegs);
  14093. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14094. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14095. else
  14096. { p and hp1 will be adjacent }
  14097. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14098. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14099. end;
  14100. begin
  14101. Result := False;
  14102. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14103. (taicpu(p).oper[1]^.typ = top_reg) then
  14104. begin
  14105. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14106. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14107. (hp1.typ <> ait_instruction) or
  14108. not
  14109. (
  14110. (cs_opt_level3 in current_settings.optimizerswitches) or
  14111. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14112. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14113. ) then
  14114. Exit;
  14115. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14116. addq $x, %rax
  14117. movq %rax, %rdx
  14118. sarq $63, %rdx
  14119. (%rax still in use)
  14120. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14121. leaq $x(%rax),%rdx
  14122. addq $x, %rax
  14123. sarq $63, %rdx
  14124. ...which is okay since it breaks the dependency chain between
  14125. addq and movq, but if OptPass2MOV is called first:
  14126. addq $x, %rax
  14127. cqto
  14128. ...which is better in all ways, taking only 2 cycles to execute
  14129. and much smaller in code size.
  14130. }
  14131. { The extra register tracking is quite strenuous }
  14132. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14133. MatchInstruction(hp1, A_MOV, []) then
  14134. begin
  14135. { Update the register tracking to the MOV instruction }
  14136. CopyUsedRegs(TempTracking);
  14137. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14138. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14139. else
  14140. { p and hp1 will be adjacent }
  14141. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14142. hp2 := hp1;
  14143. if OptPass2MOV(hp1) then
  14144. Include(OptsToCheck, aoc_ForceNewIteration);
  14145. { Reset the tracking to the current instruction }
  14146. RestoreUsedRegs(TempTracking);
  14147. ReleaseUsedRegs(TempTracking);
  14148. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14149. OptPass2ADD get called again }
  14150. if (hp1 <> hp2) then
  14151. begin
  14152. Result := True;
  14153. Exit;
  14154. end;
  14155. end;
  14156. { Change:
  14157. add %reg2,%reg1
  14158. (%reg2 not modified in between)
  14159. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14160. To:
  14161. mov/s/z #(%reg1,%reg2),%reg1
  14162. }
  14163. if (taicpu(p).oper[0]^.typ = top_reg) and
  14164. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14165. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14166. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14167. (
  14168. (
  14169. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14170. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14171. { r/esp cannot be an index }
  14172. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14173. ) or (
  14174. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14175. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14176. )
  14177. ) and (
  14178. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14179. (
  14180. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14181. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14182. MemRegisterNotUsedLater
  14183. )
  14184. ) then
  14185. begin
  14186. if (
  14187. { Instructions are guaranteed to be adjacent on -O2 and under }
  14188. (cs_opt_level3 in current_settings.optimizerswitches) and
  14189. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14190. ) then
  14191. begin
  14192. { If the other register is used in between, move the MOV
  14193. instruction to right after the ADD instruction so a
  14194. saving can still be made }
  14195. Asml.Remove(hp1);
  14196. Asml.InsertAfter(hp1, p);
  14197. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14198. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14199. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14200. RemoveCurrentp(p, hp1);
  14201. end
  14202. else
  14203. begin
  14204. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14205. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14206. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14207. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14208. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14209. { hp1 may not be the immediate next instruction under -O3 }
  14210. RemoveCurrentp(p)
  14211. else
  14212. RemoveCurrentp(p, hp1);
  14213. end;
  14214. Result := True;
  14215. Exit;
  14216. end;
  14217. { Change:
  14218. addl/q $x,%reg1
  14219. movl/q %reg1,%reg2
  14220. To:
  14221. leal/q $x(%reg1),%reg2
  14222. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14223. Breaks the dependency chain.
  14224. }
  14225. if (taicpu(p).oper[0]^.typ = top_const) and
  14226. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14227. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14228. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14229. (
  14230. { Instructions are guaranteed to be adjacent on -O2 and under }
  14231. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14232. (
  14233. { If the flags are used, don't make the optimisation,
  14234. otherwise they will be scrambled. Fixes #41148 }
  14235. (
  14236. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14237. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14238. ) and
  14239. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14240. )
  14241. ) then
  14242. begin
  14243. TransferUsedRegs(TmpUsedRegs);
  14244. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14245. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14246. else
  14247. { p and hp1 will be adjacent }
  14248. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14249. if (
  14250. SetAndTest(
  14251. (
  14252. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14253. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14254. ),
  14255. DoAddMov2Lea
  14256. ) or
  14257. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14258. not (cs_opt_size in current_settings.optimizerswitches)
  14259. ) then
  14260. begin
  14261. { Change the MOV instruction to a LEA instruction, and update the
  14262. first operand }
  14263. reference_reset(NewRef, 1, []);
  14264. NewRef.base := taicpu(p).oper[1]^.reg;
  14265. NewRef.scalefactor := 1;
  14266. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14267. taicpu(hp1).opcode := A_LEA;
  14268. taicpu(hp1).loadref(0, NewRef);
  14269. if DoAddMov2Lea then
  14270. begin
  14271. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14272. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14273. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14274. { hp1 may not be the immediate next instruction under -O3 }
  14275. RemoveCurrentp(p)
  14276. else
  14277. RemoveCurrentp(p, hp1);
  14278. end
  14279. else
  14280. begin
  14281. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14282. { Move what is now the LEA instruction to before the ADD instruction }
  14283. Asml.Remove(hp1);
  14284. Asml.InsertBefore(hp1, p);
  14285. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14286. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14287. p := hp1;
  14288. end;
  14289. Result := True;
  14290. end;
  14291. end;
  14292. end;
  14293. end;
  14294. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14295. var
  14296. SubReg: TSubRegister;
  14297. hp1, hp2: tai;
  14298. CallJmp: Boolean;
  14299. begin
  14300. Result := False;
  14301. CallJmp := False;
  14302. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14303. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14304. with taicpu(p).oper[0]^.ref^ do
  14305. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14306. if (offset = 0) then
  14307. begin
  14308. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14309. begin
  14310. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14311. taicpu(p).opcode := A_ADD;
  14312. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14313. Result := True;
  14314. end
  14315. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14316. begin
  14317. if (base <> NR_NO) then
  14318. begin
  14319. if (scalefactor <= 1) then
  14320. begin
  14321. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14322. taicpu(p).opcode := A_ADD;
  14323. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14324. Result := True;
  14325. end;
  14326. end
  14327. else
  14328. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14329. if (scalefactor in [2, 4, 8]) then
  14330. begin
  14331. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14332. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14333. taicpu(p).opcode := A_SHL;
  14334. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14335. Result := True;
  14336. end;
  14337. end;
  14338. end
  14339. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14340. lot of latency, so break off the offset if %reg3 is used soon
  14341. afterwards }
  14342. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14343. { If 3-component addresses don't have additional latency, don't
  14344. perform this optimisation }
  14345. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14346. GetNextInstruction(p, hp1) and
  14347. (hp1.typ = ait_instruction) and
  14348. (
  14349. (
  14350. { Permit jumps and calls since they have a larger degree of overhead }
  14351. (
  14352. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14353. (
  14354. { ... unless the register specifies the location }
  14355. (taicpu(hp1).ops > 0) and
  14356. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14357. )
  14358. ) and
  14359. (
  14360. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14361. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14362. )
  14363. )
  14364. or
  14365. (
  14366. { Check up to two instructions ahead }
  14367. GetNextInstruction(hp1, hp2) and
  14368. (hp2.typ = ait_instruction) and
  14369. (
  14370. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14371. (
  14372. { Same as above }
  14373. (taicpu(hp2).ops > 0) and
  14374. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14375. )
  14376. ) and
  14377. (
  14378. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14379. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14380. )
  14381. )
  14382. ) then
  14383. begin
  14384. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14385. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14386. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14387. offset := 0;
  14388. if Assigned(symbol) or Assigned(relsymbol) then
  14389. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14390. else
  14391. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14392. { Inserting before the next instruction rather than after the
  14393. current instruction gives more accurate register tracking }
  14394. asml.InsertBefore(hp2, hp1);
  14395. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14396. Result := True;
  14397. end;
  14398. end;
  14399. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14400. var
  14401. hp1, hp2: tai;
  14402. NewRef: TReference;
  14403. Distance: Cardinal;
  14404. TempTracking: TAllUsedRegs;
  14405. DoSubMov2Lea: Boolean;
  14406. begin
  14407. Result := False;
  14408. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14409. MatchOpType(taicpu(p),top_const,top_reg) then
  14410. begin
  14411. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14412. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14413. (hp1.typ <> ait_instruction) or
  14414. not
  14415. (
  14416. (cs_opt_level3 in current_settings.optimizerswitches) or
  14417. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14418. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14419. ) then
  14420. Exit;
  14421. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14422. subq $x, %rax
  14423. movq %rax, %rdx
  14424. sarq $63, %rdx
  14425. (%rax still in use)
  14426. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14427. leaq $-x(%rax),%rdx
  14428. movq $x, %rax
  14429. sarq $63, %rdx
  14430. ...which is okay since it breaks the dependency chain between
  14431. subq and movq, but if OptPass2MOV is called first:
  14432. subq $x, %rax
  14433. cqto
  14434. ...which is better in all ways, taking only 2 cycles to execute
  14435. and much smaller in code size.
  14436. }
  14437. { The extra register tracking is quite strenuous }
  14438. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14439. MatchInstruction(hp1, A_MOV, []) then
  14440. begin
  14441. { Update the register tracking to the MOV instruction }
  14442. CopyUsedRegs(TempTracking);
  14443. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14444. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14445. else
  14446. { p and hp1 will be adjacent }
  14447. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14448. hp2 := hp1;
  14449. if OptPass2MOV(hp1) then
  14450. Include(OptsToCheck, aoc_ForceNewIteration);
  14451. { Reset the tracking to the current instruction }
  14452. RestoreUsedRegs(TempTracking);
  14453. ReleaseUsedRegs(TempTracking);
  14454. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14455. OptPass2SUB get called again }
  14456. if (hp1 <> hp2) then
  14457. begin
  14458. Result := True;
  14459. Exit;
  14460. end;
  14461. end;
  14462. { Change:
  14463. subl/q $x,%reg1
  14464. movl/q %reg1,%reg2
  14465. To:
  14466. leal/q $-x(%reg1),%reg2
  14467. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14468. Breaks the dependency chain and potentially permits the removal of
  14469. a CMP instruction if one follows.
  14470. }
  14471. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14472. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14473. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14474. (
  14475. { Instructions are guaranteed to be adjacent on -O2 and under }
  14476. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14477. (
  14478. { If the flags are used, don't make the optimisation,
  14479. otherwise they will be scrambled. Fixes #41148 }
  14480. (
  14481. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14482. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14483. ) and
  14484. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14485. )
  14486. ) then
  14487. begin
  14488. TransferUsedRegs(TmpUsedRegs);
  14489. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14490. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14491. else
  14492. { p and hp1 will be adjacent }
  14493. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14494. if (
  14495. SetAndTest(
  14496. (
  14497. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14498. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14499. ),
  14500. DoSubMov2Lea
  14501. ) or
  14502. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14503. not (cs_opt_size in current_settings.optimizerswitches)
  14504. ) then
  14505. begin
  14506. { Change the MOV instruction to a LEA instruction, and update the
  14507. first operand }
  14508. reference_reset(NewRef, 1, []);
  14509. NewRef.base := taicpu(p).oper[1]^.reg;
  14510. NewRef.scalefactor := 1;
  14511. NewRef.offset := -taicpu(p).oper[0]^.val;
  14512. taicpu(hp1).opcode := A_LEA;
  14513. taicpu(hp1).loadref(0, NewRef);
  14514. if DoSubMov2Lea then
  14515. begin
  14516. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14517. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14518. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14519. { hp1 may not be the immediate next instruction under -O3 }
  14520. RemoveCurrentp(p)
  14521. else
  14522. RemoveCurrentp(p, hp1);
  14523. end
  14524. else
  14525. begin
  14526. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14527. { Move what is now the LEA instruction to before the SUB instruction }
  14528. Asml.Remove(hp1);
  14529. Asml.InsertBefore(hp1, p);
  14530. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14531. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14532. p := hp1;
  14533. end;
  14534. Result := True;
  14535. end;
  14536. end;
  14537. end;
  14538. end;
  14539. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14540. begin
  14541. { we can skip all instructions not messing with the stack pointer }
  14542. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14543. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14544. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14545. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14546. ({(taicpu(hp1).ops=0) or }
  14547. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14548. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14549. ) and }
  14550. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14551. )
  14552. ) do
  14553. GetNextInstruction(hp1,hp1);
  14554. Result:=assigned(hp1);
  14555. end;
  14556. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14557. var
  14558. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14559. begin
  14560. Result:=false;
  14561. hp5:=nil;
  14562. hp6:=nil;
  14563. hp7:=nil;
  14564. hp8:=nil;
  14565. { replace
  14566. leal(q) x(<stackpointer>),<stackpointer>
  14567. <optional .seh_stackalloc ...>
  14568. <optional .seh_endprologue ...>
  14569. call procname
  14570. <optional NOP>
  14571. leal(q) -x(<stackpointer>),<stackpointer>
  14572. <optional VZEROUPPER>
  14573. ret
  14574. by
  14575. jmp procname
  14576. but do it only on level 4 because it destroys stack back traces
  14577. }
  14578. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14579. MatchOpType(taicpu(p),top_ref,top_reg) and
  14580. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14581. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14582. { the -8, -24, -40 are not required, but bail out early if possible,
  14583. higher values are unlikely }
  14584. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14585. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14586. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14587. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14588. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14589. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14590. GetNextInstruction(p, hp1) and
  14591. { Take a copy of hp1 }
  14592. SetAndTest(hp1, hp4) and
  14593. { trick to skip label }
  14594. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14595. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14596. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14597. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14598. SkipSimpleInstructions(hp1) and
  14599. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14600. GetNextInstruction(hp1, hp2) and
  14601. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14602. { skip nop instruction on win64 }
  14603. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14604. SetAndTest(hp2,hp6) and
  14605. GetNextInstruction(hp2,hp2) and
  14606. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14607. ) and
  14608. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14609. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14610. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14611. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14612. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14613. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14614. { Segment register will be NR_NO }
  14615. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14616. GetNextInstruction(hp2, hp3) and
  14617. { trick to skip label }
  14618. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14619. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14620. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14621. SetAndTest(hp3,hp5) and
  14622. GetNextInstruction(hp3,hp3) and
  14623. MatchInstruction(hp3,A_RET,[S_NO])
  14624. )
  14625. ) and
  14626. (taicpu(hp3).ops=0) then
  14627. begin
  14628. taicpu(hp1).opcode := A_JMP;
  14629. taicpu(hp1).is_jmp := true;
  14630. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14631. { search for the stackalloc directive and remove it }
  14632. hp7:=tai(p.next);
  14633. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14634. begin
  14635. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14636. begin
  14637. { sanity check }
  14638. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14639. Internalerror(2024012201);
  14640. hp8:=tai(hp7.next);
  14641. RemoveInstruction(tai(hp7));
  14642. hp7:=hp8;
  14643. break;
  14644. end
  14645. else
  14646. hp7:=tai(hp7.next);
  14647. end;
  14648. RemoveCurrentP(p, hp4);
  14649. RemoveInstruction(hp2);
  14650. RemoveInstruction(hp3);
  14651. { if there is a vzeroupper instruction then move it before the jmp }
  14652. if Assigned(hp5) then
  14653. begin
  14654. AsmL.Remove(hp5);
  14655. ASmL.InsertBefore(hp5,hp1)
  14656. end;
  14657. { remove nop on win64 }
  14658. if Assigned(hp6) then
  14659. RemoveInstruction(hp6);
  14660. Result:=true;
  14661. end;
  14662. end;
  14663. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14664. {$ifdef x86_64}
  14665. var
  14666. hp1, hp2, hp3, hp4, hp5: tai;
  14667. {$endif x86_64}
  14668. begin
  14669. Result:=false;
  14670. {$ifdef x86_64}
  14671. hp5:=nil;
  14672. { replace
  14673. push %rax
  14674. call procname
  14675. pop %rcx
  14676. ret
  14677. by
  14678. jmp procname
  14679. but do it only on level 4 because it destroys stack back traces
  14680. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14681. for all supported calling conventions
  14682. }
  14683. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14684. MatchOpType(taicpu(p),top_reg) and
  14685. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14686. GetNextInstruction(p, hp1) and
  14687. { Take a copy of hp1 }
  14688. SetAndTest(hp1, hp4) and
  14689. { trick to skip label }
  14690. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14691. SkipSimpleInstructions(hp1) and
  14692. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14693. GetNextInstruction(hp1, hp2) and
  14694. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14695. MatchOpType(taicpu(hp2),top_reg) and
  14696. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14697. GetNextInstruction(hp2, hp3) and
  14698. { trick to skip label }
  14699. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14700. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14701. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14702. SetAndTest(hp3,hp5) and
  14703. GetNextInstruction(hp3,hp3) and
  14704. MatchInstruction(hp3,A_RET,[S_NO])
  14705. )
  14706. ) and
  14707. (taicpu(hp3).ops=0) then
  14708. begin
  14709. taicpu(hp1).opcode := A_JMP;
  14710. taicpu(hp1).is_jmp := true;
  14711. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14712. RemoveCurrentP(p, hp4);
  14713. RemoveInstruction(hp2);
  14714. RemoveInstruction(hp3);
  14715. if Assigned(hp5) then
  14716. begin
  14717. AsmL.Remove(hp5);
  14718. ASmL.InsertBefore(hp5,hp1)
  14719. end;
  14720. Result:=true;
  14721. end;
  14722. {$endif x86_64}
  14723. end;
  14724. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14725. var
  14726. Value, RegName: string;
  14727. hp1: tai;
  14728. begin
  14729. Result:=false;
  14730. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14731. begin
  14732. case taicpu(p).oper[0]^.val of
  14733. 0:
  14734. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14735. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14736. (
  14737. { See if we can still convert the instruction }
  14738. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14739. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14740. ) then
  14741. begin
  14742. { change "mov $0,%reg" into "xor %reg,%reg" }
  14743. taicpu(p).opcode := A_XOR;
  14744. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14745. Result := True;
  14746. {$ifdef x86_64}
  14747. end
  14748. else if (taicpu(p).opsize = S_Q) then
  14749. begin
  14750. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14751. { The actual optimization }
  14752. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14753. taicpu(p).changeopsize(S_L);
  14754. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14755. Result := True;
  14756. end;
  14757. $1..$FFFFFFFF:
  14758. begin
  14759. { Code size reduction by J. Gareth "Kit" Moreton }
  14760. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14761. case taicpu(p).opsize of
  14762. S_Q:
  14763. begin
  14764. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14765. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14766. { The actual optimization }
  14767. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14768. taicpu(p).changeopsize(S_L);
  14769. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14770. Result := True;
  14771. end;
  14772. else
  14773. { Do nothing };
  14774. end;
  14775. {$endif x86_64}
  14776. end;
  14777. -1:
  14778. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14779. if (cs_opt_size in current_settings.optimizerswitches) and
  14780. (taicpu(p).opsize <> S_B) and
  14781. (
  14782. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14783. (
  14784. { See if we can still convert the instruction }
  14785. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14786. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14787. )
  14788. ) then
  14789. begin
  14790. { change "mov $-1,%reg" into "or $-1,%reg" }
  14791. { NOTES:
  14792. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14793. - This operation creates a false dependency on the register, so only do it when optimising for size
  14794. - 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
  14795. }
  14796. taicpu(p).opcode := A_OR;
  14797. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14798. Result := True;
  14799. end;
  14800. else
  14801. { Do nothing };
  14802. end;
  14803. end;
  14804. end;
  14805. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14806. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14807. begin
  14808. Result := False;
  14809. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14810. Exit;
  14811. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14812. so don't bother optimising }
  14813. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14814. Exit;
  14815. if (taicpu(p).oper[0]^.typ <> top_const) or
  14816. { If the value can fit into an 8-bit signed integer, a smaller
  14817. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14818. falls within this range }
  14819. (
  14820. (taicpu(p).oper[0]^.val > -128) and
  14821. (taicpu(p).oper[0]^.val <= 127)
  14822. ) then
  14823. Exit;
  14824. { If we're optimising for size, this is acceptable }
  14825. if (cs_opt_size in current_settings.optimizerswitches) then
  14826. Exit(True);
  14827. if (taicpu(p).oper[1]^.typ = top_reg) and
  14828. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14829. Exit(True);
  14830. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14831. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14832. Exit(True);
  14833. end;
  14834. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14835. var
  14836. hp1: tai;
  14837. Value: TCGInt;
  14838. begin
  14839. Result := False;
  14840. if MatchOpType(taicpu(p), top_const, top_reg) then
  14841. begin
  14842. { Detect:
  14843. andw x, %ax (0 <= x < $8000)
  14844. ...
  14845. movzwl %ax,%eax
  14846. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14847. }
  14848. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14849. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14850. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14851. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14852. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14853. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14854. begin
  14855. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14856. taicpu(hp1).opcode := A_CWDE;
  14857. taicpu(hp1).clearop(0);
  14858. taicpu(hp1).clearop(1);
  14859. taicpu(hp1).ops := 0;
  14860. { A change was made, but not with p, so don't set Result, but
  14861. notify the compiler that a change was made }
  14862. Include(OptsToCheck, aoc_ForceNewIteration);
  14863. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14864. end;
  14865. end;
  14866. { If "not x" is a power of 2 (popcnt = 1), change:
  14867. and $x, %reg/ref
  14868. To:
  14869. btr lb(x), %reg/ref
  14870. }
  14871. if IsBTXAcceptable(p) and
  14872. (
  14873. { Make sure a TEST doesn't follow that plays with the register }
  14874. not GetNextInstruction(p, hp1) or
  14875. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14876. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14877. ) then
  14878. begin
  14879. {$push}{$R-}{$Q-}
  14880. { Value is a sign-extended 32-bit integer - just correct it
  14881. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14882. checks to see if this operand is an immediate. }
  14883. Value := not taicpu(p).oper[0]^.val;
  14884. {$pop}
  14885. {$ifdef x86_64}
  14886. if taicpu(p).opsize = S_L then
  14887. {$endif x86_64}
  14888. Value := Value and $FFFFFFFF;
  14889. if (PopCnt(QWord(Value)) = 1) then
  14890. begin
  14891. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14892. taicpu(p).opcode := A_BTR;
  14893. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14894. Result := True;
  14895. Exit;
  14896. end;
  14897. end;
  14898. end;
  14899. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14900. begin
  14901. Result := False;
  14902. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14903. Exit;
  14904. { Convert:
  14905. movswl %ax,%eax -> cwtl
  14906. movslq %eax,%rax -> cdqe
  14907. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14908. refer to the same opcode and depends only on the assembler's
  14909. current operand-size attribute. [Kit]
  14910. }
  14911. with taicpu(p) do
  14912. case opsize of
  14913. S_WL:
  14914. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14915. begin
  14916. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14917. opcode := A_CWDE;
  14918. clearop(0);
  14919. clearop(1);
  14920. ops := 0;
  14921. Result := True;
  14922. end;
  14923. {$ifdef x86_64}
  14924. S_LQ:
  14925. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14926. begin
  14927. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14928. opcode := A_CDQE;
  14929. clearop(0);
  14930. clearop(1);
  14931. ops := 0;
  14932. Result := True;
  14933. end;
  14934. {$endif x86_64}
  14935. else
  14936. ;
  14937. end;
  14938. end;
  14939. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14940. var
  14941. hp1, hp2: tai;
  14942. IdentityMask, Shift: TCGInt;
  14943. LimitSize: Topsize;
  14944. DoNotMerge: Boolean;
  14945. begin
  14946. Result := False;
  14947. { All these optimisations work on "shr const,%reg" }
  14948. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14949. Exit;
  14950. DoNotMerge := False;
  14951. Shift := taicpu(p).oper[0]^.val;
  14952. LimitSize := taicpu(p).opsize;
  14953. hp1 := p;
  14954. repeat
  14955. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14956. Break;
  14957. { Detect:
  14958. shr x, %reg
  14959. and y, %reg
  14960. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14961. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14962. }
  14963. case taicpu(hp1).opcode of
  14964. A_AND:
  14965. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14966. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14967. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14968. begin
  14969. { Make sure the FLAGS register isn't in use }
  14970. TransferUsedRegs(TmpUsedRegs);
  14971. hp2 := p;
  14972. repeat
  14973. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14974. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14975. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14976. begin
  14977. { Generate the identity mask }
  14978. case taicpu(p).opsize of
  14979. S_B:
  14980. IdentityMask := $FF shr Shift;
  14981. S_W:
  14982. IdentityMask := $FFFF shr Shift;
  14983. S_L:
  14984. IdentityMask := $FFFFFFFF shr Shift;
  14985. {$ifdef x86_64}
  14986. S_Q:
  14987. { We need to force the operands to be unsigned 64-bit
  14988. integers otherwise the wrong value is generated }
  14989. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14990. {$endif x86_64}
  14991. else
  14992. InternalError(2022081501);
  14993. end;
  14994. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14995. begin
  14996. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14997. { All the possible 1 bits are covered, so we can remove the AND }
  14998. hp2 := tai(hp1.Previous);
  14999. RemoveInstruction(hp1);
  15000. { p wasn't actually changed, so don't set Result to True,
  15001. but a change was nonetheless made elsewhere }
  15002. Include(OptsToCheck, aoc_ForceNewIteration);
  15003. { Do another pass in case other AND or MOVZX instructions
  15004. follow }
  15005. hp1 := hp2;
  15006. Continue;
  15007. end;
  15008. end;
  15009. end;
  15010. A_TEST, A_CMP, A_Jcc:
  15011. { Skip over conditional jumps and relevant comparisons }
  15012. Continue;
  15013. A_MOVZX:
  15014. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15015. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  15016. begin
  15017. { Since the original register is being read as is, subsequent
  15018. SHRs must not be merged at this point }
  15019. DoNotMerge := True;
  15020. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  15021. begin
  15022. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  15023. begin
  15024. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  15025. { All the possible 1 bits are covered, so we can remove the AND }
  15026. hp2 := tai(hp1.Previous);
  15027. RemoveInstruction(hp1);
  15028. hp1 := hp2;
  15029. end
  15030. else { Different register target }
  15031. begin
  15032. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  15033. taicpu(hp1).opcode := A_MOV;
  15034. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  15035. case taicpu(hp1).opsize of
  15036. S_BW:
  15037. taicpu(hp1).opsize := S_W;
  15038. S_BL, S_WL:
  15039. taicpu(hp1).opsize := S_L;
  15040. else
  15041. InternalError(2022081503);
  15042. end;
  15043. end;
  15044. end
  15045. else if (Shift > 0) and
  15046. (taicpu(p).opsize = S_W) and
  15047. (taicpu(hp1).opsize = S_WL) and
  15048. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  15049. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  15050. begin
  15051. { Detect:
  15052. shr x, %ax (x > 0)
  15053. ...
  15054. movzwl %ax,%eax
  15055. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15056. }
  15057. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  15058. taicpu(hp1).opcode := A_CWDE;
  15059. taicpu(hp1).clearop(0);
  15060. taicpu(hp1).clearop(1);
  15061. taicpu(hp1).ops := 0;
  15062. end;
  15063. { Move onto the next instruction }
  15064. Continue;
  15065. end;
  15066. A_SHL, A_SAL, A_SHR:
  15067. if (taicpu(hp1).opsize <= LimitSize) and
  15068. MatchOpType(taicpu(hp1), top_const, top_reg) and
  15069. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  15070. begin
  15071. { Make sure the sizes don't exceed the register size limit
  15072. (measured by the shift value falling below the limit) }
  15073. if taicpu(hp1).opsize < LimitSize then
  15074. LimitSize := taicpu(hp1).opsize;
  15075. if taicpu(hp1).opcode = A_SHR then
  15076. Inc(Shift, taicpu(hp1).oper[0]^.val)
  15077. else
  15078. begin
  15079. Dec(Shift, taicpu(hp1).oper[0]^.val);
  15080. DoNotMerge := True;
  15081. end;
  15082. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  15083. Break;
  15084. { Since we've established that the combined shift is within
  15085. limits, we can actually combine the adjacent SHR
  15086. instructions even if they're different sizes }
  15087. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  15088. begin
  15089. hp2 := tai(hp1.Previous);
  15090. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  15091. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  15092. RemoveInstruction(hp1);
  15093. hp1 := hp2;
  15094. end;
  15095. { Move onto the next instruction }
  15096. Continue;
  15097. end;
  15098. else
  15099. { If the register isn't actually modified, move onto the next instruction,
  15100. but set DoNotMerge to True since the register is being read }
  15101. if (
  15102. { Under -O2 and below, GetNextInstructionUsingReg only returns
  15103. the next instruction, whether or not it contains the register }
  15104. (cs_opt_level3 in current_settings.optimizerswitches) or
  15105. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  15106. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  15107. begin
  15108. DoNotMerge := True;
  15109. Continue;
  15110. end;
  15111. end;
  15112. Break;
  15113. until False;
  15114. { Detect the following (looking backwards):
  15115. shr %cl,%reg
  15116. shr x, %reg
  15117. Swap the two SHR instructions to minimise a pipeline stall.
  15118. }
  15119. if GetLastInstruction(p, hp1) and
  15120. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15121. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15122. { First operand will be %cl }
  15123. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15124. { Just to be sure }
  15125. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15126. begin
  15127. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15128. { Moving the entries this way ensures the register tracking remains correct }
  15129. Asml.Remove(p);
  15130. Asml.InsertBefore(p, hp1);
  15131. p := hp1;
  15132. { Don't set Result to True because the current instruction is now
  15133. "shr %cl,%reg" and there's nothing more we can do with it }
  15134. end;
  15135. end;
  15136. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15137. var
  15138. hp1, hp2: tai;
  15139. Opposite, SecondOpposite: TAsmOp;
  15140. NewCond: TAsmCond;
  15141. begin
  15142. Result := False;
  15143. { Change:
  15144. add/sub 128,(dest)
  15145. To:
  15146. sub/add -128,(dest)
  15147. This generaally takes fewer bytes to encode because -128 can be stored
  15148. in a signed byte, whereas +128 cannot.
  15149. }
  15150. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15151. begin
  15152. if taicpu(p).opcode = A_ADD then
  15153. Opposite := A_SUB
  15154. else
  15155. Opposite := A_ADD;
  15156. { Be careful if the flags are in use, because the CF flag inverts
  15157. when changing from ADD to SUB and vice versa }
  15158. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15159. GetNextInstruction(p, hp1) then
  15160. begin
  15161. TransferUsedRegs(TmpUsedRegs);
  15162. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15163. hp2 := hp1;
  15164. { Scan ahead to check if everything's safe }
  15165. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15166. begin
  15167. if (hp1.typ <> ait_instruction) then
  15168. { Probably unsafe since the flags are still in use }
  15169. Exit;
  15170. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15171. { Stop searching at an unconditional jump }
  15172. Break;
  15173. if not
  15174. (
  15175. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15176. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15177. ) and
  15178. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15179. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15180. Exit;
  15181. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15182. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15183. { Move to the next instruction }
  15184. GetNextInstruction(hp1, hp1);
  15185. end;
  15186. while Assigned(hp2) and (hp2 <> hp1) do
  15187. begin
  15188. NewCond := C_None;
  15189. case taicpu(hp2).condition of
  15190. C_A, C_NBE:
  15191. NewCond := C_BE;
  15192. C_B, C_C, C_NAE:
  15193. NewCond := C_AE;
  15194. C_AE, C_NB, C_NC:
  15195. NewCond := C_B;
  15196. C_BE, C_NA:
  15197. NewCond := C_A;
  15198. else
  15199. { No change needed };
  15200. end;
  15201. if NewCond <> C_None then
  15202. begin
  15203. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15204. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15205. taicpu(hp2).condition := NewCond;
  15206. end
  15207. else
  15208. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15209. begin
  15210. { Because of the flipping of the carry bit, to ensure
  15211. the operation remains equivalent, ADC becomes SBB
  15212. and vice versa, and the constant is not-inverted.
  15213. If multiple ADCs or SBBs appear in a row, each one
  15214. changed causes the carry bit to invert, so they all
  15215. need to be flipped }
  15216. if taicpu(hp2).opcode = A_ADC then
  15217. SecondOpposite := A_SBB
  15218. else
  15219. SecondOpposite := A_ADC;
  15220. if taicpu(hp2).oper[0]^.typ <> top_const then
  15221. { Should have broken out of this optimisation already }
  15222. InternalError(2021112901);
  15223. 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]^) + ' -> ' +
  15224. 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);
  15225. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15226. taicpu(hp2).opcode := SecondOpposite;
  15227. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15228. end;
  15229. { Move to the next instruction }
  15230. GetNextInstruction(hp2, hp2);
  15231. end;
  15232. if (hp2 <> hp1) then
  15233. InternalError(2021111501);
  15234. end;
  15235. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15236. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15237. taicpu(p).opcode := Opposite;
  15238. taicpu(p).oper[0]^.val := -128;
  15239. { No further optimisations can be made on this instruction, so move
  15240. onto the next one to save time }
  15241. p := tai(p.Next);
  15242. UpdateUsedRegs(p);
  15243. Result := True;
  15244. Exit;
  15245. end;
  15246. { Detect:
  15247. add/sub %reg2,(dest)
  15248. add/sub x, (dest)
  15249. (dest can be a register or a reference)
  15250. Swap the instructions to minimise a pipeline stall. This reverses the
  15251. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15252. optimisations could be made.
  15253. }
  15254. if (taicpu(p).oper[0]^.typ = top_reg) and
  15255. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15256. (
  15257. (
  15258. (taicpu(p).oper[1]^.typ = top_reg) and
  15259. { We can try searching further ahead if we're writing to a register }
  15260. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15261. ) or
  15262. (
  15263. (taicpu(p).oper[1]^.typ = top_ref) and
  15264. GetNextInstruction(p, hp1)
  15265. )
  15266. ) and
  15267. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15268. (taicpu(hp1).oper[0]^.typ = top_const) and
  15269. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15270. begin
  15271. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15272. TransferUsedRegs(TmpUsedRegs);
  15273. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15274. hp2 := p;
  15275. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15276. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15277. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15278. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15279. begin
  15280. asml.remove(hp1);
  15281. asml.InsertBefore(hp1, p);
  15282. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15283. Result := True;
  15284. end;
  15285. end;
  15286. end;
  15287. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15288. var
  15289. hp1: tai;
  15290. begin
  15291. Result:=false;
  15292. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15293. while GetNextInstruction(p, hp1) and
  15294. TrySwapMovCmp(p, hp1) do
  15295. begin
  15296. if MatchInstruction(hp1, A_MOV, []) then
  15297. begin
  15298. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15299. begin
  15300. { A little hacky, but since CMP doesn't read the flags, only
  15301. modify them, it's safe if they get scrambled by MOV -> XOR }
  15302. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15303. Result := PostPeepholeOptMov(hp1);
  15304. {$ifdef x86_64}
  15305. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15306. { Used to shrink instruction size }
  15307. PostPeepholeOptXor(hp1);
  15308. {$endif x86_64}
  15309. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15310. end
  15311. else
  15312. begin
  15313. Result := PostPeepholeOptMov(hp1);
  15314. {$ifdef x86_64}
  15315. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15316. { Used to shrink instruction size }
  15317. PostPeepholeOptXor(hp1);
  15318. {$endif x86_64}
  15319. end;
  15320. end;
  15321. { Enabling this flag is actually a null operation, but it marks
  15322. the code as 'modified' during this pass }
  15323. Include(OptsToCheck, aoc_ForceNewIteration);
  15324. end;
  15325. { change "cmp $0, %reg" to "test %reg, %reg" }
  15326. if MatchOpType(taicpu(p),top_const,top_reg) and
  15327. (taicpu(p).oper[0]^.val = 0) then
  15328. begin
  15329. taicpu(p).opcode := A_TEST;
  15330. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15331. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15332. Result:=true;
  15333. end;
  15334. end;
  15335. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15336. var
  15337. IsTestConstX, IsValid : Boolean;
  15338. hp1,hp2 : tai;
  15339. begin
  15340. Result:=false;
  15341. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15342. if (taicpu(p).opcode = A_TEST) then
  15343. while GetNextInstruction(p, hp1) and
  15344. TrySwapMovCmp(p, hp1) do
  15345. begin
  15346. if MatchInstruction(hp1, A_MOV, []) then
  15347. begin
  15348. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15349. begin
  15350. { A little hacky, but since TEST doesn't read the flags, only
  15351. modify them, it's safe if they get scrambled by MOV -> XOR }
  15352. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15353. Result := PostPeepholeOptMov(hp1);
  15354. {$ifdef x86_64}
  15355. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15356. { Used to shrink instruction size }
  15357. PostPeepholeOptXor(hp1);
  15358. {$endif x86_64}
  15359. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15360. end
  15361. else
  15362. begin
  15363. Result := PostPeepholeOptMov(hp1);
  15364. {$ifdef x86_64}
  15365. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15366. { Used to shrink instruction size }
  15367. PostPeepholeOptXor(hp1);
  15368. {$endif x86_64}
  15369. end;
  15370. end;
  15371. { Enabling this flag is actually a null operation, but it marks
  15372. the code as 'modified' during this pass }
  15373. Include(OptsToCheck, aoc_ForceNewIteration);
  15374. end;
  15375. { If x is a power of 2 (popcnt = 1), change:
  15376. or $x, %reg/ref
  15377. To:
  15378. bts lb(x), %reg/ref
  15379. }
  15380. if (taicpu(p).opcode = A_OR) and
  15381. IsBTXAcceptable(p) and
  15382. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15383. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15384. (
  15385. { Don't optimise if a test instruction follows }
  15386. not GetNextInstruction(p, hp1) or
  15387. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15388. ) then
  15389. begin
  15390. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15391. taicpu(p).opcode := A_BTS;
  15392. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15393. Result := True;
  15394. Exit;
  15395. end;
  15396. { If x is a power of 2 (popcnt = 1), change:
  15397. test $x, %reg/ref
  15398. je / sete / cmove (or jne / setne)
  15399. To:
  15400. bt lb(x), %reg/ref
  15401. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15402. }
  15403. if (taicpu(p).opcode = A_TEST) and
  15404. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15405. (taicpu(p).oper[0]^.typ = top_const) and
  15406. (
  15407. (cs_opt_size in current_settings.optimizerswitches) or
  15408. (
  15409. (taicpu(p).oper[1]^.typ = top_reg) and
  15410. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15411. ) or
  15412. (
  15413. (taicpu(p).oper[1]^.typ <> top_reg) and
  15414. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15415. )
  15416. ) and
  15417. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15418. { For sizes less than S_L, the byte size is equal or larger with BT,
  15419. so don't bother optimising }
  15420. (taicpu(p).opsize >= S_L) then
  15421. begin
  15422. IsValid := True;
  15423. { Check the next set of instructions, watching the FLAGS register
  15424. and the conditions used }
  15425. TransferUsedRegs(TmpUsedRegs);
  15426. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15427. hp1 := p;
  15428. hp2 := nil;
  15429. while GetNextInstruction(hp1, hp1) do
  15430. begin
  15431. if not Assigned(hp2) then
  15432. { The first instruction after TEST }
  15433. hp2 := hp1;
  15434. if (hp1.typ <> ait_instruction) then
  15435. begin
  15436. { If the flags are no longer in use, everything is fine }
  15437. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15438. IsValid := False;
  15439. Break;
  15440. end;
  15441. case taicpu(hp1).condition of
  15442. C_None:
  15443. begin
  15444. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15445. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15446. { Something is not quite normal, so play safe and don't change }
  15447. IsValid := False;
  15448. Break;
  15449. end;
  15450. C_E, C_Z, C_NE, C_NZ:
  15451. { This is fine };
  15452. else
  15453. begin
  15454. { Unsupported condition }
  15455. IsValid := False;
  15456. Break;
  15457. end;
  15458. end;
  15459. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15460. end;
  15461. if IsValid then
  15462. begin
  15463. while hp2 <> hp1 do
  15464. begin
  15465. case taicpu(hp2).condition of
  15466. C_Z, C_E:
  15467. taicpu(hp2).condition := C_NC;
  15468. C_NZ, C_NE:
  15469. taicpu(hp2).condition := C_C;
  15470. else
  15471. { Should not get this by this point }
  15472. InternalError(2022110701);
  15473. end;
  15474. GetNextInstruction(hp2, hp2);
  15475. end;
  15476. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15477. taicpu(p).opcode := A_BT;
  15478. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15479. Result := True;
  15480. Exit;
  15481. end;
  15482. end;
  15483. { removes the line marked with (x) from the sequence
  15484. and/or/xor/add/sub/... $x, %y
  15485. test/or %y, %y | test $-1, %y (x)
  15486. j(n)z _Label
  15487. as the first instruction already adjusts the ZF
  15488. %y operand may also be a reference }
  15489. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15490. MatchOperand(taicpu(p).oper[0]^,-1);
  15491. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15492. GetLastInstruction(p, hp1) and
  15493. (tai(hp1).typ = ait_instruction) and
  15494. GetNextInstruction(p,hp2) and
  15495. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15496. case taicpu(hp1).opcode Of
  15497. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15498. { These two instructions set the zero flag if the result is zero }
  15499. A_POPCNT, A_LZCNT:
  15500. begin
  15501. if (
  15502. { With POPCNT, an input of zero will set the zero flag
  15503. because the population count of zero is zero }
  15504. (taicpu(hp1).opcode = A_POPCNT) and
  15505. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15506. (
  15507. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15508. { Faster than going through the second half of the 'or'
  15509. condition below }
  15510. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15511. )
  15512. ) or (
  15513. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15514. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15515. { and in case of carry for A(E)/B(E)/C/NC }
  15516. (
  15517. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15518. (
  15519. (taicpu(hp1).opcode <> A_ADD) and
  15520. (taicpu(hp1).opcode <> A_SUB) and
  15521. (taicpu(hp1).opcode <> A_LZCNT)
  15522. )
  15523. )
  15524. ) then
  15525. begin
  15526. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15527. RemoveCurrentP(p, hp2);
  15528. Result:=true;
  15529. Exit;
  15530. end;
  15531. end;
  15532. A_SHL, A_SAL, A_SHR, A_SAR:
  15533. begin
  15534. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15535. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15536. { therefore, it's only safe to do this optimization for }
  15537. { shifts by a (nonzero) constant }
  15538. (taicpu(hp1).oper[0]^.typ = top_const) and
  15539. (taicpu(hp1).oper[0]^.val <> 0) and
  15540. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15541. { and in case of carry for A(E)/B(E)/C/NC }
  15542. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15543. begin
  15544. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15545. RemoveCurrentP(p, hp2);
  15546. Result:=true;
  15547. Exit;
  15548. end;
  15549. end;
  15550. A_DEC, A_INC, A_NEG:
  15551. begin
  15552. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15553. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15554. { and in case of carry for A(E)/B(E)/C/NC }
  15555. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15556. begin
  15557. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15558. RemoveCurrentP(p, hp2);
  15559. Result:=true;
  15560. Exit;
  15561. end;
  15562. end;
  15563. A_ANDN, A_BZHI:
  15564. begin
  15565. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15566. { Only the zero and sign flags are consistent with what the result is }
  15567. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15568. begin
  15569. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15570. RemoveCurrentP(p, hp2);
  15571. Result:=true;
  15572. Exit;
  15573. end;
  15574. end;
  15575. A_BEXTR:
  15576. begin
  15577. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15578. { Only the zero flag is set }
  15579. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15580. begin
  15581. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15582. RemoveCurrentP(p, hp2);
  15583. Result:=true;
  15584. Exit;
  15585. end;
  15586. end;
  15587. else
  15588. ;
  15589. end; { case }
  15590. { change "test $-1,%reg" into "test %reg,%reg" }
  15591. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15592. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15593. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15594. if MatchInstruction(p, A_OR, []) and
  15595. { Can only match if they're both registers }
  15596. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15597. begin
  15598. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15599. taicpu(p).opcode := A_TEST;
  15600. { No need to set Result to True, as we've done all the optimisations we can }
  15601. end;
  15602. end;
  15603. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15604. var
  15605. hp1,hp3 : tai;
  15606. {$ifndef x86_64}
  15607. hp2 : taicpu;
  15608. {$endif x86_64}
  15609. begin
  15610. Result:=false;
  15611. hp3:=nil;
  15612. {$ifndef x86_64}
  15613. { don't do this on modern CPUs, this really hurts them due to
  15614. broken call/ret pairing }
  15615. if (current_settings.optimizecputype < cpu_Pentium2) and
  15616. not(cs_create_pic in current_settings.moduleswitches) and
  15617. GetNextInstruction(p, hp1) and
  15618. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15619. MatchOpType(taicpu(hp1),top_ref) and
  15620. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15621. begin
  15622. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15623. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15624. InsertLLItem(p.previous, p, hp2);
  15625. taicpu(p).opcode := A_JMP;
  15626. taicpu(p).is_jmp := true;
  15627. RemoveInstruction(hp1);
  15628. Result:=true;
  15629. end
  15630. else
  15631. {$endif x86_64}
  15632. { replace
  15633. call procname
  15634. ret
  15635. by
  15636. jmp procname
  15637. but do it only on level 4 because it destroys stack back traces
  15638. else if the subroutine is marked as no return, remove the ret
  15639. }
  15640. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15641. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15642. GetNextInstruction(p, hp1) and
  15643. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15644. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15645. SetAndTest(hp1,hp3) and
  15646. GetNextInstruction(hp1,hp1) and
  15647. MatchInstruction(hp1,A_RET,[S_NO])
  15648. )
  15649. ) and
  15650. (taicpu(hp1).ops=0) then
  15651. begin
  15652. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15653. { we might destroy stack alignment here if we do not do a call }
  15654. (target_info.stackalign<=sizeof(SizeUInt)) then
  15655. begin
  15656. taicpu(p).opcode := A_JMP;
  15657. taicpu(p).is_jmp := true;
  15658. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15659. end
  15660. else
  15661. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15662. RemoveInstruction(hp1);
  15663. if Assigned(hp3) then
  15664. begin
  15665. AsmL.Remove(hp3);
  15666. AsmL.InsertBefore(hp3,p)
  15667. end;
  15668. Result:=true;
  15669. end;
  15670. end;
  15671. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15672. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15673. begin
  15674. case OpSize of
  15675. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15676. Result := (Val <= $FF) and (Val >= -128);
  15677. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15678. Result := (Val <= $FFFF) and (Val >= -32768);
  15679. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15680. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15681. else
  15682. Result := True;
  15683. end;
  15684. end;
  15685. var
  15686. hp1, hp2 : tai;
  15687. SizeChange: Boolean;
  15688. PreMessage: string;
  15689. begin
  15690. Result := False;
  15691. if (taicpu(p).oper[0]^.typ = top_reg) and
  15692. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15693. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15694. begin
  15695. { Change (using movzbl %al,%eax as an example):
  15696. movzbl %al, %eax movzbl %al, %eax
  15697. cmpl x, %eax testl %eax,%eax
  15698. To:
  15699. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15700. movzbl %al, %eax movzbl %al, %eax
  15701. Smaller instruction and minimises pipeline stall as the CPU
  15702. doesn't have to wait for the register to get zero-extended. [Kit]
  15703. Also allow if the smaller of the two registers is being checked,
  15704. as this still removes the false dependency.
  15705. }
  15706. if
  15707. (
  15708. (
  15709. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15710. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15711. ) or (
  15712. { If MatchOperand returns True, they must both be registers }
  15713. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15714. )
  15715. ) and
  15716. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15717. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15718. begin
  15719. 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);
  15720. asml.Remove(hp1);
  15721. asml.InsertBefore(hp1, p);
  15722. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15723. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15724. begin
  15725. taicpu(hp1).opcode := A_TEST;
  15726. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15727. end;
  15728. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15729. case taicpu(p).opsize of
  15730. S_BW, S_BL:
  15731. begin
  15732. SizeChange := taicpu(hp1).opsize <> S_B;
  15733. taicpu(hp1).changeopsize(S_B);
  15734. end;
  15735. S_WL:
  15736. begin
  15737. SizeChange := taicpu(hp1).opsize <> S_W;
  15738. taicpu(hp1).changeopsize(S_W);
  15739. end
  15740. else
  15741. InternalError(2020112701);
  15742. end;
  15743. UpdateUsedRegs(tai(p.Next));
  15744. { Check if the register is used aferwards - if not, we can
  15745. remove the movzx instruction completely }
  15746. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15747. begin
  15748. { Hp1 is a better position than p for debugging purposes }
  15749. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15750. RemoveCurrentp(p, hp1);
  15751. Result := True;
  15752. end;
  15753. if SizeChange then
  15754. DebugMsg(SPeepholeOptimization + PreMessage +
  15755. 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)
  15756. else
  15757. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15758. Exit;
  15759. end;
  15760. { Change (using movzwl %ax,%eax as an example):
  15761. movzwl %ax, %eax
  15762. movb %al, (dest) (Register is smaller than read register in movz)
  15763. To:
  15764. movb %al, (dest) (Move one back to avoid a false dependency)
  15765. movzwl %ax, %eax
  15766. }
  15767. if (taicpu(hp1).opcode = A_MOV) and
  15768. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15769. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15770. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15771. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15772. begin
  15773. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15774. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15775. asml.Remove(hp1);
  15776. asml.InsertBefore(hp1, p);
  15777. if taicpu(hp1).oper[1]^.typ = top_reg then
  15778. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15779. { Check if the register is used aferwards - if not, we can
  15780. remove the movzx instruction completely }
  15781. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15782. begin
  15783. { Hp1 is a better position than p for debugging purposes }
  15784. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15785. RemoveCurrentp(p, hp1);
  15786. Result := True;
  15787. end;
  15788. Exit;
  15789. end;
  15790. end;
  15791. end;
  15792. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15793. var
  15794. hp1: tai;
  15795. {$ifdef x86_64}
  15796. PreMessage, RegName: string;
  15797. {$endif x86_64}
  15798. begin
  15799. Result := False;
  15800. { If x is a power of 2 (popcnt = 1), change:
  15801. xor $x, %reg/ref
  15802. To:
  15803. btc lb(x), %reg/ref
  15804. }
  15805. if IsBTXAcceptable(p) and
  15806. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15807. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15808. (
  15809. { Don't optimise if a test instruction follows }
  15810. not GetNextInstruction(p, hp1) or
  15811. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15812. ) then
  15813. begin
  15814. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15815. taicpu(p).opcode := A_BTC;
  15816. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15817. Result := True;
  15818. Exit;
  15819. end;
  15820. {$ifdef x86_64}
  15821. { Code size reduction by J. Gareth "Kit" Moreton }
  15822. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15823. as this removes the REX prefix }
  15824. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15825. Exit;
  15826. if taicpu(p).oper[0]^.typ <> top_reg then
  15827. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15828. InternalError(2018011500);
  15829. case taicpu(p).opsize of
  15830. S_Q:
  15831. begin
  15832. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15833. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15834. { The actual optimization }
  15835. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15836. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15837. taicpu(p).changeopsize(S_L);
  15838. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15839. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15840. end;
  15841. else
  15842. ;
  15843. end;
  15844. {$endif x86_64}
  15845. end;
  15846. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15847. var
  15848. XReg: TRegister;
  15849. begin
  15850. Result := False;
  15851. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15852. Smaller encoding and slightly faster on some platforms (also works for
  15853. ZMM-sized registers) }
  15854. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15855. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15856. begin
  15857. XReg := taicpu(p).oper[0]^.reg;
  15858. if (taicpu(p).oper[1]^.reg = XReg) then
  15859. begin
  15860. taicpu(p).changeopsize(S_XMM);
  15861. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15862. if (cs_opt_size in current_settings.optimizerswitches) then
  15863. begin
  15864. { Change input registers to %xmm0 to reduce size. Note that
  15865. there's a risk of a false dependency doing this, so only
  15866. optimise for size here }
  15867. XReg := NR_XMM0;
  15868. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15869. end
  15870. else
  15871. begin
  15872. setsubreg(XReg, R_SUBMMX);
  15873. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15874. end;
  15875. taicpu(p).oper[0]^.reg := XReg;
  15876. taicpu(p).oper[1]^.reg := XReg;
  15877. Result := True;
  15878. end;
  15879. end;
  15880. end;
  15881. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15882. var
  15883. hp1, p_new: tai;
  15884. begin
  15885. Result := False;
  15886. { Check for:
  15887. ret
  15888. .Lbl:
  15889. ret
  15890. Remove first 'ret'
  15891. }
  15892. if GetNextInstruction(p, hp1) and
  15893. { Remember where the label is }
  15894. SetAndTest(hp1, p_new) and
  15895. (hp1.typ in [ait_align, ait_label]) and
  15896. SkipLabels(hp1, hp1) and
  15897. MatchInstruction(hp1, A_RET, []) and
  15898. { To be safe, make sure the RET instructions are identical }
  15899. (taicpu(p).ops = taicpu(hp1).ops) and
  15900. (
  15901. (taicpu(p).ops = 0) or
  15902. (
  15903. (taicpu(p).ops = 1) and
  15904. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15905. )
  15906. ) then
  15907. begin
  15908. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15909. UpdateUsedRegs(tai(p.Next));
  15910. RemoveCurrentP(p, p_new);
  15911. Result := True;
  15912. Exit;
  15913. end;
  15914. end;
  15915. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15916. var
  15917. OperIdx: Integer;
  15918. begin
  15919. for OperIdx := 0 to p.ops - 1 do
  15920. if p.oper[OperIdx]^.typ = top_ref then
  15921. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15922. end;
  15923. end.