aoptx86.pas 736 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375
  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. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM 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 GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1CMOVcc(var p: tai): Boolean;
  128. function OptPass1_V_MOVAP(var p : tai) : boolean;
  129. function OptPass1VOP(var p : tai) : boolean;
  130. function OptPass1MOV(var p : tai) : boolean;
  131. function OptPass1Movx(var p : tai) : boolean;
  132. function OptPass1MOVXX(var p : tai) : boolean;
  133. function OptPass1OP(var p : tai) : boolean;
  134. function OptPass1LEA(var p : tai) : boolean;
  135. function OptPass1Sub(var p : tai) : boolean;
  136. function OptPass1SHLSAL(var p : tai) : boolean;
  137. function OptPass1SHR(var p : tai) : boolean;
  138. function OptPass1FSTP(var p : tai) : boolean;
  139. function OptPass1FLD(var p : tai) : boolean;
  140. function OptPass1Cmp(var p : tai) : boolean;
  141. function OptPass1PXor(var p : tai) : boolean;
  142. function OptPass1VPXor(var p: tai): boolean;
  143. function OptPass1Imul(var p : tai) : boolean;
  144. function OptPass1Jcc(var p : tai) : boolean;
  145. function OptPass1SHXX(var p: tai): boolean;
  146. function OptPass1VMOVDQ(var p: tai): Boolean;
  147. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  148. function OptPass1STCCLC(var p: tai): Boolean;
  149. function OptPass2STCCLC(var p: tai): Boolean;
  150. function OptPass2CMOVcc(var p: tai): Boolean;
  151. function OptPass2Movx(var p : tai): Boolean;
  152. function OptPass2MOV(var p : tai) : boolean;
  153. function OptPass2Imul(var p : tai) : boolean;
  154. function OptPass2Jmp(var p : tai) : boolean;
  155. function OptPass2Jcc(var p : tai) : boolean;
  156. function OptPass2Lea(var p: tai): Boolean;
  157. function OptPass2SUB(var p: tai): Boolean;
  158. function OptPass2ADD(var p : tai): Boolean;
  159. function OptPass2SETcc(var p : tai) : boolean;
  160. function OptPass2Cmp(var p: tai): Boolean;
  161. function OptPass2Test(var p: tai): Boolean;
  162. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  163. function PostPeepholeOptMov(var p : tai) : Boolean;
  164. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  165. function PostPeepholeOptXor(var p : tai) : Boolean;
  166. function PostPeepholeOptAnd(var p : tai) : boolean;
  167. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  168. function PostPeepholeOptCmp(var p : tai) : Boolean;
  169. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  170. function PostPeepholeOptCall(var p : tai) : Boolean;
  171. function PostPeepholeOptLea(var p : tai) : Boolean;
  172. function PostPeepholeOptPush(var p: tai): Boolean;
  173. function PostPeepholeOptShr(var p : tai) : boolean;
  174. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  175. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  176. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  177. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  178. function TrySwapMovOp(var p, hp1: tai): Boolean;
  179. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  180. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  181. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  182. { Processor-dependent reference optimisation }
  183. class procedure OptimizeRefs(var p: taicpu); static;
  184. end;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  187. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  188. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  189. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  190. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  191. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  192. {$if max_operands>2}
  193. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  194. {$endif max_operands>2}
  195. function RefsEqual(const r1, r2: treference): boolean;
  196. { Note that Result is set to True if the references COULD overlap but the
  197. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  198. might still overlap because %reg2 could be equal to %reg1-4 }
  199. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  200. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  201. { returns true, if ref is a reference using only the registers passed as base and index
  202. and having an offset }
  203. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  204. implementation
  205. uses
  206. cutils,verbose,
  207. systems,
  208. globals,
  209. cpuinfo,
  210. procinfo,
  211. paramgr,
  212. aasmbase,
  213. aoptbase,aoptutils,
  214. symconst,symsym,
  215. cgx86,
  216. itcpugas;
  217. {$ifndef 8086}
  218. const
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. type
  222. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  223. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  224. tsProcessed);
  225. { For OptPass2Jcc }
  226. TCMOVTracking = object
  227. private
  228. CMOVScore, ConstCount: LongInt;
  229. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  230. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  231. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  232. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  233. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  234. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  235. fOptimizer: TX86AsmOptimizer;
  236. fLabel: TAsmSymbol;
  237. fInsertionPoint,
  238. fCondition,
  239. fInitialJump,
  240. fFirstMovBlock,
  241. fFirstMovBlockStop,
  242. fSecondJump,
  243. fThirdJump,
  244. fSecondMovBlock,
  245. fSecondMovBlockStop,
  246. fMidLabel,
  247. fEndLabel,
  248. fAllocationRange: tai;
  249. fState: TCMovTrackingState;
  250. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  251. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  252. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  253. public
  254. RegisterTracking: TAllUsedRegs;
  255. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  256. destructor Done;
  257. procedure Process(out new_p: tai);
  258. property State: TCMovTrackingState read fState;
  259. end;
  260. PCMOVTracking = ^TCMOVTracking;
  261. {$endif 8086}
  262. {$ifdef DEBUG_AOPTCPU}
  263. const
  264. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  265. {$else DEBUG_AOPTCPU}
  266. { Empty strings help the optimizer to remove string concatenations that won't
  267. ever appear to the user on release builds. [Kit] }
  268. const
  269. SPeepholeOptimization = '';
  270. {$endif DEBUG_AOPTCPU}
  271. LIST_STEP_SIZE = 4;
  272. type
  273. TJumpTrackingItem = class(TLinkedListItem)
  274. private
  275. FSymbol: TAsmSymbol;
  276. FRefs: LongInt;
  277. public
  278. constructor Create(ASymbol: TAsmSymbol);
  279. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  280. property Symbol: TAsmSymbol read FSymbol;
  281. property Refs: LongInt read FRefs;
  282. end;
  283. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  284. begin
  285. inherited Create;
  286. FSymbol := ASymbol;
  287. FRefs := 0;
  288. end;
  289. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  290. begin
  291. Inc(FRefs);
  292. end;
  293. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  294. begin
  295. result :=
  296. (instr.typ = ait_instruction) and
  297. (taicpu(instr).opcode = op) and
  298. ((opsize = []) or (taicpu(instr).opsize in opsize));
  299. end;
  300. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. ((taicpu(instr).opcode = op1) or
  305. (taicpu(instr).opcode = op2)
  306. ) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  310. begin
  311. result :=
  312. (instr.typ = ait_instruction) and
  313. ((taicpu(instr).opcode = op1) or
  314. (taicpu(instr).opcode = op2) or
  315. (taicpu(instr).opcode = op3)
  316. ) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  320. const opsize : topsizes) : boolean;
  321. var
  322. op : TAsmOp;
  323. begin
  324. result:=false;
  325. if (instr.typ <> ait_instruction) or
  326. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  327. exit;
  328. for op in ops do
  329. begin
  330. if taicpu(instr).opcode = op then
  331. begin
  332. result:=true;
  333. exit;
  334. end;
  335. end;
  336. end;
  337. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  338. begin
  339. result := (oper.typ = top_reg) and (oper.reg = reg);
  340. end;
  341. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  342. begin
  343. result := (oper.typ = top_const) and (oper.val = a);
  344. end;
  345. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  346. begin
  347. result := oper1.typ = oper2.typ;
  348. if result then
  349. case oper1.typ of
  350. top_const:
  351. Result:=oper1.val = oper2.val;
  352. top_reg:
  353. Result:=oper1.reg = oper2.reg;
  354. top_ref:
  355. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  356. else
  357. internalerror(2013102801);
  358. end
  359. end;
  360. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  361. begin
  362. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  363. if result then
  364. case oper1.typ of
  365. top_const:
  366. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  367. top_reg:
  368. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  369. top_ref:
  370. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  371. else
  372. internalerror(2020052401);
  373. end
  374. end;
  375. function RefsEqual(const r1, r2: treference): boolean;
  376. begin
  377. RefsEqual :=
  378. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  379. (r1.relsymbol = r2.relsymbol) and
  380. (r1.segment = r2.segment) and (r1.base = r2.base) and
  381. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  382. (r1.offset = r2.offset) and
  383. (r1.volatility + r2.volatility = []);
  384. end;
  385. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  386. begin
  387. if (r1.symbol<>r2.symbol) then
  388. { If the index registers are different, there's a chance one could
  389. be set so it equals the other symbol }
  390. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  391. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  392. (r1.relsymbol = r2.relsymbol) and
  393. (r1.segment = r2.segment) and (r1.base = r2.base) and
  394. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  395. (r1.volatility + r2.volatility = []) then
  396. { In this case, it all depends on the offsets }
  397. Exit(abs(r1.offset - r2.offset) < Range);
  398. { There's a chance things MIGHT overlap, so take no chances }
  399. Result := True;
  400. end;
  401. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  402. begin
  403. Result:=(ref.offset=0) and
  404. (ref.scalefactor in [0,1]) and
  405. (ref.segment=NR_NO) and
  406. (ref.symbol=nil) and
  407. (ref.relsymbol=nil) and
  408. ((base=NR_INVALID) or
  409. (ref.base=base)) and
  410. ((index=NR_INVALID) or
  411. (ref.index=index)) and
  412. (ref.volatility=[]);
  413. end;
  414. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  415. begin
  416. Result:=(ref.scalefactor in [0,1]) and
  417. (ref.segment=NR_NO) and
  418. (ref.symbol=nil) and
  419. (ref.relsymbol=nil) and
  420. ((base=NR_INVALID) or
  421. (ref.base=base)) and
  422. ((index=NR_INVALID) or
  423. (ref.index=index)) and
  424. (ref.volatility=[]);
  425. end;
  426. function InstrReadsFlags(p: tai): boolean;
  427. begin
  428. InstrReadsFlags := true;
  429. case p.typ of
  430. ait_instruction:
  431. if InsProp[taicpu(p).opcode].Ch*
  432. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  433. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  434. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  435. exit;
  436. ait_label:
  437. exit;
  438. else
  439. ;
  440. end;
  441. InstrReadsFlags := false;
  442. end;
  443. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  444. begin
  445. Next:=Current;
  446. repeat
  447. Result:=GetNextInstruction(Next,Next);
  448. until not (Result) or
  449. not(cs_opt_level3 in current_settings.optimizerswitches) or
  450. (Next.typ<>ait_instruction) or
  451. RegInInstruction(reg,Next) or
  452. is_calljmp(taicpu(Next).opcode);
  453. end;
  454. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  455. var
  456. GetNextResult: Boolean;
  457. begin
  458. Result:=0;
  459. Next:=Current;
  460. repeat
  461. GetNextResult := GetNextInstruction(Next,Next);
  462. if GetNextResult then
  463. Inc(Result)
  464. else
  465. { Must return zero upon hitting the end of the linked list without a match }
  466. Result := 0;
  467. until not (GetNextResult) or
  468. not(cs_opt_level3 in current_settings.optimizerswitches) or
  469. (Next.typ<>ait_instruction) or
  470. RegInInstruction(reg,Next) or
  471. is_calljmp(taicpu(Next).opcode);
  472. end;
  473. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  474. procedure TrackJump(Symbol: TAsmSymbol);
  475. var
  476. Search: TJumpTrackingItem;
  477. begin
  478. { See if an entry already exists in our jump tracking list
  479. (faster to search backwards due to the higher chance of
  480. matching destinations) }
  481. Search := TJumpTrackingItem(JumpTracking.Last);
  482. while Assigned(Search) do
  483. begin
  484. if Search.Symbol = Symbol then
  485. begin
  486. { Found it - remove it so it can be pushed to the front }
  487. JumpTracking.Remove(Search);
  488. Break;
  489. end;
  490. Search := TJumpTrackingItem(Search.Previous);
  491. end;
  492. if not Assigned(Search) then
  493. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  494. JumpTracking.Concat(Search);
  495. Search.IncRefs;
  496. end;
  497. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  498. var
  499. Search: TJumpTrackingItem;
  500. begin
  501. Result := False;
  502. { See if this label appears in the tracking list }
  503. Search := TJumpTrackingItem(JumpTracking.Last);
  504. while Assigned(Search) do
  505. begin
  506. if Search.Symbol = Symbol then
  507. begin
  508. { Found it - let's see what we can discover }
  509. if Search.Symbol.getrefs = Search.Refs then
  510. begin
  511. { Success - all the references are accounted for }
  512. JumpTracking.Remove(Search);
  513. Search.Free;
  514. { It is logically impossible for CrossJump to be false here
  515. because we must have run into a conditional jump for
  516. this label at some point }
  517. if not CrossJump then
  518. InternalError(2022041710);
  519. if JumpTracking.First = nil then
  520. { Tracking list is now empty - no more cross jumps }
  521. CrossJump := False;
  522. Result := True;
  523. Exit;
  524. end;
  525. { If the references don't match, it's possible to enter
  526. this label through other means, so drop out }
  527. Exit;
  528. end;
  529. Search := TJumpTrackingItem(Search.Previous);
  530. end;
  531. end;
  532. var
  533. Next_Label: tai;
  534. begin
  535. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  536. Next := Current;
  537. repeat
  538. Result := GetNextInstruction(Next,Next);
  539. if not Result then
  540. Break;
  541. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  542. if is_calljmpuncondret(taicpu(Next).opcode) then
  543. begin
  544. if (taicpu(Next).opcode = A_JMP) and
  545. { Remove dead code now to save time }
  546. RemoveDeadCodeAfterJump(taicpu(Next)) then
  547. { A jump was removed, but not the current instruction, and
  548. Result doesn't necessarily translate into an optimisation
  549. routine's Result, so use the "Force New Iteration" flag so
  550. mark a new pass }
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) and
  563. GetNextInstruction(Next, Next_Label) then
  564. begin
  565. { If we have JMP .lbl, and the label after it has all of its
  566. references tracked, then this is probably an if-else style of
  567. block and we can keep tracking. If the label for this jump
  568. then appears later and is fully tracked, then it's the end
  569. of the if-else blocks and the code paths converge (thus
  570. marking the end of the cross-jump) }
  571. if (Next_Label.typ = ait_label) then
  572. begin
  573. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  574. begin
  575. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  576. Next := Next_Label;
  577. { CrossJump gets set to false by LabelAccountedFor if the
  578. list is completely emptied (as it indicates that all
  579. code paths have converged). We could avoid this nuance
  580. by moving the TrackJump call to before the
  581. LabelAccountedFor call, but this is slower in situations
  582. where LabelAccountedFor would return False due to the
  583. creation of a new object that is not used and destroyed
  584. soon after. }
  585. CrossJump := True;
  586. Continue;
  587. end;
  588. end
  589. else if (Next_Label.typ <> ait_marker) then
  590. { We just did a RemoveDeadCodeAfterJump, so either we find
  591. a label, the end of the procedure or some kind of marker}
  592. InternalError(2022041720);
  593. end;
  594. Result := False;
  595. Exit;
  596. end
  597. else
  598. begin
  599. if not Assigned(JumpTracking) then
  600. begin
  601. { Cross-label optimisations often causes other optimisations
  602. to perform worse because they're not given the chance to
  603. optimise locally. In this case, don't do the cross-label
  604. optimisations yet, but flag them as a potential possibility
  605. for the next iteration of Pass 1 }
  606. if not NotFirstIteration then
  607. Include(OptsToCheck, aoc_ForceNewIteration);
  608. end
  609. else if IsJumpToLabel(taicpu(Next)) then
  610. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  611. else
  612. { Conditional jumps should always be a jump to label }
  613. InternalError(2022041701);
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. if Next.typ = ait_label then
  618. begin
  619. if not Assigned(JumpTracking) then
  620. begin
  621. { Cross-label optimisations often causes other optimisations
  622. to perform worse because they're not given the chance to
  623. optimise locally. In this case, don't do the cross-label
  624. optimisations yet, but flag them as a potential possibility
  625. for the next iteration of Pass 1 }
  626. if not NotFirstIteration then
  627. Include(OptsToCheck, aoc_ForceNewIteration);
  628. end
  629. else if LabelAccountedFor(tai_label(Next).labsym) then
  630. Continue;
  631. { If we reach here, we're at a label that hasn't been seen before
  632. (or JumpTracking was nil) }
  633. Break;
  634. end;
  635. until not Result or
  636. not (cs_opt_level3 in current_settings.optimizerswitches) or
  637. not (Next.typ in [ait_label, ait_instruction]) or
  638. RegInInstruction(reg,Next);
  639. end;
  640. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  641. begin
  642. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  643. begin
  644. Result:=GetNextInstruction(Current,Next);
  645. exit;
  646. end;
  647. Next:=tai(Current.Next);
  648. Result:=false;
  649. while assigned(Next) do
  650. begin
  651. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  652. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  653. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  654. exit
  655. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  656. begin
  657. Result:=true;
  658. exit;
  659. end;
  660. Next:=tai(Next.Next);
  661. end;
  662. end;
  663. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  664. begin
  665. Result:=RegReadByInstruction(reg,hp);
  666. end;
  667. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  668. var
  669. p: taicpu;
  670. opcount: longint;
  671. begin
  672. RegReadByInstruction := false;
  673. if hp.typ <> ait_instruction then
  674. exit;
  675. p := taicpu(hp);
  676. case p.opcode of
  677. A_CALL:
  678. regreadbyinstruction := true;
  679. A_IMUL:
  680. case p.ops of
  681. 1:
  682. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  683. (
  684. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  685. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  686. );
  687. 2,3:
  688. regReadByInstruction :=
  689. reginop(reg,p.oper[0]^) or
  690. reginop(reg,p.oper[1]^);
  691. else
  692. InternalError(2019112801);
  693. end;
  694. A_MUL:
  695. begin
  696. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  697. (
  698. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  699. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  700. );
  701. end;
  702. A_IDIV,A_DIV:
  703. begin
  704. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  705. (
  706. (getregtype(reg)=R_INTREGISTER) and
  707. (
  708. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  709. )
  710. );
  711. end;
  712. else
  713. begin
  714. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  715. begin
  716. RegReadByInstruction := false;
  717. exit;
  718. end;
  719. for opcount := 0 to p.ops-1 do
  720. if (p.oper[opCount]^.typ = top_ref) and
  721. RegInRef(reg,p.oper[opcount]^.ref^) then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. { special handling for SSE MOVSD }
  727. if (p.opcode=A_MOVSD) and (p.ops>0) then
  728. begin
  729. if p.ops<>2 then
  730. internalerror(2017042702);
  731. regReadByInstruction := reginop(reg,p.oper[0]^) or
  732. (
  733. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  734. );
  735. exit;
  736. end;
  737. with insprop[p.opcode] do
  738. begin
  739. case getregtype(reg) of
  740. R_INTREGISTER:
  741. begin
  742. case getsupreg(reg) of
  743. RS_EAX:
  744. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. RS_ECX:
  750. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. RS_EDX:
  756. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  757. begin
  758. RegReadByInstruction := true;
  759. exit
  760. end;
  761. RS_EBX:
  762. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ESP:
  768. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EBP:
  774. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_ESI:
  780. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_EDI:
  786. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. end;
  792. end;
  793. R_MMREGISTER:
  794. begin
  795. case getsupreg(reg) of
  796. RS_XMM0:
  797. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. end;
  803. end;
  804. else
  805. ;
  806. end;
  807. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  808. begin
  809. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  810. begin
  811. case p.condition of
  812. C_A,C_NBE, { CF=0 and ZF=0 }
  813. C_BE,C_NA: { CF=1 or ZF=1 }
  814. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  815. C_AE,C_NB,C_NC, { CF=0 }
  816. C_B,C_NAE,C_C: { CF=1 }
  817. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  818. C_NE,C_NZ, { ZF=0 }
  819. C_E,C_Z: { ZF=1 }
  820. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  821. C_G,C_NLE, { ZF=0 and SF=OF }
  822. C_LE,C_NG: { ZF=1 or SF<>OF }
  823. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  824. C_GE,C_NL, { SF=OF }
  825. C_L,C_NGE: { SF<>OF }
  826. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  827. C_NO, { OF=0 }
  828. C_O: { OF=1 }
  829. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  830. C_NP,C_PO, { PF=0 }
  831. C_P,C_PE: { PF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  833. C_NS, { SF=0 }
  834. C_S: { SF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  836. else
  837. internalerror(2017042701);
  838. end;
  839. if RegReadByInstruction then
  840. exit;
  841. end;
  842. case getsubreg(reg) of
  843. R_SUBW,R_SUBD,R_SUBQ:
  844. RegReadByInstruction :=
  845. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  846. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  847. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  848. R_SUBFLAGCARRY:
  849. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGPARITY:
  851. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGAUXILIARY:
  853. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGZERO:
  855. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGSIGN:
  857. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGOVERFLOW:
  859. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGINTERRUPT:
  861. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. R_SUBFLAGDIRECTION:
  863. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  864. else
  865. internalerror(2017042601);
  866. end;
  867. exit;
  868. end;
  869. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  870. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  871. (p.oper[0]^.reg=p.oper[1]^.reg) then
  872. exit;
  873. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  874. begin
  875. RegReadByInstruction := true;
  876. exit
  877. end;
  878. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  879. begin
  880. RegReadByInstruction := true;
  881. exit
  882. end;
  883. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  884. begin
  885. RegReadByInstruction := true;
  886. exit
  887. end;
  888. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  889. begin
  890. RegReadByInstruction := true;
  891. exit
  892. end;
  893. end;
  894. end;
  895. end;
  896. end;
  897. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  898. begin
  899. result:=false;
  900. if p1.typ<>ait_instruction then
  901. exit;
  902. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  903. exit(true);
  904. if (getregtype(reg)=R_INTREGISTER) and
  905. { change information for xmm movsd are not correct }
  906. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  907. begin
  908. { Handle instructions that behave differently depending on the size and operand count }
  909. case taicpu(p1).opcode of
  910. A_MUL, A_DIV, A_IDIV:
  911. if taicpu(p1).opsize = S_B then
  912. Result := (getsupreg(Reg) = RS_EAX)
  913. else
  914. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  915. A_IMUL:
  916. if taicpu(p1).ops = 1 then
  917. begin
  918. if taicpu(p1).opsize = S_B then
  919. Result := (getsupreg(Reg) = RS_EAX)
  920. else
  921. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  922. end;
  923. { If ops are greater than 1, call inherited method }
  924. else
  925. case getsupreg(reg) of
  926. { RS_EAX = RS_RAX on x86-64 }
  927. RS_EAX:
  928. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_ECX:
  930. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EDX:
  932. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBX:
  934. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESP:
  936. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EBP:
  938. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_ESI:
  940. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. RS_EDI:
  942. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  943. else
  944. ;
  945. end;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if getregtype(reg)=R_MMREGISTER then
  951. begin
  952. case getsupreg(reg) of
  953. RS_XMM0:
  954. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. else
  956. ;
  957. end;
  958. if result then
  959. exit;
  960. end
  961. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  962. begin
  963. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  964. exit(true);
  965. case getsubreg(reg) of
  966. R_SUBFLAGCARRY:
  967. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGPARITY:
  969. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGAUXILIARY:
  971. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGZERO:
  973. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGSIGN:
  975. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGOVERFLOW:
  977. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGINTERRUPT:
  979. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBFLAGDIRECTION:
  981. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  982. R_SUBW,R_SUBD,R_SUBQ:
  983. { Everything except the direction bits }
  984. Result:=
  985. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  986. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  987. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  988. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  989. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  990. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  991. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. else
  993. ;
  994. end;
  995. if result then
  996. exit;
  997. end
  998. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  999. exit(true);
  1000. Result:=inherited RegInInstruction(Reg, p1);
  1001. end;
  1002. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1003. const
  1004. WriteOps: array[0..3] of set of TInsChange =
  1005. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1006. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1007. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1008. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1009. var
  1010. OperIdx: Integer;
  1011. begin
  1012. Result := False;
  1013. if p1.typ <> ait_instruction then
  1014. exit;
  1015. with insprop[taicpu(p1).opcode] do
  1016. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1017. begin
  1018. case getsubreg(reg) of
  1019. R_SUBW,R_SUBD,R_SUBQ:
  1020. Result :=
  1021. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1022. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1023. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1024. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1025. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1026. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGCARRY:
  1028. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGPARITY:
  1030. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGAUXILIARY:
  1032. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGZERO:
  1034. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGSIGN:
  1036. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGOVERFLOW:
  1038. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGINTERRUPT:
  1040. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. R_SUBFLAGDIRECTION:
  1042. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. else
  1044. internalerror(2017042602);
  1045. end;
  1046. exit;
  1047. end;
  1048. case taicpu(p1).opcode of
  1049. A_CALL:
  1050. { We could potentially set Result to False if the register in
  1051. question is non-volatile for the subroutine's calling convention,
  1052. but this would require detecting the calling convention in use and
  1053. also assuming that the routine doesn't contain malformed assembly
  1054. language, for example... so it could only be done under -O4 as it
  1055. would be considered a side-effect. [Kit] }
  1056. Result := True;
  1057. A_MOVSD:
  1058. { special handling for SSE MOVSD }
  1059. if (taicpu(p1).ops>0) then
  1060. begin
  1061. if taicpu(p1).ops<>2 then
  1062. internalerror(2017042703);
  1063. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1064. end;
  1065. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1066. so fix it here (FK)
  1067. }
  1068. A_VMOVSS,
  1069. A_VMOVSD:
  1070. begin
  1071. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1072. exit;
  1073. end;
  1074. A_MUL, A_DIV, A_IDIV:
  1075. begin
  1076. if taicpu(p1).opsize = S_B then
  1077. Result := (getsupreg(Reg) = RS_EAX)
  1078. else
  1079. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1080. end;
  1081. A_IMUL:
  1082. begin
  1083. if taicpu(p1).ops = 1 then
  1084. begin
  1085. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1086. end
  1087. else
  1088. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1089. Exit;
  1090. end;
  1091. else
  1092. ;
  1093. end;
  1094. if Result then
  1095. exit;
  1096. with insprop[taicpu(p1).opcode] do
  1097. begin
  1098. if getregtype(reg)=R_INTREGISTER then
  1099. begin
  1100. case getsupreg(reg) of
  1101. RS_EAX:
  1102. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1103. begin
  1104. Result := True;
  1105. exit
  1106. end;
  1107. RS_ECX:
  1108. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1109. begin
  1110. Result := True;
  1111. exit
  1112. end;
  1113. RS_EDX:
  1114. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1115. begin
  1116. Result := True;
  1117. exit
  1118. end;
  1119. RS_EBX:
  1120. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ESP:
  1126. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EBP:
  1132. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_ESI:
  1138. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_EDI:
  1144. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. end;
  1150. end;
  1151. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1152. if (WriteOps[OperIdx]*Ch<>[]) and
  1153. { The register doesn't get modified inside a reference }
  1154. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1155. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1156. begin
  1157. Result := true;
  1158. exit
  1159. end;
  1160. end;
  1161. end;
  1162. {$ifdef DEBUG_AOPTCPU}
  1163. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1164. begin
  1165. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1166. end;
  1167. function debug_tostr(i: tcgint): string; inline;
  1168. begin
  1169. Result := tostr(i);
  1170. end;
  1171. function debug_hexstr(i: tcgint): string;
  1172. begin
  1173. Result := '0x';
  1174. case i of
  1175. 0..$FF:
  1176. Result := Result + hexstr(i, 2);
  1177. $100..$FFFF:
  1178. Result := Result + hexstr(i, 4);
  1179. $10000..$FFFFFF:
  1180. Result := Result + hexstr(i, 6);
  1181. $1000000..$FFFFFFFF:
  1182. Result := Result + hexstr(i, 8);
  1183. else
  1184. Result := Result + hexstr(i, 16);
  1185. end;
  1186. end;
  1187. function debug_regname(r: TRegister): string; inline;
  1188. begin
  1189. Result := '%' + std_regname(r);
  1190. end;
  1191. { Debug output function - creates a string representation of an operator }
  1192. function debug_operstr(oper: TOper): string;
  1193. begin
  1194. case oper.typ of
  1195. top_const:
  1196. Result := '$' + debug_tostr(oper.val);
  1197. top_reg:
  1198. Result := debug_regname(oper.reg);
  1199. top_ref:
  1200. begin
  1201. if oper.ref^.offset <> 0 then
  1202. Result := debug_tostr(oper.ref^.offset) + '('
  1203. else
  1204. Result := '(';
  1205. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1206. begin
  1207. Result := Result + debug_regname(oper.ref^.base);
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + ',' + debug_regname(oper.ref^.index);
  1210. end
  1211. else
  1212. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1213. Result := Result + debug_regname(oper.ref^.index);
  1214. if (oper.ref^.scalefactor > 1) then
  1215. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1216. else
  1217. Result := Result + ')';
  1218. end;
  1219. else
  1220. Result := '[UNKNOWN]';
  1221. end;
  1222. end;
  1223. function debug_op2str(opcode: tasmop): string; inline;
  1224. begin
  1225. Result := std_op2str[opcode];
  1226. end;
  1227. function debug_opsize2str(opsize: topsize): string; inline;
  1228. begin
  1229. Result := gas_opsize2str[opsize];
  1230. end;
  1231. {$else DEBUG_AOPTCPU}
  1232. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1233. begin
  1234. end;
  1235. function debug_tostr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_hexstr(i: tcgint): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_regname(r: TRegister): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_operstr(oper: TOper): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_op2str(opcode: tasmop): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. function debug_opsize2str(opsize: topsize): string; inline;
  1256. begin
  1257. Result := '';
  1258. end;
  1259. {$endif DEBUG_AOPTCPU}
  1260. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1261. begin
  1262. {$ifdef x86_64}
  1263. { Always fine on x86-64 }
  1264. Result := True;
  1265. {$else x86_64}
  1266. Result :=
  1267. {$ifdef i8086}
  1268. (current_settings.cputype >= cpu_386) and
  1269. {$endif i8086}
  1270. (
  1271. { Always accept if optimising for size }
  1272. (cs_opt_size in current_settings.optimizerswitches) or
  1273. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1274. (current_settings.optimizecputype >= cpu_Pentium2)
  1275. );
  1276. {$endif x86_64}
  1277. end;
  1278. { Attempts to allocate a volatile integer register for use between p and hp,
  1279. using AUsedRegs for the current register usage information. Returns NR_NO
  1280. if no free register could be found }
  1281. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1282. var
  1283. RegSet: TCPURegisterSet;
  1284. CurrentSuperReg: Integer;
  1285. CurrentReg: TRegister;
  1286. Currentp: tai;
  1287. Breakout: Boolean;
  1288. begin
  1289. Result := NR_NO;
  1290. RegSet :=
  1291. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1292. current_procinfo.saved_regs_int;
  1293. (*
  1294. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1295. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1296. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1297. *)
  1298. for CurrentSuperReg in RegSet do
  1299. begin
  1300. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1301. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1302. {$if defined(i386) or defined(i8086)}
  1303. { If the target size is 8-bit, make sure we can actually encode it }
  1304. and (
  1305. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1306. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1307. )
  1308. {$endif i386 or i8086}
  1309. then
  1310. begin
  1311. Currentp := p;
  1312. Breakout := False;
  1313. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1314. begin
  1315. case Currentp.typ of
  1316. ait_instruction:
  1317. begin
  1318. if RegInInstruction(CurrentReg, Currentp) then
  1319. begin
  1320. Breakout := True;
  1321. Break;
  1322. end;
  1323. { Cannot allocate across an unconditional jump }
  1324. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1325. Exit;
  1326. end;
  1327. ait_marker:
  1328. { Don't try anything more if a marker is hit }
  1329. Exit;
  1330. ait_regalloc:
  1331. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. else
  1337. ;
  1338. end;
  1339. end;
  1340. if Breakout then
  1341. { Try the next register }
  1342. Continue;
  1343. { We have a free register available }
  1344. Result := CurrentReg;
  1345. if not DontAlloc then
  1346. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1347. Exit;
  1348. end;
  1349. end;
  1350. end;
  1351. { Attempts to allocate a volatile MM register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_mm;
  1366. for CurrentSuperReg in RegSet do
  1367. begin
  1368. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1369. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1370. begin
  1371. Currentp := p;
  1372. Breakout := False;
  1373. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1374. begin
  1375. case Currentp.typ of
  1376. ait_instruction:
  1377. begin
  1378. if RegInInstruction(CurrentReg, Currentp) then
  1379. begin
  1380. Breakout := True;
  1381. Break;
  1382. end;
  1383. { Cannot allocate across an unconditional jump }
  1384. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1385. Exit;
  1386. end;
  1387. ait_marker:
  1388. { Don't try anything more if a marker is hit }
  1389. Exit;
  1390. ait_regalloc:
  1391. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. else
  1397. ;
  1398. end;
  1399. end;
  1400. if Breakout then
  1401. { Try the next register }
  1402. Continue;
  1403. { We have a free register available }
  1404. Result := CurrentReg;
  1405. if not DontAlloc then
  1406. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1407. Exit;
  1408. end;
  1409. end;
  1410. end;
  1411. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1412. begin
  1413. if not SuperRegistersEqual(reg1,reg2) then
  1414. exit(false);
  1415. if getregtype(reg1)<>R_INTREGISTER then
  1416. exit(true); {because SuperRegisterEqual is true}
  1417. case getsubreg(reg1) of
  1418. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1419. higher, it preserves the high bits, so the new value depends on
  1420. reg2's previous value. In other words, it is equivalent to doing:
  1421. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1422. R_SUBL:
  1423. exit(getsubreg(reg2)=R_SUBL);
  1424. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1425. higher, it actually does a:
  1426. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1427. R_SUBH:
  1428. exit(getsubreg(reg2)=R_SUBH);
  1429. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1430. bits of reg2:
  1431. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1432. R_SUBW:
  1433. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1434. { a write to R_SUBD always overwrites every other subregister,
  1435. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1436. R_SUBD,
  1437. R_SUBQ:
  1438. exit(true);
  1439. else
  1440. internalerror(2017042801);
  1441. end;
  1442. end;
  1443. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1444. begin
  1445. if not SuperRegistersEqual(reg1,reg2) then
  1446. exit(false);
  1447. if getregtype(reg1)<>R_INTREGISTER then
  1448. exit(true); {because SuperRegisterEqual is true}
  1449. case getsubreg(reg1) of
  1450. R_SUBL:
  1451. exit(getsubreg(reg2)<>R_SUBH);
  1452. R_SUBH:
  1453. exit(getsubreg(reg2)<>R_SUBL);
  1454. R_SUBW,
  1455. R_SUBD,
  1456. R_SUBQ:
  1457. exit(true);
  1458. else
  1459. internalerror(2017042802);
  1460. end;
  1461. end;
  1462. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1463. var
  1464. hp1 : tai;
  1465. l : TCGInt;
  1466. begin
  1467. result:=false;
  1468. if not(GetNextInstruction(p, hp1)) then
  1469. exit;
  1470. { changes the code sequence
  1471. shr/sar const1, x
  1472. shl const2, x
  1473. to
  1474. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1475. if (taicpu(p).oper[0]^.typ = top_const) and
  1476. MatchInstruction(hp1,A_SHL,[]) and
  1477. (taicpu(hp1).oper[0]^.typ = top_const) and
  1478. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1479. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1480. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1481. begin
  1482. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1483. not(cs_opt_size in current_settings.optimizerswitches) then
  1484. begin
  1485. { shr/sar const1, %reg
  1486. shl const2, %reg
  1487. with const1 > const2 }
  1488. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1489. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1490. taicpu(hp1).opcode := A_AND;
  1491. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1492. case taicpu(p).opsize Of
  1493. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1494. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1495. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1496. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1497. else
  1498. Internalerror(2017050703)
  1499. end;
  1500. end
  1501. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1502. not(cs_opt_size in current_settings.optimizerswitches) then
  1503. begin
  1504. { shr/sar const1, %reg
  1505. shl const2, %reg
  1506. with const1 < const2 }
  1507. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1508. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1509. taicpu(p).opcode := A_AND;
  1510. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1511. case taicpu(p).opsize Of
  1512. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1513. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1514. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1515. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1516. else
  1517. Internalerror(2017050702)
  1518. end;
  1519. end
  1520. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1521. begin
  1522. { shr/sar const1, %reg
  1523. shl const2, %reg
  1524. with const1 = const2 }
  1525. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1526. taicpu(p).opcode := A_AND;
  1527. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1528. case taicpu(p).opsize Of
  1529. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1530. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1531. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1532. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1533. else
  1534. Internalerror(2017050701)
  1535. end;
  1536. RemoveInstruction(hp1);
  1537. end;
  1538. end;
  1539. end;
  1540. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1541. var
  1542. opsize : topsize;
  1543. hp1, hp2 : tai;
  1544. tmpref : treference;
  1545. ShiftValue : Cardinal;
  1546. BaseValue : TCGInt;
  1547. begin
  1548. result:=false;
  1549. opsize:=taicpu(p).opsize;
  1550. { changes certain "imul const, %reg"'s to lea sequences }
  1551. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1552. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1553. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1554. if (taicpu(p).oper[0]^.val = 1) then
  1555. if (taicpu(p).ops = 2) then
  1556. { remove "imul $1, reg" }
  1557. begin
  1558. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1559. Result := RemoveCurrentP(p);
  1560. end
  1561. else
  1562. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1563. begin
  1564. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1565. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1566. asml.InsertAfter(hp1, p);
  1567. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1568. RemoveCurrentP(p, hp1);
  1569. Result := True;
  1570. end
  1571. else if ((taicpu(p).ops <= 2) or
  1572. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) and
  1574. (not(GetNextInstruction(p, hp1)) or
  1575. not((tai(hp1).typ = ait_instruction) and
  1576. ((taicpu(hp1).opcode=A_Jcc) and
  1577. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1578. begin
  1579. {
  1580. imul X, reg1, reg2 to
  1581. lea (reg1,reg1,Y), reg2
  1582. shl ZZ,reg2
  1583. imul XX, reg1 to
  1584. lea (reg1,reg1,YY), reg1
  1585. shl ZZ,reg2
  1586. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1587. it does not exist as a separate optimization target in FPC though.
  1588. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1589. at most two zeros
  1590. }
  1591. reference_reset(tmpref,1,[]);
  1592. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1593. begin
  1594. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1595. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1596. TmpRef.base := taicpu(p).oper[1]^.reg;
  1597. TmpRef.index := taicpu(p).oper[1]^.reg;
  1598. if not(BaseValue in [3,5,9]) then
  1599. Internalerror(2018110101);
  1600. TmpRef.ScaleFactor := BaseValue-1;
  1601. if (taicpu(p).ops = 2) then
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1603. else
  1604. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1605. AsmL.InsertAfter(hp1,p);
  1606. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1607. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1608. RemoveCurrentP(p, hp1);
  1609. if ShiftValue>0 then
  1610. begin
  1611. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1612. AsmL.InsertAfter(hp2,hp1);
  1613. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1614. end;
  1615. Result := True;
  1616. end;
  1617. end;
  1618. end;
  1619. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1620. begin
  1621. Result := False;
  1622. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1623. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1624. begin
  1625. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1626. taicpu(p).opcode := A_MOV;
  1627. Result := True;
  1628. end;
  1629. end;
  1630. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1631. var
  1632. p: taicpu absolute hp; { Implicit typecast }
  1633. i: Integer;
  1634. begin
  1635. Result := False;
  1636. if not assigned(hp) or
  1637. (hp.typ <> ait_instruction) then
  1638. Exit;
  1639. Prefetch(insprop[p.opcode]);
  1640. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1641. with insprop[p.opcode] do
  1642. begin
  1643. case getsubreg(reg) of
  1644. R_SUBW,R_SUBD,R_SUBQ:
  1645. Result:=
  1646. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1647. uncommon flags are checked first }
  1648. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1649. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1652. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1653. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1654. R_SUBFLAGCARRY:
  1655. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGPARITY:
  1657. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGAUXILIARY:
  1659. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGZERO:
  1661. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGSIGN:
  1663. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGOVERFLOW:
  1665. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGINTERRUPT:
  1667. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1668. R_SUBFLAGDIRECTION:
  1669. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1670. else
  1671. internalerror(2017050501);
  1672. end;
  1673. exit;
  1674. end;
  1675. { Handle special cases first }
  1676. case p.opcode of
  1677. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1678. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1679. begin
  1680. Result :=
  1681. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1682. (p.oper[1]^.typ = top_reg) and
  1683. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1684. (
  1685. (p.oper[0]^.typ = top_const) or
  1686. (
  1687. (p.oper[0]^.typ = top_reg) and
  1688. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1689. ) or (
  1690. (p.oper[0]^.typ = top_ref) and
  1691. not RegInRef(reg,p.oper[0]^.ref^)
  1692. )
  1693. );
  1694. end;
  1695. A_MUL, A_IMUL:
  1696. Result :=
  1697. (
  1698. (p.ops=3) and { IMUL only }
  1699. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1700. (
  1701. (
  1702. (p.oper[1]^.typ=top_reg) and
  1703. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1704. ) or (
  1705. (p.oper[1]^.typ=top_ref) and
  1706. not RegInRef(reg,p.oper[1]^.ref^)
  1707. )
  1708. )
  1709. ) or (
  1710. (
  1711. (p.ops=1) and
  1712. (
  1713. (
  1714. (
  1715. (p.oper[0]^.typ=top_reg) and
  1716. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1717. )
  1718. ) or (
  1719. (p.oper[0]^.typ=top_ref) and
  1720. not RegInRef(reg,p.oper[0]^.ref^)
  1721. )
  1722. ) and (
  1723. (
  1724. (p.opsize=S_B) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1726. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1727. ) or (
  1728. (p.opsize=S_W) and
  1729. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1730. ) or (
  1731. (p.opsize=S_L) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1733. {$ifdef x86_64}
  1734. ) or (
  1735. (p.opsize=S_Q) and
  1736. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1737. {$endif x86_64}
  1738. )
  1739. )
  1740. )
  1741. );
  1742. A_CBW:
  1743. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1744. {$ifndef x86_64}
  1745. A_LDS:
  1746. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. A_LES:
  1748. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1749. {$endif not x86_64}
  1750. A_LFS:
  1751. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LGS:
  1753. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LSS:
  1755. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1756. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1758. A_LODSB:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1760. A_LODSW:
  1761. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1762. {$ifdef x86_64}
  1763. A_LODSQ:
  1764. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1765. {$endif x86_64}
  1766. A_LODSD:
  1767. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1768. A_FSTSW, A_FNSTSW:
  1769. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1770. else
  1771. begin
  1772. with insprop[p.opcode] do
  1773. begin
  1774. if (
  1775. { xor %reg,%reg etc. is classed as a new value }
  1776. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1777. MatchOpType(p, top_reg, top_reg) and
  1778. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1779. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1780. ) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. { Make sure the entire register is overwritten }
  1786. if (getregtype(reg) = R_INTREGISTER) then
  1787. begin
  1788. if (p.ops > 0) then
  1789. begin
  1790. if RegInOp(reg, p.oper[0]^) then
  1791. begin
  1792. if (p.oper[0]^.typ = top_ref) then
  1793. begin
  1794. if RegInRef(reg, p.oper[0]^.ref^) then
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end
  1800. else if (p.oper[0]^.typ = top_reg) then
  1801. begin
  1802. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1803. begin
  1804. Result := False;
  1805. Exit;
  1806. end
  1807. else if ([Ch_WOp1]*Ch<>[]) then
  1808. begin
  1809. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1810. Result := True
  1811. else
  1812. begin
  1813. Result := False;
  1814. Exit;
  1815. end;
  1816. end;
  1817. end;
  1818. end;
  1819. if (p.ops > 1) then
  1820. begin
  1821. if RegInOp(reg, p.oper[1]^) then
  1822. begin
  1823. if (p.oper[1]^.typ = top_ref) then
  1824. begin
  1825. if RegInRef(reg, p.oper[1]^.ref^) then
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end
  1831. else if (p.oper[1]^.typ = top_reg) then
  1832. begin
  1833. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1834. begin
  1835. Result := False;
  1836. Exit;
  1837. end
  1838. else if ([Ch_WOp2]*Ch<>[]) then
  1839. begin
  1840. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1841. Result := True
  1842. else
  1843. begin
  1844. Result := False;
  1845. Exit;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. if (p.ops > 2) then
  1851. begin
  1852. if RegInOp(reg, p.oper[2]^) then
  1853. begin
  1854. if (p.oper[2]^.typ = top_ref) then
  1855. begin
  1856. if RegInRef(reg, p.oper[2]^.ref^) then
  1857. begin
  1858. Result := False;
  1859. Exit;
  1860. end;
  1861. end
  1862. else if (p.oper[2]^.typ = top_reg) then
  1863. begin
  1864. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1865. begin
  1866. Result := False;
  1867. Exit;
  1868. end
  1869. else if ([Ch_WOp3]*Ch<>[]) then
  1870. begin
  1871. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1872. Result := True
  1873. else
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1882. begin
  1883. if (p.oper[3]^.typ = top_ref) then
  1884. begin
  1885. if RegInRef(reg, p.oper[3]^.ref^) then
  1886. begin
  1887. Result := False;
  1888. Exit;
  1889. end;
  1890. end
  1891. else if (p.oper[3]^.typ = top_reg) then
  1892. begin
  1893. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1894. begin
  1895. Result := False;
  1896. Exit;
  1897. end
  1898. else if ([Ch_WOp4]*Ch<>[]) then
  1899. begin
  1900. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1901. Result := True
  1902. else
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1914. case getsupreg(reg) of
  1915. RS_EAX:
  1916. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1917. begin
  1918. Result := True;
  1919. Exit;
  1920. end;
  1921. RS_ECX:
  1922. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1923. begin
  1924. Result := True;
  1925. Exit;
  1926. end;
  1927. RS_EDX:
  1928. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1929. begin
  1930. Result := True;
  1931. Exit;
  1932. end;
  1933. RS_EBX:
  1934. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1935. begin
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. RS_ESP:
  1940. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1941. begin
  1942. Result := True;
  1943. Exit;
  1944. end;
  1945. RS_EBP:
  1946. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1947. begin
  1948. Result := True;
  1949. Exit;
  1950. end;
  1951. RS_ESI:
  1952. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1953. begin
  1954. Result := True;
  1955. Exit;
  1956. end;
  1957. RS_EDI:
  1958. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1959. begin
  1960. Result := True;
  1961. Exit;
  1962. end;
  1963. else
  1964. ;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. end;
  1970. end;
  1971. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1972. var
  1973. hp2,hp3 : tai;
  1974. begin
  1975. { some x86-64 issue a NOP before the real exit code }
  1976. if MatchInstruction(p,A_NOP,[]) then
  1977. GetNextInstruction(p,p);
  1978. result:=assigned(p) and (p.typ=ait_instruction) and
  1979. ((taicpu(p).opcode = A_RET) or
  1980. ((taicpu(p).opcode=A_LEAVE) and
  1981. GetNextInstruction(p,hp2) and
  1982. MatchInstruction(hp2,A_RET,[S_NO])
  1983. ) or
  1984. (((taicpu(p).opcode=A_LEA) and
  1985. MatchOpType(taicpu(p),top_ref,top_reg) and
  1986. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1987. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1988. ) and
  1989. GetNextInstruction(p,hp2) and
  1990. MatchInstruction(hp2,A_RET,[S_NO])
  1991. ) or
  1992. ((((taicpu(p).opcode=A_MOV) and
  1993. MatchOpType(taicpu(p),top_reg,top_reg) and
  1994. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1996. ((taicpu(p).opcode=A_LEA) and
  1997. MatchOpType(taicpu(p),top_ref,top_reg) and
  1998. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1999. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2000. )
  2001. ) and
  2002. GetNextInstruction(p,hp2) and
  2003. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2004. MatchOpType(taicpu(hp2),top_reg) and
  2005. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2006. GetNextInstruction(hp2,hp3) and
  2007. MatchInstruction(hp3,A_RET,[S_NO])
  2008. )
  2009. );
  2010. end;
  2011. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2012. begin
  2013. isFoldableArithOp := False;
  2014. case hp1.opcode of
  2015. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2016. isFoldableArithOp :=
  2017. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2018. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2020. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[1]^.reg = reg);
  2022. A_INC,A_DEC,A_NEG,A_NOT:
  2023. isFoldableArithOp :=
  2024. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2025. (taicpu(hp1).oper[0]^.reg = reg);
  2026. else
  2027. ;
  2028. end;
  2029. end;
  2030. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2031. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2032. var
  2033. hp2: tai;
  2034. begin
  2035. hp2 := p;
  2036. repeat
  2037. hp2 := tai(hp2.previous);
  2038. if assigned(hp2) and
  2039. (hp2.typ = ait_regalloc) and
  2040. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2041. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2042. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2043. begin
  2044. RemoveInstruction(hp2);
  2045. break;
  2046. end;
  2047. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2048. end;
  2049. begin
  2050. case current_procinfo.procdef.returndef.typ of
  2051. arraydef,recorddef,pointerdef,
  2052. stringdef,enumdef,procdef,objectdef,errordef,
  2053. filedef,setdef,procvardef,
  2054. classrefdef,forwarddef:
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. orddef:
  2057. if current_procinfo.procdef.returndef.size <> 0 then
  2058. begin
  2059. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2060. { for int64/qword }
  2061. if current_procinfo.procdef.returndef.size = 8 then
  2062. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2063. end;
  2064. else
  2065. ;
  2066. end;
  2067. end;
  2068. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2069. var
  2070. hp1: tai;
  2071. operswap: poper;
  2072. begin
  2073. Result := False;
  2074. { Optimise:
  2075. cmov(c) %reg1,%reg2
  2076. mov %reg2,%reg1
  2077. (%reg2 dealloc.)
  2078. To:
  2079. cmov(~c) %reg2,%reg1
  2080. }
  2081. if (taicpu(p).oper[0]^.typ = top_reg) then
  2082. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2083. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2084. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2085. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2086. begin
  2087. TransferUsedRegs(TmpUsedRegs);
  2088. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2089. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2090. begin
  2091. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2092. { Save time by swapping the pointers (they're both registers, so
  2093. we don't need to worry about reference counts) }
  2094. operswap := taicpu(p).oper[0];
  2095. taicpu(p).oper[0] := taicpu(p).oper[1];
  2096. taicpu(p).oper[1] := operswap;
  2097. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2098. RemoveInstruction(hp1);
  2099. { It's still a CMOV, so we can look further ahead }
  2100. Include(OptsToCheck, aoc_ForceNewIteration);
  2101. { But first, let's see if this will get optimised again
  2102. (probably won't happen, but best to be sure) }
  2103. Continue;
  2104. end;
  2105. Break;
  2106. end;
  2107. end;
  2108. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2109. var
  2110. hp1,hp2 : tai;
  2111. begin
  2112. result:=false;
  2113. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2114. begin
  2115. { vmova* reg1,reg1
  2116. =>
  2117. <nop> }
  2118. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2119. begin
  2120. RemoveCurrentP(p);
  2121. result:=true;
  2122. exit;
  2123. end;
  2124. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2125. (hp1.typ = ait_instruction) and
  2126. (
  2127. { Under -O2 and below, the instructions are always adjacent }
  2128. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2129. (taicpu(hp1).ops <= 1) or
  2130. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2131. { If reg1 = reg3, reg1 must not be modified in between }
  2132. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2133. ) then
  2134. begin
  2135. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmova* reg2,reg3
  2141. dealloc reg2
  2142. =>
  2143. vmova* reg1,reg3 }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2146. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2147. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2148. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2151. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2152. TransferUsedRegs(TmpUsedRegs);
  2153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2154. RemoveInstruction(hp1);
  2155. result:=true;
  2156. exit;
  2157. end;
  2158. { special case:
  2159. vmova* reg1,<op>
  2160. ...
  2161. vmova* <op>,reg1
  2162. =>
  2163. vmova* reg1,<op> }
  2164. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2165. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2166. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2167. ) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2170. RemoveInstruction(hp1);
  2171. result:=true;
  2172. exit;
  2173. end
  2174. end
  2175. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2176. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2177. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2178. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2179. ) and
  2180. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2181. begin
  2182. { vmova* reg1,reg2
  2183. ...
  2184. vmovs* reg2,<op>
  2185. dealloc reg2
  2186. =>
  2187. vmovs* reg1,<op> }
  2188. TransferUsedRegs(TmpUsedRegs);
  2189. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2190. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2193. taicpu(p).opcode:=taicpu(hp1).opcode;
  2194. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2197. RemoveInstruction(hp1);
  2198. result:=true;
  2199. exit;
  2200. end
  2201. end;
  2202. if MatchInstruction(hp1,[A_VFMADDPD,
  2203. A_VFMADD132PD,
  2204. A_VFMADD132PS,
  2205. A_VFMADD132SD,
  2206. A_VFMADD132SS,
  2207. A_VFMADD213PD,
  2208. A_VFMADD213PS,
  2209. A_VFMADD213SD,
  2210. A_VFMADD213SS,
  2211. A_VFMADD231PD,
  2212. A_VFMADD231PS,
  2213. A_VFMADD231SD,
  2214. A_VFMADD231SS,
  2215. A_VFMADDSUB132PD,
  2216. A_VFMADDSUB132PS,
  2217. A_VFMADDSUB213PD,
  2218. A_VFMADDSUB213PS,
  2219. A_VFMADDSUB231PD,
  2220. A_VFMADDSUB231PS,
  2221. A_VFMSUB132PD,
  2222. A_VFMSUB132PS,
  2223. A_VFMSUB132SD,
  2224. A_VFMSUB132SS,
  2225. A_VFMSUB213PD,
  2226. A_VFMSUB213PS,
  2227. A_VFMSUB213SD,
  2228. A_VFMSUB213SS,
  2229. A_VFMSUB231PD,
  2230. A_VFMSUB231PS,
  2231. A_VFMSUB231SD,
  2232. A_VFMSUB231SS,
  2233. A_VFMSUBADD132PD,
  2234. A_VFMSUBADD132PS,
  2235. A_VFMSUBADD213PD,
  2236. A_VFMSUBADD213PS,
  2237. A_VFMSUBADD231PD,
  2238. A_VFMSUBADD231PS,
  2239. A_VFNMADD132PD,
  2240. A_VFNMADD132PS,
  2241. A_VFNMADD132SD,
  2242. A_VFNMADD132SS,
  2243. A_VFNMADD213PD,
  2244. A_VFNMADD213PS,
  2245. A_VFNMADD213SD,
  2246. A_VFNMADD213SS,
  2247. A_VFNMADD231PD,
  2248. A_VFNMADD231PS,
  2249. A_VFNMADD231SD,
  2250. A_VFNMADD231SS,
  2251. A_VFNMSUB132PD,
  2252. A_VFNMSUB132PS,
  2253. A_VFNMSUB132SD,
  2254. A_VFNMSUB132SS,
  2255. A_VFNMSUB213PD,
  2256. A_VFNMSUB213PS,
  2257. A_VFNMSUB213SD,
  2258. A_VFNMSUB213SS,
  2259. A_VFNMSUB231PD,
  2260. A_VFNMSUB231PS,
  2261. A_VFNMSUB231SD,
  2262. A_VFNMSUB231SS],[S_NO]) and
  2263. { we mix single and double opperations here because we assume that the compiler
  2264. generates vmovapd only after double operations and vmovaps only after single operations }
  2265. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2266. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2267. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2268. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2269. begin
  2270. TransferUsedRegs(TmpUsedRegs);
  2271. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2272. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2273. begin
  2274. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2275. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2276. RemoveCurrentP(p)
  2277. else
  2278. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2279. RemoveInstruction(hp2);
  2280. end;
  2281. end
  2282. else if (hp1.typ = ait_instruction) and
  2283. (((taicpu(p).opcode=A_MOVAPS) and
  2284. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2285. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2286. ((taicpu(p).opcode=A_MOVAPD) and
  2287. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2288. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2289. ) and
  2290. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2291. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2292. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2293. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2294. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2295. { change
  2296. movapX reg,reg2
  2297. addsX/subsX/... reg3, reg2
  2298. movapX reg2,reg
  2299. to
  2300. addsX/subsX/... reg3,reg
  2301. }
  2302. begin
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2305. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2306. begin
  2307. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2308. debug_op2str(taicpu(p).opcode)+' '+
  2309. debug_op2str(taicpu(hp1).opcode)+' '+
  2310. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2311. { we cannot eliminate the first move if
  2312. the operations uses the same register for source and dest }
  2313. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2314. { Remember that hp1 is not necessarily the immediate
  2315. next instruction }
  2316. RemoveCurrentP(p);
  2317. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2318. RemoveInstruction(hp2);
  2319. result:=true;
  2320. end;
  2321. end
  2322. else if (hp1.typ = ait_instruction) and
  2323. (((taicpu(p).opcode=A_VMOVAPD) and
  2324. (taicpu(hp1).opcode=A_VCOMISD)) or
  2325. ((taicpu(p).opcode=A_VMOVAPS) and
  2326. ((taicpu(hp1).opcode=A_VCOMISS))
  2327. )
  2328. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2329. { change
  2330. movapX reg,reg1
  2331. vcomisX reg1,reg1
  2332. to
  2333. vcomisX reg,reg
  2334. }
  2335. begin
  2336. TransferUsedRegs(TmpUsedRegs);
  2337. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2338. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2339. begin
  2340. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2341. debug_op2str(taicpu(p).opcode)+' '+
  2342. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2343. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2344. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2345. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2346. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2347. RemoveCurrentP(p);
  2348. result:=true;
  2349. exit;
  2350. end;
  2351. end
  2352. end;
  2353. end;
  2354. end;
  2355. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2356. var
  2357. hp1 : tai;
  2358. begin
  2359. result:=false;
  2360. { replace
  2361. V<Op>X %mreg1,%mreg2,%mreg3
  2362. VMovX %mreg3,%mreg4
  2363. dealloc %mreg3
  2364. by
  2365. V<Op>X %mreg1,%mreg2,%mreg4
  2366. ?
  2367. }
  2368. if GetNextInstruction(p,hp1) and
  2369. { we mix single and double operations here because we assume that the compiler
  2370. generates vmovapd only after double operations and vmovaps only after single operations }
  2371. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2372. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2373. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2377. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2378. begin
  2379. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2380. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2381. RemoveInstruction(hp1);
  2382. result:=true;
  2383. end;
  2384. end;
  2385. end;
  2386. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2387. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2388. begin
  2389. Result := False;
  2390. { For safety reasons, only check for exact register matches }
  2391. { Check base register }
  2392. if (ref.base = AOldReg) then
  2393. begin
  2394. ref.base := ANewReg;
  2395. Result := True;
  2396. end;
  2397. { Check index register }
  2398. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2399. begin
  2400. ref.index := ANewReg;
  2401. Result := True;
  2402. end;
  2403. end;
  2404. { Replaces all references to AOldReg in an operand to ANewReg }
  2405. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2406. var
  2407. OldSupReg, NewSupReg: TSuperRegister;
  2408. OldSubReg, NewSubReg: TSubRegister;
  2409. OldRegType: TRegisterType;
  2410. ThisOper: POper;
  2411. begin
  2412. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2413. Result := False;
  2414. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2415. InternalError(2020011801);
  2416. OldSupReg := getsupreg(AOldReg);
  2417. OldSubReg := getsubreg(AOldReg);
  2418. OldRegType := getregtype(AOldReg);
  2419. NewSupReg := getsupreg(ANewReg);
  2420. NewSubReg := getsubreg(ANewReg);
  2421. if OldRegType <> getregtype(ANewReg) then
  2422. InternalError(2020011802);
  2423. if OldSubReg <> NewSubReg then
  2424. InternalError(2020011803);
  2425. case ThisOper^.typ of
  2426. top_reg:
  2427. if (
  2428. (ThisOper^.reg = AOldReg) or
  2429. (
  2430. (OldRegType = R_INTREGISTER) and
  2431. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2432. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2433. (
  2434. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2435. {$ifndef x86_64}
  2436. and (
  2437. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2438. don't have an 8-bit representation }
  2439. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2440. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2441. )
  2442. {$endif x86_64}
  2443. )
  2444. )
  2445. ) then
  2446. begin
  2447. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2448. Result := True;
  2449. end;
  2450. top_ref:
  2451. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2452. Result := True;
  2453. else
  2454. ;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in an instruction to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2459. const
  2460. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2461. var
  2462. OperIdx: Integer;
  2463. begin
  2464. Result := False;
  2465. for OperIdx := 0 to p.ops - 1 do
  2466. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2467. begin
  2468. { The shift and rotate instructions can only use CL }
  2469. if not (
  2470. (OperIdx = 0) and
  2471. { This second condition just helps to avoid unnecessarily
  2472. calling MatchInstruction for 10 different opcodes }
  2473. (p.oper[0]^.reg = NR_CL) and
  2474. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2475. ) then
  2476. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2477. end
  2478. else if p.oper[OperIdx]^.typ = top_ref then
  2479. { It's okay to replace registers in references that get written to }
  2480. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2481. end;
  2482. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2483. begin
  2484. Result :=
  2485. (ref^.index = NR_NO) and
  2486. (
  2487. {$ifdef x86_64}
  2488. (
  2489. (ref^.base = NR_RIP) and
  2490. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2491. ) or
  2492. {$endif x86_64}
  2493. (ref^.refaddr = addr_full) or
  2494. (ref^.base = NR_STACK_POINTER_REG) or
  2495. (ref^.base = current_procinfo.framepointer)
  2496. );
  2497. end;
  2498. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2499. var
  2500. l: asizeint;
  2501. begin
  2502. Result := False;
  2503. { Should have been checked previously }
  2504. if p.opcode <> A_LEA then
  2505. InternalError(2020072501);
  2506. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2507. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2508. not(cs_opt_size in current_settings.optimizerswitches) then
  2509. exit;
  2510. with p.oper[0]^.ref^ do
  2511. begin
  2512. if (base <> p.oper[1]^.reg) or
  2513. (index <> NR_NO) or
  2514. assigned(symbol) then
  2515. exit;
  2516. l:=offset;
  2517. if (l=1) and UseIncDec then
  2518. begin
  2519. p.opcode:=A_INC;
  2520. p.loadreg(0,p.oper[1]^.reg);
  2521. p.ops:=1;
  2522. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2523. end
  2524. else if (l=-1) and UseIncDec then
  2525. begin
  2526. p.opcode:=A_DEC;
  2527. p.loadreg(0,p.oper[1]^.reg);
  2528. p.ops:=1;
  2529. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2530. end
  2531. else
  2532. begin
  2533. if (l<0) and (l<>-2147483648) then
  2534. begin
  2535. p.opcode:=A_SUB;
  2536. p.loadConst(0,-l);
  2537. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2538. end
  2539. else
  2540. begin
  2541. p.opcode:=A_ADD;
  2542. p.loadConst(0,l);
  2543. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2544. end;
  2545. end;
  2546. end;
  2547. Result := True;
  2548. end;
  2549. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2550. var
  2551. CurrentReg, ReplaceReg: TRegister;
  2552. begin
  2553. Result := False;
  2554. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2555. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2556. case hp.opcode of
  2557. A_FSTSW, A_FNSTSW,
  2558. A_IN, A_INS, A_OUT, A_OUTS,
  2559. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2560. { These routines have explicit operands, but they are restricted in
  2561. what they can be (e.g. IN and OUT can only read from AL, AX or
  2562. EAX. }
  2563. Exit;
  2564. A_IMUL:
  2565. begin
  2566. { The 1-operand version writes to implicit registers
  2567. The 2-operand version reads from the first operator, and reads
  2568. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2569. the 3-operand version reads from a register that it doesn't write to
  2570. }
  2571. case hp.ops of
  2572. 1:
  2573. if (
  2574. (
  2575. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2576. ) or
  2577. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2578. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2579. begin
  2580. Result := True;
  2581. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2582. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2583. end;
  2584. 2:
  2585. { Only modify the first parameter }
  2586. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2587. begin
  2588. Result := True;
  2589. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2590. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2591. end;
  2592. 3:
  2593. { Only modify the second parameter }
  2594. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2595. begin
  2596. Result := True;
  2597. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2598. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2599. end;
  2600. else
  2601. InternalError(2020012901);
  2602. end;
  2603. end;
  2604. else
  2605. if (hp.ops > 0) and
  2606. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2607. begin
  2608. Result := True;
  2609. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2610. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2615. var
  2616. hp2, hp_regalloc: tai;
  2617. p_SourceReg, p_TargetReg: TRegister;
  2618. begin
  2619. Result := False;
  2620. { Backward optimisation. If we have:
  2621. func. %reg1,%reg2
  2622. mov %reg2,%reg3
  2623. (dealloc %reg2)
  2624. Change to:
  2625. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2626. Perform similar optimisations with 1, 3 and 4-operand instructions
  2627. that only have one output.
  2628. }
  2629. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2630. begin
  2631. p_SourceReg := taicpu(p).oper[0]^.reg;
  2632. p_TargetReg := taicpu(p).oper[1]^.reg;
  2633. TransferUsedRegs(TmpUsedRegs);
  2634. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2635. GetLastInstruction(p, hp2) and
  2636. (hp2.typ = ait_instruction) and
  2637. { Have to make sure it's an instruction that only reads from
  2638. the first operands and only writes (not reads or modifies) to
  2639. the last one; in essence, a pure function such as BSR, POPCNT
  2640. or ANDN }
  2641. (
  2642. (
  2643. (taicpu(hp2).ops = 1) and
  2644. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2645. ) or
  2646. (
  2647. (taicpu(hp2).ops = 2) and
  2648. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2649. ) or
  2650. (
  2651. (taicpu(hp2).ops = 3) and
  2652. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2653. ) or
  2654. (
  2655. (taicpu(hp2).ops = 4) and
  2656. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2657. )
  2658. ) and
  2659. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2660. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2661. begin
  2662. case taicpu(hp2).opcode of
  2663. A_FSTSW, A_FNSTSW,
  2664. A_IN, A_INS, A_OUT, A_OUTS,
  2665. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2666. { These routines have explicit operands, but they are restricted in
  2667. what they can be (e.g. IN and OUT can only read from AL, AX or
  2668. EAX. }
  2669. ;
  2670. else
  2671. begin
  2672. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2673. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2674. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2675. if Assigned(hp_regalloc) then
  2676. begin
  2677. Asml.Remove(hp_regalloc);
  2678. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2679. begin
  2680. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2681. hp_regalloc.Free;
  2682. end
  2683. else
  2684. { If the register is not explicitly deallocated, it's
  2685. being reused, so move the allocation to after func. }
  2686. AsmL.InsertAfter(hp_regalloc, hp2);
  2687. end;
  2688. if not RegInInstruction(p_TargetReg, hp2) then
  2689. begin
  2690. TransferUsedRegs(TmpUsedRegs);
  2691. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2692. end;
  2693. { Actually make the changes }
  2694. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2695. RemoveCurrentp(p, hp1);
  2696. { If the Func was another MOV instruction, we might get
  2697. "mov %reg,%reg" that doesn't get removed in Pass 2
  2698. otherwise, so deal with it here (also do something
  2699. similar with lea (%reg),%reg}
  2700. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2703. if p = hp2 then
  2704. RemoveCurrentp(p)
  2705. else
  2706. RemoveInstruction(hp2);
  2707. end;
  2708. Result := True;
  2709. Exit;
  2710. end;
  2711. end;
  2712. end;
  2713. end;
  2714. end;
  2715. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2716. begin
  2717. Result := False;
  2718. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2719. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2720. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2721. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2722. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2723. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2724. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2725. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2726. begin
  2727. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2728. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2729. Result := True;
  2730. end;
  2731. end;
  2732. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2733. var
  2734. hp1, hp2, hp3, hp4: tai;
  2735. DoOptimisation, TempBool: Boolean;
  2736. {$ifdef x86_64}
  2737. NewConst: TCGInt;
  2738. {$endif x86_64}
  2739. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2740. begin
  2741. if taicpu(hp1).opcode = signed_movop then
  2742. begin
  2743. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2744. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2745. end
  2746. else
  2747. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2748. end;
  2749. function TryConstMerge(var p1, p2: tai): Boolean;
  2750. var
  2751. ThisRef: TReference;
  2752. begin
  2753. Result := False;
  2754. ThisRef := taicpu(p2).oper[1]^.ref^;
  2755. { Only permit writes to the stack, since we can guarantee alignment with that }
  2756. if (ThisRef.index = NR_NO) and
  2757. (
  2758. (ThisRef.base = NR_STACK_POINTER_REG) or
  2759. (ThisRef.base = current_procinfo.framepointer)
  2760. ) then
  2761. begin
  2762. case taicpu(p).opsize of
  2763. S_B:
  2764. begin
  2765. { Word writes must be on a 2-byte boundary }
  2766. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2767. begin
  2768. { Reduce offset of second reference to see if it is sequential with the first }
  2769. Dec(ThisRef.offset, 1);
  2770. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2771. begin
  2772. { Make sure the constants aren't represented as a
  2773. negative number, as these won't merge properly }
  2774. taicpu(p1).opsize := S_W;
  2775. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2776. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2777. RemoveInstruction(p2);
  2778. Result := True;
  2779. end;
  2780. end;
  2781. end;
  2782. S_W:
  2783. begin
  2784. { Longword writes must be on a 4-byte boundary }
  2785. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2786. begin
  2787. { Reduce offset of second reference to see if it is sequential with the first }
  2788. Dec(ThisRef.offset, 2);
  2789. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2790. begin
  2791. { Make sure the constants aren't represented as a
  2792. negative number, as these won't merge properly }
  2793. taicpu(p1).opsize := S_L;
  2794. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2795. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2796. RemoveInstruction(p2);
  2797. Result := True;
  2798. end;
  2799. end;
  2800. end;
  2801. {$ifdef x86_64}
  2802. S_L:
  2803. begin
  2804. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2805. see if the constants can be encoded this way. }
  2806. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2807. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2808. { Quadword writes must be on an 8-byte boundary }
  2809. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2810. begin
  2811. { Reduce offset of second reference to see if it is sequential with the first }
  2812. Dec(ThisRef.offset, 4);
  2813. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2814. begin
  2815. { Make sure the constants aren't represented as a
  2816. negative number, as these won't merge properly }
  2817. taicpu(p1).opsize := S_Q;
  2818. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2819. taicpu(p1).oper[0]^.val := NewConst;
  2820. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2821. RemoveInstruction(p2);
  2822. Result := True;
  2823. end;
  2824. end;
  2825. end;
  2826. {$endif x86_64}
  2827. else
  2828. ;
  2829. end;
  2830. end;
  2831. end;
  2832. var
  2833. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2834. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2835. NewSize: topsize; NewOffset: asizeint;
  2836. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2837. SourceRef, TargetRef: TReference;
  2838. MovAligned, MovUnaligned: TAsmOp;
  2839. ThisRef: TReference;
  2840. JumpTracking: TLinkedList;
  2841. begin
  2842. Result:=false;
  2843. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2844. { remove mov reg1,reg1? }
  2845. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2846. then
  2847. begin
  2848. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2849. { take care of the register (de)allocs following p }
  2850. RemoveCurrentP(p, hp1);
  2851. Result:=true;
  2852. exit;
  2853. end;
  2854. { All the next optimisations require a next instruction }
  2855. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2856. Exit;
  2857. { Prevent compiler warnings }
  2858. p_TargetReg := NR_NO;
  2859. if taicpu(p).oper[1]^.typ = top_reg then
  2860. begin
  2861. { Saves on a large number of dereferences }
  2862. p_TargetReg := taicpu(p).oper[1]^.reg;
  2863. { Look for:
  2864. mov %reg1,%reg2
  2865. ??? %reg2,r/m
  2866. Change to:
  2867. mov %reg1,%reg2
  2868. ??? %reg1,r/m
  2869. }
  2870. if taicpu(p).oper[0]^.typ = top_reg then
  2871. begin
  2872. if RegReadByInstruction(p_TargetReg, hp1) and
  2873. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2874. begin
  2875. { A change has occurred, just not in p }
  2876. Result := True;
  2877. TransferUsedRegs(TmpUsedRegs);
  2878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2879. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2880. { Just in case something didn't get modified (e.g. an
  2881. implicit register) }
  2882. not RegReadByInstruction(p_TargetReg, hp1) then
  2883. begin
  2884. { We can remove the original MOV }
  2885. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2886. RemoveCurrentp(p, hp1);
  2887. { UsedRegs got updated by RemoveCurrentp }
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. { If we know a MOV instruction has become a null operation, we might as well
  2892. get rid of it now to save time. }
  2893. if (taicpu(hp1).opcode = A_MOV) and
  2894. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2895. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2896. { Just being a register is enough to confirm it's a null operation }
  2897. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2898. begin
  2899. Result := True;
  2900. { Speed-up to reduce a pipeline stall... if we had something like...
  2901. movl %eax,%edx
  2902. movw %dx,%ax
  2903. ... the second instruction would change to movw %ax,%ax, but
  2904. given that it is now %ax that's active rather than %eax,
  2905. penalties might occur due to a partial register write, so instead,
  2906. change it to a MOVZX instruction when optimising for speed.
  2907. }
  2908. if not (cs_opt_size in current_settings.optimizerswitches) and
  2909. IsMOVZXAcceptable and
  2910. (taicpu(hp1).opsize < taicpu(p).opsize)
  2911. {$ifdef x86_64}
  2912. { operations already implicitly set the upper 64 bits to zero }
  2913. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2914. {$endif x86_64}
  2915. then
  2916. begin
  2917. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2918. case taicpu(p).opsize of
  2919. S_W:
  2920. if taicpu(hp1).opsize = S_B then
  2921. taicpu(hp1).opsize := S_BL
  2922. else
  2923. InternalError(2020012911);
  2924. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2925. case taicpu(hp1).opsize of
  2926. S_B:
  2927. taicpu(hp1).opsize := S_BL;
  2928. S_W:
  2929. taicpu(hp1).opsize := S_WL;
  2930. else
  2931. InternalError(2020012912);
  2932. end;
  2933. else
  2934. InternalError(2020012910);
  2935. end;
  2936. taicpu(hp1).opcode := A_MOVZX;
  2937. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2938. end
  2939. else
  2940. begin
  2941. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2942. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2943. RemoveInstruction(hp1);
  2944. { The instruction after what was hp1 is now the immediate next instruction,
  2945. so we can continue to make optimisations if it's present }
  2946. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2947. Exit;
  2948. hp1 := hp2;
  2949. end;
  2950. end;
  2951. end;
  2952. end;
  2953. end;
  2954. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2955. overwrites the original destination register. e.g.
  2956. movl ###,%reg2d
  2957. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2958. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2959. }
  2960. if (taicpu(p).oper[1]^.typ = top_reg) and
  2961. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2962. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2963. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2964. begin
  2965. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2966. begin
  2967. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2968. case taicpu(p).oper[0]^.typ of
  2969. top_const:
  2970. { We have something like:
  2971. movb $x, %regb
  2972. movzbl %regb,%regd
  2973. Change to:
  2974. movl $x, %regd
  2975. }
  2976. begin
  2977. case taicpu(hp1).opsize of
  2978. S_BW:
  2979. begin
  2980. convert_mov_value(A_MOVSX, $FF);
  2981. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2982. taicpu(p).opsize := S_W;
  2983. end;
  2984. S_BL:
  2985. begin
  2986. convert_mov_value(A_MOVSX, $FF);
  2987. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2988. taicpu(p).opsize := S_L;
  2989. end;
  2990. S_WL:
  2991. begin
  2992. convert_mov_value(A_MOVSX, $FFFF);
  2993. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2994. taicpu(p).opsize := S_L;
  2995. end;
  2996. {$ifdef x86_64}
  2997. S_BQ:
  2998. begin
  2999. convert_mov_value(A_MOVSX, $FF);
  3000. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3001. taicpu(p).opsize := S_Q;
  3002. end;
  3003. S_WQ:
  3004. begin
  3005. convert_mov_value(A_MOVSX, $FFFF);
  3006. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3007. taicpu(p).opsize := S_Q;
  3008. end;
  3009. S_LQ:
  3010. begin
  3011. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3012. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3013. taicpu(p).opsize := S_Q;
  3014. end;
  3015. {$endif x86_64}
  3016. else
  3017. { If hp1 was a MOV instruction, it should have been
  3018. optimised already }
  3019. InternalError(2020021001);
  3020. end;
  3021. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3022. RemoveInstruction(hp1);
  3023. Result := True;
  3024. Exit;
  3025. end;
  3026. top_ref:
  3027. begin
  3028. { We have something like:
  3029. movb mem, %regb
  3030. movzbl %regb,%regd
  3031. Change to:
  3032. movzbl mem, %regd
  3033. }
  3034. ThisRef := taicpu(p).oper[0]^.ref^;
  3035. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3036. begin
  3037. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3038. taicpu(hp1).loadref(0, ThisRef);
  3039. { Make sure any registers in the references are properly tracked }
  3040. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  3041. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  3042. if (ThisRef.index <> NR_NO) then
  3043. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  3044. RemoveCurrentP(p, hp1);
  3045. Result := True;
  3046. Exit;
  3047. end;
  3048. end;
  3049. else
  3050. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3051. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3052. Exit;
  3053. end;
  3054. end
  3055. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3056. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3057. optimised }
  3058. else
  3059. begin
  3060. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3061. RemoveCurrentP(p, hp1);
  3062. Result := True;
  3063. Exit;
  3064. end;
  3065. end;
  3066. if (taicpu(hp1).opcode = A_AND) and
  3067. (taicpu(p).oper[1]^.typ = top_reg) and
  3068. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3069. begin
  3070. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3071. begin
  3072. case taicpu(p).opsize of
  3073. S_L:
  3074. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3075. begin
  3076. { Optimize out:
  3077. mov x, %reg
  3078. and ffffffffh, %reg
  3079. }
  3080. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3081. RemoveInstruction(hp1);
  3082. Result:=true;
  3083. exit;
  3084. end;
  3085. S_Q: { TODO: Confirm if this is even possible }
  3086. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3087. begin
  3088. { Optimize out:
  3089. mov x, %reg
  3090. and ffffffffffffffffh, %reg
  3091. }
  3092. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3093. RemoveInstruction(hp1);
  3094. Result:=true;
  3095. exit;
  3096. end;
  3097. else
  3098. ;
  3099. end;
  3100. if (
  3101. (taicpu(p).oper[0]^.typ=top_reg) or
  3102. (
  3103. (taicpu(p).oper[0]^.typ=top_ref) and
  3104. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3105. )
  3106. ) and
  3107. GetNextInstruction(hp1,hp2) and
  3108. MatchInstruction(hp2,A_TEST,[]) and
  3109. (
  3110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3111. (
  3112. { If the register being tested is smaller than the one
  3113. that received a bitwise AND, permit it if the constant
  3114. fits into the smaller size }
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3116. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3117. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3118. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3119. (
  3120. (
  3121. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3122. (taicpu(hp1).oper[0]^.val <= $FF)
  3123. ) or
  3124. (
  3125. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3126. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3127. {$ifdef x86_64}
  3128. ) or
  3129. (
  3130. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3131. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3132. {$endif x86_64}
  3133. )
  3134. )
  3135. )
  3136. ) and
  3137. (
  3138. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3139. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3140. ) and
  3141. GetNextInstruction(hp2,hp3) and
  3142. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3143. (taicpu(hp3).condition in [C_E,C_NE]) then
  3144. begin
  3145. TransferUsedRegs(TmpUsedRegs);
  3146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3147. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3148. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3149. begin
  3150. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3151. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3152. taicpu(hp1).opcode:=A_TEST;
  3153. { Shrink the TEST instruction down to the smallest possible size }
  3154. case taicpu(hp1).oper[0]^.val of
  3155. 0..255:
  3156. if (taicpu(hp1).opsize <> S_B)
  3157. {$ifndef x86_64}
  3158. and (
  3159. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3160. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3161. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3162. )
  3163. {$endif x86_64}
  3164. then
  3165. begin
  3166. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3167. { Only print debug message if the TEST instruction
  3168. is a different size before and after }
  3169. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3170. taicpu(hp1).opsize := S_B;
  3171. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3172. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3173. end;
  3174. 256..65535:
  3175. if (taicpu(hp1).opsize <> S_W) then
  3176. begin
  3177. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3178. { Only print debug message if the TEST instruction
  3179. is a different size before and after }
  3180. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3181. taicpu(hp1).opsize := S_W;
  3182. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3183. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3184. end;
  3185. {$ifdef x86_64}
  3186. 65536..$7FFFFFFF:
  3187. if (taicpu(hp1).opsize <> S_L) then
  3188. begin
  3189. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3190. { Only print debug message if the TEST instruction
  3191. is a different size before and after }
  3192. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3193. taicpu(hp1).opsize := S_L;
  3194. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3195. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3196. end;
  3197. {$endif x86_64}
  3198. else
  3199. ;
  3200. end;
  3201. RemoveInstruction(hp2);
  3202. RemoveCurrentP(p, hp1);
  3203. Result:=true;
  3204. exit;
  3205. end;
  3206. end;
  3207. end
  3208. else if IsMOVZXAcceptable and
  3209. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3210. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3211. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3212. then
  3213. begin
  3214. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3215. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3216. case taicpu(p).opsize of
  3217. S_B:
  3218. if (taicpu(hp1).oper[0]^.val = $ff) then
  3219. begin
  3220. { Convert:
  3221. movb x, %regl movb x, %regl
  3222. andw ffh, %regw andl ffh, %regd
  3223. To:
  3224. movzbw x, %regd movzbl x, %regd
  3225. (Identical registers, just different sizes)
  3226. }
  3227. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3228. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3229. case taicpu(hp1).opsize of
  3230. S_W: NewSize := S_BW;
  3231. S_L: NewSize := S_BL;
  3232. {$ifdef x86_64}
  3233. S_Q: NewSize := S_BQ;
  3234. {$endif x86_64}
  3235. else
  3236. InternalError(2018011510);
  3237. end;
  3238. end
  3239. else
  3240. NewSize := S_NO;
  3241. S_W:
  3242. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3243. begin
  3244. { Convert:
  3245. movw x, %regw
  3246. andl ffffh, %regd
  3247. To:
  3248. movzwl x, %regd
  3249. (Identical registers, just different sizes)
  3250. }
  3251. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3252. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3253. case taicpu(hp1).opsize of
  3254. S_L: NewSize := S_WL;
  3255. {$ifdef x86_64}
  3256. S_Q: NewSize := S_WQ;
  3257. {$endif x86_64}
  3258. else
  3259. InternalError(2018011511);
  3260. end;
  3261. end
  3262. else
  3263. NewSize := S_NO;
  3264. else
  3265. NewSize := S_NO;
  3266. end;
  3267. if NewSize <> S_NO then
  3268. begin
  3269. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3270. { The actual optimization }
  3271. taicpu(p).opcode := A_MOVZX;
  3272. taicpu(p).changeopsize(NewSize);
  3273. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3274. { Safeguard if "and" is followed by a conditional command }
  3275. TransferUsedRegs(TmpUsedRegs);
  3276. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3277. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3278. begin
  3279. { At this point, the "and" command is effectively equivalent to
  3280. "test %reg,%reg". This will be handled separately by the
  3281. Peephole Optimizer. [Kit] }
  3282. DebugMsg(SPeepholeOptimization + PreMessage +
  3283. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3284. end
  3285. else
  3286. begin
  3287. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3288. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3289. RemoveInstruction(hp1);
  3290. end;
  3291. Result := True;
  3292. Exit;
  3293. end;
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).opcode = A_OR) and
  3297. (taicpu(p).oper[1]^.typ = top_reg) and
  3298. MatchOperand(taicpu(p).oper[0]^, 0) and
  3299. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3300. begin
  3301. { mov 0, %reg
  3302. or ###,%reg
  3303. Change to (only if the flags are not used):
  3304. mov ###,%reg
  3305. }
  3306. TransferUsedRegs(TmpUsedRegs);
  3307. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3308. DoOptimisation := True;
  3309. { Even if the flags are used, we might be able to do the optimisation
  3310. if the conditions are predictable }
  3311. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3312. begin
  3313. { Only perform if ### = %reg (the same register) or equal to 0,
  3314. so %reg is guaranteed to still have a value of zero }
  3315. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3316. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3317. begin
  3318. hp2 := hp1;
  3319. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3320. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3321. GetNextInstruction(hp2, hp3) do
  3322. begin
  3323. { Don't continue modifying if the flags state is getting changed }
  3324. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3325. Break;
  3326. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3327. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3328. begin
  3329. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3330. begin
  3331. { Condition is always true }
  3332. case taicpu(hp3).opcode of
  3333. A_Jcc:
  3334. begin
  3335. { Check for jump shortcuts before we destroy the condition }
  3336. hp4 := hp3;
  3337. DoJumpOptimizations(hp3, TempBool);
  3338. { Make sure hp3 hasn't changed }
  3339. if (hp4 = hp3) then
  3340. begin
  3341. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3342. MakeUnconditional(taicpu(hp3));
  3343. end;
  3344. Result := True;
  3345. end;
  3346. A_CMOVcc:
  3347. begin
  3348. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3349. taicpu(hp3).opcode := A_MOV;
  3350. taicpu(hp3).condition := C_None;
  3351. Result := True;
  3352. end;
  3353. A_SETcc:
  3354. begin
  3355. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3356. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3357. taicpu(hp3).opcode := A_MOV;
  3358. taicpu(hp3).ops := 2;
  3359. taicpu(hp3).condition := C_None;
  3360. taicpu(hp3).opsize := S_B;
  3361. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3362. taicpu(hp3).loadconst(0, 1);
  3363. Result := True;
  3364. end;
  3365. else
  3366. InternalError(2021090701);
  3367. end;
  3368. end
  3369. 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
  3370. begin
  3371. { Condition is always false }
  3372. case taicpu(hp3).opcode of
  3373. A_Jcc:
  3374. begin
  3375. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3376. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3377. RemoveInstruction(hp3);
  3378. Result := True;
  3379. { Since hp3 was deleted, hp2 must not be updated }
  3380. Continue;
  3381. end;
  3382. A_CMOVcc:
  3383. begin
  3384. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3385. RemoveInstruction(hp3);
  3386. Result := True;
  3387. { Since hp3 was deleted, hp2 must not be updated }
  3388. Continue;
  3389. end;
  3390. A_SETcc:
  3391. begin
  3392. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3393. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3394. taicpu(hp3).opcode := A_MOV;
  3395. taicpu(hp3).ops := 2;
  3396. taicpu(hp3).condition := C_None;
  3397. taicpu(hp3).opsize := S_B;
  3398. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3399. taicpu(hp3).loadconst(0, 0);
  3400. Result := True;
  3401. end;
  3402. else
  3403. InternalError(2021090702);
  3404. end;
  3405. end
  3406. else
  3407. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3408. DoOptimisation := False;
  3409. end;
  3410. hp2 := hp3;
  3411. end;
  3412. { Flags are still in use - don't optimise }
  3413. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3414. DoOptimisation := False;
  3415. end
  3416. else
  3417. DoOptimisation := False;
  3418. end;
  3419. if DoOptimisation then
  3420. begin
  3421. {$ifdef x86_64}
  3422. { OR only supports 32-bit sign-extended constants for 64-bit
  3423. instructions, so compensate for this if the constant is
  3424. encoded as a value greater than or equal to 2^31 }
  3425. if (taicpu(hp1).opsize = S_Q) and
  3426. (taicpu(hp1).oper[0]^.typ = top_const) and
  3427. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3428. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3429. {$endif x86_64}
  3430. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3431. taicpu(hp1).opcode := A_MOV;
  3432. RemoveCurrentP(p, hp1);
  3433. Result := True;
  3434. Exit;
  3435. end;
  3436. end;
  3437. { Next instruction is also a MOV ? }
  3438. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3439. begin
  3440. if MatchOpType(taicpu(p), top_const, top_ref) and
  3441. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3442. TryConstMerge(p, hp1) then
  3443. begin
  3444. Result := True;
  3445. { In case we have four byte writes in a row, check for 2 more
  3446. right now so we don't have to wait for another iteration of
  3447. pass 1
  3448. }
  3449. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3450. case taicpu(p).opsize of
  3451. S_W:
  3452. begin
  3453. if GetNextInstruction(p, hp1) and
  3454. MatchInstruction(hp1, A_MOV, [S_B]) and
  3455. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3456. GetNextInstruction(hp1, hp2) and
  3457. MatchInstruction(hp2, A_MOV, [S_B]) and
  3458. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3459. { Try to merge the two bytes }
  3460. TryConstMerge(hp1, hp2) then
  3461. { Now try to merge the two words (hp2 will get deleted) }
  3462. TryConstMerge(p, hp1);
  3463. end;
  3464. S_L:
  3465. begin
  3466. { Though this only really benefits x86_64 and not i386, it
  3467. gets a potential optimisation done faster and hence
  3468. reduces the number of times OptPass1MOV is entered }
  3469. if GetNextInstruction(p, hp1) and
  3470. MatchInstruction(hp1, A_MOV, [S_W]) and
  3471. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3472. GetNextInstruction(hp1, hp2) and
  3473. MatchInstruction(hp2, A_MOV, [S_W]) and
  3474. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3475. { Try to merge the two words }
  3476. TryConstMerge(hp1, hp2) then
  3477. { This will always fail on i386, so don't bother
  3478. calling it unless we're doing x86_64 }
  3479. {$ifdef x86_64}
  3480. { Now try to merge the two longwords (hp2 will get deleted) }
  3481. TryConstMerge(p, hp1)
  3482. {$endif x86_64}
  3483. ;
  3484. end;
  3485. else
  3486. ;
  3487. end;
  3488. Exit;
  3489. end;
  3490. if (taicpu(p).oper[1]^.typ = top_reg) and
  3491. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3492. begin
  3493. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3494. TransferUsedRegs(TmpUsedRegs);
  3495. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3496. { we have
  3497. mov x, %treg
  3498. mov %treg, y
  3499. }
  3500. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3501. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3502. { we've got
  3503. mov x, %treg
  3504. mov %treg, y
  3505. with %treg is not used after }
  3506. case taicpu(p).oper[0]^.typ Of
  3507. { top_reg is covered by DeepMOVOpt }
  3508. top_const:
  3509. begin
  3510. { change
  3511. mov const, %treg
  3512. mov %treg, y
  3513. to
  3514. mov const, y
  3515. }
  3516. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3517. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3518. begin
  3519. if taicpu(hp1).oper[1]^.typ=top_reg then
  3520. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3521. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3522. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3523. RemoveInstruction(hp1);
  3524. Result:=true;
  3525. Exit;
  3526. end;
  3527. end;
  3528. top_ref:
  3529. case taicpu(hp1).oper[1]^.typ of
  3530. top_reg:
  3531. begin
  3532. { change
  3533. mov mem, %treg
  3534. mov %treg, %reg
  3535. to
  3536. mov mem, %reg"
  3537. }
  3538. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3539. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3540. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3541. RemoveInstruction(hp1);
  3542. Result:=true;
  3543. Exit;
  3544. end;
  3545. top_ref:
  3546. begin
  3547. {$ifdef x86_64}
  3548. { Look for the following to simplify:
  3549. mov x(mem1), %reg
  3550. mov %reg, y(mem2)
  3551. mov x+8(mem1), %reg
  3552. mov %reg, y+8(mem2)
  3553. Change to:
  3554. movdqu x(mem1), %xmmreg
  3555. movdqu %xmmreg, y(mem2)
  3556. ...but only as long as the memory blocks don't overlap
  3557. }
  3558. SourceRef := taicpu(p).oper[0]^.ref^;
  3559. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3560. if (taicpu(p).opsize = S_Q) and
  3561. GetNextInstruction(hp1, hp2) and
  3562. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3563. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3564. begin
  3565. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3567. Inc(SourceRef.offset, 8);
  3568. if UseAVX then
  3569. begin
  3570. MovAligned := A_VMOVDQA;
  3571. MovUnaligned := A_VMOVDQU;
  3572. end
  3573. else
  3574. begin
  3575. MovAligned := A_MOVDQA;
  3576. MovUnaligned := A_MOVDQU;
  3577. end;
  3578. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3579. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3580. begin
  3581. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3582. Inc(TargetRef.offset, 8);
  3583. if GetNextInstruction(hp2, hp3) and
  3584. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3585. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3586. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3587. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3588. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3589. begin
  3590. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3591. if NewMMReg <> NR_NO then
  3592. begin
  3593. { Remember that the offsets are 8 ahead }
  3594. if ((SourceRef.offset mod 16) = 8) and
  3595. (
  3596. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3597. (SourceRef.base = current_procinfo.framepointer) or
  3598. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3599. ) then
  3600. taicpu(p).opcode := MovAligned
  3601. else
  3602. taicpu(p).opcode := MovUnaligned;
  3603. taicpu(p).opsize := S_XMM;
  3604. taicpu(p).oper[1]^.reg := NewMMReg;
  3605. if ((TargetRef.offset mod 16) = 8) and
  3606. (
  3607. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3608. (TargetRef.base = current_procinfo.framepointer) or
  3609. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3610. ) then
  3611. taicpu(hp1).opcode := MovAligned
  3612. else
  3613. taicpu(hp1).opcode := MovUnaligned;
  3614. taicpu(hp1).opsize := S_XMM;
  3615. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3616. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3617. RemoveInstruction(hp2);
  3618. RemoveInstruction(hp3);
  3619. Result := True;
  3620. Exit;
  3621. end;
  3622. end;
  3623. end
  3624. else
  3625. begin
  3626. { See if the next references are 8 less rather than 8 greater }
  3627. Dec(SourceRef.offset, 16); { -8 the other way }
  3628. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3629. begin
  3630. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3631. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3632. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3633. GetNextInstruction(hp2, hp3) and
  3634. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3635. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3636. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3637. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3638. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3639. begin
  3640. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3641. if NewMMReg <> NR_NO then
  3642. begin
  3643. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3644. if ((SourceRef.offset mod 16) = 0) and
  3645. (
  3646. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3647. (SourceRef.base = current_procinfo.framepointer) or
  3648. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3649. ) then
  3650. taicpu(hp2).opcode := MovAligned
  3651. else
  3652. taicpu(hp2).opcode := MovUnaligned;
  3653. taicpu(hp2).opsize := S_XMM;
  3654. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3655. if ((TargetRef.offset mod 16) = 0) and
  3656. (
  3657. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3658. (TargetRef.base = current_procinfo.framepointer) or
  3659. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3660. ) then
  3661. taicpu(hp3).opcode := MovAligned
  3662. else
  3663. taicpu(hp3).opcode := MovUnaligned;
  3664. taicpu(hp3).opsize := S_XMM;
  3665. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3666. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3667. RemoveInstruction(hp1);
  3668. RemoveCurrentP(p, hp2);
  3669. Result := True;
  3670. Exit;
  3671. end;
  3672. end;
  3673. end;
  3674. end;
  3675. end;
  3676. {$endif x86_64}
  3677. end;
  3678. else
  3679. { The write target should be a reg or a ref }
  3680. InternalError(2021091601);
  3681. end;
  3682. else
  3683. ;
  3684. end
  3685. else
  3686. { %treg is used afterwards, but all eventualities
  3687. other than the first MOV instruction being a constant
  3688. are covered by DeepMOVOpt, so only check for that }
  3689. if (taicpu(p).oper[0]^.typ = top_const) and
  3690. (
  3691. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3692. not (cs_opt_size in current_settings.optimizerswitches) or
  3693. (taicpu(hp1).opsize = S_B)
  3694. ) and
  3695. (
  3696. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3697. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3698. ) then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3701. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3702. end;
  3703. end;
  3704. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3705. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3706. { mov reg1, mem1 or mov mem1, reg1
  3707. mov mem2, reg2 mov reg2, mem2}
  3708. begin
  3709. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3710. { mov reg1, mem1 or mov mem1, reg1
  3711. mov mem2, reg1 mov reg2, mem1}
  3712. begin
  3713. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3714. { Removes the second statement from
  3715. mov reg1, mem1/reg2
  3716. mov mem1/reg2, reg1 }
  3717. begin
  3718. if taicpu(p).oper[0]^.typ=top_reg then
  3719. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3720. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3721. RemoveInstruction(hp1);
  3722. Result:=true;
  3723. exit;
  3724. end
  3725. else
  3726. begin
  3727. TransferUsedRegs(TmpUsedRegs);
  3728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3729. if (taicpu(p).oper[1]^.typ = top_ref) and
  3730. { mov reg1, mem1
  3731. mov mem2, reg1 }
  3732. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3733. GetNextInstruction(hp1, hp2) and
  3734. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3735. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3736. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3737. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3738. { change to
  3739. mov reg1, mem1 mov reg1, mem1
  3740. mov mem2, reg1 cmp reg1, mem2
  3741. cmp mem1, reg1
  3742. }
  3743. begin
  3744. RemoveInstruction(hp2);
  3745. taicpu(hp1).opcode := A_CMP;
  3746. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3747. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3748. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3749. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3750. end;
  3751. end;
  3752. end
  3753. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3754. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3755. begin
  3756. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3757. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3758. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3759. end
  3760. else
  3761. begin
  3762. TransferUsedRegs(TmpUsedRegs);
  3763. if GetNextInstruction(hp1, hp2) and
  3764. MatchOpType(taicpu(p),top_ref,top_reg) and
  3765. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3766. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3767. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3768. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3769. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3770. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3771. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3772. { mov mem1, %reg1
  3773. mov %reg1, mem2
  3774. mov mem2, reg2
  3775. to:
  3776. mov mem1, reg2
  3777. mov reg2, mem2}
  3778. begin
  3779. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3780. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3781. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3782. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3783. RemoveInstruction(hp2);
  3784. Result := True;
  3785. end
  3786. {$ifdef i386}
  3787. { this is enabled for i386 only, as the rules to create the reg sets below
  3788. are too complicated for x86-64, so this makes this code too error prone
  3789. on x86-64
  3790. }
  3791. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3792. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3793. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3794. { mov mem1, reg1 mov mem1, reg1
  3795. mov reg1, mem2 mov reg1, mem2
  3796. mov mem2, reg2 mov mem2, reg1
  3797. to: to:
  3798. mov mem1, reg1 mov mem1, reg1
  3799. mov mem1, reg2 mov reg1, mem2
  3800. mov reg1, mem2
  3801. or (if mem1 depends on reg1
  3802. and/or if mem2 depends on reg2)
  3803. to:
  3804. mov mem1, reg1
  3805. mov reg1, mem2
  3806. mov reg1, reg2
  3807. }
  3808. begin
  3809. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3810. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3811. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3812. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3813. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3814. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3815. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3816. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3817. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3818. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3819. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3820. end
  3821. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3822. begin
  3823. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3824. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3825. end
  3826. else
  3827. begin
  3828. RemoveInstruction(hp2);
  3829. end
  3830. {$endif i386}
  3831. ;
  3832. end;
  3833. end
  3834. { movl [mem1],reg1
  3835. movl [mem1],reg2
  3836. to
  3837. movl [mem1],reg1
  3838. movl reg1,reg2
  3839. }
  3840. else if not CheckMovMov2MovMov2(p, hp1) and
  3841. { movl const1,[mem1]
  3842. movl [mem1],reg1
  3843. to
  3844. movl const1,reg1
  3845. movl reg1,[mem1]
  3846. }
  3847. MatchOpType(Taicpu(p),top_const,top_ref) and
  3848. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3849. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3850. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3851. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3852. begin
  3853. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3854. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3855. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3856. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3857. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3858. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3859. Result:=true;
  3860. exit;
  3861. end;
  3862. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3863. { Change:
  3864. movl %reg1,%reg2
  3865. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3866. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3867. To:
  3868. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3869. movl x(%reg1),%reg1
  3870. movl %reg1,%regX
  3871. }
  3872. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3873. begin
  3874. p_SourceReg := taicpu(p).oper[0]^.reg;
  3875. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3876. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3877. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3878. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3879. GetNextInstruction(hp1, hp2) and
  3880. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3881. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3882. begin
  3883. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3884. if RegInRef(p_TargetReg, SourceRef) and
  3885. { If %reg1 also appears in the second reference, then it will
  3886. not refer to the same memory block as the first reference }
  3887. not RegInRef(p_SourceReg, SourceRef) then
  3888. begin
  3889. { Check to see if the references match if %reg2 is changed to %reg1 }
  3890. if SourceRef.base = p_TargetReg then
  3891. SourceRef.base := p_SourceReg;
  3892. if SourceRef.index = p_TargetReg then
  3893. SourceRef.index := p_SourceReg;
  3894. { RefsEqual also checks to ensure both references are non-volatile }
  3895. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3896. begin
  3897. taicpu(hp2).loadreg(0, p_SourceReg);
  3898. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3899. Result := True;
  3900. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3901. begin
  3902. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3903. RemoveCurrentP(p, hp1);
  3904. Exit;
  3905. end
  3906. else
  3907. begin
  3908. { Check to see if %reg2 is no longer in use }
  3909. TransferUsedRegs(TmpUsedRegs);
  3910. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3911. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3912. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3913. begin
  3914. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3915. RemoveCurrentP(p, hp1);
  3916. Exit;
  3917. end;
  3918. end;
  3919. { If we reach this point, p and hp1 weren't actually modified,
  3920. so we can do a bit more work on this pass }
  3921. end;
  3922. end;
  3923. end;
  3924. end;
  3925. end;
  3926. {$ifdef x86_64}
  3927. { Change:
  3928. movl %reg1l,%reg2l
  3929. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3930. To:
  3931. movl %reg1l,%reg2l
  3932. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3933. If %reg1 = %reg3, convert to:
  3934. movl %reg1l,%reg2l
  3935. andl %reg1l,%reg1l
  3936. }
  3937. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3938. MatchOpType(taicpu(p), top_reg, top_reg) and
  3939. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3940. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3941. begin
  3942. TransferUsedRegs(TmpUsedRegs);
  3943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3944. taicpu(hp1).opsize := S_L;
  3945. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3946. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3947. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3948. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3949. begin
  3950. { %reg1 = %reg3 }
  3951. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3952. taicpu(hp1).opcode := A_AND;
  3953. end
  3954. else
  3955. begin
  3956. { %reg1 <> %reg3 }
  3957. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3958. end;
  3959. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3962. RemoveCurrentP(p, hp1);
  3963. Result := True;
  3964. Exit;
  3965. end
  3966. else
  3967. begin
  3968. { Initial instruction wasn't actually changed }
  3969. Include(OptsToCheck, aoc_ForceNewIteration);
  3970. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3971. appears below since %reg1 has technically changed }
  3972. if taicpu(hp1).opcode = A_AND then
  3973. Exit;
  3974. end;
  3975. end;
  3976. {$endif x86_64}
  3977. { search further than the next instruction for a mov (as long as it's not a jump) }
  3978. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3979. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3980. (taicpu(p).oper[1]^.typ = top_reg) and
  3981. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3982. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3983. begin
  3984. { we work with hp2 here, so hp1 can be still used later on when
  3985. checking for GetNextInstruction_p }
  3986. hp3 := hp1;
  3987. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3988. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3989. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3990. TransferUsedRegs(TmpUsedRegs);
  3991. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3992. if NotFirstIteration then
  3993. JumpTracking := TLinkedList.Create
  3994. else
  3995. JumpTracking := nil;
  3996. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3997. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3998. (hp2.typ=ait_instruction) do
  3999. begin
  4000. case taicpu(hp2).opcode of
  4001. A_POP:
  4002. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4003. begin
  4004. if not CrossJump and
  4005. not RegUsedBetween(p_TargetReg, p, hp2) then
  4006. begin
  4007. { We can remove the original MOV since the register
  4008. wasn't used between it and its popping from the stack }
  4009. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4010. RemoveCurrentp(p, hp1);
  4011. Result := True;
  4012. JumpTracking.Free;
  4013. Exit;
  4014. end;
  4015. { Can't go any further }
  4016. Break;
  4017. end;
  4018. A_MOV:
  4019. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4020. ((taicpu(p).oper[0]^.typ=top_const) or
  4021. ((taicpu(p).oper[0]^.typ=top_reg) and
  4022. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4023. )
  4024. ) then
  4025. begin
  4026. { we have
  4027. mov x, %treg
  4028. mov %treg, y
  4029. }
  4030. { We don't need to call UpdateUsedRegs for every instruction between
  4031. p and hp2 because the register we're concerned about will not
  4032. become deallocated (otherwise GetNextInstructionUsingReg would
  4033. have stopped at an earlier instruction). [Kit] }
  4034. TempRegUsed :=
  4035. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4036. RegReadByInstruction(p_TargetReg, hp3) or
  4037. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4038. case taicpu(p).oper[0]^.typ Of
  4039. top_reg:
  4040. begin
  4041. { change
  4042. mov %reg, %treg
  4043. mov %treg, y
  4044. to
  4045. mov %reg, y
  4046. }
  4047. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4048. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4049. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4050. begin
  4051. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4052. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4053. if TempRegUsed then
  4054. begin
  4055. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4056. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4057. { Set the start of the next GetNextInstructionUsingRegCond search
  4058. to start at the entry right before hp2 (which is about to be removed) }
  4059. hp3 := tai(hp2.Previous);
  4060. RemoveInstruction(hp2);
  4061. Include(OptsToCheck, aoc_ForceNewIteration);
  4062. { See if there's more we can optimise }
  4063. Continue;
  4064. end
  4065. else
  4066. begin
  4067. RemoveInstruction(hp2);
  4068. { We can remove the original MOV too }
  4069. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4070. RemoveCurrentP(p, hp1);
  4071. Result:=true;
  4072. JumpTracking.Free;
  4073. Exit;
  4074. end;
  4075. end
  4076. else
  4077. begin
  4078. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4079. taicpu(hp2).loadReg(0, p_SourceReg);
  4080. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4081. { Check to see if the register also appears in the reference }
  4082. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4083. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4084. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4085. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4086. begin
  4087. { Don't remove the first instruction if the temporary register is in use }
  4088. if not TempRegUsed then
  4089. begin
  4090. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4091. RemoveCurrentP(p, hp1);
  4092. Result:=true;
  4093. JumpTracking.Free;
  4094. Exit;
  4095. end;
  4096. { No need to set Result to True here. If there's another instruction later
  4097. on that can be optimised, it will be detected when the main Pass 1 loop
  4098. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4099. hp3 := hp2;
  4100. Continue;
  4101. end;
  4102. end;
  4103. end;
  4104. top_const:
  4105. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4106. begin
  4107. { change
  4108. mov const, %treg
  4109. mov %treg, y
  4110. to
  4111. mov const, y
  4112. }
  4113. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4114. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4115. begin
  4116. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4117. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4118. if TempRegUsed then
  4119. begin
  4120. { Don't remove the first instruction if the temporary register is in use }
  4121. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4122. { No need to set Result to True. If there's another instruction later on
  4123. that can be optimised, it will be detected when the main Pass 1 loop
  4124. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4125. end
  4126. else
  4127. begin
  4128. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4129. RemoveCurrentP(p, hp1);
  4130. Result:=true;
  4131. Exit;
  4132. end;
  4133. end;
  4134. end;
  4135. else
  4136. Internalerror(2019103001);
  4137. end;
  4138. end
  4139. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4140. begin
  4141. if not CrossJump and
  4142. not RegUsedBetween(p_TargetReg, p, hp2) and
  4143. not RegReadByInstruction(p_TargetReg, hp2) then
  4144. begin
  4145. { Register is not used before it is overwritten }
  4146. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4147. RemoveCurrentp(p, hp1);
  4148. Result := True;
  4149. Exit;
  4150. end;
  4151. if (taicpu(p).oper[0]^.typ = top_const) and
  4152. (taicpu(hp2).oper[0]^.typ = top_const) then
  4153. begin
  4154. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4155. begin
  4156. { Same value - register hasn't changed }
  4157. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4158. RemoveInstruction(hp2);
  4159. Include(OptsToCheck, aoc_ForceNewIteration);
  4160. { See if there's more we can optimise }
  4161. Continue;
  4162. end;
  4163. end;
  4164. {$ifdef x86_64}
  4165. end
  4166. { Change:
  4167. movl %reg1l,%reg2l
  4168. ...
  4169. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4170. To:
  4171. movl %reg1l,%reg2l
  4172. ...
  4173. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4174. If %reg1 = %reg3, convert to:
  4175. movl %reg1l,%reg2l
  4176. ...
  4177. andl %reg1l,%reg1l
  4178. }
  4179. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4180. (taicpu(p).oper[0]^.typ = top_reg) and
  4181. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4182. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4183. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4184. begin
  4185. TempRegUsed :=
  4186. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4187. RegReadByInstruction(p_TargetReg, hp3) or
  4188. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4189. taicpu(hp2).opsize := S_L;
  4190. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4191. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4192. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4193. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4194. begin
  4195. { %reg1 = %reg3 }
  4196. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4197. taicpu(hp2).opcode := A_AND;
  4198. end
  4199. else
  4200. begin
  4201. { %reg1 <> %reg3 }
  4202. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4203. end;
  4204. if not TempRegUsed then
  4205. begin
  4206. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4207. RemoveCurrentP(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end
  4211. else
  4212. begin
  4213. { Initial instruction wasn't actually changed }
  4214. Include(OptsToCheck, aoc_ForceNewIteration);
  4215. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4216. appears below since %reg1 has technically changed }
  4217. if taicpu(hp2).opcode = A_AND then
  4218. Break;
  4219. end;
  4220. {$endif x86_64}
  4221. end
  4222. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4223. GetNextInstruction(hp2, hp4) and
  4224. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4225. { Optimise the following first:
  4226. movl [mem1],reg1
  4227. movl [mem1],reg2
  4228. to
  4229. movl [mem1],reg1
  4230. movl reg1,reg2
  4231. If [mem1] contains the target register and reg1 is the
  4232. the source register, this optimisation will get missed
  4233. and produce less efficient code later on.
  4234. }
  4235. if CheckMovMov2MovMov2(hp2, hp4) then
  4236. { Initial instruction wasn't actually changed }
  4237. Include(OptsToCheck, aoc_ForceNewIteration);
  4238. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4239. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4240. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4241. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4242. begin
  4243. {
  4244. Change from:
  4245. mov ###, %reg
  4246. ...
  4247. movs/z %reg,%reg (Same register, just different sizes)
  4248. To:
  4249. movs/z ###, %reg (Longer version)
  4250. ...
  4251. (remove)
  4252. }
  4253. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4254. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4255. { Keep the first instruction as mov if ### is a constant }
  4256. if taicpu(p).oper[0]^.typ = top_const then
  4257. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4258. else
  4259. begin
  4260. taicpu(p).opcode := taicpu(hp2).opcode;
  4261. taicpu(p).opsize := taicpu(hp2).opsize;
  4262. end;
  4263. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4264. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4265. RemoveInstruction(hp2);
  4266. Result := True;
  4267. JumpTracking.Free;
  4268. Exit;
  4269. end;
  4270. else
  4271. { Move down to the if-block below };
  4272. end;
  4273. { Also catches MOV/S/Z instructions that aren't modified }
  4274. if taicpu(p).oper[0]^.typ = top_reg then
  4275. begin
  4276. p_SourceReg := taicpu(p).oper[0]^.reg;
  4277. if
  4278. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4279. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4280. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4281. begin
  4282. Result := True;
  4283. { Just in case something didn't get modified (e.g. an
  4284. implicit register). Also, if it does read from this
  4285. register, then there's no longer an advantage to
  4286. changing the register on subsequent instructions.}
  4287. if not RegReadByInstruction(p_TargetReg, hp2) then
  4288. begin
  4289. { If a conditional jump was crossed, do not delete
  4290. the original MOV no matter what }
  4291. if not CrossJump and
  4292. { RegEndOfLife returns True if the register is
  4293. deallocated before the next instruction or has
  4294. been loaded with a new value }
  4295. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4296. begin
  4297. { We can remove the original MOV }
  4298. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4299. RemoveCurrentp(p, hp1);
  4300. JumpTracking.Free;
  4301. Result := True;
  4302. Exit;
  4303. end;
  4304. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4305. begin
  4306. { See if there's more we can optimise }
  4307. hp3 := hp2;
  4308. Continue;
  4309. end;
  4310. end;
  4311. end;
  4312. end;
  4313. { Break out of the while loop under normal circumstances }
  4314. Break;
  4315. end;
  4316. JumpTracking.Free;
  4317. end;
  4318. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4319. (taicpu(p).oper[1]^.typ = top_reg) and
  4320. (taicpu(p).opsize = S_L) and
  4321. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4322. (hp2.typ = ait_instruction) and
  4323. (taicpu(hp2).opcode = A_AND) and
  4324. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4325. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4326. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4327. ) then
  4328. begin
  4329. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4330. begin
  4331. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4332. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4333. begin
  4334. { Optimize out:
  4335. mov x, %reg
  4336. and ffffffffh, %reg
  4337. }
  4338. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4339. RemoveInstruction(hp2);
  4340. Result:=true;
  4341. exit;
  4342. end;
  4343. end;
  4344. end;
  4345. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4346. x >= RetOffset) as it doesn't do anything (it writes either to a
  4347. parameter or to the temporary storage room for the function
  4348. result)
  4349. }
  4350. if IsExitCode(hp1) and
  4351. (taicpu(p).oper[1]^.typ = top_ref) and
  4352. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4353. (
  4354. (
  4355. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4356. not (
  4357. assigned(current_procinfo.procdef.funcretsym) and
  4358. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4359. )
  4360. ) or
  4361. { Also discard writes to the stack that are below the base pointer,
  4362. as this is temporary storage rather than a function result on the
  4363. stack, say. }
  4364. (
  4365. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4366. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4367. )
  4368. ) then
  4369. begin
  4370. RemoveCurrentp(p, hp1);
  4371. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4372. RemoveLastDeallocForFuncRes(p);
  4373. Result:=true;
  4374. exit;
  4375. end;
  4376. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4377. begin
  4378. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4379. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4380. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4381. begin
  4382. { change
  4383. mov reg1, mem1
  4384. test/cmp x, mem1
  4385. to
  4386. mov reg1, mem1
  4387. test/cmp x, reg1
  4388. }
  4389. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4390. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4391. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4392. Result := True;
  4393. Exit;
  4394. end;
  4395. if DoMovCmpMemOpt(p, hp1) then
  4396. begin
  4397. Result := True;
  4398. Exit;
  4399. end;
  4400. end;
  4401. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4402. { If the flags register is in use, don't change the instruction to an
  4403. ADD otherwise this will scramble the flags. [Kit] }
  4404. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4405. begin
  4406. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4407. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4408. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4409. ) or
  4410. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4411. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4412. )
  4413. ) then
  4414. { mov reg1,ref
  4415. lea reg2,[reg1,reg2]
  4416. to
  4417. add reg2,ref}
  4418. begin
  4419. TransferUsedRegs(TmpUsedRegs);
  4420. { reg1 may not be used afterwards }
  4421. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4422. begin
  4423. Taicpu(hp1).opcode:=A_ADD;
  4424. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4425. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4426. RemoveCurrentp(p, hp1);
  4427. result:=true;
  4428. exit;
  4429. end;
  4430. end;
  4431. { If the LEA instruction can be converted into an arithmetic instruction,
  4432. it may be possible to then fold it in the next optimisation, otherwise
  4433. there's nothing more that can be optimised here. }
  4434. if not ConvertLEA(taicpu(hp1)) then
  4435. Exit;
  4436. end;
  4437. if (taicpu(p).oper[1]^.typ = top_reg) and
  4438. (hp1.typ = ait_instruction) and
  4439. GetNextInstruction(hp1, hp2) and
  4440. MatchInstruction(hp2,A_MOV,[]) and
  4441. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4442. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4443. (
  4444. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4445. {$ifdef x86_64}
  4446. or
  4447. (
  4448. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4449. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4450. )
  4451. {$endif x86_64}
  4452. ) then
  4453. begin
  4454. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4455. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4456. { change movsX/movzX reg/ref, reg2
  4457. add/sub/or/... reg3/$const, reg2
  4458. mov reg2 reg/ref
  4459. dealloc reg2
  4460. to
  4461. add/sub/or/... reg3/$const, reg/ref }
  4462. begin
  4463. TransferUsedRegs(TmpUsedRegs);
  4464. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4465. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4466. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4467. begin
  4468. { by example:
  4469. movswl %si,%eax movswl %si,%eax p
  4470. decl %eax addl %edx,%eax hp1
  4471. movw %ax,%si movw %ax,%si hp2
  4472. ->
  4473. movswl %si,%eax movswl %si,%eax p
  4474. decw %eax addw %edx,%eax hp1
  4475. movw %ax,%si movw %ax,%si hp2
  4476. }
  4477. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4478. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4479. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4480. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4481. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4482. {
  4483. ->
  4484. movswl %si,%eax movswl %si,%eax p
  4485. decw %si addw %dx,%si hp1
  4486. movw %ax,%si movw %ax,%si hp2
  4487. }
  4488. case taicpu(hp1).ops of
  4489. 1:
  4490. begin
  4491. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4492. if taicpu(hp1).oper[0]^.typ=top_reg then
  4493. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4494. end;
  4495. 2:
  4496. begin
  4497. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4498. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4499. (taicpu(hp1).opcode<>A_SHL) and
  4500. (taicpu(hp1).opcode<>A_SHR) and
  4501. (taicpu(hp1).opcode<>A_SAR) then
  4502. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4503. end;
  4504. else
  4505. internalerror(2008042701);
  4506. end;
  4507. {
  4508. ->
  4509. decw %si addw %dx,%si p
  4510. }
  4511. RemoveInstruction(hp2);
  4512. RemoveCurrentP(p, hp1);
  4513. Result:=True;
  4514. Exit;
  4515. end;
  4516. end;
  4517. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4518. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4519. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4520. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4521. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4522. )
  4523. {$ifdef i386}
  4524. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4525. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4526. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4527. {$endif i386}
  4528. then
  4529. { change movsX/movzX reg/ref, reg2
  4530. add/sub/or/... regX/$const, reg2
  4531. mov reg2, reg3
  4532. dealloc reg2
  4533. to
  4534. movsX/movzX reg/ref, reg3
  4535. add/sub/or/... reg3/$const, reg3
  4536. }
  4537. begin
  4538. TransferUsedRegs(TmpUsedRegs);
  4539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4541. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4542. begin
  4543. { by example:
  4544. movswl %si,%eax movswl %si,%eax p
  4545. decl %eax addl %edx,%eax hp1
  4546. movw %ax,%si movw %ax,%si hp2
  4547. ->
  4548. movswl %si,%eax movswl %si,%eax p
  4549. decw %eax addw %edx,%eax hp1
  4550. movw %ax,%si movw %ax,%si hp2
  4551. }
  4552. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4553. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4554. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4555. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4556. { limit size of constants as well to avoid assembler errors, but
  4557. check opsize to avoid overflow when left shifting the 1 }
  4558. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4559. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4560. {$ifdef x86_64}
  4561. { Be careful of, for example:
  4562. movl %reg1,%reg2
  4563. addl %reg3,%reg2
  4564. movq %reg2,%reg4
  4565. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4566. }
  4567. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4568. begin
  4569. taicpu(hp2).changeopsize(S_L);
  4570. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4571. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4572. end;
  4573. {$endif x86_64}
  4574. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4575. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4576. if taicpu(p).oper[0]^.typ=top_reg then
  4577. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4578. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4579. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4580. {
  4581. ->
  4582. movswl %si,%eax movswl %si,%eax p
  4583. decw %si addw %dx,%si hp1
  4584. movw %ax,%si movw %ax,%si hp2
  4585. }
  4586. case taicpu(hp1).ops of
  4587. 1:
  4588. begin
  4589. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4590. if taicpu(hp1).oper[0]^.typ=top_reg then
  4591. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4592. end;
  4593. 2:
  4594. begin
  4595. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4596. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4597. (taicpu(hp1).opcode<>A_SHL) and
  4598. (taicpu(hp1).opcode<>A_SHR) and
  4599. (taicpu(hp1).opcode<>A_SAR) then
  4600. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4601. end;
  4602. else
  4603. internalerror(2018111801);
  4604. end;
  4605. {
  4606. ->
  4607. decw %si addw %dx,%si p
  4608. }
  4609. RemoveInstruction(hp2);
  4610. end;
  4611. end;
  4612. end;
  4613. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4614. GetNextInstruction(hp1, hp2) and
  4615. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4616. MatchOperand(Taicpu(p).oper[0]^,0) and
  4617. (Taicpu(p).oper[1]^.typ = top_reg) and
  4618. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4619. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4620. { mov reg1,0
  4621. bts reg1,operand1 --> mov reg1,operand2
  4622. or reg1,operand2 bts reg1,operand1}
  4623. begin
  4624. Taicpu(hp2).opcode:=A_MOV;
  4625. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4626. asml.remove(hp1);
  4627. insertllitem(hp2,hp2.next,hp1);
  4628. RemoveCurrentp(p, hp1);
  4629. Result:=true;
  4630. exit;
  4631. end;
  4632. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4633. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4634. GetNextInstruction(hp1, hp2) and
  4635. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4636. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4637. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4638. { change
  4639. mov reg1,reg2
  4640. sub reg3,reg2
  4641. cmp reg3,reg1
  4642. into
  4643. mov reg1,reg2
  4644. sub reg3,reg2
  4645. }
  4646. begin
  4647. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4648. RemoveInstruction(hp2);
  4649. Result:=true;
  4650. exit;
  4651. end;
  4652. {
  4653. mov ref,reg0
  4654. <op> reg0,reg1
  4655. dealloc reg0
  4656. to
  4657. <op> ref,reg1
  4658. }
  4659. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4660. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4661. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4662. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4663. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4664. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4665. begin
  4666. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4667. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4668. RemoveCurrentp(p, hp1);
  4669. Result:=true;
  4670. exit;
  4671. end;
  4672. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4673. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4674. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4675. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4676. begin
  4677. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4678. {$ifdef x86_64}
  4679. { Convert:
  4680. movq x(ref),%reg64
  4681. shrq y,%reg64
  4682. To:
  4683. movl x+4(ref),%reg32
  4684. shrl y-32,%reg32 (Remove if y = 32)
  4685. }
  4686. if (taicpu(p).opsize = S_Q) and
  4687. (taicpu(hp1).opcode = A_SHR) and
  4688. (taicpu(hp1).oper[0]^.val >= 32) then
  4689. begin
  4690. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4691. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4692. { Convert to 32-bit }
  4693. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4694. taicpu(p).opsize := S_L;
  4695. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4696. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4697. if (taicpu(hp1).oper[0]^.val = 32) then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4700. RemoveInstruction(hp1);
  4701. end
  4702. else
  4703. begin
  4704. { This will potentially open up more arithmetic operations since
  4705. the peephole optimizer now has a big hint that only the lower
  4706. 32 bits are currently in use (and opcodes are smaller in size) }
  4707. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4708. taicpu(hp1).opsize := S_L;
  4709. Dec(taicpu(hp1).oper[0]^.val, 32);
  4710. DebugMsg(SPeepholeOptimization + PreMessage +
  4711. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4712. end;
  4713. Result := True;
  4714. Exit;
  4715. end;
  4716. {$endif x86_64}
  4717. { Convert:
  4718. movl x(ref),%reg
  4719. shrl $24,%reg
  4720. To:
  4721. movzbl x+3(ref),%reg
  4722. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4723. Also accept sar instead of shr, but convert to movsx instead of movzx
  4724. }
  4725. if taicpu(hp1).opcode = A_SHR then
  4726. MovUnaligned := A_MOVZX
  4727. else
  4728. MovUnaligned := A_MOVSX;
  4729. NewSize := S_NO;
  4730. NewOffset := 0;
  4731. case taicpu(p).opsize of
  4732. S_B:
  4733. { No valid combinations };
  4734. S_W:
  4735. if (taicpu(hp1).oper[0]^.val = 8) then
  4736. begin
  4737. NewSize := S_BW;
  4738. NewOffset := 1;
  4739. end;
  4740. S_L:
  4741. case taicpu(hp1).oper[0]^.val of
  4742. 16:
  4743. begin
  4744. NewSize := S_WL;
  4745. NewOffset := 2;
  4746. end;
  4747. 24:
  4748. begin
  4749. NewSize := S_BL;
  4750. NewOffset := 3;
  4751. end;
  4752. else
  4753. ;
  4754. end;
  4755. {$ifdef x86_64}
  4756. S_Q:
  4757. case taicpu(hp1).oper[0]^.val of
  4758. 32:
  4759. begin
  4760. if taicpu(hp1).opcode = A_SAR then
  4761. begin
  4762. { 32-bit to 64-bit is a distinct instruction }
  4763. MovUnaligned := A_MOVSXD;
  4764. NewSize := S_LQ;
  4765. NewOffset := 4;
  4766. end
  4767. else
  4768. { Should have been handled by MovShr2Mov above }
  4769. InternalError(2022081811);
  4770. end;
  4771. 48:
  4772. begin
  4773. NewSize := S_WQ;
  4774. NewOffset := 6;
  4775. end;
  4776. 56:
  4777. begin
  4778. NewSize := S_BQ;
  4779. NewOffset := 7;
  4780. end;
  4781. else
  4782. ;
  4783. end;
  4784. {$endif x86_64}
  4785. else
  4786. InternalError(2022081810);
  4787. end;
  4788. if (NewSize <> S_NO) and
  4789. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4790. begin
  4791. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4792. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4793. debug_op2str(MovUnaligned);
  4794. {$ifdef x86_64}
  4795. if MovUnaligned <> A_MOVSXD then
  4796. { Don't add size suffix for MOVSXD }
  4797. {$endif x86_64}
  4798. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4799. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4800. taicpu(p).opcode := MovUnaligned;
  4801. taicpu(p).opsize := NewSize;
  4802. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4803. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4804. RemoveInstruction(hp1);
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. end;
  4809. { Backward optimisation shared with OptPass2MOV }
  4810. if FuncMov2Func(p, hp1) then
  4811. begin
  4812. Result := True;
  4813. Exit;
  4814. end;
  4815. end;
  4816. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4817. var
  4818. hp1 : tai;
  4819. begin
  4820. Result:=false;
  4821. if taicpu(p).ops <> 2 then
  4822. exit;
  4823. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4824. GetNextInstruction(p,hp1) then
  4825. begin
  4826. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4827. (taicpu(hp1).ops = 2) then
  4828. begin
  4829. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4830. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4831. { movXX reg1, mem1 or movXX mem1, reg1
  4832. movXX mem2, reg2 movXX reg2, mem2}
  4833. begin
  4834. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4835. { movXX reg1, mem1 or movXX mem1, reg1
  4836. movXX mem2, reg1 movXX reg2, mem1}
  4837. begin
  4838. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4839. begin
  4840. { Removes the second statement from
  4841. movXX reg1, mem1/reg2
  4842. movXX mem1/reg2, reg1
  4843. }
  4844. if taicpu(p).oper[0]^.typ=top_reg then
  4845. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4846. { Removes the second statement from
  4847. movXX mem1/reg1, reg2
  4848. movXX reg2, mem1/reg1
  4849. }
  4850. if (taicpu(p).oper[1]^.typ=top_reg) and
  4851. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4852. begin
  4853. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4854. RemoveInstruction(hp1);
  4855. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4856. Result:=true;
  4857. exit;
  4858. end
  4859. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4860. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4861. begin
  4862. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4863. RemoveInstruction(hp1);
  4864. Result:=true;
  4865. exit;
  4866. end;
  4867. end
  4868. end;
  4869. end;
  4870. end;
  4871. end;
  4872. end;
  4873. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4874. var
  4875. hp1 : tai;
  4876. begin
  4877. result:=false;
  4878. { replace
  4879. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4880. MovX %mreg2,%mreg1
  4881. dealloc %mreg2
  4882. by
  4883. <Op>X %mreg2,%mreg1
  4884. ?
  4885. }
  4886. if GetNextInstruction(p,hp1) and
  4887. { we mix single and double opperations here because we assume that the compiler
  4888. generates vmovapd only after double operations and vmovaps only after single operations }
  4889. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4890. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4891. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4892. (taicpu(p).oper[0]^.typ=top_reg) then
  4893. begin
  4894. TransferUsedRegs(TmpUsedRegs);
  4895. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4897. begin
  4898. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4899. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4900. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4901. RemoveInstruction(hp1);
  4902. result:=true;
  4903. end;
  4904. end;
  4905. end;
  4906. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4907. var
  4908. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4909. JumpLabel, JumpLabel_dist: TAsmLabel;
  4910. FirstValue, SecondValue: TCGInt;
  4911. function OptimizeJump(var InputP: tai): Boolean;
  4912. var
  4913. TempBool: Boolean;
  4914. begin
  4915. Result := False;
  4916. TempBool := True;
  4917. if DoJumpOptimizations(InputP, TempBool) or
  4918. not TempBool then
  4919. begin
  4920. Result := True;
  4921. if Assigned(InputP) then
  4922. begin
  4923. { CollapseZeroDistJump will be set to the label or an align
  4924. before it after the jump if it optimises, whether or not
  4925. the label is live or dead }
  4926. if (InputP.typ = ait_align) or
  4927. (
  4928. (InputP.typ = ait_label) and
  4929. not (tai_label(InputP).labsym.is_used)
  4930. ) then
  4931. GetNextInstruction(InputP, InputP);
  4932. end;
  4933. Exit;
  4934. end;
  4935. end;
  4936. begin
  4937. Result := False;
  4938. if (taicpu(p).oper[0]^.typ = top_const) and
  4939. (taicpu(p).oper[0]^.val <> -1) then
  4940. begin
  4941. { Convert unsigned maximum constants to -1 to aid optimisation }
  4942. case taicpu(p).opsize of
  4943. S_B:
  4944. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4945. begin
  4946. taicpu(p).oper[0]^.val := -1;
  4947. Result := True;
  4948. Exit;
  4949. end;
  4950. S_W:
  4951. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4952. begin
  4953. taicpu(p).oper[0]^.val := -1;
  4954. Result := True;
  4955. Exit;
  4956. end;
  4957. S_L:
  4958. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4959. begin
  4960. taicpu(p).oper[0]^.val := -1;
  4961. Result := True;
  4962. Exit;
  4963. end;
  4964. {$ifdef x86_64}
  4965. S_Q:
  4966. { Storing anything greater than $7FFFFFFF is not possible so do
  4967. nothing };
  4968. {$endif x86_64}
  4969. else
  4970. InternalError(2021121001);
  4971. end;
  4972. end;
  4973. if GetNextInstruction(p, hp1) and
  4974. TrySwapMovCmp(p, hp1) then
  4975. begin
  4976. Result := True;
  4977. Exit;
  4978. end;
  4979. p_label := nil;
  4980. JumpLabel := nil;
  4981. if MatchInstruction(hp1, A_Jcc, []) then
  4982. begin
  4983. if OptimizeJump(hp1) then
  4984. begin
  4985. Result := True;
  4986. if Assigned(hp1) then
  4987. begin
  4988. { CollapseZeroDistJump will be set to the label or an align
  4989. before it after the jump if it optimises, whether or not
  4990. the label is live or dead }
  4991. if (hp1.typ = ait_align) or
  4992. (
  4993. (hp1.typ = ait_label) and
  4994. not (tai_label(hp1).labsym.is_used)
  4995. ) then
  4996. GetNextInstruction(hp1, hp1);
  4997. end;
  4998. TransferUsedRegs(TmpUsedRegs);
  4999. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5000. if not Assigned(hp1) or
  5001. (
  5002. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5003. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5004. ) then
  5005. begin
  5006. { No more conditional jumps; conditional statement is no longer required }
  5007. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5008. RemoveCurrentP(p);
  5009. end;
  5010. Exit;
  5011. end;
  5012. if IsJumpToLabel(taicpu(hp1)) then
  5013. begin
  5014. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5015. if Assigned(JumpLabel) then
  5016. p_label := getlabelwithsym(JumpLabel);
  5017. end;
  5018. end;
  5019. { Search for:
  5020. test $x,(reg/ref)
  5021. jne @lbl1
  5022. test $y,(reg/ref) (same register or reference)
  5023. jne @lbl1
  5024. Change to:
  5025. test $(x or y),(reg/ref)
  5026. jne @lbl1
  5027. (Note, this doesn't work with je instead of jne)
  5028. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5029. Also search for:
  5030. test $x,(reg/ref)
  5031. je @lbl1
  5032. ...
  5033. test $y,(reg/ref)
  5034. je/jne @lbl2
  5035. If (x or y) = x, then the second jump is deterministic
  5036. }
  5037. if (
  5038. (
  5039. (taicpu(p).oper[0]^.typ = top_const) or
  5040. (
  5041. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5042. (taicpu(p).oper[0]^.typ = top_reg) and
  5043. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5044. )
  5045. ) and
  5046. MatchInstruction(hp1, A_JCC, [])
  5047. ) then
  5048. begin
  5049. if (taicpu(p).oper[0]^.typ = top_reg) and
  5050. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5051. FirstValue := -1
  5052. else
  5053. FirstValue := taicpu(p).oper[0]^.val;
  5054. { If we have several test/jne's in a row, it might be the case that
  5055. the second label doesn't go to the same location, but the one
  5056. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5057. so accommodate for this with a while loop.
  5058. }
  5059. hp1_last := hp1;
  5060. while (
  5061. (
  5062. (taicpu(p).oper[1]^.typ = top_reg) and
  5063. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5064. ) or GetNextInstruction(hp1_last, p_dist)
  5065. ) and (p_dist.typ = ait_instruction) do
  5066. begin
  5067. if (
  5068. (
  5069. (taicpu(p_dist).opcode = A_TEST) and
  5070. (
  5071. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5072. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5073. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5074. )
  5075. ) or
  5076. (
  5077. { cmp 0,%reg = test %reg,%reg }
  5078. (taicpu(p_dist).opcode = A_CMP) and
  5079. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5080. )
  5081. ) and
  5082. { Make sure the destination operands are actually the same }
  5083. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5084. GetNextInstruction(p_dist, hp1_dist) and
  5085. MatchInstruction(hp1_dist, A_JCC, []) then
  5086. begin
  5087. if OptimizeJump(hp1_dist) then
  5088. begin
  5089. Result := True;
  5090. Exit;
  5091. end;
  5092. if
  5093. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5094. (
  5095. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5096. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5097. ) then
  5098. SecondValue := -1
  5099. else
  5100. SecondValue := taicpu(p_dist).oper[0]^.val;
  5101. { If both of the TEST constants are identical, delete the
  5102. second TEST that is unnecessary (be careful though, just
  5103. in case the flags are modified in between) }
  5104. if (FirstValue = SecondValue) then
  5105. begin
  5106. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5107. begin
  5108. { Since the second jump's condition is a subset of the first, we
  5109. know it will never branch because the first jump dominates it.
  5110. Get it out of the way now rather than wait for the jump
  5111. optimisations for a speed boost. }
  5112. if IsJumpToLabel(taicpu(hp1_dist)) then
  5113. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5114. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5115. RemoveInstruction(hp1_dist);
  5116. Result := True;
  5117. end
  5118. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5119. begin
  5120. { If the inverse of the first condition is a subset of the second,
  5121. the second one will definitely branch if the first one doesn't }
  5122. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5123. { We can remove the TEST instruction too }
  5124. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5125. RemoveInstruction(p_dist);
  5126. MakeUnconditional(taicpu(hp1_dist));
  5127. RemoveDeadCodeAfterJump(hp1_dist);
  5128. { Since the jump is now unconditional, we can't
  5129. continue any further with this particular
  5130. optimisation. The original TEST is still intact
  5131. though, so there might be something else we can
  5132. do }
  5133. Include(OptsToCheck, aoc_ForceNewIteration);
  5134. Break;
  5135. end;
  5136. if Result or
  5137. { If a jump wasn't removed or made unconditional, only
  5138. remove the identical TEST instruction if the flags
  5139. weren't modified }
  5140. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5141. begin
  5142. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5143. RemoveInstruction(p_dist);
  5144. { If the jump was removed or made unconditional, we
  5145. don't need to allocate NR_DEFAULTFLAGS over the
  5146. entire range }
  5147. if not Result then
  5148. begin
  5149. { Mark the flags as 'in use' over the entire range }
  5150. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5151. { Speed gain - continue search from the Jcc instruction }
  5152. hp1_last := hp1_dist;
  5153. { Only the TEST instruction was removed, and the
  5154. original was unchanged, so we can safely do
  5155. another iteration of the while loop }
  5156. Include(OptsToCheck, aoc_ForceNewIteration);
  5157. Continue;
  5158. end;
  5159. Exit;
  5160. end;
  5161. end;
  5162. hp1_last := nil;
  5163. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5164. (
  5165. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5166. { Always adjacent under -O2 and under }
  5167. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5168. (
  5169. GetNextInstruction(hp1, hp1_last) and
  5170. (hp1_last = p_dist)
  5171. )
  5172. ) and
  5173. (
  5174. (
  5175. { Test the following variant:
  5176. test $x,(reg/ref)
  5177. jne @lbl1
  5178. test $y,(reg/ref)
  5179. je @lbl2
  5180. @lbl1:
  5181. Becomes:
  5182. test $(x or y),(reg/ref)
  5183. je @lbl2
  5184. @lbl1: (may become a dead label)
  5185. }
  5186. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5187. GetNextInstruction(hp1_dist, hp1_last) and
  5188. (hp1_last = p_label)
  5189. ) or
  5190. (
  5191. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5192. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5193. then the second jump will never branch, so it can also be
  5194. removed regardless of where it goes }
  5195. (
  5196. (FirstValue = -1) or
  5197. (SecondValue = -1) or
  5198. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5199. )
  5200. )
  5201. ) then
  5202. begin
  5203. { Same jump location... can be a register since nothing's changed }
  5204. { If any of the entries are equivalent to test %reg,%reg, then the
  5205. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5206. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5207. if (hp1_last = p_label) then
  5208. begin
  5209. { Variant }
  5210. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5211. RemoveInstruction(p_dist);
  5212. if Assigned(JumpLabel) then
  5213. JumpLabel.decrefs;
  5214. RemoveInstruction(hp1);
  5215. end
  5216. else
  5217. begin
  5218. { Only remove the second test if no jumps or other conditional instructions follow }
  5219. TransferUsedRegs(TmpUsedRegs);
  5220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5222. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5223. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5224. begin
  5225. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5226. RemoveInstruction(p_dist);
  5227. { Remove the first jump, not the second, to keep
  5228. any register deallocations between the second
  5229. TEST/JNE pair in the same place. Aids future
  5230. optimisation. }
  5231. if Assigned(JumpLabel) then
  5232. JumpLabel.decrefs;
  5233. RemoveInstruction(hp1);
  5234. end
  5235. else
  5236. begin
  5237. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5238. if IsJumpToLabel(taicpu(hp1_dist)) then
  5239. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5240. { Remove second jump in this instance }
  5241. RemoveInstruction(hp1_dist);
  5242. end;
  5243. end;
  5244. Result := True;
  5245. Exit;
  5246. end;
  5247. end;
  5248. if { If -O2 and under, it may stop on any old instruction }
  5249. (cs_opt_level3 in current_settings.optimizerswitches) and
  5250. (taicpu(p).oper[1]^.typ = top_reg) and
  5251. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5252. begin
  5253. hp1_last := p_dist;
  5254. Continue;
  5255. end;
  5256. Break;
  5257. end;
  5258. end;
  5259. { Search for:
  5260. test %reg,%reg
  5261. j(c1) @lbl1
  5262. ...
  5263. @lbl:
  5264. test %reg,%reg (same register)
  5265. j(c2) @lbl2
  5266. If c2 is a subset of c1, change to:
  5267. test %reg,%reg
  5268. j(c1) @lbl2
  5269. (@lbl1 may become a dead label as a result)
  5270. }
  5271. if (taicpu(p).oper[1]^.typ = top_reg) and
  5272. (taicpu(p).oper[0]^.typ = top_reg) and
  5273. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5274. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5275. Assigned(p_label) and
  5276. GetNextInstruction(p_label, p_dist) and
  5277. MatchInstruction(p_dist, A_TEST, []) and
  5278. { It's fine if the second test uses smaller sub-registers }
  5279. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5280. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5281. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5282. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5283. GetNextInstruction(p_dist, hp1_dist) and
  5284. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5285. begin
  5286. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5287. if JumpLabel = JumpLabel_dist then
  5288. { This is an infinite loop }
  5289. Exit;
  5290. { Best optimisation when the first condition is a subset (or equal) of the second }
  5291. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5292. begin
  5293. { Any registers used here will already be allocated }
  5294. if Assigned(JumpLabel) then
  5295. JumpLabel.DecRefs;
  5296. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5297. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5298. Result := True;
  5299. Exit;
  5300. end;
  5301. end;
  5302. end;
  5303. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5304. var
  5305. hp1, hp2: tai;
  5306. ActiveReg: TRegister;
  5307. OldOffset: asizeint;
  5308. ThisConst: TCGInt;
  5309. function RegDeallocated: Boolean;
  5310. begin
  5311. TransferUsedRegs(TmpUsedRegs);
  5312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5313. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5314. end;
  5315. begin
  5316. result:=false;
  5317. hp1 := nil;
  5318. { replace
  5319. addX const,%reg1
  5320. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5321. dealloc %reg1
  5322. by
  5323. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5324. }
  5325. if MatchOpType(taicpu(p),top_const,top_reg) then
  5326. begin
  5327. ActiveReg := taicpu(p).oper[1]^.reg;
  5328. { Ensures the entire register was updated }
  5329. if (taicpu(p).opsize >= S_L) and
  5330. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5331. MatchInstruction(hp1,A_LEA,[]) and
  5332. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5333. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5334. (
  5335. { Cover the case where the register in the reference is also the destination register }
  5336. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5337. (
  5338. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5339. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5340. RegDeallocated
  5341. )
  5342. ) then
  5343. begin
  5344. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5345. {$push}
  5346. {$R-}{$Q-}
  5347. { Explicitly disable overflow checking for these offset calculation
  5348. as those do not matter for the final result }
  5349. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5350. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5351. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5352. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5353. {$pop}
  5354. {$ifdef x86_64}
  5355. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5356. begin
  5357. { Overflow; abort }
  5358. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5359. end
  5360. else
  5361. {$endif x86_64}
  5362. begin
  5363. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5364. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5365. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5366. RemoveCurrentP(p, hp1)
  5367. else
  5368. RemoveCurrentP(p);
  5369. result:=true;
  5370. Exit;
  5371. end;
  5372. end;
  5373. if (
  5374. { Save calling GetNextInstructionUsingReg again }
  5375. Assigned(hp1) or
  5376. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5377. ) and
  5378. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5379. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5380. begin
  5381. if taicpu(hp1).oper[0]^.typ = top_const then
  5382. begin
  5383. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5384. if taicpu(hp1).opcode = A_ADD then
  5385. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5386. else
  5387. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5388. Result := True;
  5389. { Handle any overflows }
  5390. case taicpu(p).opsize of
  5391. S_B:
  5392. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5393. S_W:
  5394. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5395. S_L:
  5396. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5397. {$ifdef x86_64}
  5398. S_Q:
  5399. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5400. { Overflow; abort }
  5401. Result := False
  5402. else
  5403. taicpu(p).oper[0]^.val := ThisConst;
  5404. {$endif x86_64}
  5405. else
  5406. InternalError(2021102610);
  5407. end;
  5408. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5409. if Result then
  5410. begin
  5411. if (taicpu(p).oper[0]^.val < 0) and
  5412. (
  5413. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5414. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5415. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5416. ) then
  5417. begin
  5418. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5419. taicpu(p).opcode := A_SUB;
  5420. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5421. end
  5422. else
  5423. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5424. RemoveInstruction(hp1);
  5425. end;
  5426. end
  5427. else
  5428. begin
  5429. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5430. TransferUsedRegs(TmpUsedRegs);
  5431. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5432. hp2 := p;
  5433. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5434. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5435. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5436. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5437. begin
  5438. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5439. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5440. Asml.Remove(p);
  5441. Asml.InsertAfter(p, hp1);
  5442. p := hp1;
  5443. Result := True;
  5444. Exit;
  5445. end;
  5446. end;
  5447. end;
  5448. if DoArithCombineOpt(p) then
  5449. Result:=true;
  5450. end;
  5451. end;
  5452. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5453. var
  5454. hp1, hp2: tai;
  5455. ref: Integer;
  5456. saveref: treference;
  5457. offsetcalc: Int64;
  5458. TempReg: TRegister;
  5459. Multiple: TCGInt;
  5460. Adjacent, IntermediateRegDiscarded: Boolean;
  5461. begin
  5462. Result:=false;
  5463. { play save and throw an error if LEA uses a seg register prefix,
  5464. this is most likely an error somewhere else }
  5465. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5466. internalerror(2022022001);
  5467. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5468. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5469. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5470. (
  5471. { do not mess with leas accessing the stack pointer
  5472. unless it's a null operation }
  5473. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5474. (
  5475. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5476. (taicpu(p).oper[0]^.ref^.offset = 0)
  5477. )
  5478. ) and
  5479. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5480. begin
  5481. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5482. begin
  5483. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5484. begin
  5485. taicpu(p).opcode := A_MOV;
  5486. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5487. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5488. end
  5489. else
  5490. begin
  5491. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5492. RemoveCurrentP(p);
  5493. end;
  5494. Result:=true;
  5495. exit;
  5496. end
  5497. else if (
  5498. { continue to use lea to adjust the stack pointer,
  5499. it is the recommended way, but only if not optimizing for size }
  5500. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5501. (cs_opt_size in current_settings.optimizerswitches)
  5502. ) and
  5503. { If the flags register is in use, don't change the instruction
  5504. to an ADD otherwise this will scramble the flags. [Kit] }
  5505. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5506. ConvertLEA(taicpu(p)) then
  5507. begin
  5508. Result:=true;
  5509. exit;
  5510. end;
  5511. end;
  5512. { Don't optimise if the stack or frame pointer is the destination register }
  5513. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5514. Exit;
  5515. if GetNextInstruction(p,hp1) and
  5516. (hp1.typ=ait_instruction) then
  5517. begin
  5518. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5519. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5520. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5521. begin
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5524. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5525. begin
  5526. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5527. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5528. RemoveInstruction(hp1);
  5529. result:=true;
  5530. exit;
  5531. end;
  5532. end;
  5533. { changes
  5534. lea <ref1>, reg1
  5535. <op> ...,<ref. with reg1>,...
  5536. to
  5537. <op> ...,<ref1>,... }
  5538. { find a reference which uses reg1 }
  5539. 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
  5540. ref:=0
  5541. 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
  5542. ref:=1
  5543. else
  5544. ref:=-1;
  5545. if (ref<>-1) and
  5546. { reg1 must be either the base or the index }
  5547. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5548. begin
  5549. { reg1 can be removed from the reference }
  5550. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5551. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5552. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5553. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5554. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5555. else
  5556. Internalerror(2019111201);
  5557. { check if the can insert all data of the lea into the second instruction }
  5558. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5559. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5560. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5561. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5562. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5563. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5564. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5565. {$ifdef x86_64}
  5566. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5567. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5568. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5569. )
  5570. {$endif x86_64}
  5571. then
  5572. begin
  5573. { reg1 might not used by the second instruction after it is remove from the reference }
  5574. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5575. begin
  5576. TransferUsedRegs(TmpUsedRegs);
  5577. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5578. { reg1 is not updated so it might not be used afterwards }
  5579. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5580. begin
  5581. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5582. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5583. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5584. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5585. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5586. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5587. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5588. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5589. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5590. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5591. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5592. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5593. RemoveCurrentP(p, hp1);
  5594. result:=true;
  5595. exit;
  5596. end
  5597. end;
  5598. end;
  5599. { recover }
  5600. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5601. end;
  5602. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5603. if Adjacent or
  5604. { Check further ahead (up to 2 instructions ahead for -O2) }
  5605. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5606. begin
  5607. { Check common LEA/LEA conditions }
  5608. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5609. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5610. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5611. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5612. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5613. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5614. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5615. (
  5616. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5617. calling it (since it calls GetNextInstruction) }
  5618. Adjacent or
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5622. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5623. ) and (
  5624. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5625. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5626. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5627. )
  5628. )
  5629. ) then
  5630. begin
  5631. TransferUsedRegs(TmpUsedRegs);
  5632. hp2 := p;
  5633. repeat
  5634. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5635. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5636. IntermediateRegDiscarded :=
  5637. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5638. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5639. { changes
  5640. lea offset1(regX,scale), reg1
  5641. lea offset2(reg1,reg1), reg2
  5642. to
  5643. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5644. and
  5645. lea offset1(regX,scale1), reg1
  5646. lea offset2(reg1,scale2), reg2
  5647. to
  5648. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5649. and
  5650. lea offset1(regX,scale1), reg1
  5651. lea offset2(reg3,reg1,scale2), reg2
  5652. to
  5653. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5654. ... so long as the final scale does not exceed 8
  5655. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5656. }
  5657. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5658. (
  5659. { Don't optimise if size is a concern and the intermediate register remains in use }
  5660. IntermediateRegDiscarded or
  5661. not (cs_opt_size in current_settings.optimizerswitches)
  5662. ) and
  5663. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5664. (
  5665. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5666. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5667. ) and (
  5668. (
  5669. { lea (reg1,scale2), reg2 variant }
  5670. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5671. (
  5672. Adjacent or
  5673. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5674. ) and
  5675. (
  5676. (
  5677. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5678. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5679. ) or (
  5680. { lea (regX,regX), reg1 variant }
  5681. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5683. )
  5684. )
  5685. ) or (
  5686. { lea (reg1,reg1), reg1 variant }
  5687. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5689. )
  5690. ) then
  5691. begin
  5692. { Make everything homogeneous to make calculations easier }
  5693. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5694. begin
  5695. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5696. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5697. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5698. else
  5699. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5700. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5701. end;
  5702. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5703. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5704. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5705. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5706. begin
  5707. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5708. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5709. begin
  5710. { Put the register to change in the index register }
  5711. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5712. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5713. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5714. end;
  5715. { Change lea (reg,reg) to lea(,reg,2) }
  5716. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5717. begin
  5718. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5719. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5720. end;
  5721. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5722. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5723. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5724. { Just to prevent miscalculations }
  5725. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5726. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5727. else
  5728. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5729. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5730. if IntermediateRegDiscarded then
  5731. begin
  5732. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5733. RemoveCurrentP(p);
  5734. end
  5735. else
  5736. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5737. result:=true;
  5738. exit;
  5739. end;
  5740. end;
  5741. { changes
  5742. lea offset1(regX), reg1
  5743. lea offset2(reg1), reg2
  5744. to
  5745. lea offset1+offset2(regX), reg2 }
  5746. if (
  5747. { Don't optimise if size is a concern and the intermediate register remains in use }
  5748. IntermediateRegDiscarded or
  5749. not (cs_opt_size in current_settings.optimizerswitches)
  5750. ) and
  5751. (
  5752. (
  5753. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5754. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5755. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5756. ) or (
  5757. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5758. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5759. (
  5760. (
  5761. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5762. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5763. ) or (
  5764. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5765. (
  5766. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5767. (
  5768. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5769. (
  5770. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5771. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5772. )
  5773. )
  5774. )
  5775. )
  5776. )
  5777. )
  5778. ) then
  5779. begin
  5780. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5781. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5782. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5783. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5784. begin
  5785. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5786. begin
  5787. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5788. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5789. { if the register is used as index and base, we have to increase for base as well
  5790. and adapt base }
  5791. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5792. begin
  5793. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5794. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5795. end;
  5796. end
  5797. else
  5798. begin
  5799. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5800. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5801. end;
  5802. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5803. begin
  5804. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5805. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5806. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5807. { Catch the situation where the base = index
  5808. and treat this as *2. The scalefactor of
  5809. p will be 0 or 1 due to the conditional
  5810. checks above. Fixes i40647 }
  5811. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5812. else
  5813. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5814. end;
  5815. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5816. if IntermediateRegDiscarded then
  5817. begin
  5818. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5819. RemoveCurrentP(p);
  5820. end
  5821. else
  5822. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5823. result:=true;
  5824. exit;
  5825. end;
  5826. end;
  5827. end;
  5828. { Change:
  5829. leal/q $x(%reg1),%reg2
  5830. ...
  5831. shll/q $y,%reg2
  5832. To:
  5833. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5834. }
  5835. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5836. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5837. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5838. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5839. (taicpu(hp1).oper[0]^.val <= 3) then
  5840. begin
  5841. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5842. TransferUsedRegs(TmpUsedRegs);
  5843. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5844. if
  5845. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5846. (this works even if scalefactor is zero) }
  5847. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5848. { Ensure offset doesn't go out of bounds }
  5849. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5850. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5851. (
  5852. (
  5853. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5854. (
  5855. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5856. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5857. (
  5858. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5859. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5860. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5861. )
  5862. )
  5863. ) or (
  5864. (
  5865. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5866. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5867. ) and
  5868. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5869. )
  5870. ) then
  5871. begin
  5872. repeat
  5873. with taicpu(p).oper[0]^.ref^ do
  5874. begin
  5875. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5876. if index = base then
  5877. begin
  5878. if Multiple > 4 then
  5879. { Optimisation will no longer work because resultant
  5880. scale factor will exceed 8 }
  5881. Break;
  5882. base := NR_NO;
  5883. scalefactor := 2;
  5884. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5885. end
  5886. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5887. begin
  5888. { Scale factor only works on the index register }
  5889. index := base;
  5890. base := NR_NO;
  5891. end;
  5892. { For safety }
  5893. if scalefactor <= 1 then
  5894. begin
  5895. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5896. scalefactor := Multiple;
  5897. end
  5898. else
  5899. begin
  5900. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5901. scalefactor := scalefactor * Multiple;
  5902. end;
  5903. offset := offset * Multiple;
  5904. end;
  5905. RemoveInstruction(hp1);
  5906. Result := True;
  5907. Exit;
  5908. { This repeat..until loop exists for the benefit of Break }
  5909. until True;
  5910. end;
  5911. end;
  5912. end;
  5913. end;
  5914. end;
  5915. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5916. var
  5917. hp1 : tai;
  5918. SubInstr: Boolean;
  5919. ThisConst: TCGInt;
  5920. const
  5921. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5922. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5923. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5924. begin
  5925. Result := False;
  5926. if taicpu(p).oper[0]^.typ <> top_const then
  5927. { Should have been confirmed before calling }
  5928. InternalError(2021102601);
  5929. SubInstr := (taicpu(p).opcode = A_SUB);
  5930. if GetLastInstruction(p, hp1) and
  5931. (hp1.typ = ait_instruction) and
  5932. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5933. begin
  5934. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5935. { Bad size }
  5936. InternalError(2022042001);
  5937. case taicpu(hp1).opcode Of
  5938. A_INC:
  5939. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5940. begin
  5941. if SubInstr then
  5942. ThisConst := taicpu(p).oper[0]^.val - 1
  5943. else
  5944. ThisConst := taicpu(p).oper[0]^.val + 1;
  5945. end
  5946. else
  5947. Exit;
  5948. A_DEC:
  5949. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5950. begin
  5951. if SubInstr then
  5952. ThisConst := taicpu(p).oper[0]^.val + 1
  5953. else
  5954. ThisConst := taicpu(p).oper[0]^.val - 1;
  5955. end
  5956. else
  5957. Exit;
  5958. A_SUB:
  5959. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5960. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5961. begin
  5962. if SubInstr then
  5963. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5964. else
  5965. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5966. end
  5967. else
  5968. Exit;
  5969. A_ADD:
  5970. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5971. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5972. begin
  5973. if SubInstr then
  5974. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5975. else
  5976. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5977. end
  5978. else
  5979. Exit;
  5980. else
  5981. Exit;
  5982. end;
  5983. { Check that the values are in range }
  5984. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5985. { Overflow; abort }
  5986. Exit;
  5987. if (ThisConst = 0) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5990. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5991. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5992. RemoveInstruction(hp1);
  5993. hp1 := tai(p.next);
  5994. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5995. if not GetLastInstruction(hp1, p) then
  5996. p := hp1;
  5997. end
  5998. else
  5999. begin
  6000. if taicpu(hp1).opercnt=1 then
  6001. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6002. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6003. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6004. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6005. else
  6006. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6007. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6008. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6009. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6010. RemoveInstruction(hp1);
  6011. taicpu(p).loadconst(0, ThisConst);
  6012. end;
  6013. Result := True;
  6014. end;
  6015. end;
  6016. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6017. begin
  6018. Result := False;
  6019. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6020. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6021. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6022. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6023. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6024. (
  6025. (
  6026. (taicpu(hp1).opcode = A_TEST)
  6027. ) or (
  6028. (taicpu(hp1).opcode = A_CMP) and
  6029. { A sanity check more than anything }
  6030. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6031. )
  6032. ) then
  6033. begin
  6034. { change
  6035. mov mem, %reg
  6036. ...
  6037. cmp/test x, %reg / test %reg,%reg
  6038. (reg deallocated)
  6039. to
  6040. cmp/test x, mem / cmp 0, mem
  6041. }
  6042. TransferUsedRegs(TmpUsedRegs);
  6043. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6044. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6045. begin
  6046. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6047. if (taicpu(hp1).opcode = A_TEST) and
  6048. (
  6049. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6050. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6051. ) then
  6052. begin
  6053. taicpu(hp1).opcode := A_CMP;
  6054. taicpu(hp1).loadconst(0, 0);
  6055. end;
  6056. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6057. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6058. RemoveCurrentP(p);
  6059. if (p <> hp1) then
  6060. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6061. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6062. { Make sure the flags are allocated across the CMP instruction }
  6063. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6064. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6065. Result := True;
  6066. Exit;
  6067. end;
  6068. end;
  6069. end;
  6070. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6071. var
  6072. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6073. ThisReg, SecondReg: TRegister;
  6074. JumpLoc: TAsmLabel;
  6075. NewSize: TOpSize;
  6076. begin
  6077. Result := False;
  6078. {
  6079. Convert:
  6080. j<c> .L1
  6081. .L2:
  6082. mov 1,reg
  6083. jmp .L3 (or ret, although it might not be a RET yet)
  6084. .L1:
  6085. mov 0,reg
  6086. jmp .L3 (or ret)
  6087. ( As long as .L3 <> .L1 or .L2)
  6088. To:
  6089. mov 0,reg
  6090. set<not(c)> reg
  6091. jmp .L3 (or ret)
  6092. .L2:
  6093. mov 1,reg
  6094. jmp .L3 (or ret)
  6095. .L1:
  6096. mov 0,reg
  6097. jmp .L3 (or ret)
  6098. }
  6099. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6100. Exit;
  6101. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6102. if GetNextInstruction(hp_label, hp2) and
  6103. MatchInstruction(hp2,A_MOV,[]) and
  6104. (taicpu(hp2).oper[0]^.typ = top_const) and
  6105. (
  6106. (
  6107. (taicpu(hp2).oper[1]^.typ = top_reg)
  6108. {$ifdef i386}
  6109. { Under i386, ESI, EDI, EBP and ESP
  6110. don't have an 8-bit representation }
  6111. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6112. {$endif i386}
  6113. ) or (
  6114. {$ifdef i386}
  6115. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6116. {$endif i386}
  6117. (taicpu(hp2).opsize = S_B)
  6118. )
  6119. ) and
  6120. GetNextInstruction(hp2, hp3) and
  6121. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6122. (
  6123. (taicpu(hp3).opcode=A_RET) or
  6124. (
  6125. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6126. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6127. )
  6128. ) and
  6129. GetNextInstruction(hp3, hp4) and
  6130. (hp4.typ=ait_label) and
  6131. (tai_label(hp4).labsym=JumpLoc) and
  6132. (
  6133. not (cs_opt_size in current_settings.optimizerswitches) or
  6134. { If the initial jump is the label's only reference, then it will
  6135. become a dead label if the other conditions are met and hence
  6136. remove at least 2 instructions, including a jump }
  6137. (JumpLoc.getrefs = 1)
  6138. ) and
  6139. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6140. that will be optimised out }
  6141. GetNextInstruction(hp4, hp5) and
  6142. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6143. (taicpu(hp5).oper[0]^.typ = top_const) and
  6144. (
  6145. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6146. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6147. ) and
  6148. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6149. GetNextInstruction(hp5,hp6) and
  6150. (
  6151. (hp6.typ<>ait_label) or
  6152. SkipLabels(hp6, hp6)
  6153. ) and
  6154. (hp6.typ=ait_instruction) then
  6155. begin
  6156. { First, let's look at the two jumps that are hp3 and hp6 }
  6157. if not
  6158. (
  6159. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6160. (
  6161. (taicpu(hp6).opcode=A_RET) or
  6162. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6163. )
  6164. ) then
  6165. { If condition is False, then the JMP/RET instructions matched conventionally }
  6166. begin
  6167. { See if one of the jumps can be instantly converted into a RET }
  6168. if (taicpu(hp3).opcode=A_JMP) then
  6169. begin
  6170. { Reuse hp5 }
  6171. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6172. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6173. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6174. Exit;
  6175. if MatchInstruction(hp5, A_RET, []) then
  6176. begin
  6177. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6178. ConvertJumpToRET(hp3, hp5);
  6179. Result := True;
  6180. end
  6181. else
  6182. Exit;
  6183. end;
  6184. if (taicpu(hp6).opcode=A_JMP) then
  6185. begin
  6186. { Reuse hp5 }
  6187. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6188. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6189. Exit;
  6190. if MatchInstruction(hp5, A_RET, []) then
  6191. begin
  6192. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6193. ConvertJumpToRET(hp6, hp5);
  6194. Result := True;
  6195. end
  6196. else
  6197. Exit;
  6198. end;
  6199. if not
  6200. (
  6201. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6202. (
  6203. (taicpu(hp6).opcode=A_RET) or
  6204. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6205. )
  6206. ) then
  6207. { Still doesn't match }
  6208. Exit;
  6209. end;
  6210. if (taicpu(hp2).oper[0]^.val = 1) then
  6211. begin
  6212. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6213. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6214. end
  6215. else
  6216. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6217. if taicpu(hp2).opsize=S_B then
  6218. begin
  6219. if taicpu(hp2).oper[1]^.typ = top_reg then
  6220. begin
  6221. SecondReg := taicpu(hp2).oper[1]^.reg;
  6222. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6223. end
  6224. else
  6225. begin
  6226. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6227. SecondReg := NR_NO;
  6228. end;
  6229. hp_pos := p;
  6230. hp_allocstart := hp4;
  6231. end
  6232. else
  6233. begin
  6234. { Will be a register because the size can't be S_B otherwise }
  6235. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6236. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6237. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6238. if (cs_opt_size in current_settings.optimizerswitches) then
  6239. begin
  6240. { Favour using MOVZX when optimising for size }
  6241. case taicpu(hp2).opsize of
  6242. S_W:
  6243. NewSize := S_BW;
  6244. S_L:
  6245. NewSize := S_BL;
  6246. {$ifdef x86_64}
  6247. S_Q:
  6248. begin
  6249. NewSize := S_BL;
  6250. { Will implicitly zero-extend to 64-bit }
  6251. setsubreg(SecondReg, R_SUBD);
  6252. end;
  6253. {$endif x86_64}
  6254. else
  6255. InternalError(2022101301);
  6256. end;
  6257. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6258. { Inserting it right before p will guarantee that the flags are also tracked }
  6259. Asml.InsertBefore(hp5, p);
  6260. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6261. hp_pos := hp5;
  6262. hp_allocstart := hp4;
  6263. end
  6264. else
  6265. begin
  6266. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6267. { Inserting it right before p will guarantee that the flags are also tracked }
  6268. Asml.InsertBefore(hp5, p);
  6269. hp_pos := p;
  6270. hp_allocstart := hp5;
  6271. end;
  6272. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6273. end;
  6274. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6275. taicpu(hp4).condition := taicpu(p).condition;
  6276. asml.InsertBefore(hp4, hp_pos);
  6277. if taicpu(hp3).is_jmp then
  6278. begin
  6279. JumpLoc.decrefs;
  6280. MakeUnconditional(taicpu(p));
  6281. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6282. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6283. end
  6284. else
  6285. ConvertJumpToRET(p, hp3);
  6286. if SecondReg <> NR_NO then
  6287. { Ensure the destination register is allocated over this region }
  6288. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6289. if (JumpLoc.getrefs = 0) then
  6290. RemoveDeadCodeAfterJump(hp3);
  6291. Result:=true;
  6292. exit;
  6293. end;
  6294. end;
  6295. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6296. var
  6297. hp1, hp2: tai;
  6298. ActiveReg: TRegister;
  6299. OldOffset: asizeint;
  6300. ThisConst: TCGInt;
  6301. function RegDeallocated: Boolean;
  6302. begin
  6303. TransferUsedRegs(TmpUsedRegs);
  6304. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6305. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6306. end;
  6307. begin
  6308. Result:=false;
  6309. hp1 := nil;
  6310. { replace
  6311. subX const,%reg1
  6312. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6313. dealloc %reg1
  6314. by
  6315. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6316. }
  6317. if MatchOpType(taicpu(p),top_const,top_reg) then
  6318. begin
  6319. ActiveReg := taicpu(p).oper[1]^.reg;
  6320. { Ensures the entire register was updated }
  6321. if (taicpu(p).opsize >= S_L) and
  6322. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6323. MatchInstruction(hp1,A_LEA,[]) and
  6324. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6325. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6326. (
  6327. { Cover the case where the register in the reference is also the destination register }
  6328. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6329. (
  6330. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6331. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6332. RegDeallocated
  6333. )
  6334. ) then
  6335. begin
  6336. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6337. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6338. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6339. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6340. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6341. {$ifdef x86_64}
  6342. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6343. begin
  6344. { Overflow; abort }
  6345. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6346. end
  6347. else
  6348. {$endif x86_64}
  6349. begin
  6350. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6351. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6352. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6353. RemoveCurrentP(p, hp1)
  6354. else
  6355. RemoveCurrentP(p);
  6356. result:=true;
  6357. Exit;
  6358. end;
  6359. end;
  6360. if (
  6361. { Save calling GetNextInstructionUsingReg again }
  6362. Assigned(hp1) or
  6363. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6364. ) and
  6365. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6366. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6367. begin
  6368. if taicpu(hp1).oper[0]^.typ = top_const then
  6369. begin
  6370. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6371. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6372. Result := True;
  6373. { Handle any overflows }
  6374. case taicpu(p).opsize of
  6375. S_B:
  6376. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6377. S_W:
  6378. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6379. S_L:
  6380. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6381. {$ifdef x86_64}
  6382. S_Q:
  6383. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6384. { Overflow; abort }
  6385. Result := False
  6386. else
  6387. taicpu(p).oper[0]^.val := ThisConst;
  6388. {$endif x86_64}
  6389. else
  6390. InternalError(2021102611);
  6391. end;
  6392. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6393. if Result then
  6394. begin
  6395. if (taicpu(p).oper[0]^.val < 0) and
  6396. (
  6397. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6398. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6399. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6400. ) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6403. taicpu(p).opcode := A_SUB;
  6404. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6405. end
  6406. else
  6407. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6408. RemoveInstruction(hp1);
  6409. end;
  6410. end
  6411. else
  6412. begin
  6413. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6414. TransferUsedRegs(TmpUsedRegs);
  6415. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6416. hp2 := p;
  6417. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6418. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6419. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6420. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6421. begin
  6422. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6423. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6424. Asml.Remove(p);
  6425. Asml.InsertAfter(p, hp1);
  6426. p := hp1;
  6427. Result := True;
  6428. Exit;
  6429. end;
  6430. end;
  6431. end;
  6432. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6433. { * change "sub/add const1, reg" or "dec reg" followed by
  6434. "sub const2, reg" to one "sub ..., reg" }
  6435. {$ifdef i386}
  6436. if (taicpu(p).oper[0]^.val = 2) and
  6437. (ActiveReg = NR_ESP) and
  6438. { Don't do the sub/push optimization if the sub }
  6439. { comes from setting up the stack frame (JM) }
  6440. (not(GetLastInstruction(p,hp1)) or
  6441. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6442. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6443. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6444. begin
  6445. hp1 := tai(p.next);
  6446. while Assigned(hp1) and
  6447. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6448. not RegReadByInstruction(NR_ESP,hp1) and
  6449. not RegModifiedByInstruction(NR_ESP,hp1) do
  6450. hp1 := tai(hp1.next);
  6451. if Assigned(hp1) and
  6452. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6453. begin
  6454. taicpu(hp1).changeopsize(S_L);
  6455. if taicpu(hp1).oper[0]^.typ=top_reg then
  6456. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6457. hp1 := tai(p.next);
  6458. RemoveCurrentp(p, hp1);
  6459. Result:=true;
  6460. exit;
  6461. end;
  6462. end;
  6463. {$endif i386}
  6464. if DoArithCombineOpt(p) then
  6465. Result:=true;
  6466. end;
  6467. end;
  6468. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6469. var
  6470. TmpBool1,TmpBool2 : Boolean;
  6471. tmpref : treference;
  6472. hp1,hp2: tai;
  6473. mask, shiftval: tcgint;
  6474. begin
  6475. Result:=false;
  6476. { All these optimisations work on "shl/sal const,%reg" }
  6477. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6478. Exit;
  6479. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6480. (taicpu(p).oper[0]^.val <= 3) then
  6481. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6482. begin
  6483. { should we check the next instruction? }
  6484. TmpBool1 := True;
  6485. { have we found an add/sub which could be
  6486. integrated in the lea? }
  6487. TmpBool2 := False;
  6488. reference_reset(tmpref,2,[]);
  6489. TmpRef.index := taicpu(p).oper[1]^.reg;
  6490. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6491. while TmpBool1 and
  6492. GetNextInstruction(p, hp1) and
  6493. (tai(hp1).typ = ait_instruction) and
  6494. ((((taicpu(hp1).opcode = A_ADD) or
  6495. (taicpu(hp1).opcode = A_SUB)) and
  6496. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6497. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6498. (((taicpu(hp1).opcode = A_INC) or
  6499. (taicpu(hp1).opcode = A_DEC)) and
  6500. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6501. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6502. ((taicpu(hp1).opcode = A_LEA) and
  6503. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6504. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6505. (not GetNextInstruction(hp1,hp2) or
  6506. not instrReadsFlags(hp2)) Do
  6507. begin
  6508. TmpBool1 := False;
  6509. if taicpu(hp1).opcode=A_LEA then
  6510. begin
  6511. if (TmpRef.base = NR_NO) and
  6512. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6513. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6514. { Segment register isn't a concern here }
  6515. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6516. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6517. begin
  6518. TmpBool1 := True;
  6519. TmpBool2 := True;
  6520. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6521. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6522. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6523. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6524. RemoveInstruction(hp1);
  6525. end
  6526. end
  6527. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6528. begin
  6529. TmpBool1 := True;
  6530. TmpBool2 := True;
  6531. case taicpu(hp1).opcode of
  6532. A_ADD:
  6533. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6534. A_SUB:
  6535. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6536. else
  6537. internalerror(2019050536);
  6538. end;
  6539. RemoveInstruction(hp1);
  6540. end
  6541. else
  6542. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6543. (((taicpu(hp1).opcode = A_ADD) and
  6544. (TmpRef.base = NR_NO)) or
  6545. (taicpu(hp1).opcode = A_INC) or
  6546. (taicpu(hp1).opcode = A_DEC)) then
  6547. begin
  6548. TmpBool1 := True;
  6549. TmpBool2 := True;
  6550. case taicpu(hp1).opcode of
  6551. A_ADD:
  6552. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6553. A_INC:
  6554. inc(TmpRef.offset);
  6555. A_DEC:
  6556. dec(TmpRef.offset);
  6557. else
  6558. internalerror(2019050535);
  6559. end;
  6560. RemoveInstruction(hp1);
  6561. end;
  6562. end;
  6563. if TmpBool2
  6564. {$ifndef x86_64}
  6565. or
  6566. ((current_settings.optimizecputype < cpu_Pentium2) and
  6567. (taicpu(p).oper[0]^.val <= 3) and
  6568. not(cs_opt_size in current_settings.optimizerswitches))
  6569. {$endif x86_64}
  6570. then
  6571. begin
  6572. if not(TmpBool2) and
  6573. (taicpu(p).oper[0]^.val=1) then
  6574. begin
  6575. taicpu(p).opcode := A_ADD;
  6576. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6577. end
  6578. else
  6579. begin
  6580. taicpu(p).opcode := A_LEA;
  6581. taicpu(p).loadref(0, TmpRef);
  6582. end;
  6583. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6584. Result := True;
  6585. end;
  6586. end
  6587. {$ifndef x86_64}
  6588. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6589. begin
  6590. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6591. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6592. (unlike shl, which is only Tairable in the U pipe) }
  6593. if taicpu(p).oper[0]^.val=1 then
  6594. begin
  6595. taicpu(p).opcode := A_ADD;
  6596. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6597. Result := True;
  6598. end
  6599. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6600. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6601. else if (taicpu(p).opsize = S_L) and
  6602. (taicpu(p).oper[0]^.val<= 3) then
  6603. begin
  6604. reference_reset(tmpref,2,[]);
  6605. TmpRef.index := taicpu(p).oper[1]^.reg;
  6606. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6607. taicpu(p).opcode := A_LEA;
  6608. taicpu(p).loadref(0, TmpRef);
  6609. Result := True;
  6610. end;
  6611. end
  6612. {$endif x86_64}
  6613. else if
  6614. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6615. (
  6616. (
  6617. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6618. SetAndTest(hp1, hp2)
  6619. {$ifdef x86_64}
  6620. ) or
  6621. (
  6622. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6623. GetNextInstruction(hp1, hp2) and
  6624. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6625. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6626. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6627. {$endif x86_64}
  6628. )
  6629. ) and
  6630. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6631. begin
  6632. { Change:
  6633. shl x, %reg1
  6634. mov -(1<<x), %reg2
  6635. and %reg2, %reg1
  6636. Or:
  6637. shl x, %reg1
  6638. and -(1<<x), %reg1
  6639. To just:
  6640. shl x, %reg1
  6641. Since the and operation only zeroes bits that are already zero from the shl operation
  6642. }
  6643. case taicpu(p).oper[0]^.val of
  6644. 8:
  6645. mask:=$FFFFFFFFFFFFFF00;
  6646. 16:
  6647. mask:=$FFFFFFFFFFFF0000;
  6648. 32:
  6649. mask:=$FFFFFFFF00000000;
  6650. 63:
  6651. { Constant pre-calculated to prevent overflow errors with Int64 }
  6652. mask:=$8000000000000000;
  6653. else
  6654. begin
  6655. if taicpu(p).oper[0]^.val >= 64 then
  6656. { Shouldn't happen realistically, since the register
  6657. is guaranteed to be set to zero at this point }
  6658. mask := 0
  6659. else
  6660. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6661. end;
  6662. end;
  6663. if taicpu(hp1).oper[0]^.val = mask then
  6664. begin
  6665. { Everything checks out, perform the optimisation, as long as
  6666. the FLAGS register isn't being used}
  6667. TransferUsedRegs(TmpUsedRegs);
  6668. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6669. {$ifdef x86_64}
  6670. if (hp1 <> hp2) then
  6671. begin
  6672. { "shl/mov/and" version }
  6673. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6674. { Don't do the optimisation if the FLAGS register is in use }
  6675. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6676. begin
  6677. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6678. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6679. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6680. begin
  6681. RemoveInstruction(hp1);
  6682. Result := True;
  6683. end;
  6684. { Only set Result to True if the 'mov' instruction was removed }
  6685. RemoveInstruction(hp2);
  6686. end;
  6687. end
  6688. else
  6689. {$endif x86_64}
  6690. begin
  6691. { "shl/and" version }
  6692. { Don't do the optimisation if the FLAGS register is in use }
  6693. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6694. begin
  6695. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6696. RemoveInstruction(hp1);
  6697. Result := True;
  6698. end;
  6699. end;
  6700. Exit;
  6701. end
  6702. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6703. begin
  6704. { Even if the mask doesn't allow for its removal, we might be
  6705. able to optimise the mask for the "shl/and" version, which
  6706. may permit other peephole optimisations }
  6707. {$ifdef DEBUG_AOPTCPU}
  6708. mask := taicpu(hp1).oper[0]^.val and mask;
  6709. if taicpu(hp1).oper[0]^.val <> mask then
  6710. begin
  6711. DebugMsg(
  6712. SPeepholeOptimization +
  6713. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6714. ' to $' + debug_tostr(mask) +
  6715. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6716. taicpu(hp1).oper[0]^.val := mask;
  6717. end;
  6718. {$else DEBUG_AOPTCPU}
  6719. { If debugging is off, just set the operand even if it's the same }
  6720. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6721. {$endif DEBUG_AOPTCPU}
  6722. end;
  6723. end;
  6724. {
  6725. change
  6726. shl/sal const,reg
  6727. <op> ...(...,reg,1),...
  6728. into
  6729. <op> ...(...,reg,1 shl const),...
  6730. if const in 1..3
  6731. }
  6732. if MatchOpType(taicpu(p), top_const, top_reg) and
  6733. (taicpu(p).oper[0]^.val in [1..3]) and
  6734. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6735. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6736. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6737. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6738. MatchOpType(taicpu(hp1),top_ref))
  6739. ) and
  6740. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6741. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6742. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6743. begin
  6744. TransferUsedRegs(TmpUsedRegs);
  6745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6746. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6747. begin
  6748. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6749. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6750. RemoveCurrentP(p);
  6751. Result:=true;
  6752. exit;
  6753. end;
  6754. end;
  6755. if MatchOpType(taicpu(p), top_const, top_reg) and
  6756. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6757. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6758. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6759. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6760. begin
  6761. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6762. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6763. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6764. {$ifdef x86_64}
  6765. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6766. {$endif x86_64}
  6767. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6768. begin
  6769. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6770. taicpu(hp1).opcode:=A_MOV;
  6771. taicpu(hp1).oper[0]^.val:=0;
  6772. end
  6773. else
  6774. begin
  6775. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6776. taicpu(hp1).oper[0]^.val:=shiftval;
  6777. end;
  6778. RemoveCurrentP(p);
  6779. Result:=true;
  6780. exit;
  6781. end;
  6782. end;
  6783. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6784. begin
  6785. case shr_size of
  6786. S_B:
  6787. { No valid combinations }
  6788. Result := False;
  6789. S_W:
  6790. Result := (Shift >= 8) and (movz_size = S_BW);
  6791. S_L:
  6792. Result :=
  6793. (Shift >= 24) { Any opsize is valid for this shift } or
  6794. ((Shift >= 16) and (movz_size = S_WL));
  6795. {$ifdef x86_64}
  6796. S_Q:
  6797. Result :=
  6798. (Shift >= 56) { Any opsize is valid for this shift } or
  6799. ((Shift >= 48) and (movz_size = S_WL));
  6800. {$endif x86_64}
  6801. else
  6802. InternalError(2022081510);
  6803. end;
  6804. end;
  6805. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6806. var
  6807. hp1, hp2: tai;
  6808. Shift: TCGInt;
  6809. LimitSize: Topsize;
  6810. DoNotMerge: Boolean;
  6811. begin
  6812. Result := False;
  6813. { All these optimisations work on "shr const,%reg" }
  6814. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6815. Exit;
  6816. DoNotMerge := False;
  6817. Shift := taicpu(p).oper[0]^.val;
  6818. LimitSize := taicpu(p).opsize;
  6819. hp1 := p;
  6820. repeat
  6821. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6822. Exit;
  6823. case taicpu(hp1).opcode of
  6824. A_TEST, A_CMP, A_Jcc:
  6825. { Skip over conditional jumps and relevant comparisons }
  6826. Continue;
  6827. A_MOVZX:
  6828. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6829. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6830. begin
  6831. { Since the original register is being read as is, subsequent
  6832. SHRs must not be merged at this point }
  6833. DoNotMerge := True;
  6834. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6835. begin
  6836. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6839. taicpu(hp1).opcode := A_MOV;
  6840. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6841. case taicpu(hp1).opsize of
  6842. S_BW:
  6843. taicpu(hp1).opsize := S_W;
  6844. S_BL, S_WL:
  6845. taicpu(hp1).opsize := S_L;
  6846. else
  6847. InternalError(2022081503);
  6848. end;
  6849. { p itself hasn't changed, so no need to set Result to True }
  6850. Include(OptsToCheck, aoc_ForceNewIteration);
  6851. { See if there's anything afterwards that can be
  6852. optimised, since the input register hasn't changed }
  6853. Continue;
  6854. end;
  6855. { NOTE: If the MOVZX instruction reads and writes the same
  6856. register, defer this to the post-peephole optimisation stage }
  6857. Exit;
  6858. end;
  6859. end;
  6860. A_SHL, A_SAL, A_SHR:
  6861. if (taicpu(hp1).opsize <= LimitSize) and
  6862. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6863. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6864. begin
  6865. { Make sure the sizes don't exceed the register size limit
  6866. (measured by the shift value falling below the limit) }
  6867. if taicpu(hp1).opsize < LimitSize then
  6868. LimitSize := taicpu(hp1).opsize;
  6869. if taicpu(hp1).opcode = A_SHR then
  6870. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6871. else
  6872. begin
  6873. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6874. DoNotMerge := True;
  6875. end;
  6876. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6877. Exit;
  6878. { Since we've established that the combined shift is within
  6879. limits, we can actually combine the adjacent SHR
  6880. instructions even if they're different sizes }
  6881. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6882. begin
  6883. hp2 := tai(hp1.Previous);
  6884. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6885. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6886. RemoveInstruction(hp1);
  6887. hp1 := hp2;
  6888. { Though p has changed, only the constant has, and its
  6889. effects can still be detected on the next iteration of
  6890. the repeat..until loop }
  6891. Include(OptsToCheck, aoc_ForceNewIteration);
  6892. end;
  6893. { Move onto the next instruction }
  6894. Continue;
  6895. end;
  6896. else
  6897. ;
  6898. end;
  6899. Break;
  6900. until False;
  6901. end;
  6902. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6903. var
  6904. CurrentRef: TReference;
  6905. FullReg: TRegister;
  6906. hp1, hp2: tai;
  6907. begin
  6908. Result := False;
  6909. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6910. Exit;
  6911. { We assume you've checked if the operand is actually a reference by
  6912. this point. If it isn't, you'll most likely get an access violation }
  6913. CurrentRef := first_mov.oper[1]^.ref^;
  6914. { Memory must be aligned }
  6915. if (CurrentRef.offset mod 4) <> 0 then
  6916. Exit;
  6917. Inc(CurrentRef.offset);
  6918. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6919. if MatchOperand(second_mov.oper[0]^, 0) and
  6920. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6921. GetNextInstruction(second_mov, hp1) and
  6922. (hp1.typ = ait_instruction) and
  6923. (taicpu(hp1).opcode = A_MOV) and
  6924. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6925. (taicpu(hp1).oper[0]^.val = 0) then
  6926. begin
  6927. Inc(CurrentRef.offset);
  6928. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6929. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6930. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6931. begin
  6932. case taicpu(hp1).opsize of
  6933. S_B:
  6934. if GetNextInstruction(hp1, hp2) and
  6935. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6936. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6937. (taicpu(hp2).oper[0]^.val = 0) then
  6938. begin
  6939. Inc(CurrentRef.offset);
  6940. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6941. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6942. (taicpu(hp2).opsize = S_B) then
  6943. begin
  6944. RemoveInstruction(hp1);
  6945. RemoveInstruction(hp2);
  6946. first_mov.opsize := S_L;
  6947. if first_mov.oper[0]^.typ = top_reg then
  6948. begin
  6949. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6950. { Reuse second_mov as a MOVZX instruction }
  6951. second_mov.opcode := A_MOVZX;
  6952. second_mov.opsize := S_BL;
  6953. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6954. second_mov.loadreg(1, FullReg);
  6955. first_mov.oper[0]^.reg := FullReg;
  6956. asml.Remove(second_mov);
  6957. asml.InsertBefore(second_mov, first_mov);
  6958. end
  6959. else
  6960. { It's a value }
  6961. begin
  6962. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6963. RemoveInstruction(second_mov);
  6964. end;
  6965. Result := True;
  6966. Exit;
  6967. end;
  6968. end;
  6969. S_W:
  6970. begin
  6971. RemoveInstruction(hp1);
  6972. first_mov.opsize := S_L;
  6973. if first_mov.oper[0]^.typ = top_reg then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6976. { Reuse second_mov as a MOVZX instruction }
  6977. second_mov.opcode := A_MOVZX;
  6978. second_mov.opsize := S_BL;
  6979. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6980. second_mov.loadreg(1, FullReg);
  6981. first_mov.oper[0]^.reg := FullReg;
  6982. asml.Remove(second_mov);
  6983. asml.InsertBefore(second_mov, first_mov);
  6984. end
  6985. else
  6986. { It's a value }
  6987. begin
  6988. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6989. RemoveInstruction(second_mov);
  6990. end;
  6991. Result := True;
  6992. Exit;
  6993. end;
  6994. else
  6995. ;
  6996. end;
  6997. end;
  6998. end;
  6999. end;
  7000. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7001. { returns true if a "continue" should be done after this optimization }
  7002. var
  7003. hp1, hp2, hp3: tai;
  7004. begin
  7005. Result := false;
  7006. hp3 := nil;
  7007. if MatchOpType(taicpu(p),top_ref) and
  7008. GetNextInstruction(p, hp1) and
  7009. (hp1.typ = ait_instruction) and
  7010. (((taicpu(hp1).opcode = A_FLD) and
  7011. (taicpu(p).opcode = A_FSTP)) or
  7012. ((taicpu(p).opcode = A_FISTP) and
  7013. (taicpu(hp1).opcode = A_FILD))) and
  7014. MatchOpType(taicpu(hp1),top_ref) and
  7015. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7016. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7017. begin
  7018. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7019. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7020. GetNextInstruction(hp1, hp2) and
  7021. (((hp2.typ = ait_instruction) and
  7022. IsExitCode(hp2) and
  7023. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7024. not(assigned(current_procinfo.procdef.funcretsym) and
  7025. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7026. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7027. { fstp <temp>
  7028. fld <temp>
  7029. <dealloc> <temp>
  7030. }
  7031. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7032. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7033. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7034. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7035. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7036. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7037. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7038. )
  7039. )
  7040. ) then
  7041. begin
  7042. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7043. RemoveInstruction(hp1);
  7044. RemoveCurrentP(p, hp2);
  7045. { first case: exit code }
  7046. if hp2.typ = ait_instruction then
  7047. RemoveLastDeallocForFuncRes(p);
  7048. Result := true;
  7049. end
  7050. else
  7051. { we can do this only in fast math mode as fstp is rounding ...
  7052. ... still disabled as it breaks the compiler and/or rtl }
  7053. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7054. { ... or if another fstp equal to the first one follows }
  7055. GetNextInstruction(hp1,hp2) and
  7056. (hp2.typ = ait_instruction) and
  7057. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7058. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7059. begin
  7060. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7061. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7062. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7063. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7064. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7065. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7066. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7067. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7068. ) then
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7071. RemoveCurrentP(p,hp2);
  7072. RemoveInstruction(hp1);
  7073. Result := true;
  7074. end
  7075. else if { fst can't store an extended/comp value }
  7076. (taicpu(p).opsize <> S_FX) and
  7077. (taicpu(p).opsize <> S_IQ) then
  7078. begin
  7079. if (taicpu(p).opcode = A_FSTP) then
  7080. taicpu(p).opcode := A_FST
  7081. else
  7082. taicpu(p).opcode := A_FIST;
  7083. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7084. RemoveInstruction(hp1);
  7085. Result := true;
  7086. end;
  7087. end;
  7088. end;
  7089. end;
  7090. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7091. var
  7092. hp1, hp2, hp3: tai;
  7093. begin
  7094. result:=false;
  7095. if MatchOpType(taicpu(p),top_reg) and
  7096. GetNextInstruction(p, hp1) and
  7097. (hp1.typ = Ait_Instruction) and
  7098. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7099. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7100. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7101. { change to
  7102. fld reg fxxx reg,st
  7103. fxxxp st, st1 (hp1)
  7104. Remark: non commutative operations must be reversed!
  7105. }
  7106. begin
  7107. case taicpu(hp1).opcode Of
  7108. A_FMULP,A_FADDP,
  7109. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7110. begin
  7111. case taicpu(hp1).opcode Of
  7112. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7113. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7114. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7115. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7116. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7117. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7118. else
  7119. internalerror(2019050534);
  7120. end;
  7121. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7122. taicpu(hp1).oper[1]^.reg := NR_ST;
  7123. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7124. RemoveCurrentP(p, hp1);
  7125. Result:=true;
  7126. exit;
  7127. end;
  7128. else
  7129. ;
  7130. end;
  7131. end
  7132. else
  7133. if MatchOpType(taicpu(p),top_ref) and
  7134. GetNextInstruction(p, hp2) and
  7135. (hp2.typ = Ait_Instruction) and
  7136. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7137. (taicpu(p).opsize in [S_FS, S_FL]) and
  7138. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7139. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7140. if GetLastInstruction(p, hp1) and
  7141. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7142. MatchOpType(taicpu(hp1),top_ref) and
  7143. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7144. if ((taicpu(hp2).opcode = A_FMULP) or
  7145. (taicpu(hp2).opcode = A_FADDP)) then
  7146. { change to
  7147. fld/fst mem1 (hp1) fld/fst mem1
  7148. fld mem1 (p) fadd/
  7149. faddp/ fmul st, st
  7150. fmulp st, st1 (hp2) }
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7153. RemoveCurrentP(p, hp1);
  7154. if (taicpu(hp2).opcode = A_FADDP) then
  7155. taicpu(hp2).opcode := A_FADD
  7156. else
  7157. taicpu(hp2).opcode := A_FMUL;
  7158. taicpu(hp2).oper[1]^.reg := NR_ST;
  7159. end
  7160. else
  7161. { change to
  7162. fld/fst mem1 (hp1) fld/fst mem1
  7163. fld mem1 (p) fld st
  7164. }
  7165. begin
  7166. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7167. taicpu(p).changeopsize(S_FL);
  7168. taicpu(p).loadreg(0,NR_ST);
  7169. end
  7170. else
  7171. begin
  7172. case taicpu(hp2).opcode Of
  7173. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7174. { change to
  7175. fld/fst mem1 (hp1) fld/fst mem1
  7176. fld mem2 (p) fxxx mem2
  7177. fxxxp st, st1 (hp2) }
  7178. begin
  7179. case taicpu(hp2).opcode Of
  7180. A_FADDP: taicpu(p).opcode := A_FADD;
  7181. A_FMULP: taicpu(p).opcode := A_FMUL;
  7182. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7183. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7184. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7185. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7186. else
  7187. internalerror(2019050533);
  7188. end;
  7189. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7190. RemoveInstruction(hp2);
  7191. end
  7192. else
  7193. ;
  7194. end
  7195. end
  7196. end;
  7197. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7198. begin
  7199. Result := condition_in(cond1, cond2) or
  7200. { Not strictly subsets due to the actual flags checked, but because we're
  7201. comparing integers, E is a subset of AE and GE and their aliases }
  7202. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7203. end;
  7204. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7205. var
  7206. v: TCGInt;
  7207. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7208. FirstMatch, TempBool: Boolean;
  7209. NewReg: TRegister;
  7210. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7211. begin
  7212. Result:=false;
  7213. { All these optimisations need a next instruction }
  7214. if not GetNextInstruction(p, hp1) then
  7215. Exit;
  7216. true_hp1 := hp1;
  7217. { Search for:
  7218. cmp ###,###
  7219. j(c1) @lbl1
  7220. ...
  7221. @lbl:
  7222. cmp ###,### (same comparison as above)
  7223. j(c2) @lbl2
  7224. If c1 is a subset of c2, change to:
  7225. cmp ###,###
  7226. j(c1) @lbl2
  7227. (@lbl1 may become a dead label as a result)
  7228. }
  7229. { Also handle cases where there are multiple jumps in a row }
  7230. p_jump := hp1;
  7231. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7232. begin
  7233. Prefetch(p_jump.Next);
  7234. if IsJumpToLabel(taicpu(p_jump)) then
  7235. begin
  7236. { Do jump optimisations first in case the condition becomes
  7237. unnecessary }
  7238. TempBool := True;
  7239. if DoJumpOptimizations(p_jump, TempBool) or
  7240. not TempBool then
  7241. begin
  7242. if Assigned(p_jump) then
  7243. begin
  7244. { CollapseZeroDistJump will be set to the label or an align
  7245. before it after the jump if it optimises, whether or not
  7246. the label is live or dead }
  7247. if (p_jump.typ = ait_align) or
  7248. (
  7249. (p_jump.typ = ait_label) and
  7250. not (tai_label(p_jump).labsym.is_used)
  7251. ) then
  7252. GetNextInstruction(p_jump, p_jump);
  7253. end;
  7254. TransferUsedRegs(TmpUsedRegs);
  7255. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7256. if not Assigned(p_jump) or
  7257. (
  7258. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7259. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7260. ) then
  7261. begin
  7262. { No more conditional jumps; conditional statement is no longer required }
  7263. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7264. RemoveCurrentP(p);
  7265. Result := True;
  7266. Exit;
  7267. end;
  7268. hp1 := p_jump;
  7269. Include(OptsToCheck, aoc_ForceNewIteration);
  7270. Continue;
  7271. end;
  7272. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7273. if GetNextInstruction(p_jump, hp2) and
  7274. (
  7275. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7276. not TempBool
  7277. ) then
  7278. begin
  7279. hp1 := p_jump;
  7280. Include(OptsToCheck, aoc_ForceNewIteration);
  7281. Continue;
  7282. end;
  7283. p_label := nil;
  7284. if Assigned(JumpLabel) then
  7285. p_label := getlabelwithsym(JumpLabel);
  7286. if Assigned(p_label) and
  7287. GetNextInstruction(p_label, p_dist) and
  7288. MatchInstruction(p_dist, A_CMP, []) and
  7289. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7290. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7291. GetNextInstruction(p_dist, hp1_dist) and
  7292. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7293. begin
  7294. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7295. if JumpLabel = JumpLabel_dist then
  7296. { This is an infinite loop }
  7297. Exit;
  7298. { Best optimisation when the first condition is a subset (or equal) of the second }
  7299. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7300. begin
  7301. { Any registers used here will already be allocated }
  7302. if Assigned(JumpLabel) then
  7303. JumpLabel.DecRefs;
  7304. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7305. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7306. Include(OptsToCheck, aoc_ForceNewIteration);
  7307. { Don't exit yet. Since p and p_jump haven't actually been
  7308. removed, we can check for more on this iteration }
  7309. end
  7310. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7311. GetNextInstruction(hp1_dist, hp1_label) and
  7312. (hp1_label.typ = ait_label) then
  7313. begin
  7314. JumpLabel_far := tai_label(hp1_label).labsym;
  7315. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7316. { This is an infinite loop }
  7317. Exit;
  7318. if Assigned(JumpLabel_far) then
  7319. begin
  7320. { In this situation, if the first jump branches, the second one will never,
  7321. branch so change the destination label to after the second jump }
  7322. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7323. if Assigned(JumpLabel) then
  7324. JumpLabel.DecRefs;
  7325. JumpLabel_far.IncRefs;
  7326. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7327. Result := True;
  7328. { Don't exit yet. Since p and p_jump haven't actually been
  7329. removed, we can check for more on this iteration }
  7330. Continue;
  7331. end;
  7332. end;
  7333. end;
  7334. end;
  7335. { Search for:
  7336. cmp ###,###
  7337. j(c1) @lbl1
  7338. cmp ###,### (same as first)
  7339. Remove second cmp
  7340. }
  7341. if GetNextInstruction(p_jump, hp2) and
  7342. (
  7343. (
  7344. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7345. (
  7346. (
  7347. MatchOpType(taicpu(p), top_const, top_reg) and
  7348. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7349. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7350. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7351. ) or (
  7352. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7353. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7354. )
  7355. )
  7356. ) or (
  7357. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7358. MatchOperand(taicpu(p).oper[0]^, 0) and
  7359. (taicpu(p).oper[1]^.typ = top_reg) and
  7360. MatchInstruction(hp2, A_TEST, []) and
  7361. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7362. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7363. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7364. )
  7365. ) then
  7366. begin
  7367. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7368. TransferUsedRegs(TmpUsedRegs);
  7369. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7370. RemoveInstruction(hp2);
  7371. Result := True;
  7372. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7373. end
  7374. else
  7375. begin
  7376. { hp2 is the next instruction, so save time and just set p_jump
  7377. to it instead of calling GetNextInstruction below }
  7378. p_jump := hp2;
  7379. Continue;
  7380. end;
  7381. GetNextInstruction(p_jump, p_jump);
  7382. end;
  7383. if (
  7384. { Don't call GetNextInstruction again if we already have it }
  7385. (true_hp1 = p_jump) or
  7386. GetNextInstruction(p, hp1)
  7387. ) and
  7388. MatchInstruction(hp1, A_Jcc, []) and
  7389. IsJumpToLabel(taicpu(hp1)) and
  7390. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7391. GetNextInstruction(hp1, hp2) then
  7392. begin
  7393. {
  7394. cmp x, y (or "cmp y, x")
  7395. je @lbl
  7396. mov x, y
  7397. @lbl:
  7398. (x and y can be constants, registers or references)
  7399. Change to:
  7400. mov x, y (x and y will always be equal in the end)
  7401. @lbl: (may beceome a dead label)
  7402. Also:
  7403. cmp x, y (or "cmp y, x")
  7404. jne @lbl
  7405. mov x, y
  7406. @lbl:
  7407. (x and y can be constants, registers or references)
  7408. Change to:
  7409. Absolutely nothing! (Except @lbl if it's still live)
  7410. }
  7411. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7412. (
  7413. (
  7414. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7415. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7416. ) or (
  7417. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7418. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7419. )
  7420. ) and
  7421. GetNextInstruction(hp2, hp1_label) and
  7422. (hp1_label.typ = ait_label) and
  7423. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7424. begin
  7425. tai_label(hp1_label).labsym.DecRefs;
  7426. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7427. begin
  7428. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7429. RemoveInstruction(hp2);
  7430. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7431. end
  7432. else
  7433. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7434. RemoveInstruction(hp1);
  7435. RemoveCurrentp(p, hp2);
  7436. Result := True;
  7437. Exit;
  7438. end;
  7439. {
  7440. Try to optimise the following:
  7441. cmp $x,### ($x and $y can be registers or constants)
  7442. je @lbl1 (only reference)
  7443. cmp $y,### (### are identical)
  7444. @Lbl:
  7445. sete %reg1
  7446. Change to:
  7447. cmp $x,###
  7448. sete %reg2 (allocate new %reg2)
  7449. cmp $y,###
  7450. sete %reg1
  7451. orb %reg2,%reg1
  7452. (dealloc %reg2)
  7453. This adds an instruction (so don't perform under -Os), but it removes
  7454. a conditional branch.
  7455. }
  7456. if not (cs_opt_size in current_settings.optimizerswitches) and
  7457. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7458. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7459. { The first operand of CMP instructions can only be a register or
  7460. immediate anyway, so no need to check }
  7461. GetNextInstruction(hp2, p_label) and
  7462. (p_label.typ = ait_label) and
  7463. (tai_label(p_label).labsym.getrefs = 1) and
  7464. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7465. GetNextInstruction(p_label, p_dist) and
  7466. MatchInstruction(p_dist, A_SETcc, []) and
  7467. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7468. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7469. begin
  7470. TransferUsedRegs(TmpUsedRegs);
  7471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7472. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7473. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7474. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7475. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7476. { Get the instruction after the SETcc instruction so we can
  7477. allocate a new register over the entire range }
  7478. GetNextInstruction(p_dist, hp1_dist) then
  7479. begin
  7480. { Register can appear in p if it's not used afterwards, so only
  7481. allocate between hp1 and hp1_dist }
  7482. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7483. if NewReg <> NR_NO then
  7484. begin
  7485. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7486. { Change the jump instruction into a SETcc instruction }
  7487. taicpu(hp1).opcode := A_SETcc;
  7488. taicpu(hp1).opsize := S_B;
  7489. taicpu(hp1).loadreg(0, NewReg);
  7490. { This is now a dead label }
  7491. tai_label(p_label).labsym.decrefs;
  7492. { Prefer adding before the next instruction so the FLAGS
  7493. register is deallicated first }
  7494. AsmL.InsertBefore(
  7495. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7496. hp1_dist
  7497. );
  7498. Result := True;
  7499. { Don't exit yet, as p wasn't changed and hp1, while
  7500. modified, is still intact and might be optimised by the
  7501. SETcc optimisation below }
  7502. end;
  7503. end;
  7504. end;
  7505. end;
  7506. if (taicpu(p).oper[0]^.typ = top_const) and
  7507. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7508. begin
  7509. if (taicpu(p).oper[0]^.val = 0) and
  7510. (taicpu(p).oper[1]^.typ = top_reg) then
  7511. begin
  7512. hp2 := p;
  7513. FirstMatch := True;
  7514. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7515. anything meaningful once it's converted to "test %reg,%reg";
  7516. additionally, some jumps will always (or never) branch, so
  7517. evaluate every jump immediately following the
  7518. comparison, optimising the conditions if possible.
  7519. Similarly with SETcc... those that are always set to 0 or 1
  7520. are changed to MOV instructions }
  7521. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7522. (
  7523. GetNextInstruction(hp2, hp1) and
  7524. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7525. ) do
  7526. begin
  7527. Prefetch(hp1.Next);
  7528. FirstMatch := False;
  7529. case taicpu(hp1).condition of
  7530. C_B, C_C, C_NAE, C_O:
  7531. { For B/NAE:
  7532. Will never branch since an unsigned integer can never be below zero
  7533. For C/O:
  7534. Result cannot overflow because 0 is being subtracted
  7535. }
  7536. begin
  7537. if taicpu(hp1).opcode = A_Jcc then
  7538. begin
  7539. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7540. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7541. RemoveInstruction(hp1);
  7542. { Since hp1 was deleted, hp2 must not be updated }
  7543. Continue;
  7544. end
  7545. else
  7546. begin
  7547. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7548. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7549. taicpu(hp1).opcode := A_MOV;
  7550. taicpu(hp1).ops := 2;
  7551. taicpu(hp1).condition := C_None;
  7552. taicpu(hp1).opsize := S_B;
  7553. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7554. taicpu(hp1).loadconst(0, 0);
  7555. end;
  7556. end;
  7557. C_BE, C_NA:
  7558. begin
  7559. { Will only branch if equal to zero }
  7560. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7561. taicpu(hp1).condition := C_E;
  7562. end;
  7563. C_A, C_NBE:
  7564. begin
  7565. { Will only branch if not equal to zero }
  7566. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7567. taicpu(hp1).condition := C_NE;
  7568. end;
  7569. C_AE, C_NB, C_NC, C_NO:
  7570. begin
  7571. { Will always branch }
  7572. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7573. if taicpu(hp1).opcode = A_Jcc then
  7574. begin
  7575. MakeUnconditional(taicpu(hp1));
  7576. { Any jumps/set that follow will now be dead code }
  7577. RemoveDeadCodeAfterJump(taicpu(hp1));
  7578. Break;
  7579. end
  7580. else
  7581. begin
  7582. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7583. taicpu(hp1).opcode := A_MOV;
  7584. taicpu(hp1).ops := 2;
  7585. taicpu(hp1).condition := C_None;
  7586. taicpu(hp1).opsize := S_B;
  7587. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7588. taicpu(hp1).loadconst(0, 1);
  7589. end;
  7590. end;
  7591. C_None:
  7592. InternalError(2020012201);
  7593. C_P, C_PE, C_NP, C_PO:
  7594. { We can't handle parity checks and they should never be generated
  7595. after a general-purpose CMP (it's used in some floating-point
  7596. comparisons that don't use CMP) }
  7597. InternalError(2020012202);
  7598. else
  7599. { Zero/Equality, Sign, their complements and all of the
  7600. signed comparisons do not need to be converted };
  7601. end;
  7602. hp2 := hp1;
  7603. end;
  7604. { Convert the instruction to a TEST }
  7605. taicpu(p).opcode := A_TEST;
  7606. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7607. Result := True;
  7608. Exit;
  7609. end
  7610. else
  7611. begin
  7612. TransferUsedRegs(TmpUsedRegs);
  7613. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7614. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7615. begin
  7616. if (taicpu(p).oper[0]^.val = 1) and
  7617. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7618. begin
  7619. { Convert; To:
  7620. cmp $1,r/m cmp $0,r/m
  7621. jl @lbl jle @lbl
  7622. (Also do inverted conditions)
  7623. }
  7624. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7625. taicpu(p).oper[0]^.val := 0;
  7626. if taicpu(hp1).condition in [C_L, C_NGE] then
  7627. taicpu(hp1).condition := C_LE
  7628. else
  7629. taicpu(hp1).condition := C_NLE;
  7630. { If the instruction is now "cmp $0,%reg", convert it to a
  7631. TEST (and effectively do the work of the "cmp $0,%reg" in
  7632. the block above)
  7633. }
  7634. if (taicpu(p).oper[1]^.typ = top_reg) then
  7635. begin
  7636. taicpu(p).opcode := A_TEST;
  7637. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7638. end;
  7639. Result := True;
  7640. Exit;
  7641. end
  7642. else if (taicpu(p).oper[1]^.typ = top_reg)
  7643. {$ifdef x86_64}
  7644. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7645. {$endif x86_64}
  7646. then
  7647. begin
  7648. { cmp register,$8000 neg register
  7649. je target --> jo target
  7650. .... only if register is deallocated before jump.}
  7651. case Taicpu(p).opsize of
  7652. S_B: v:=$80;
  7653. S_W: v:=$8000;
  7654. S_L: v:=qword($80000000);
  7655. else
  7656. internalerror(2013112905);
  7657. end;
  7658. if (taicpu(p).oper[0]^.val=v) and
  7659. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7660. begin
  7661. TransferUsedRegs(TmpUsedRegs);
  7662. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7663. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7664. begin
  7665. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7666. Taicpu(p).opcode:=A_NEG;
  7667. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7668. Taicpu(p).clearop(1);
  7669. Taicpu(p).ops:=1;
  7670. if Taicpu(hp1).condition=C_E then
  7671. Taicpu(hp1).condition:=C_O
  7672. else
  7673. Taicpu(hp1).condition:=C_NO;
  7674. Result:=true;
  7675. exit;
  7676. end;
  7677. end;
  7678. end;
  7679. end;
  7680. end;
  7681. end;
  7682. if TrySwapMovCmp(p, hp1) then
  7683. begin
  7684. Result := True;
  7685. Exit;
  7686. end;
  7687. end;
  7688. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7689. var
  7690. hp1: tai;
  7691. begin
  7692. {
  7693. remove the second (v)pxor from
  7694. pxor reg,reg
  7695. ...
  7696. pxor reg,reg
  7697. }
  7698. Result:=false;
  7699. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7700. MatchOpType(taicpu(p),top_reg,top_reg) and
  7701. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7702. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7703. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7704. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7705. begin
  7706. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7707. RemoveInstruction(hp1);
  7708. Result:=true;
  7709. Exit;
  7710. end
  7711. {
  7712. replace
  7713. pxor reg1,reg1
  7714. movapd/s reg1,reg2
  7715. dealloc reg1
  7716. by
  7717. pxor reg2,reg2
  7718. }
  7719. else if GetNextInstruction(p,hp1) and
  7720. { we mix single and double opperations here because we assume that the compiler
  7721. generates vmovapd only after double operations and vmovaps only after single operations }
  7722. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7723. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7724. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7725. (taicpu(p).oper[0]^.typ=top_reg) then
  7726. begin
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7729. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7730. begin
  7731. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7732. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7733. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7734. RemoveInstruction(hp1);
  7735. result:=true;
  7736. end;
  7737. end;
  7738. end;
  7739. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7740. var
  7741. hp1: tai;
  7742. begin
  7743. {
  7744. remove the second (v)pxor from
  7745. (v)pxor reg,reg
  7746. ...
  7747. (v)pxor reg,reg
  7748. }
  7749. Result:=false;
  7750. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7751. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7752. begin
  7753. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7754. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7755. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7756. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7757. begin
  7758. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7759. RemoveInstruction(hp1);
  7760. Result:=true;
  7761. Exit;
  7762. end;
  7763. {$ifdef x86_64}
  7764. {
  7765. replace
  7766. vpxor reg1,reg1,reg1
  7767. vmov reg,mem
  7768. by
  7769. movq $0,mem
  7770. }
  7771. if GetNextInstruction(p,hp1) and
  7772. MatchInstruction(hp1,A_VMOVSD,[]) and
  7773. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7774. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7775. begin
  7776. TransferUsedRegs(TmpUsedRegs);
  7777. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7778. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7779. begin
  7780. taicpu(hp1).loadconst(0,0);
  7781. taicpu(hp1).opcode:=A_MOV;
  7782. taicpu(hp1).opsize:=S_Q;
  7783. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7784. RemoveCurrentP(p);
  7785. result:=true;
  7786. Exit;
  7787. end;
  7788. end;
  7789. {$endif x86_64}
  7790. end
  7791. {
  7792. replace
  7793. vpxor reg1,reg1,reg2
  7794. by
  7795. vpxor reg2,reg2,reg2
  7796. to avoid unncessary data dependencies
  7797. }
  7798. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7799. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7800. begin
  7801. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7802. { avoid unncessary data dependency }
  7803. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7804. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7805. result:=true;
  7806. exit;
  7807. end;
  7808. Result:=OptPass1VOP(p);
  7809. end;
  7810. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7811. var
  7812. hp1 : tai;
  7813. begin
  7814. result:=false;
  7815. { replace
  7816. IMul const,%mreg1,%mreg2
  7817. Mov %reg2,%mreg3
  7818. dealloc %mreg3
  7819. by
  7820. Imul const,%mreg1,%mreg23
  7821. }
  7822. if (taicpu(p).ops=3) and
  7823. GetNextInstruction(p,hp1) and
  7824. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7825. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7826. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7827. begin
  7828. TransferUsedRegs(TmpUsedRegs);
  7829. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7830. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7831. begin
  7832. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7833. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7834. RemoveInstruction(hp1);
  7835. result:=true;
  7836. end;
  7837. end;
  7838. end;
  7839. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7840. var
  7841. hp1 : tai;
  7842. begin
  7843. result:=false;
  7844. { replace
  7845. IMul %reg0,%reg1,%reg2
  7846. Mov %reg2,%reg3
  7847. dealloc %reg2
  7848. by
  7849. Imul %reg0,%reg1,%reg3
  7850. }
  7851. if GetNextInstruction(p,hp1) and
  7852. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7853. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7854. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7855. begin
  7856. TransferUsedRegs(TmpUsedRegs);
  7857. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7858. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7859. begin
  7860. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7861. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7862. RemoveInstruction(hp1);
  7863. result:=true;
  7864. end;
  7865. end;
  7866. end;
  7867. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7868. var
  7869. hp1: tai;
  7870. begin
  7871. Result:=false;
  7872. { get rid of
  7873. (v)cvtss2sd reg0,<reg1,>reg2
  7874. (v)cvtss2sd reg2,<reg2,>reg0
  7875. }
  7876. if GetNextInstruction(p,hp1) and
  7877. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7878. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7879. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7880. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7881. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7882. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7883. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7884. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7885. )
  7886. ) then
  7887. begin
  7888. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7889. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7890. begin
  7891. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7892. RemoveCurrentP(p);
  7893. RemoveInstruction(hp1);
  7894. end
  7895. else
  7896. begin
  7897. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7898. if taicpu(hp1).opcode=A_CVTSD2SS then
  7899. begin
  7900. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7901. taicpu(p).opcode:=A_MOVAPS;
  7902. end
  7903. else
  7904. begin
  7905. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7906. taicpu(p).opcode:=A_VMOVAPS;
  7907. end;
  7908. taicpu(p).ops:=2;
  7909. RemoveInstruction(hp1);
  7910. end;
  7911. Result:=true;
  7912. Exit;
  7913. end;
  7914. end;
  7915. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7916. var
  7917. hp1, hp2, hp3, hp4, hp5: tai;
  7918. ThisReg: TRegister;
  7919. begin
  7920. Result := False;
  7921. if not GetNextInstruction(p,hp1) then
  7922. Exit;
  7923. {
  7924. convert
  7925. j<c> .L1
  7926. mov 1,reg
  7927. jmp .L2
  7928. .L1
  7929. mov 0,reg
  7930. .L2
  7931. into
  7932. mov 0,reg
  7933. set<not(c)> reg
  7934. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7935. would destroy the flag contents
  7936. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7937. executed at the same time as a previous comparison.
  7938. set<not(c)> reg
  7939. movzx reg, reg
  7940. }
  7941. if MatchInstruction(hp1,A_MOV,[]) and
  7942. (taicpu(hp1).oper[0]^.typ = top_const) and
  7943. (
  7944. (
  7945. (taicpu(hp1).oper[1]^.typ = top_reg)
  7946. {$ifdef i386}
  7947. { Under i386, ESI, EDI, EBP and ESP
  7948. don't have an 8-bit representation }
  7949. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7950. {$endif i386}
  7951. ) or (
  7952. {$ifdef i386}
  7953. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7954. {$endif i386}
  7955. (taicpu(hp1).opsize = S_B)
  7956. )
  7957. ) and
  7958. GetNextInstruction(hp1,hp2) and
  7959. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7960. GetNextInstruction(hp2,hp3) and
  7961. (hp3.typ=ait_label) and
  7962. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7963. GetNextInstruction(hp3,hp4) and
  7964. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7965. (taicpu(hp4).oper[0]^.typ = top_const) and
  7966. (
  7967. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7968. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7969. ) and
  7970. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7971. GetNextInstruction(hp4,hp5) and
  7972. (hp5.typ=ait_label) and
  7973. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7974. begin
  7975. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7976. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7977. tai_label(hp3).labsym.DecRefs;
  7978. { If this isn't the only reference to the middle label, we can
  7979. still make a saving - only that the first jump and everything
  7980. that follows will remain. }
  7981. if (tai_label(hp3).labsym.getrefs = 0) then
  7982. begin
  7983. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7984. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7985. else
  7986. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7987. { remove jump, first label and second MOV (also catching any aligns) }
  7988. repeat
  7989. if not GetNextInstruction(hp2, hp3) then
  7990. InternalError(2021040810);
  7991. RemoveInstruction(hp2);
  7992. hp2 := hp3;
  7993. until hp2 = hp5;
  7994. { Don't decrement reference count before the removal loop
  7995. above, otherwise GetNextInstruction won't stop on the
  7996. the label }
  7997. tai_label(hp5).labsym.DecRefs;
  7998. end
  7999. else
  8000. begin
  8001. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8002. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8003. else
  8004. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8005. end;
  8006. taicpu(p).opcode:=A_SETcc;
  8007. taicpu(p).opsize:=S_B;
  8008. taicpu(p).is_jmp:=False;
  8009. if taicpu(hp1).opsize=S_B then
  8010. begin
  8011. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8012. if taicpu(hp1).oper[1]^.typ = top_reg then
  8013. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8014. RemoveInstruction(hp1);
  8015. end
  8016. else
  8017. begin
  8018. { Will be a register because the size can't be S_B otherwise }
  8019. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8020. taicpu(p).loadreg(0, ThisReg);
  8021. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8022. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8023. begin
  8024. case taicpu(hp1).opsize of
  8025. S_W:
  8026. taicpu(hp1).opsize := S_BW;
  8027. S_L:
  8028. taicpu(hp1).opsize := S_BL;
  8029. {$ifdef x86_64}
  8030. S_Q:
  8031. begin
  8032. taicpu(hp1).opsize := S_BL;
  8033. { Change the destination register to 32-bit }
  8034. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8035. end;
  8036. {$endif x86_64}
  8037. else
  8038. InternalError(2021040820);
  8039. end;
  8040. taicpu(hp1).opcode := A_MOVZX;
  8041. taicpu(hp1).loadreg(0, ThisReg);
  8042. end
  8043. else
  8044. begin
  8045. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8046. { hp1 is already a MOV instruction with the correct register }
  8047. taicpu(hp1).loadconst(0, 0);
  8048. { Inserting it right before p will guarantee that the flags are also tracked }
  8049. asml.Remove(hp1);
  8050. asml.InsertBefore(hp1, p);
  8051. end;
  8052. end;
  8053. Result:=true;
  8054. exit;
  8055. end
  8056. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8057. Result := TryJccStcClcOpt(p, hp1)
  8058. else if (hp1.typ = ait_label) then
  8059. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8060. end;
  8061. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8062. var
  8063. hp1, hp2, hp3: tai;
  8064. SourceRef, TargetRef: TReference;
  8065. CurrentReg: TRegister;
  8066. begin
  8067. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8068. if not UseAVX then
  8069. InternalError(2021100501);
  8070. Result := False;
  8071. { Look for the following to simplify:
  8072. vmovdqa/u x(mem1), %xmmreg
  8073. vmovdqa/u %xmmreg, y(mem2)
  8074. vmovdqa/u x+16(mem1), %xmmreg
  8075. vmovdqa/u %xmmreg, y+16(mem2)
  8076. Change to:
  8077. vmovdqa/u x(mem1), %ymmreg
  8078. vmovdqa/u %ymmreg, y(mem2)
  8079. vpxor %ymmreg, %ymmreg, %ymmreg
  8080. ( The VPXOR instruction is to zero the upper half, thus removing the
  8081. need to call the potentially expensive VZEROUPPER instruction. Other
  8082. peephole optimisations can remove VPXOR if it's unnecessary )
  8083. }
  8084. TransferUsedRegs(TmpUsedRegs);
  8085. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8086. { NOTE: In the optimisations below, if the references dictate that an
  8087. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8088. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8089. if (taicpu(p).opsize = S_XMM) and
  8090. MatchOpType(taicpu(p), top_ref, top_reg) and
  8091. GetNextInstruction(p, hp1) and
  8092. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8093. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8094. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8095. begin
  8096. SourceRef := taicpu(p).oper[0]^.ref^;
  8097. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8098. if GetNextInstruction(hp1, hp2) and
  8099. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8100. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8101. begin
  8102. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8103. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8104. Inc(SourceRef.offset, 16);
  8105. { Reuse the register in the first block move }
  8106. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8107. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8108. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8109. begin
  8110. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8111. Inc(TargetRef.offset, 16);
  8112. if GetNextInstruction(hp2, hp3) and
  8113. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8114. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8115. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8116. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8117. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8118. begin
  8119. { Update the register tracking to the new size }
  8120. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8121. { Remember that the offsets are 16 ahead }
  8122. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8123. if not (
  8124. ((SourceRef.offset mod 32) = 16) and
  8125. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8126. ) then
  8127. taicpu(p).opcode := A_VMOVDQU;
  8128. taicpu(p).opsize := S_YMM;
  8129. taicpu(p).oper[1]^.reg := CurrentReg;
  8130. if not (
  8131. ((TargetRef.offset mod 32) = 16) and
  8132. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8133. ) then
  8134. taicpu(hp1).opcode := A_VMOVDQU;
  8135. taicpu(hp1).opsize := S_YMM;
  8136. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8137. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8138. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8139. if (pi_uses_ymm in current_procinfo.flags) then
  8140. RemoveInstruction(hp2)
  8141. else
  8142. begin
  8143. taicpu(hp2).opcode := A_VPXOR;
  8144. taicpu(hp2).opsize := S_YMM;
  8145. taicpu(hp2).loadreg(0, CurrentReg);
  8146. taicpu(hp2).loadreg(1, CurrentReg);
  8147. taicpu(hp2).loadreg(2, CurrentReg);
  8148. taicpu(hp2).ops := 3;
  8149. end;
  8150. RemoveInstruction(hp3);
  8151. Result := True;
  8152. Exit;
  8153. end;
  8154. end
  8155. else
  8156. begin
  8157. { See if the next references are 16 less rather than 16 greater }
  8158. Dec(SourceRef.offset, 32); { -16 the other way }
  8159. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8160. begin
  8161. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8162. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8163. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8164. GetNextInstruction(hp2, hp3) and
  8165. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8166. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8167. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8168. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8169. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8170. begin
  8171. { Update the register tracking to the new size }
  8172. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8173. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8174. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8175. if not(
  8176. ((SourceRef.offset mod 32) = 0) and
  8177. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8178. ) then
  8179. taicpu(hp2).opcode := A_VMOVDQU;
  8180. taicpu(hp2).opsize := S_YMM;
  8181. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8182. if not (
  8183. ((TargetRef.offset mod 32) = 0) and
  8184. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8185. ) then
  8186. taicpu(hp3).opcode := A_VMOVDQU;
  8187. taicpu(hp3).opsize := S_YMM;
  8188. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8189. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8190. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8191. if (pi_uses_ymm in current_procinfo.flags) then
  8192. RemoveInstruction(hp1)
  8193. else
  8194. begin
  8195. taicpu(hp1).opcode := A_VPXOR;
  8196. taicpu(hp1).opsize := S_YMM;
  8197. taicpu(hp1).loadreg(0, CurrentReg);
  8198. taicpu(hp1).loadreg(1, CurrentReg);
  8199. taicpu(hp1).loadreg(2, CurrentReg);
  8200. taicpu(hp1).ops := 3;
  8201. Asml.Remove(hp1);
  8202. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8203. end;
  8204. RemoveCurrentP(p, hp2);
  8205. Result := True;
  8206. Exit;
  8207. end;
  8208. end;
  8209. end;
  8210. end;
  8211. end;
  8212. end;
  8213. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8214. var
  8215. hp2, hp3, first_assignment: tai;
  8216. IncCount, OperIdx: Integer;
  8217. OrigLabel: TAsmLabel;
  8218. begin
  8219. Count := 0;
  8220. Result := False;
  8221. first_assignment := nil;
  8222. if (LoopCount >= 20) then
  8223. begin
  8224. { Guard against infinite loops }
  8225. Exit;
  8226. end;
  8227. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8228. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8229. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8230. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8231. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8232. Exit;
  8233. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8234. {
  8235. change
  8236. jmp .L1
  8237. ...
  8238. .L1:
  8239. mov ##, ## ( multiple movs possible )
  8240. jmp/ret
  8241. into
  8242. mov ##, ##
  8243. jmp/ret
  8244. }
  8245. if not Assigned(hp1) then
  8246. begin
  8247. hp1 := GetLabelWithSym(OrigLabel);
  8248. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8249. Exit;
  8250. end;
  8251. hp2 := hp1;
  8252. while Assigned(hp2) do
  8253. begin
  8254. if Assigned(hp2) and (hp2.typ = ait_label) then
  8255. SkipLabels(hp2,hp2);
  8256. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8257. Break;
  8258. case taicpu(hp2).opcode of
  8259. A_MOVSD:
  8260. begin
  8261. if taicpu(hp2).ops = 0 then
  8262. { Wrong MOVSD }
  8263. Break;
  8264. Inc(Count);
  8265. if Count >= 5 then
  8266. { Too many to be worthwhile }
  8267. Break;
  8268. GetNextInstruction(hp2, hp2);
  8269. Continue;
  8270. end;
  8271. A_MOV,
  8272. A_MOVD,
  8273. A_MOVQ,
  8274. A_MOVSX,
  8275. {$ifdef x86_64}
  8276. A_MOVSXD,
  8277. {$endif x86_64}
  8278. A_MOVZX,
  8279. A_MOVAPS,
  8280. A_MOVUPS,
  8281. A_MOVSS,
  8282. A_MOVAPD,
  8283. A_MOVUPD,
  8284. A_MOVDQA,
  8285. A_MOVDQU,
  8286. A_VMOVSS,
  8287. A_VMOVAPS,
  8288. A_VMOVUPS,
  8289. A_VMOVSD,
  8290. A_VMOVAPD,
  8291. A_VMOVUPD,
  8292. A_VMOVDQA,
  8293. A_VMOVDQU:
  8294. begin
  8295. Inc(Count);
  8296. if Count >= 5 then
  8297. { Too many to be worthwhile }
  8298. Break;
  8299. GetNextInstruction(hp2, hp2);
  8300. Continue;
  8301. end;
  8302. A_JMP:
  8303. begin
  8304. { Guard against infinite loops }
  8305. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8306. Exit;
  8307. { Analyse this jump first in case it also duplicates assignments }
  8308. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8309. begin
  8310. { Something did change! }
  8311. Result := True;
  8312. Inc(Count, IncCount);
  8313. if Count >= 5 then
  8314. begin
  8315. { Too many to be worthwhile }
  8316. Exit;
  8317. end;
  8318. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8319. Break;
  8320. end;
  8321. Result := True;
  8322. Break;
  8323. end;
  8324. A_RET:
  8325. begin
  8326. Result := True;
  8327. Break;
  8328. end;
  8329. else
  8330. Break;
  8331. end;
  8332. end;
  8333. if Result then
  8334. begin
  8335. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8336. if Count = 0 then
  8337. begin
  8338. Result := False;
  8339. Exit;
  8340. end;
  8341. TransferUsedRegs(TmpUsedRegs);
  8342. hp3 := p;
  8343. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8344. while True do
  8345. begin
  8346. if Assigned(hp1) and (hp1.typ = ait_label) then
  8347. SkipLabels(hp1,hp1);
  8348. if (hp1.typ <> ait_instruction) then
  8349. InternalError(2021040720);
  8350. case taicpu(hp1).opcode of
  8351. A_JMP:
  8352. begin
  8353. { Change the original jump to the new destination }
  8354. OrigLabel.decrefs;
  8355. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8356. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8357. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8358. if not Assigned(first_assignment) then
  8359. InternalError(2021040810)
  8360. else
  8361. p := first_assignment;
  8362. Exit;
  8363. end;
  8364. A_RET:
  8365. begin
  8366. { Now change the jump into a RET instruction }
  8367. ConvertJumpToRET(p, hp1);
  8368. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8369. if not Assigned(first_assignment) then
  8370. InternalError(2021040811)
  8371. else
  8372. p := first_assignment;
  8373. Exit;
  8374. end;
  8375. else
  8376. begin
  8377. { Duplicate the MOV instruction }
  8378. hp3:=tai(hp1.getcopy);
  8379. asml.InsertBefore(hp3, p);
  8380. { Make sure the compiler knows about any final registers written here }
  8381. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8382. with taicpu(hp3).oper[OperIdx]^ do
  8383. begin
  8384. case typ of
  8385. top_ref:
  8386. begin
  8387. if (ref^.base <> NR_NO) and
  8388. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8389. (
  8390. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8391. (
  8392. { Allow the frame pointer if it's not being used by the procedure as such }
  8393. Assigned(current_procinfo) and
  8394. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8395. )
  8396. )
  8397. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8398. then
  8399. begin
  8400. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8401. if not Assigned(first_assignment) then
  8402. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8403. end;
  8404. if (ref^.index <> NR_NO) and
  8405. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8406. (
  8407. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8408. (
  8409. { Allow the frame pointer if it's not being used by the procedure as such }
  8410. Assigned(current_procinfo) and
  8411. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8412. )
  8413. )
  8414. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8415. (ref^.index <> ref^.base) then
  8416. begin
  8417. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8418. if not Assigned(first_assignment) then
  8419. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8420. end;
  8421. end;
  8422. top_reg:
  8423. begin
  8424. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8425. if not Assigned(first_assignment) then
  8426. IncludeRegInUsedRegs(reg, UsedRegs);
  8427. end;
  8428. else
  8429. ;
  8430. end;
  8431. end;
  8432. if first_assignment = nil then
  8433. first_assignment := hp3;
  8434. end;
  8435. end;
  8436. if not GetNextInstruction(hp1, hp1) then
  8437. { Should have dropped out earlier }
  8438. InternalError(2021040710);
  8439. end;
  8440. end;
  8441. end;
  8442. const
  8443. WriteOp: array[0..3] of set of TInsChange = (
  8444. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8445. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8446. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8447. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8448. RegWriteFlags: array[0..7] of set of TInsChange = (
  8449. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8450. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8451. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8452. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8453. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8454. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8455. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8456. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8457. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8458. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8459. var
  8460. hp2: tai;
  8461. X: Integer;
  8462. begin
  8463. { If we have something like:
  8464. op ###,###
  8465. mov ###,###
  8466. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8467. interfere in regards to what they write to.
  8468. NOTE: p must be a 2-operand instruction
  8469. }
  8470. Result := False;
  8471. if (hp1.typ <> ait_instruction) or
  8472. taicpu(hp1).is_jmp or
  8473. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8474. Exit;
  8475. { NOP is a pipeline fence, likely marking the beginning of the function
  8476. epilogue, so drop out. Similarly, drop out if POP or RET are
  8477. encountered }
  8478. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8479. Exit;
  8480. if (taicpu(hp1).opcode = A_MOVSD) and
  8481. (taicpu(hp1).ops = 0) then
  8482. { Wrong MOVSD }
  8483. Exit;
  8484. { Check for writes to specific registers first }
  8485. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8486. for X := 0 to 7 do
  8487. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8488. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8489. Exit;
  8490. for X := 0 to taicpu(hp1).ops - 1 do
  8491. begin
  8492. { Check to see if this operand writes to something }
  8493. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8494. { And matches something in the CMP/TEST instruction }
  8495. (
  8496. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8497. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8498. (
  8499. { If it's a register, make sure the register written to doesn't
  8500. appear in the cmp instruction as part of a reference }
  8501. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8502. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8503. )
  8504. ) then
  8505. Exit;
  8506. end;
  8507. { Check p to make sure it doesn't write to something that affects hp1 }
  8508. { Check for writes to specific registers first }
  8509. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8510. for X := 0 to 7 do
  8511. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8512. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8513. Exit;
  8514. for X := 0 to taicpu(p).ops - 1 do
  8515. begin
  8516. { Check to see if this operand writes to something }
  8517. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8518. { And matches something in hp1 }
  8519. (taicpu(p).oper[X]^.typ = top_reg) and
  8520. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8521. Exit;
  8522. end;
  8523. { The instruction can be safely moved }
  8524. asml.Remove(hp1);
  8525. { Try to insert after the last instructions where the FLAGS register is not
  8526. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8527. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8528. asml.InsertBefore(hp1, hp2)
  8529. { Failing that, try to insert after the last instructions where the
  8530. FLAGS register is not yet in use }
  8531. else if GetLastInstruction(p, hp2) and
  8532. (
  8533. (hp2.typ <> ait_instruction) or
  8534. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8535. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8536. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8537. ) then
  8538. asml.InsertAfter(hp1, hp2)
  8539. else
  8540. { Note, if p.Previous is nil (even if it should logically never be the
  8541. case), FindRegAllocBackward immediately exits with False and so we
  8542. safely land here (we can't just pass p because FindRegAllocBackward
  8543. immediately exits on an instruction). [Kit] }
  8544. asml.InsertBefore(hp1, p);
  8545. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8546. { We can't trust UsedRegs because we're looking backwards, although we
  8547. know the registers are allocated after p at the very least, so manually
  8548. create tai_regalloc objects if needed }
  8549. for X := 0 to taicpu(hp1).ops - 1 do
  8550. case taicpu(hp1).oper[X]^.typ of
  8551. top_reg:
  8552. begin
  8553. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8554. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8555. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8556. end;
  8557. top_ref:
  8558. begin
  8559. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8560. begin
  8561. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8562. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8563. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8564. end;
  8565. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8566. begin
  8567. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8568. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8569. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8570. end;
  8571. end;
  8572. else
  8573. ;
  8574. end;
  8575. Result := True;
  8576. end;
  8577. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8578. var
  8579. hp2: tai;
  8580. X: Integer;
  8581. begin
  8582. { If we have something like:
  8583. cmp ###,%reg1
  8584. mov 0,%reg2
  8585. And no modified registers are shared, move the instruction to before
  8586. the comparison as this means it can be optimised without worrying
  8587. about the FLAGS register. (CMP/MOV is generated by
  8588. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8589. As long as the second instruction doesn't use the flags or one of the
  8590. registers used by CMP or TEST (also check any references that use the
  8591. registers), then it can be moved prior to the comparison.
  8592. }
  8593. Result := False;
  8594. if not TrySwapMovOp(p, hp1) then
  8595. Exit;
  8596. if taicpu(hp1).opcode = A_LEA then
  8597. { The flags will be overwritten by the CMP/TEST instruction }
  8598. ConvertLEA(taicpu(hp1));
  8599. Result := True;
  8600. { Can we move it one further back? }
  8601. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8602. { Check to see if CMP/TEST is a comparison against zero }
  8603. (
  8604. (
  8605. (taicpu(p).opcode = A_CMP) and
  8606. MatchOperand(taicpu(p).oper[0]^, 0)
  8607. ) or
  8608. (
  8609. (taicpu(p).opcode = A_TEST) and
  8610. (
  8611. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8612. MatchOperand(taicpu(p).oper[0]^, -1)
  8613. )
  8614. )
  8615. ) and
  8616. { These instructions set the zero flag if the result is zero }
  8617. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8618. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8619. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8620. TrySwapMovOp(hp2, hp1);
  8621. end;
  8622. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8623. var
  8624. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8625. JumpLabel: TAsmLabel;
  8626. TmpBool: Boolean;
  8627. begin
  8628. Result := False;
  8629. { Look for:
  8630. stc/clc
  8631. j(c) .L1
  8632. ...
  8633. .L1:
  8634. set(n)cb %reg
  8635. (flags deallocated)
  8636. j(c) .L2
  8637. Change to:
  8638. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8639. j(c) .L2
  8640. }
  8641. p_last := p;
  8642. while GetNextInstruction(p_last, hp1) and
  8643. (hp1.typ = ait_instruction) and
  8644. IsJumpToLabel(taicpu(hp1)) do
  8645. begin
  8646. if DoJumpOptimizations(hp1, TmpBool) then
  8647. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8648. Continue;
  8649. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8650. if not Assigned(JumpLabel) then
  8651. InternalError(2024012801);
  8652. { Optimise the J(c); stc/clc optimisation first since this will
  8653. get missed if the main optimisation takes place }
  8654. if (taicpu(hp1).opcode = A_JCC) then
  8655. begin
  8656. if GetNextInstruction(hp1, hp2) and
  8657. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8658. TryJccStcClcOpt(hp1, hp2) then
  8659. begin
  8660. Result := True;
  8661. Exit;
  8662. end;
  8663. hp2 := nil; { Suppress compiler warning }
  8664. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8665. { Make sure the flags aren't used again }
  8666. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8667. begin
  8668. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8669. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8670. begin
  8671. if (taicpu(p).opcode = A_STC) then
  8672. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8673. else
  8674. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8675. MakeUnconditional(taicpu(hp1));
  8676. { Move the jump to after the flag deallocations }
  8677. Asml.Remove(hp1);
  8678. Asml.InsertAfter(hp1, hp2);
  8679. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8680. Result := True;
  8681. Exit;
  8682. end
  8683. else
  8684. begin
  8685. if (taicpu(p).opcode = A_STC) then
  8686. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8687. else
  8688. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8689. { In this case, the jump is deterministic in that it will never be taken }
  8690. JumpLabel.DecRefs;
  8691. RemoveInstruction(hp1);
  8692. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8693. Result := True;
  8694. Exit;
  8695. end;
  8696. end;
  8697. end;
  8698. hp2 := nil; { Suppress compiler warning }
  8699. if
  8700. { Make sure the carry flag doesn't appear in the jump conditions }
  8701. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8702. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8703. GetNextInstruction(hp2, p_dist) and
  8704. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8705. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8706. begin
  8707. case taicpu(p_dist).opcode of
  8708. A_Jcc:
  8709. begin
  8710. if DoJumpOptimizations(p_dist, TmpBool) then
  8711. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8712. Continue;
  8713. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8714. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8715. begin
  8716. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8717. JumpLabel.decrefs;
  8718. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8719. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8720. Result := True;
  8721. Exit;
  8722. end
  8723. else if GetNextInstruction(p_dist, hp1_dist) and
  8724. (hp1_dist.typ = ait_label) then
  8725. begin
  8726. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8727. JumpLabel.decrefs;
  8728. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8729. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8730. Result := True;
  8731. Exit;
  8732. end;
  8733. end;
  8734. A_SETcc:
  8735. if { Make sure the flags aren't used again }
  8736. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8737. GetNextInstruction(hp2, hp1_dist) and
  8738. (hp1_dist.typ = ait_instruction) and
  8739. IsJumpToLabel(taicpu(hp1_dist)) and
  8740. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8741. { This works if hp1_dist or both are regular JMP instructions }
  8742. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8743. (
  8744. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8745. { Make sure the register isn't still in use, otherwise it
  8746. may get corrupted (fixes #40659) }
  8747. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8748. ) then
  8749. begin
  8750. taicpu(p).allocate_oper(2);
  8751. taicpu(p).ops := 2;
  8752. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8753. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8754. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8755. taicpu(p).opcode := A_MOV;
  8756. taicpu(p).opsize := S_B;
  8757. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8758. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8759. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8760. JumpLabel.decrefs;
  8761. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8762. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8763. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8764. (tai_regalloc(hp2).ratype = ra_alloc) then
  8765. begin
  8766. Asml.Remove(hp2);
  8767. Asml.InsertAfter(hp2, p);
  8768. end;
  8769. Result := True;
  8770. Exit;
  8771. end;
  8772. else
  8773. ;
  8774. end;
  8775. end;
  8776. p_last := hp1;
  8777. end;
  8778. end;
  8779. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8780. var
  8781. hp2, hp3: tai;
  8782. TempBool: Boolean;
  8783. begin
  8784. Result := False;
  8785. {
  8786. j(c) .L1
  8787. stc/clc
  8788. .L1:
  8789. jc/jnc .L2
  8790. (Flags deallocated)
  8791. Change to:
  8792. j)c) .L1
  8793. jmp .L2
  8794. .L1:
  8795. jc/jnc .L2
  8796. Then call DoJumpOptimizations to convert to:
  8797. j(nc) .L2
  8798. .L1: (may become a dead label)
  8799. jc/jnc .L2
  8800. }
  8801. if GetNextInstruction(hp1, hp2) and
  8802. (hp2.typ = ait_label) and
  8803. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8804. GetNextInstruction(hp2, hp3) and
  8805. MatchInstruction(hp3, A_Jcc, []) and
  8806. (
  8807. (
  8808. (taicpu(hp3).condition = C_C) and
  8809. (taicpu(hp1).opcode = A_STC)
  8810. ) or (
  8811. (taicpu(hp3).condition = C_NC) and
  8812. (taicpu(hp1).opcode = A_CLC)
  8813. )
  8814. ) and
  8815. { Make sure the flags aren't used again }
  8816. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8817. begin
  8818. taicpu(hp1).allocate_oper(1);
  8819. taicpu(hp1).ops := 1;
  8820. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8821. taicpu(hp1).opcode := A_JMP;
  8822. taicpu(hp1).is_jmp := True;
  8823. TempBool := True; { Prevent compiler warnings }
  8824. if DoJumpOptimizations(p, TempBool) then
  8825. Result := True
  8826. else
  8827. Include(OptsToCheck, aoc_ForceNewIteration);
  8828. end;
  8829. end;
  8830. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8831. begin
  8832. { This generally only executes under -O3 and above }
  8833. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8834. end;
  8835. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8836. var
  8837. hp1, hp2: tai;
  8838. FoundComparison: Boolean;
  8839. begin
  8840. { Run the pass 1 optimisations as well, since they may have some effect
  8841. after the CMOV blocks are created in OptPass2Jcc }
  8842. Result := False;
  8843. { Result := OptPass1CMOVcc(p);
  8844. if Result then
  8845. Exit;}
  8846. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8847. and make a slightly inefficent result on branching-type blocks, notably
  8848. when setting a function result then jumping to the function epilogue.
  8849. In this case, change:
  8850. cmov(c) %reg1,%reg2
  8851. j(c) @lbl
  8852. (%reg2 deallocated)
  8853. To:
  8854. mov %reg11,%reg2
  8855. j(c) @lbl
  8856. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8857. jump because if it's not present, we may end up with a jump that's
  8858. completely unrelated.
  8859. }
  8860. hp1 := p;
  8861. while GetNextInstruction(hp1, hp1) and
  8862. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8863. if (hp1.typ = ait_instruction) and
  8864. (taicpu(hp1).opcode = A_Jcc) and
  8865. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8866. begin
  8867. TransferUsedRegs(TmpUsedRegs);
  8868. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8869. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8870. (
  8871. { See if we can find a more distant instruction that overwrites
  8872. the destination register }
  8873. (cs_opt_level3 in current_settings.optimizerswitches) and
  8874. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8875. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8876. ) then
  8877. begin
  8878. if (taicpu(p).oper[0]^.typ = top_reg) then
  8879. begin
  8880. { Search backwards to see if the source register is set to a
  8881. constant }
  8882. FoundComparison := False;
  8883. hp1 := p;
  8884. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8885. begin
  8886. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8887. begin
  8888. FoundComparison := True;
  8889. Continue;
  8890. end;
  8891. { Once we find the CMP, TEST or similar instruction, we
  8892. have to stop if we find anything other than a MOV }
  8893. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8894. Break;
  8895. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8896. { Destination register was modified }
  8897. Break;
  8898. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8899. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8900. begin
  8901. { Found a constant! }
  8902. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8903. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8904. { The source register is no longer in use }
  8905. RemoveInstruction(hp1);
  8906. Break;
  8907. end;
  8908. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8909. { Some other instruction has modified the source register }
  8910. Break;
  8911. end;
  8912. end;
  8913. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  8914. taicpu(p).opcode := A_MOV;
  8915. taicpu(p).condition := C_None;
  8916. { Rely on the post peephole stage to put the MOV before the
  8917. CMP/TEST instruction that appears prior }
  8918. Result := True;
  8919. Exit;
  8920. end;
  8921. end;
  8922. end;
  8923. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8924. function IsXCHGAcceptable: Boolean; inline;
  8925. begin
  8926. { Always accept if optimising for size }
  8927. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8928. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8929. than 3, so it becomes a saving compared to three MOVs with two of
  8930. them able to execute simultaneously. [Kit] }
  8931. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8932. end;
  8933. var
  8934. NewRef: TReference;
  8935. hp1, hp2, hp3, hp4: Tai;
  8936. {$ifndef x86_64}
  8937. OperIdx: Integer;
  8938. {$endif x86_64}
  8939. NewInstr : Taicpu;
  8940. NewAligh : Tai_align;
  8941. DestLabel: TAsmLabel;
  8942. TempTracking: TAllUsedRegs;
  8943. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8944. var
  8945. NextInstr: tai;
  8946. begin
  8947. Result := False;
  8948. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8949. if not GetNextInstruction(InputInstr, NextInstr) or
  8950. (
  8951. { The FLAGS register isn't always tracked properly, so do not
  8952. perform this optimisation if a conditional statement follows }
  8953. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8954. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8955. ) then
  8956. begin
  8957. reference_reset(NewRef, 1, []);
  8958. NewRef.base := taicpu(p).oper[0]^.reg;
  8959. NewRef.scalefactor := 1;
  8960. if taicpu(InputInstr).opcode = A_ADD then
  8961. begin
  8962. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8963. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8964. end
  8965. else
  8966. begin
  8967. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8968. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8969. end;
  8970. taicpu(p).opcode := A_LEA;
  8971. taicpu(p).loadref(0, NewRef);
  8972. { For the sake of debugging, have the line info match the
  8973. arithmetic instruction rather than the MOV instruction }
  8974. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  8975. RemoveInstruction(InputInstr);
  8976. Result := True;
  8977. end;
  8978. end;
  8979. begin
  8980. Result:=false;
  8981. { This optimisation adds an instruction, so only do it for speed }
  8982. if not (cs_opt_size in current_settings.optimizerswitches) and
  8983. MatchOpType(taicpu(p), top_const, top_reg) and
  8984. (taicpu(p).oper[0]^.val = 0) then
  8985. begin
  8986. { To avoid compiler warning }
  8987. DestLabel := nil;
  8988. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8989. InternalError(2021040750);
  8990. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8991. Exit;
  8992. case hp1.typ of
  8993. ait_label:
  8994. begin
  8995. { Change:
  8996. mov $0,%reg mov $0,%reg
  8997. @Lbl1: @Lbl1:
  8998. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8999. je @Lbl2 jne @Lbl2
  9000. To: To:
  9001. mov $0,%reg mov $0,%reg
  9002. jmp @Lbl2 jmp @Lbl3
  9003. (align) (align)
  9004. @Lbl1: @Lbl1:
  9005. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9006. je @Lbl2 je @Lbl2
  9007. @Lbl3: <-- Only if label exists
  9008. (Not if it's optimised for size)
  9009. }
  9010. if not GetNextInstruction(hp1, hp2) then
  9011. Exit;
  9012. if (hp2.typ = ait_instruction) and
  9013. (
  9014. { Register sizes must exactly match }
  9015. (
  9016. (taicpu(hp2).opcode = A_CMP) and
  9017. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9018. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9019. ) or (
  9020. (taicpu(hp2).opcode = A_TEST) and
  9021. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9022. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9023. )
  9024. ) and GetNextInstruction(hp2, hp3) and
  9025. (hp3.typ = ait_instruction) and
  9026. (taicpu(hp3).opcode = A_JCC) and
  9027. (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
  9028. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9029. begin
  9030. { Check condition of jump }
  9031. { Always true? }
  9032. if condition_in(C_E, taicpu(hp3).condition) then
  9033. begin
  9034. { Copy label symbol and obtain matching label entry for the
  9035. conditional jump, as this will be our destination}
  9036. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9037. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9038. Result := True;
  9039. end
  9040. { Always false? }
  9041. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9042. begin
  9043. { This is only worth it if there's a jump to take }
  9044. case hp2.typ of
  9045. ait_instruction:
  9046. begin
  9047. if taicpu(hp2).opcode = A_JMP then
  9048. begin
  9049. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9050. { An unconditional jump follows the conditional jump which will always be false,
  9051. so use this jump's destination for the new jump }
  9052. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9053. Result := True;
  9054. end
  9055. else if taicpu(hp2).opcode = A_JCC then
  9056. begin
  9057. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9058. if condition_in(C_E, taicpu(hp2).condition) then
  9059. begin
  9060. { A second conditional jump follows the conditional jump which will always be false,
  9061. while the second jump is always True, so use this jump's destination for the new jump }
  9062. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9063. Result := True;
  9064. end;
  9065. { Don't risk it if the jump isn't always true (Result remains False) }
  9066. end;
  9067. end;
  9068. else
  9069. { If anything else don't optimise };
  9070. end;
  9071. end;
  9072. if Result then
  9073. begin
  9074. { Just so we have something to insert as a paremeter}
  9075. reference_reset(NewRef, 1, []);
  9076. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9077. { Now actually load the correct parameter (this also
  9078. increases the reference count) }
  9079. NewInstr.loadsymbol(0, DestLabel, 0);
  9080. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9081. begin
  9082. { Get instruction before original label (may not be p under -O3) }
  9083. if not GetLastInstruction(hp1, hp2) then
  9084. { Shouldn't fail here }
  9085. InternalError(2021040701);
  9086. end
  9087. else
  9088. hp2 := p;
  9089. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9090. AsmL.InsertAfter(NewInstr, hp2);
  9091. { Add new alignment field }
  9092. (* AsmL.InsertAfter(
  9093. cai_align.create_max(
  9094. current_settings.alignment.jumpalign,
  9095. current_settings.alignment.jumpalignskipmax
  9096. ),
  9097. NewInstr
  9098. ); *)
  9099. end;
  9100. Exit;
  9101. end;
  9102. end;
  9103. else
  9104. ;
  9105. end;
  9106. end;
  9107. if not GetNextInstruction(p, hp1) then
  9108. Exit;
  9109. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9110. begin
  9111. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9112. begin
  9113. Result := True;
  9114. Exit;
  9115. end;
  9116. { This optimisation is only effective on a second run of Pass 2,
  9117. hence -O3 or above.
  9118. Change:
  9119. mov %reg1,%reg2
  9120. cmp/test (contains %reg1)
  9121. mov x, %reg1
  9122. (another mov or a j(c))
  9123. To:
  9124. mov %reg1,%reg2
  9125. mov x, %reg1
  9126. cmp (%reg1 replaced with %reg2)
  9127. (another mov or a j(c))
  9128. The requirement of an additional MOV or a jump ensures there
  9129. isn't performance loss, since a j(c) will permit macro-fusion
  9130. with the cmp instruction, while another MOV likely means it's
  9131. not all being executed in a single cycle due to parallelisation.
  9132. }
  9133. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9134. MatchOpType(taicpu(p), top_reg, top_reg) and
  9135. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9136. GetNextInstruction(hp1, hp2) and
  9137. MatchInstruction(hp2, A_MOV, []) and
  9138. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9139. { Registers don't have to be the same size in this case }
  9140. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9141. GetNextInstruction(hp2, hp3) and
  9142. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9143. { Make sure the operands in the camparison can be safely replaced }
  9144. (
  9145. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9146. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9147. ) and
  9148. (
  9149. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9150. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9151. ) then
  9152. begin
  9153. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9154. AsmL.Remove(hp2);
  9155. AsmL.InsertAfter(hp2, p);
  9156. Result := True;
  9157. Exit;
  9158. end;
  9159. end;
  9160. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9161. begin
  9162. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9163. further, but we can't just put this jump optimisation in pass 1
  9164. because it tends to perform worse when conditional jumps are
  9165. nearby (e.g. when converting CMOV instructions). [Kit] }
  9166. CopyUsedRegs(TempTracking);
  9167. UpdateUsedRegs(tai(p.Next));
  9168. if OptPass2JMP(hp1) then
  9169. begin
  9170. { Restore register state }
  9171. RestoreUsedRegs(TempTracking);
  9172. ReleaseUsedRegs(TempTracking);
  9173. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9174. OptPass1MOV(p);
  9175. Result := True;
  9176. Exit;
  9177. end;
  9178. { If OptPass2JMP returned False, no optimisations were done to
  9179. the jump and there are no further optimisations that can be done
  9180. to the MOV instruction on this pass other than FuncMov2Func }
  9181. { Restore register state }
  9182. RestoreUsedRegs(TempTracking);
  9183. ReleaseUsedRegs(TempTracking);
  9184. Result := FuncMov2Func(p, hp1);
  9185. Exit;
  9186. end;
  9187. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9188. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9189. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9190. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9191. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9192. begin
  9193. { Change:
  9194. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9195. addl/q $x,%reg2 subl/q $x,%reg2
  9196. To:
  9197. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9198. }
  9199. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9200. { be lazy, checking separately for sub would be slightly better }
  9201. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9202. begin
  9203. TransferUsedRegs(TmpUsedRegs);
  9204. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9205. if TryMovArith2Lea(hp1) then
  9206. begin
  9207. Result := True;
  9208. Exit;
  9209. end
  9210. end
  9211. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9212. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9213. { Same as above, but also adds or subtracts to %reg2 in between.
  9214. It's still valid as long as the flags aren't in use }
  9215. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9216. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9217. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9218. { be lazy, checking separately for sub would be slightly better }
  9219. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9220. begin
  9221. TransferUsedRegs(TmpUsedRegs);
  9222. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9223. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9224. if TryMovArith2Lea(hp2) then
  9225. begin
  9226. Result := True;
  9227. Exit;
  9228. end;
  9229. end;
  9230. end;
  9231. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9232. {$ifdef x86_64}
  9233. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9234. {$else x86_64}
  9235. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9236. {$endif x86_64}
  9237. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9238. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9239. { mov reg1, reg2 mov reg1, reg2
  9240. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9241. begin
  9242. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9243. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9244. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9245. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9246. TransferUsedRegs(TmpUsedRegs);
  9247. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9248. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9249. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9250. then
  9251. begin
  9252. RemoveCurrentP(p, hp1);
  9253. Result:=true;
  9254. end;
  9255. Exit;
  9256. end;
  9257. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9258. IsXCHGAcceptable and
  9259. { XCHG doesn't support 8-bit registers }
  9260. (taicpu(p).opsize <> S_B) and
  9261. MatchInstruction(hp1, A_MOV, []) and
  9262. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9263. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9264. GetNextInstruction(hp1, hp2) and
  9265. MatchInstruction(hp2, A_MOV, []) and
  9266. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9267. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9268. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9269. begin
  9270. { mov %reg1,%reg2
  9271. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9272. mov %reg2,%reg3
  9273. (%reg2 not used afterwards)
  9274. Note that xchg takes 3 cycles to execute, and generally mov's take
  9275. only one cycle apiece, but the first two mov's can be executed in
  9276. parallel, only taking 2 cycles overall. Older processors should
  9277. therefore only optimise for size. [Kit]
  9278. }
  9279. TransferUsedRegs(TmpUsedRegs);
  9280. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9281. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9282. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9283. begin
  9284. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9285. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9286. taicpu(hp1).opcode := A_XCHG;
  9287. RemoveCurrentP(p, hp1);
  9288. RemoveInstruction(hp2);
  9289. Result := True;
  9290. Exit;
  9291. end;
  9292. end;
  9293. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9294. MatchInstruction(hp1, A_SAR, []) then
  9295. begin
  9296. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9297. begin
  9298. { the use of %edx also covers the opsize being S_L }
  9299. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9300. begin
  9301. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9302. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9303. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9304. begin
  9305. { Change:
  9306. movl %eax,%edx
  9307. sarl $31,%edx
  9308. To:
  9309. cltd
  9310. }
  9311. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9312. RemoveInstruction(hp1);
  9313. taicpu(p).opcode := A_CDQ;
  9314. taicpu(p).opsize := S_NO;
  9315. taicpu(p).clearop(1);
  9316. taicpu(p).clearop(0);
  9317. taicpu(p).ops:=0;
  9318. Result := True;
  9319. Exit;
  9320. end
  9321. else if (cs_opt_size in current_settings.optimizerswitches) and
  9322. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9323. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9324. begin
  9325. { Change:
  9326. movl %edx,%eax
  9327. sarl $31,%edx
  9328. To:
  9329. movl %edx,%eax
  9330. cltd
  9331. Note that this creates a dependency between the two instructions,
  9332. so only perform if optimising for size.
  9333. }
  9334. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9335. taicpu(hp1).opcode := A_CDQ;
  9336. taicpu(hp1).opsize := S_NO;
  9337. taicpu(hp1).clearop(1);
  9338. taicpu(hp1).clearop(0);
  9339. taicpu(hp1).ops:=0;
  9340. Include(OptsToCheck, aoc_ForceNewIteration);
  9341. Exit;
  9342. end;
  9343. {$ifndef x86_64}
  9344. end
  9345. { Don't bother if CMOV is supported, because a more optimal
  9346. sequence would have been generated for the Abs() intrinsic }
  9347. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9348. { the use of %eax also covers the opsize being S_L }
  9349. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9350. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9351. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9352. GetNextInstruction(hp1, hp2) and
  9353. MatchInstruction(hp2, A_XOR, [S_L]) and
  9354. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9355. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9356. GetNextInstruction(hp2, hp3) and
  9357. MatchInstruction(hp3, A_SUB, [S_L]) and
  9358. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9359. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9360. begin
  9361. { Change:
  9362. movl %eax,%edx
  9363. sarl $31,%eax
  9364. xorl %eax,%edx
  9365. subl %eax,%edx
  9366. (Instruction that uses %edx)
  9367. (%eax deallocated)
  9368. (%edx deallocated)
  9369. To:
  9370. cltd
  9371. xorl %edx,%eax <-- Note the registers have swapped
  9372. subl %edx,%eax
  9373. (Instruction that uses %eax) <-- %eax rather than %edx
  9374. }
  9375. TransferUsedRegs(TmpUsedRegs);
  9376. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9377. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9378. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9379. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9380. begin
  9381. if GetNextInstruction(hp3, hp4) and
  9382. not RegModifiedByInstruction(NR_EDX, hp4) and
  9383. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9384. begin
  9385. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9386. taicpu(p).opcode := A_CDQ;
  9387. taicpu(p).clearop(1);
  9388. taicpu(p).clearop(0);
  9389. taicpu(p).ops:=0;
  9390. RemoveInstruction(hp1);
  9391. taicpu(hp2).loadreg(0, NR_EDX);
  9392. taicpu(hp2).loadreg(1, NR_EAX);
  9393. taicpu(hp3).loadreg(0, NR_EDX);
  9394. taicpu(hp3).loadreg(1, NR_EAX);
  9395. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9396. { Convert references in the following instruction (hp4) from %edx to %eax }
  9397. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9398. with taicpu(hp4).oper[OperIdx]^ do
  9399. case typ of
  9400. top_reg:
  9401. if getsupreg(reg) = RS_EDX then
  9402. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9403. top_ref:
  9404. begin
  9405. if getsupreg(reg) = RS_EDX then
  9406. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9407. if getsupreg(reg) = RS_EDX then
  9408. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9409. end;
  9410. else
  9411. ;
  9412. end;
  9413. Result := True;
  9414. Exit;
  9415. end;
  9416. end;
  9417. {$else x86_64}
  9418. end;
  9419. end
  9420. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9421. { the use of %rdx also covers the opsize being S_Q }
  9422. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9423. begin
  9424. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9425. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9426. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9427. begin
  9428. { Change:
  9429. movq %rax,%rdx
  9430. sarq $63,%rdx
  9431. To:
  9432. cqto
  9433. }
  9434. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9435. RemoveInstruction(hp1);
  9436. taicpu(p).opcode := A_CQO;
  9437. taicpu(p).opsize := S_NO;
  9438. taicpu(p).clearop(1);
  9439. taicpu(p).clearop(0);
  9440. taicpu(p).ops:=0;
  9441. Result := True;
  9442. Exit;
  9443. end
  9444. else if (cs_opt_size in current_settings.optimizerswitches) and
  9445. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9446. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9447. begin
  9448. { Change:
  9449. movq %rdx,%rax
  9450. sarq $63,%rdx
  9451. To:
  9452. movq %rdx,%rax
  9453. cqto
  9454. Note that this creates a dependency between the two instructions,
  9455. so only perform if optimising for size.
  9456. }
  9457. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9458. taicpu(hp1).opcode := A_CQO;
  9459. taicpu(hp1).opsize := S_NO;
  9460. taicpu(hp1).clearop(1);
  9461. taicpu(hp1).clearop(0);
  9462. taicpu(hp1).ops:=0;
  9463. Include(OptsToCheck, aoc_ForceNewIteration);
  9464. Exit;
  9465. {$endif x86_64}
  9466. end;
  9467. end;
  9468. end;
  9469. if MatchInstruction(hp1, A_MOV, []) and
  9470. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9471. { Though "GetNextInstruction" could be factored out, along with
  9472. the instructions that depend on hp2, it is an expensive call that
  9473. should be delayed for as long as possible, hence we do cheaper
  9474. checks first that are likely to be False. [Kit] }
  9475. begin
  9476. if (
  9477. (
  9478. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9479. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9480. (
  9481. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9482. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9483. )
  9484. ) or
  9485. (
  9486. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9487. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9488. (
  9489. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9490. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9491. )
  9492. )
  9493. ) and
  9494. GetNextInstruction(hp1, hp2) and
  9495. MatchInstruction(hp2, A_SAR, []) and
  9496. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9497. begin
  9498. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9499. begin
  9500. { Change:
  9501. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9502. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9503. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9504. To:
  9505. movl r/m,%eax <- Note the change in register
  9506. cltd
  9507. }
  9508. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9509. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9510. taicpu(p).loadreg(1, NR_EAX);
  9511. taicpu(hp1).opcode := A_CDQ;
  9512. taicpu(hp1).clearop(1);
  9513. taicpu(hp1).clearop(0);
  9514. taicpu(hp1).ops:=0;
  9515. RemoveInstruction(hp2);
  9516. Include(OptsToCheck, aoc_ForceNewIteration);
  9517. (*
  9518. {$ifdef x86_64}
  9519. end
  9520. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9521. { This code sequence does not get generated - however it might become useful
  9522. if and when 128-bit signed integer types make an appearance, so the code
  9523. is kept here for when it is eventually needed. [Kit] }
  9524. (
  9525. (
  9526. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9527. (
  9528. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9529. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9530. )
  9531. ) or
  9532. (
  9533. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9534. (
  9535. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9536. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9537. )
  9538. )
  9539. ) and
  9540. GetNextInstruction(hp1, hp2) and
  9541. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9542. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9543. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9544. begin
  9545. { Change:
  9546. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9547. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9548. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9549. To:
  9550. movq r/m,%rax <- Note the change in register
  9551. cqto
  9552. }
  9553. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9554. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9555. taicpu(p).loadreg(1, NR_RAX);
  9556. taicpu(hp1).opcode := A_CQO;
  9557. taicpu(hp1).clearop(1);
  9558. taicpu(hp1).clearop(0);
  9559. taicpu(hp1).ops:=0;
  9560. RemoveInstruction(hp2);
  9561. Include(OptsToCheck, aoc_ForceNewIteration);
  9562. {$endif x86_64}
  9563. *)
  9564. end;
  9565. end;
  9566. {$ifdef x86_64}
  9567. end;
  9568. if (taicpu(p).opsize = S_L) and
  9569. (taicpu(p).oper[1]^.typ = top_reg) and
  9570. (
  9571. MatchInstruction(hp1, A_MOV,[]) and
  9572. (taicpu(hp1).opsize = S_L) and
  9573. (taicpu(hp1).oper[1]^.typ = top_reg)
  9574. ) and (
  9575. GetNextInstruction(hp1, hp2) and
  9576. (tai(hp2).typ=ait_instruction) and
  9577. (taicpu(hp2).opsize = S_Q) and
  9578. (
  9579. (
  9580. MatchInstruction(hp2, A_ADD,[]) and
  9581. (taicpu(hp2).opsize = S_Q) and
  9582. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9583. (
  9584. (
  9585. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9586. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9587. ) or (
  9588. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9589. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9590. )
  9591. )
  9592. ) or (
  9593. MatchInstruction(hp2, A_LEA,[]) and
  9594. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9595. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9596. (
  9597. (
  9598. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9599. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9600. ) or (
  9601. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9602. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9603. )
  9604. ) and (
  9605. (
  9606. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9607. ) or (
  9608. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9609. )
  9610. )
  9611. )
  9612. )
  9613. ) and (
  9614. GetNextInstruction(hp2, hp3) and
  9615. MatchInstruction(hp3, A_SHR,[]) and
  9616. (taicpu(hp3).opsize = S_Q) and
  9617. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9618. (taicpu(hp3).oper[0]^.val = 1) and
  9619. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9620. ) then
  9621. begin
  9622. { Change movl x, reg1d movl x, reg1d
  9623. movl y, reg2d movl y, reg2d
  9624. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9625. shrq $1, reg1q shrq $1, reg1q
  9626. ( reg1d and reg2d can be switched around in the first two instructions )
  9627. To movl x, reg1d
  9628. addl y, reg1d
  9629. rcrl $1, reg1d
  9630. This corresponds to the common expression (x + y) shr 1, where
  9631. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9632. smaller code, but won't account for x + y causing an overflow). [Kit]
  9633. }
  9634. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9635. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9636. begin
  9637. { Change first MOV command to have the same register as the final output }
  9638. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9639. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9640. Result := True;
  9641. end
  9642. else
  9643. begin
  9644. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9645. Include(OptsToCheck, aoc_ForceNewIteration);
  9646. end;
  9647. { Change second MOV command to an ADD command. This is easier than
  9648. converting the existing command because it means we don't have to
  9649. touch 'y', which might be a complicated reference, and also the
  9650. fact that the third command might either be ADD or LEA. [Kit] }
  9651. taicpu(hp1).opcode := A_ADD;
  9652. { Delete old ADD/LEA instruction }
  9653. RemoveInstruction(hp2);
  9654. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9655. taicpu(hp3).opcode := A_RCR;
  9656. taicpu(hp3).changeopsize(S_L);
  9657. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9658. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9659. called, so FuncMov2Func below is safe to call }
  9660. {$endif x86_64}
  9661. end;
  9662. if FuncMov2Func(p, hp1) then
  9663. begin
  9664. Result := True;
  9665. Exit;
  9666. end;
  9667. end;
  9668. {$push}
  9669. {$q-}{$r-}
  9670. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9671. var
  9672. ThisReg: TRegister;
  9673. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9674. TargetSubReg: TSubRegister;
  9675. hp1, hp2: tai;
  9676. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9677. { Store list of found instructions so we don't have to call
  9678. GetNextInstructionUsingReg multiple times }
  9679. InstrList: array of taicpu;
  9680. InstrMax, Index: Integer;
  9681. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9682. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9683. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9684. WorkingValue: TCgInt;
  9685. PreMessage: string;
  9686. { Data flow analysis }
  9687. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9688. BitwiseOnly, OrXorUsed,
  9689. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9690. function CheckOverflowConditions: Boolean;
  9691. begin
  9692. Result := True;
  9693. if (TestValSignedMax > SignedUpperLimit) then
  9694. UpperSignedOverflow := True;
  9695. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9696. LowerSignedOverflow := True;
  9697. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9698. LowerUnsignedOverflow := True;
  9699. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9700. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9701. begin
  9702. { Absolute overflow }
  9703. Result := False;
  9704. Exit;
  9705. end;
  9706. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9707. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9708. ShiftDownOverflow := True;
  9709. if (TestValMin < 0) or (TestValMax < 0) then
  9710. begin
  9711. LowerUnsignedOverflow := True;
  9712. UpperUnsignedOverflow := True;
  9713. end;
  9714. end;
  9715. function AdjustInitialLoadAndSize: Boolean;
  9716. begin
  9717. Result := False;
  9718. if not p_removed then
  9719. begin
  9720. if TargetSize = MinSize then
  9721. begin
  9722. { Convert the input MOVZX to a MOV }
  9723. if (taicpu(p).oper[0]^.typ = top_reg) and
  9724. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9725. begin
  9726. { Or remove it completely! }
  9727. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9728. RemoveCurrentP(p);
  9729. p_removed := True;
  9730. end
  9731. else
  9732. begin
  9733. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9734. taicpu(p).opcode := A_MOV;
  9735. taicpu(p).oper[1]^.reg := ThisReg;
  9736. taicpu(p).opsize := TargetSize;
  9737. end;
  9738. Result := True;
  9739. end
  9740. else if TargetSize <> MaxSize then
  9741. begin
  9742. case MaxSize of
  9743. S_L:
  9744. if TargetSize = S_W then
  9745. begin
  9746. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9747. taicpu(p).opsize := S_BW;
  9748. taicpu(p).oper[1]^.reg := ThisReg;
  9749. Result := True;
  9750. end
  9751. else
  9752. InternalError(2020112341);
  9753. S_W:
  9754. if TargetSize = S_L then
  9755. begin
  9756. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9757. taicpu(p).opsize := S_BL;
  9758. taicpu(p).oper[1]^.reg := ThisReg;
  9759. Result := True;
  9760. end
  9761. else
  9762. InternalError(2020112342);
  9763. else
  9764. ;
  9765. end;
  9766. end
  9767. else if not hp1_removed and not RegInUse then
  9768. begin
  9769. { If we have something like:
  9770. movzbl (oper),%regd
  9771. add x, %regd
  9772. movzbl %regb, %regd
  9773. We can reduce the register size to the input of the final
  9774. movzbl instruction. Overflows won't have any effect.
  9775. }
  9776. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9777. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9778. begin
  9779. TargetSize := S_B;
  9780. setsubreg(ThisReg, R_SUBL);
  9781. Result := True;
  9782. end
  9783. else if (taicpu(p).opsize = S_WL) and
  9784. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9785. begin
  9786. TargetSize := S_W;
  9787. setsubreg(ThisReg, R_SUBW);
  9788. Result := True;
  9789. end;
  9790. if Result then
  9791. begin
  9792. { Convert the input MOVZX to a MOV }
  9793. if (taicpu(p).oper[0]^.typ = top_reg) and
  9794. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9795. begin
  9796. { Or remove it completely! }
  9797. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9798. RemoveCurrentP(p);
  9799. p_removed := True;
  9800. end
  9801. else
  9802. begin
  9803. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9804. taicpu(p).opcode := A_MOV;
  9805. taicpu(p).oper[1]^.reg := ThisReg;
  9806. taicpu(p).opsize := TargetSize;
  9807. end;
  9808. end;
  9809. end;
  9810. end;
  9811. end;
  9812. procedure AdjustFinalLoad;
  9813. begin
  9814. if not LowerUnsignedOverflow then
  9815. begin
  9816. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9817. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9818. begin
  9819. { Convert the output MOVZX to a MOV }
  9820. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9821. begin
  9822. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9823. if (MinSize = S_B) or
  9824. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9825. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9826. begin
  9827. { Remove it completely! }
  9828. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9829. { Be careful; if p = hp1 and p was also removed, p
  9830. will become a dangling pointer }
  9831. if p = hp1 then
  9832. begin
  9833. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9834. p_removed := True;
  9835. end
  9836. else
  9837. RemoveInstruction(hp1);
  9838. hp1_removed := True;
  9839. end;
  9840. end
  9841. else
  9842. begin
  9843. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9844. taicpu(hp1).opcode := A_MOV;
  9845. taicpu(hp1).oper[0]^.reg := ThisReg;
  9846. taicpu(hp1).opsize := TargetSize;
  9847. end;
  9848. end
  9849. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9850. begin
  9851. { Need to change the size of the output }
  9852. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9853. taicpu(hp1).oper[0]^.reg := ThisReg;
  9854. taicpu(hp1).opsize := S_BL;
  9855. end;
  9856. end;
  9857. end;
  9858. function CompressInstructions: Boolean;
  9859. var
  9860. LocalIndex: Integer;
  9861. begin
  9862. Result := False;
  9863. { The objective here is to try to find a combination that
  9864. removes one of the MOV/Z instructions. }
  9865. if (
  9866. (taicpu(p).oper[0]^.typ <> top_reg) or
  9867. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9868. ) and
  9869. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9870. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9871. begin
  9872. { Make a preference to remove the second MOVZX instruction }
  9873. case taicpu(hp1).opsize of
  9874. S_BL, S_WL:
  9875. begin
  9876. TargetSize := S_L;
  9877. TargetSubReg := R_SUBD;
  9878. end;
  9879. S_BW:
  9880. begin
  9881. TargetSize := S_W;
  9882. TargetSubReg := R_SUBW;
  9883. end;
  9884. else
  9885. InternalError(2020112302);
  9886. end;
  9887. end
  9888. else
  9889. begin
  9890. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9891. begin
  9892. { Exceeded lower bound but not upper bound }
  9893. TargetSize := MaxSize;
  9894. end
  9895. else if not LowerUnsignedOverflow then
  9896. begin
  9897. { Size didn't exceed lower bound }
  9898. TargetSize := MinSize;
  9899. end
  9900. else
  9901. Exit;
  9902. end;
  9903. case TargetSize of
  9904. S_B:
  9905. TargetSubReg := R_SUBL;
  9906. S_W:
  9907. TargetSubReg := R_SUBW;
  9908. S_L:
  9909. TargetSubReg := R_SUBD;
  9910. else
  9911. InternalError(2020112350);
  9912. end;
  9913. { Update the register to its new size }
  9914. setsubreg(ThisReg, TargetSubReg);
  9915. RegInUse := False;
  9916. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9917. begin
  9918. { Check to see if the active register is used afterwards;
  9919. if not, we can change it and make a saving. }
  9920. TransferUsedRegs(TmpUsedRegs);
  9921. { The target register may be marked as in use to cross
  9922. a jump to a distant label, so exclude it }
  9923. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9924. hp2 := p;
  9925. repeat
  9926. { Explicitly check for the excluded register (don't include the first
  9927. instruction as it may be reading from here }
  9928. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9929. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9930. begin
  9931. RegInUse := True;
  9932. Break;
  9933. end;
  9934. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9935. if not GetNextInstruction(hp2, hp2) then
  9936. InternalError(2020112340);
  9937. until (hp2 = hp1);
  9938. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9939. { We might still be able to get away with this }
  9940. RegInUse := not
  9941. (
  9942. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9943. (hp2.typ = ait_instruction) and
  9944. (
  9945. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9946. instruction that doesn't actually contain ThisReg }
  9947. (cs_opt_level3 in current_settings.optimizerswitches) or
  9948. RegInInstruction(ThisReg, hp2)
  9949. ) and
  9950. RegLoadedWithNewValue(ThisReg, hp2)
  9951. );
  9952. if not RegInUse then
  9953. begin
  9954. { Force the register size to the same as this instruction so it can be removed}
  9955. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9956. begin
  9957. TargetSize := S_L;
  9958. TargetSubReg := R_SUBD;
  9959. end
  9960. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9961. begin
  9962. TargetSize := S_W;
  9963. TargetSubReg := R_SUBW;
  9964. end;
  9965. ThisReg := taicpu(hp1).oper[1]^.reg;
  9966. setsubreg(ThisReg, TargetSubReg);
  9967. RegChanged := True;
  9968. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9969. TransferUsedRegs(TmpUsedRegs);
  9970. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9971. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9972. if p = hp1 then
  9973. begin
  9974. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9975. p_removed := True;
  9976. end
  9977. else
  9978. RemoveInstruction(hp1);
  9979. hp1_removed := True;
  9980. { Instruction will become "mov %reg,%reg" }
  9981. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9982. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9983. begin
  9984. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9985. RemoveCurrentP(p);
  9986. p_removed := True;
  9987. end
  9988. else
  9989. taicpu(p).oper[1]^.reg := ThisReg;
  9990. Result := True;
  9991. end
  9992. else
  9993. begin
  9994. if TargetSize <> MaxSize then
  9995. begin
  9996. { Since the register is in use, we have to force it to
  9997. MaxSize otherwise part of it may become undefined later on }
  9998. TargetSize := MaxSize;
  9999. case TargetSize of
  10000. S_B:
  10001. TargetSubReg := R_SUBL;
  10002. S_W:
  10003. TargetSubReg := R_SUBW;
  10004. S_L:
  10005. TargetSubReg := R_SUBD;
  10006. else
  10007. InternalError(2020112351);
  10008. end;
  10009. setsubreg(ThisReg, TargetSubReg);
  10010. end;
  10011. AdjustFinalLoad;
  10012. end;
  10013. end
  10014. else
  10015. AdjustFinalLoad;
  10016. Result := AdjustInitialLoadAndSize or Result;
  10017. { Now go through every instruction we found and change the
  10018. size. If TargetSize = MaxSize, then almost no changes are
  10019. needed and Result can remain False if it hasn't been set
  10020. yet.
  10021. If RegChanged is True, then the register requires changing
  10022. and so the point about TargetSize = MaxSize doesn't apply. }
  10023. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10024. begin
  10025. for LocalIndex := 0 to InstrMax do
  10026. begin
  10027. { If p_removed is true, then the original MOV/Z was removed
  10028. and removing the AND instruction may not be safe if it
  10029. appears first }
  10030. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10031. InternalError(2020112310);
  10032. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10033. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10034. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10035. InstrList[LocalIndex].opsize := TargetSize;
  10036. end;
  10037. Result := True;
  10038. end;
  10039. end;
  10040. begin
  10041. Result := False;
  10042. p_removed := False;
  10043. hp1_removed := False;
  10044. ThisReg := taicpu(p).oper[1]^.reg;
  10045. { Check for:
  10046. movs/z ###,%ecx (or %cx or %rcx)
  10047. ...
  10048. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10049. (dealloc %ecx)
  10050. Change to:
  10051. mov ###,%cl (if ### = %cl, then remove completely)
  10052. ...
  10053. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10054. }
  10055. if (getsupreg(ThisReg) = RS_ECX) and
  10056. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10057. (hp1.typ = ait_instruction) and
  10058. (
  10059. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10060. instruction that doesn't actually contain ECX }
  10061. (cs_opt_level3 in current_settings.optimizerswitches) or
  10062. RegInInstruction(NR_ECX, hp1) or
  10063. (
  10064. { It's common for the shift/rotate's read/write register to be
  10065. initialised in between, so under -O2 and under, search ahead
  10066. one more instruction
  10067. }
  10068. GetNextInstruction(hp1, hp1) and
  10069. (hp1.typ = ait_instruction) and
  10070. RegInInstruction(NR_ECX, hp1)
  10071. )
  10072. ) and
  10073. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10074. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10075. begin
  10076. TransferUsedRegs(TmpUsedRegs);
  10077. hp2 := p;
  10078. repeat
  10079. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10080. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10081. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10082. begin
  10083. case taicpu(p).opsize of
  10084. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10085. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10086. begin
  10087. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10088. RemoveCurrentP(p);
  10089. end
  10090. else
  10091. begin
  10092. taicpu(p).opcode := A_MOV;
  10093. taicpu(p).opsize := S_B;
  10094. taicpu(p).oper[1]^.reg := NR_CL;
  10095. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10096. end;
  10097. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10098. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10099. begin
  10100. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10101. RemoveCurrentP(p);
  10102. end
  10103. else
  10104. begin
  10105. taicpu(p).opcode := A_MOV;
  10106. taicpu(p).opsize := S_W;
  10107. taicpu(p).oper[1]^.reg := NR_CX;
  10108. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10109. end;
  10110. {$ifdef x86_64}
  10111. S_LQ:
  10112. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10113. begin
  10114. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10115. RemoveCurrentP(p);
  10116. end
  10117. else
  10118. begin
  10119. taicpu(p).opcode := A_MOV;
  10120. taicpu(p).opsize := S_L;
  10121. taicpu(p).oper[1]^.reg := NR_ECX;
  10122. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10123. end;
  10124. {$endif x86_64}
  10125. else
  10126. InternalError(2021120401);
  10127. end;
  10128. Result := True;
  10129. Exit;
  10130. end;
  10131. end;
  10132. { This is anything but quick! }
  10133. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10134. Exit;
  10135. SetLength(InstrList, 0);
  10136. InstrMax := -1;
  10137. case taicpu(p).opsize of
  10138. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10139. begin
  10140. {$if defined(i386) or defined(i8086)}
  10141. { If the target size is 8-bit, make sure we can actually encode it }
  10142. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10143. Exit;
  10144. {$endif i386 or i8086}
  10145. LowerLimit := $FF;
  10146. SignedLowerLimit := $7F;
  10147. SignedLowerLimitBottom := -128;
  10148. MinSize := S_B;
  10149. if taicpu(p).opsize = S_BW then
  10150. begin
  10151. MaxSize := S_W;
  10152. UpperLimit := $FFFF;
  10153. SignedUpperLimit := $7FFF;
  10154. SignedUpperLimitBottom := -32768;
  10155. end
  10156. else
  10157. begin
  10158. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10159. MaxSize := S_L;
  10160. UpperLimit := $FFFFFFFF;
  10161. SignedUpperLimit := $7FFFFFFF;
  10162. SignedUpperLimitBottom := -2147483648;
  10163. end;
  10164. end;
  10165. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10166. begin
  10167. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10168. LowerLimit := $FFFF;
  10169. SignedLowerLimit := $7FFF;
  10170. SignedLowerLimitBottom := -32768;
  10171. UpperLimit := $FFFFFFFF;
  10172. SignedUpperLimit := $7FFFFFFF;
  10173. SignedUpperLimitBottom := -2147483648;
  10174. MinSize := S_W;
  10175. MaxSize := S_L;
  10176. end;
  10177. {$ifdef x86_64}
  10178. S_LQ:
  10179. begin
  10180. { Both the lower and upper limits are set to 32-bit. If a limit
  10181. is breached, then optimisation is impossible }
  10182. LowerLimit := $FFFFFFFF;
  10183. SignedLowerLimit := $7FFFFFFF;
  10184. SignedLowerLimitBottom := -2147483648;
  10185. UpperLimit := $FFFFFFFF;
  10186. SignedUpperLimit := $7FFFFFFF;
  10187. SignedUpperLimitBottom := -2147483648;
  10188. MinSize := S_L;
  10189. MaxSize := S_L;
  10190. end;
  10191. {$endif x86_64}
  10192. else
  10193. InternalError(2020112301);
  10194. end;
  10195. TestValMin := 0;
  10196. TestValMax := LowerLimit;
  10197. TestValSignedMax := SignedLowerLimit;
  10198. TryShiftDownLimit := LowerLimit;
  10199. TryShiftDown := S_NO;
  10200. ShiftDownOverflow := False;
  10201. RegChanged := False;
  10202. BitwiseOnly := True;
  10203. OrXorUsed := False;
  10204. UpperSignedOverflow := False;
  10205. LowerSignedOverflow := False;
  10206. UpperUnsignedOverflow := False;
  10207. LowerUnsignedOverflow := False;
  10208. hp1 := p;
  10209. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10210. (hp1.typ = ait_instruction) and
  10211. (
  10212. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10213. instruction that doesn't actually contain ThisReg }
  10214. (cs_opt_level3 in current_settings.optimizerswitches) or
  10215. { This allows this Movx optimisation to work through the SETcc instructions
  10216. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10217. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10218. skip over these SETcc instructions). }
  10219. (taicpu(hp1).opcode = A_SETcc) or
  10220. RegInInstruction(ThisReg, hp1)
  10221. ) do
  10222. begin
  10223. case taicpu(hp1).opcode of
  10224. A_INC,A_DEC:
  10225. begin
  10226. { Has to be an exact match on the register }
  10227. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10228. Break;
  10229. if taicpu(hp1).opcode = A_INC then
  10230. begin
  10231. Inc(TestValMin);
  10232. Inc(TestValMax);
  10233. Inc(TestValSignedMax);
  10234. end
  10235. else
  10236. begin
  10237. Dec(TestValMin);
  10238. Dec(TestValMax);
  10239. Dec(TestValSignedMax);
  10240. end;
  10241. end;
  10242. A_TEST, A_CMP:
  10243. begin
  10244. if (
  10245. { Too high a risk of non-linear behaviour that breaks DFA
  10246. here, unless it's cmp $0,%reg, which is equivalent to
  10247. test %reg,%reg }
  10248. OrXorUsed and
  10249. (taicpu(hp1).opcode = A_CMP) and
  10250. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10251. ) or
  10252. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10253. { Has to be an exact match on the register }
  10254. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10255. (
  10256. { Permit "test %reg,%reg" }
  10257. (taicpu(hp1).opcode = A_TEST) and
  10258. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10259. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10260. ) or
  10261. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10262. { Make sure the comparison value is not smaller than the
  10263. smallest allowed signed value for the minimum size (e.g.
  10264. -128 for 8-bit) }
  10265. not (
  10266. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10267. { Is it in the negative range? }
  10268. (
  10269. (taicpu(hp1).oper[0]^.val < 0) and
  10270. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10271. )
  10272. ) then
  10273. Break;
  10274. { Check to see if the active register is used afterwards }
  10275. TransferUsedRegs(TmpUsedRegs);
  10276. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10277. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10278. begin
  10279. { Make sure the comparison or any previous instructions
  10280. hasn't pushed the test values outside of the range of
  10281. MinSize }
  10282. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10283. begin
  10284. { Exceeded lower bound but not upper bound }
  10285. Exit;
  10286. end
  10287. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10288. begin
  10289. { Size didn't exceed lower bound }
  10290. TargetSize := MinSize;
  10291. end
  10292. else
  10293. Break;
  10294. case TargetSize of
  10295. S_B:
  10296. TargetSubReg := R_SUBL;
  10297. S_W:
  10298. TargetSubReg := R_SUBW;
  10299. S_L:
  10300. TargetSubReg := R_SUBD;
  10301. else
  10302. InternalError(2021051002);
  10303. end;
  10304. if TargetSize <> MaxSize then
  10305. begin
  10306. { Update the register to its new size }
  10307. setsubreg(ThisReg, TargetSubReg);
  10308. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10309. taicpu(hp1).oper[1]^.reg := ThisReg;
  10310. taicpu(hp1).opsize := TargetSize;
  10311. { Convert the input MOVZX to a MOV if necessary }
  10312. AdjustInitialLoadAndSize;
  10313. if (InstrMax >= 0) then
  10314. begin
  10315. for Index := 0 to InstrMax do
  10316. begin
  10317. { If p_removed is true, then the original MOV/Z was removed
  10318. and removing the AND instruction may not be safe if it
  10319. appears first }
  10320. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10321. InternalError(2020112311);
  10322. if InstrList[Index].oper[0]^.typ = top_reg then
  10323. InstrList[Index].oper[0]^.reg := ThisReg;
  10324. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10325. InstrList[Index].opsize := MinSize;
  10326. end;
  10327. end;
  10328. Result := True;
  10329. end;
  10330. Exit;
  10331. end;
  10332. end;
  10333. A_SETcc:
  10334. begin
  10335. { This allows this Movx optimisation to work through the SETcc instructions
  10336. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10337. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10338. skip over these SETcc instructions). }
  10339. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10340. { Of course, break out if the current register is used }
  10341. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10342. Break
  10343. else
  10344. { We must use Continue so the instruction doesn't get added
  10345. to InstrList }
  10346. Continue;
  10347. end;
  10348. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10349. begin
  10350. if
  10351. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10352. { Has to be an exact match on the register }
  10353. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10354. (
  10355. (
  10356. (taicpu(hp1).oper[0]^.typ = top_const) and
  10357. (
  10358. (
  10359. (taicpu(hp1).opcode = A_SHL) and
  10360. (
  10361. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10362. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10363. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10364. )
  10365. ) or (
  10366. (taicpu(hp1).opcode <> A_SHL) and
  10367. (
  10368. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10369. { Is it in the negative range? }
  10370. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10371. )
  10372. )
  10373. )
  10374. ) or (
  10375. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10376. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10377. )
  10378. ) then
  10379. Break;
  10380. { Only process OR and XOR if there are only bitwise operations,
  10381. since otherwise they can too easily fool the data flow
  10382. analysis (they can cause non-linear behaviour) }
  10383. case taicpu(hp1).opcode of
  10384. A_ADD:
  10385. begin
  10386. if OrXorUsed then
  10387. { Too high a risk of non-linear behaviour that breaks DFA here }
  10388. Break
  10389. else
  10390. BitwiseOnly := False;
  10391. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10392. begin
  10393. TestValMin := TestValMin * 2;
  10394. TestValMax := TestValMax * 2;
  10395. TestValSignedMax := TestValSignedMax * 2;
  10396. end
  10397. else
  10398. begin
  10399. WorkingValue := taicpu(hp1).oper[0]^.val;
  10400. TestValMin := TestValMin + WorkingValue;
  10401. TestValMax := TestValMax + WorkingValue;
  10402. TestValSignedMax := TestValSignedMax + WorkingValue;
  10403. end;
  10404. end;
  10405. A_SUB:
  10406. begin
  10407. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10408. begin
  10409. TestValMin := 0;
  10410. TestValMax := 0;
  10411. TestValSignedMax := 0;
  10412. end
  10413. else
  10414. begin
  10415. if OrXorUsed then
  10416. { Too high a risk of non-linear behaviour that breaks DFA here }
  10417. Break
  10418. else
  10419. BitwiseOnly := False;
  10420. WorkingValue := taicpu(hp1).oper[0]^.val;
  10421. TestValMin := TestValMin - WorkingValue;
  10422. TestValMax := TestValMax - WorkingValue;
  10423. TestValSignedMax := TestValSignedMax - WorkingValue;
  10424. end;
  10425. end;
  10426. A_AND:
  10427. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10428. begin
  10429. { we might be able to go smaller if AND appears first }
  10430. if InstrMax = -1 then
  10431. case MinSize of
  10432. S_B:
  10433. ;
  10434. S_W:
  10435. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10436. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10437. begin
  10438. TryShiftDown := S_B;
  10439. TryShiftDownLimit := $FF;
  10440. end;
  10441. S_L:
  10442. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10443. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10444. begin
  10445. TryShiftDown := S_B;
  10446. TryShiftDownLimit := $FF;
  10447. end
  10448. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10449. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10450. begin
  10451. TryShiftDown := S_W;
  10452. TryShiftDownLimit := $FFFF;
  10453. end;
  10454. else
  10455. InternalError(2020112320);
  10456. end;
  10457. WorkingValue := taicpu(hp1).oper[0]^.val;
  10458. TestValMin := TestValMin and WorkingValue;
  10459. TestValMax := TestValMax and WorkingValue;
  10460. TestValSignedMax := TestValSignedMax and WorkingValue;
  10461. end;
  10462. A_OR:
  10463. begin
  10464. if not BitwiseOnly then
  10465. Break;
  10466. OrXorUsed := True;
  10467. WorkingValue := taicpu(hp1).oper[0]^.val;
  10468. TestValMin := TestValMin or WorkingValue;
  10469. TestValMax := TestValMax or WorkingValue;
  10470. TestValSignedMax := TestValSignedMax or WorkingValue;
  10471. end;
  10472. A_XOR:
  10473. begin
  10474. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10475. begin
  10476. TestValMin := 0;
  10477. TestValMax := 0;
  10478. TestValSignedMax := 0;
  10479. end
  10480. else
  10481. begin
  10482. if not BitwiseOnly then
  10483. Break;
  10484. OrXorUsed := True;
  10485. WorkingValue := taicpu(hp1).oper[0]^.val;
  10486. TestValMin := TestValMin xor WorkingValue;
  10487. TestValMax := TestValMax xor WorkingValue;
  10488. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10489. end;
  10490. end;
  10491. A_SHL:
  10492. begin
  10493. BitwiseOnly := False;
  10494. WorkingValue := taicpu(hp1).oper[0]^.val;
  10495. TestValMin := TestValMin shl WorkingValue;
  10496. TestValMax := TestValMax shl WorkingValue;
  10497. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10498. end;
  10499. A_SHR,
  10500. { The first instruction was MOVZX, so the value won't be negative }
  10501. A_SAR:
  10502. begin
  10503. if InstrMax <> -1 then
  10504. BitwiseOnly := False
  10505. else
  10506. { we might be able to go smaller if SHR appears first }
  10507. case MinSize of
  10508. S_B:
  10509. ;
  10510. S_W:
  10511. if (taicpu(hp1).oper[0]^.val >= 8) then
  10512. begin
  10513. TryShiftDown := S_B;
  10514. TryShiftDownLimit := $FF;
  10515. TryShiftDownSignedLimit := $7F;
  10516. TryShiftDownSignedLimitLower := -128;
  10517. end;
  10518. S_L:
  10519. if (taicpu(hp1).oper[0]^.val >= 24) then
  10520. begin
  10521. TryShiftDown := S_B;
  10522. TryShiftDownLimit := $FF;
  10523. TryShiftDownSignedLimit := $7F;
  10524. TryShiftDownSignedLimitLower := -128;
  10525. end
  10526. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10527. begin
  10528. TryShiftDown := S_W;
  10529. TryShiftDownLimit := $FFFF;
  10530. TryShiftDownSignedLimit := $7FFF;
  10531. TryShiftDownSignedLimitLower := -32768;
  10532. end;
  10533. else
  10534. InternalError(2020112321);
  10535. end;
  10536. WorkingValue := taicpu(hp1).oper[0]^.val;
  10537. if taicpu(hp1).opcode = A_SAR then
  10538. begin
  10539. TestValMin := SarInt64(TestValMin, WorkingValue);
  10540. TestValMax := SarInt64(TestValMax, WorkingValue);
  10541. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10542. end
  10543. else
  10544. begin
  10545. TestValMin := TestValMin shr WorkingValue;
  10546. TestValMax := TestValMax shr WorkingValue;
  10547. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10548. end;
  10549. end;
  10550. else
  10551. InternalError(2020112303);
  10552. end;
  10553. end;
  10554. (*
  10555. A_IMUL:
  10556. case taicpu(hp1).ops of
  10557. 2:
  10558. begin
  10559. if not MatchOpType(hp1, top_reg, top_reg) or
  10560. { Has to be an exact match on the register }
  10561. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10562. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10563. Break;
  10564. TestValMin := TestValMin * TestValMin;
  10565. TestValMax := TestValMax * TestValMax;
  10566. TestValSignedMax := TestValSignedMax * TestValMax;
  10567. end;
  10568. 3:
  10569. begin
  10570. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10571. { Has to be an exact match on the register }
  10572. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10573. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10574. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10575. { Is it in the negative range? }
  10576. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10577. Break;
  10578. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10579. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10580. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10581. end;
  10582. else
  10583. Break;
  10584. end;
  10585. A_IDIV:
  10586. case taicpu(hp1).ops of
  10587. 3:
  10588. begin
  10589. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10590. { Has to be an exact match on the register }
  10591. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10592. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10593. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10594. { Is it in the negative range? }
  10595. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10596. Break;
  10597. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10598. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10599. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10600. end;
  10601. else
  10602. Break;
  10603. end;
  10604. *)
  10605. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10606. begin
  10607. { If there are no instructions in between, then we might be able to make a saving }
  10608. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10609. Break;
  10610. { We have something like:
  10611. movzbw %dl,%dx
  10612. ...
  10613. movswl %dx,%edx
  10614. Change the latter to a zero-extension then enter the
  10615. A_MOVZX case branch.
  10616. }
  10617. {$ifdef x86_64}
  10618. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10619. begin
  10620. { this becomes a zero extension from 32-bit to 64-bit, but
  10621. the upper 32 bits are already zero, so just delete the
  10622. instruction }
  10623. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10624. RemoveInstruction(hp1);
  10625. Result := True;
  10626. Exit;
  10627. end
  10628. else
  10629. {$endif x86_64}
  10630. begin
  10631. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10632. taicpu(hp1).opcode := A_MOVZX;
  10633. {$ifdef x86_64}
  10634. case taicpu(hp1).opsize of
  10635. S_BQ:
  10636. begin
  10637. taicpu(hp1).opsize := S_BL;
  10638. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10639. end;
  10640. S_WQ:
  10641. begin
  10642. taicpu(hp1).opsize := S_WL;
  10643. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10644. end;
  10645. S_LQ:
  10646. begin
  10647. taicpu(hp1).opcode := A_MOV;
  10648. taicpu(hp1).opsize := S_L;
  10649. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10650. { In this instance, we need to break out because the
  10651. instruction is no longer MOVZX or MOVSXD }
  10652. Result := True;
  10653. Exit;
  10654. end;
  10655. else
  10656. ;
  10657. end;
  10658. {$endif x86_64}
  10659. Result := CompressInstructions;
  10660. Exit;
  10661. end;
  10662. end;
  10663. A_MOVZX:
  10664. begin
  10665. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10666. Break;
  10667. if (InstrMax = -1) then
  10668. begin
  10669. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10670. begin
  10671. { Optimise around i40003 }
  10672. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10673. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10674. {$ifndef x86_64}
  10675. and (
  10676. (taicpu(p).oper[0]^.typ <> top_reg) or
  10677. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10678. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10679. )
  10680. {$endif not x86_64}
  10681. then
  10682. begin
  10683. if (taicpu(p).oper[0]^.typ = top_reg) then
  10684. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10685. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10686. taicpu(p).opsize := S_BL;
  10687. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10688. RemoveInstruction(hp1);
  10689. Result := True;
  10690. Exit;
  10691. end;
  10692. end
  10693. else
  10694. begin
  10695. { Will return false if the second parameter isn't ThisReg
  10696. (can happen on -O2 and under) }
  10697. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10698. begin
  10699. { The two MOVZX instructions are adjacent, so remove the first one }
  10700. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10701. RemoveCurrentP(p);
  10702. Result := True;
  10703. Exit;
  10704. end;
  10705. Break;
  10706. end;
  10707. end;
  10708. Result := CompressInstructions;
  10709. Exit;
  10710. end;
  10711. else
  10712. { This includes ADC, SBB and IDIV }
  10713. Break;
  10714. end;
  10715. if not CheckOverflowConditions then
  10716. Break;
  10717. { Contains highest index (so instruction count - 1) }
  10718. Inc(InstrMax);
  10719. if InstrMax > High(InstrList) then
  10720. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10721. InstrList[InstrMax] := taicpu(hp1);
  10722. end;
  10723. end;
  10724. {$pop}
  10725. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10726. var
  10727. hp1 : tai;
  10728. begin
  10729. Result:=false;
  10730. if (taicpu(p).ops >= 2) and
  10731. ((taicpu(p).oper[0]^.typ = top_const) or
  10732. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10733. (taicpu(p).oper[1]^.typ = top_reg) and
  10734. ((taicpu(p).ops = 2) or
  10735. ((taicpu(p).oper[2]^.typ = top_reg) and
  10736. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10737. GetLastInstruction(p,hp1) and
  10738. MatchInstruction(hp1,A_MOV,[]) and
  10739. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10740. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10741. begin
  10742. TransferUsedRegs(TmpUsedRegs);
  10743. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10744. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10745. { change
  10746. mov reg1,reg2
  10747. imul y,reg2 to imul y,reg1,reg2 }
  10748. begin
  10749. taicpu(p).ops := 3;
  10750. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10751. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10752. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10753. RemoveInstruction(hp1);
  10754. result:=true;
  10755. end;
  10756. end;
  10757. end;
  10758. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10759. var
  10760. ThisLabel: TAsmLabel;
  10761. begin
  10762. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10763. ThisLabel.decrefs;
  10764. taicpu(p).condition := C_None;
  10765. taicpu(p).opcode := A_RET;
  10766. taicpu(p).is_jmp := false;
  10767. taicpu(p).ops := taicpu(ret_p).ops;
  10768. case taicpu(ret_p).ops of
  10769. 0:
  10770. taicpu(p).clearop(0);
  10771. 1:
  10772. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10773. else
  10774. internalerror(2016041301);
  10775. end;
  10776. { If the original label is now dead, it might turn out that the label
  10777. immediately follows p. As a result, everything beyond it, which will
  10778. be just some final register configuration and a RET instruction, is
  10779. now dead code. [Kit] }
  10780. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10781. running RemoveDeadCodeAfterJump for each RET instruction, because
  10782. this optimisation rarely happens and most RETs appear at the end of
  10783. routines where there is nothing that can be stripped. [Kit] }
  10784. if not ThisLabel.is_used then
  10785. RemoveDeadCodeAfterJump(p);
  10786. end;
  10787. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10788. var
  10789. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10790. Unconditional, PotentialModified: Boolean;
  10791. OperPtr: POper;
  10792. NewRef: TReference;
  10793. InstrList: array of taicpu;
  10794. InstrMax, Index: Integer;
  10795. const
  10796. {$ifdef DEBUG_AOPTCPU}
  10797. SNoFlags: shortstring = ' so the flags aren''t modified';
  10798. {$else DEBUG_AOPTCPU}
  10799. SNoFlags = '';
  10800. {$endif DEBUG_AOPTCPU}
  10801. begin
  10802. Result:=false;
  10803. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10804. begin
  10805. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10806. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10807. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10808. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10809. GetNextInstruction(hp1, hp2) and
  10810. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10811. { Change from: To:
  10812. set(C) %reg j(~C) label
  10813. test %reg,%reg/cmp $0,%reg
  10814. je label
  10815. set(C) %reg j(C) label
  10816. test %reg,%reg/cmp $0,%reg
  10817. jne label
  10818. (Also do something similar with sete/setne instead of je/jne)
  10819. }
  10820. begin
  10821. { Before we do anything else, we need to check the instructions
  10822. in between SETcc and TEST to make sure they don't modify the
  10823. FLAGS register - if -O2 or under, there won't be any
  10824. instructions between SET and TEST }
  10825. TransferUsedRegs(TmpUsedRegs);
  10826. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10827. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10828. begin
  10829. next := p;
  10830. SetLength(InstrList, 0);
  10831. InstrMax := -1;
  10832. PotentialModified := False;
  10833. { Make a note of every instruction that modifies the FLAGS
  10834. register }
  10835. while GetNextInstruction(next, next) and (next <> hp1) do
  10836. begin
  10837. if next.typ <> ait_instruction then
  10838. { GetNextInstructionUsingReg should have returned False }
  10839. InternalError(2021051701);
  10840. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10841. begin
  10842. case taicpu(next).opcode of
  10843. A_SETcc,
  10844. A_CMOVcc,
  10845. A_Jcc:
  10846. begin
  10847. if PotentialModified then
  10848. { Not safe because the flags were modified earlier }
  10849. Exit
  10850. else
  10851. { Condition is the same as the initial SETcc, so this is safe
  10852. (don't add to instruction list though) }
  10853. Continue;
  10854. end;
  10855. A_ADD:
  10856. begin
  10857. if (taicpu(next).opsize = S_B) or
  10858. { LEA doesn't support 8-bit operands }
  10859. (taicpu(next).oper[1]^.typ <> top_reg) or
  10860. { Must write to a register }
  10861. (taicpu(next).oper[0]^.typ = top_ref) then
  10862. { Require a constant or a register }
  10863. Exit;
  10864. PotentialModified := True;
  10865. end;
  10866. A_SUB:
  10867. begin
  10868. if (taicpu(next).opsize = S_B) or
  10869. { LEA doesn't support 8-bit operands }
  10870. (taicpu(next).oper[1]^.typ <> top_reg) or
  10871. { Must write to a register }
  10872. (taicpu(next).oper[0]^.typ <> top_const) or
  10873. (taicpu(next).oper[0]^.val = $80000000) then
  10874. { Can't subtract a register with LEA - also
  10875. check that the value isn't -2^31, as this
  10876. can't be negated }
  10877. Exit;
  10878. PotentialModified := True;
  10879. end;
  10880. A_SAL,
  10881. A_SHL:
  10882. begin
  10883. if (taicpu(next).opsize = S_B) or
  10884. { LEA doesn't support 8-bit operands }
  10885. (taicpu(next).oper[1]^.typ <> top_reg) or
  10886. { Must write to a register }
  10887. (taicpu(next).oper[0]^.typ <> top_const) or
  10888. (taicpu(next).oper[0]^.val < 0) or
  10889. (taicpu(next).oper[0]^.val > 3) then
  10890. Exit;
  10891. PotentialModified := True;
  10892. end;
  10893. A_IMUL:
  10894. begin
  10895. if (taicpu(next).ops <> 3) or
  10896. (taicpu(next).oper[1]^.typ <> top_reg) or
  10897. { Must write to a register }
  10898. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10899. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10900. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10901. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10902. Exit
  10903. else
  10904. PotentialModified := True;
  10905. end;
  10906. else
  10907. { Don't know how to change this, so abort }
  10908. Exit;
  10909. end;
  10910. { Contains highest index (so instruction count - 1) }
  10911. Inc(InstrMax);
  10912. if InstrMax > High(InstrList) then
  10913. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10914. InstrList[InstrMax] := taicpu(next);
  10915. end;
  10916. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10917. end;
  10918. if not Assigned(next) or (next <> hp1) then
  10919. { It should be equal to hp1 }
  10920. InternalError(2021051702);
  10921. { Cycle through each instruction and check to see if we can
  10922. change them to versions that don't modify the flags }
  10923. if (InstrMax >= 0) then
  10924. begin
  10925. for Index := 0 to InstrMax do
  10926. case InstrList[Index].opcode of
  10927. A_ADD:
  10928. begin
  10929. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10930. InstrList[Index].opcode := A_LEA;
  10931. reference_reset(NewRef, 1, []);
  10932. NewRef.base := InstrList[Index].oper[1]^.reg;
  10933. if InstrList[Index].oper[0]^.typ = top_reg then
  10934. begin
  10935. NewRef.index := InstrList[Index].oper[0]^.reg;
  10936. NewRef.scalefactor := 1;
  10937. end
  10938. else
  10939. NewRef.offset := InstrList[Index].oper[0]^.val;
  10940. InstrList[Index].loadref(0, NewRef);
  10941. end;
  10942. A_SUB:
  10943. begin
  10944. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10945. InstrList[Index].opcode := A_LEA;
  10946. reference_reset(NewRef, 1, []);
  10947. NewRef.base := InstrList[Index].oper[1]^.reg;
  10948. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10949. InstrList[Index].loadref(0, NewRef);
  10950. end;
  10951. A_SHL,
  10952. A_SAL:
  10953. begin
  10954. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10955. InstrList[Index].opcode := A_LEA;
  10956. reference_reset(NewRef, 1, []);
  10957. NewRef.index := InstrList[Index].oper[1]^.reg;
  10958. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10959. InstrList[Index].loadref(0, NewRef);
  10960. end;
  10961. A_IMUL:
  10962. begin
  10963. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10964. InstrList[Index].opcode := A_LEA;
  10965. reference_reset(NewRef, 1, []);
  10966. NewRef.index := InstrList[Index].oper[1]^.reg;
  10967. case InstrList[Index].oper[0]^.val of
  10968. 2, 4, 8:
  10969. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10970. else {3, 5 and 9}
  10971. begin
  10972. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10973. NewRef.base := InstrList[Index].oper[1]^.reg;
  10974. end;
  10975. end;
  10976. InstrList[Index].loadref(0, NewRef);
  10977. end;
  10978. else
  10979. InternalError(2021051710);
  10980. end;
  10981. end;
  10982. { Mark the FLAGS register as used across this whole block }
  10983. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10984. end;
  10985. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10986. JumpC := taicpu(hp2).condition;
  10987. Unconditional := False;
  10988. if conditions_equal(JumpC, C_E) then
  10989. SetC := inverse_cond(taicpu(p).condition)
  10990. else if conditions_equal(JumpC, C_NE) then
  10991. SetC := taicpu(p).condition
  10992. else
  10993. { We've got something weird here (and inefficent) }
  10994. begin
  10995. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10996. SetC := C_NONE;
  10997. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10998. if condition_in(C_AE, JumpC) then
  10999. Unconditional := True
  11000. else
  11001. { Not sure what to do with this jump - drop out }
  11002. Exit;
  11003. end;
  11004. RemoveInstruction(hp1);
  11005. if Unconditional then
  11006. MakeUnconditional(taicpu(hp2))
  11007. else
  11008. begin
  11009. if SetC = C_NONE then
  11010. InternalError(2018061402);
  11011. taicpu(hp2).SetCondition(SetC);
  11012. end;
  11013. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11014. TmpUsedRegs }
  11015. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11016. begin
  11017. RemoveCurrentp(p, hp2);
  11018. if taicpu(hp2).opcode = A_SETcc then
  11019. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11020. else
  11021. begin
  11022. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11023. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11024. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11025. end;
  11026. end
  11027. else
  11028. if taicpu(hp2).opcode = A_SETcc then
  11029. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11030. else
  11031. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11032. Result := True;
  11033. end
  11034. else if
  11035. { Make sure the instructions are adjacent }
  11036. (
  11037. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11038. GetNextInstruction(p, hp1)
  11039. ) and
  11040. MatchInstruction(hp1, A_MOV, [S_B]) and
  11041. { Writing to memory is allowed }
  11042. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11043. begin
  11044. {
  11045. Watch out for sequences such as:
  11046. set(c)b %regb
  11047. movb %regb,(ref)
  11048. movb $0,1(ref)
  11049. movb $0,2(ref)
  11050. movb $0,3(ref)
  11051. Much more efficient to turn it into:
  11052. movl $0,%regl
  11053. set(c)b %regb
  11054. movl %regl,(ref)
  11055. Or:
  11056. set(c)b %regb
  11057. movzbl %regb,%regl
  11058. movl %regl,(ref)
  11059. }
  11060. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11061. GetNextInstruction(hp1, hp2) and
  11062. MatchInstruction(hp2, A_MOV, [S_B]) and
  11063. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11064. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11065. begin
  11066. { Don't do anything else except set Result to True }
  11067. end
  11068. else
  11069. begin
  11070. if taicpu(p).oper[0]^.typ = top_reg then
  11071. begin
  11072. TransferUsedRegs(TmpUsedRegs);
  11073. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11074. end;
  11075. { If it's not a register, it's a memory address }
  11076. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11077. begin
  11078. { Even if the register is still in use, we can minimise the
  11079. pipeline stall by changing the MOV into another SETcc. }
  11080. taicpu(hp1).opcode := A_SETcc;
  11081. taicpu(hp1).condition := taicpu(p).condition;
  11082. if taicpu(hp1).oper[1]^.typ = top_ref then
  11083. begin
  11084. { Swapping the operand pointers like this is probably a
  11085. bit naughty, but it is far faster than using loadoper
  11086. to transfer the reference from oper[1] to oper[0] if
  11087. you take into account the extra procedure calls and
  11088. the memory allocation and deallocation required }
  11089. OperPtr := taicpu(hp1).oper[1];
  11090. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11091. taicpu(hp1).oper[0] := OperPtr;
  11092. end
  11093. else
  11094. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11095. taicpu(hp1).clearop(1);
  11096. taicpu(hp1).ops := 1;
  11097. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11098. end
  11099. else
  11100. begin
  11101. if taicpu(hp1).oper[1]^.typ = top_reg then
  11102. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11103. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11104. RemoveInstruction(hp1);
  11105. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11106. end
  11107. end;
  11108. Result := True;
  11109. end;
  11110. end;
  11111. end;
  11112. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11113. var
  11114. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11115. TargetReg: TRegister;
  11116. condition, inverted_condition: TAsmCond;
  11117. FoundMOV: Boolean;
  11118. begin
  11119. Result := False;
  11120. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11121. create the most optimial instructions possible due to limited
  11122. register availability, and there are situations where two
  11123. complementary "simple" CMOV blocks are created which, after the fact
  11124. can be merged into a "double" block. For example:
  11125. movw $257,%ax
  11126. movw $2,%r8w
  11127. xorl r9d,%r9d
  11128. testw $16,18(%rcx)
  11129. cmovew %ax,%dx
  11130. cmovew %r8w,%bx
  11131. cmovel %r9d,%r14d
  11132. movw $1283,%ax
  11133. movw $4,%r8w
  11134. movl $9,%r9d
  11135. cmovnew %ax,%dx
  11136. cmovnew %r8w,%bx
  11137. cmovnel %r9d,%r14d
  11138. The CMOVNE instructions at the end can be removed, and the
  11139. destination registers copied into the MOV instructions directly
  11140. above them, before finally being moved to before the first CMOVE
  11141. instructions, to produce:
  11142. movw $257,%ax
  11143. movw $2,%r8w
  11144. xorl r9d,%r9d
  11145. testw $16,18(%rcx)
  11146. movw $1283,%dx
  11147. movw $4,%bx
  11148. movl $9,%r14d
  11149. cmovew %ax,%dx
  11150. cmovew %r8w,%bx
  11151. cmovel %r9d,%r14d
  11152. Which can then be later optimised to:
  11153. movw $257,%ax
  11154. movw $2,%r8w
  11155. xorl r9d,%r9d
  11156. movw $1283,%dx
  11157. movw $4,%bx
  11158. movl $9,%r14d
  11159. testw $16,18(%rcx)
  11160. cmovew %ax,%dx
  11161. cmovew %r8w,%bx
  11162. cmovel %r9d,%r14d
  11163. }
  11164. TargetReg := taicpu(hp1).oper[1]^.reg;
  11165. condition := taicpu(hp1).condition;
  11166. inverted_condition := inverse_cond(condition);
  11167. pFirstMov := nil;
  11168. pLastMov := nil;
  11169. pCMOV := nil;
  11170. if (p.typ = ait_instruction) then
  11171. pCond := p
  11172. else if not GetNextInstruction(p, pCond) then
  11173. InternalError(2024012501);
  11174. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11175. { We should get the CMP or TEST instructeion }
  11176. InternalError(2024012502);
  11177. if (
  11178. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11179. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11180. ) then
  11181. begin
  11182. { We have to tread carefully here, hence why we're not using
  11183. GetNextInstructionUsingReg... we can only accept MOV and other
  11184. CMOV instructions. Anything else and we must drop out}
  11185. hp2 := hp1;
  11186. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11187. begin
  11188. if (hp2.typ <> ait_instruction) then
  11189. Exit;
  11190. case taicpu(hp2).opcode of
  11191. A_MOV:
  11192. begin
  11193. if not Assigned(pFirstMov) then
  11194. pFirstMov := hp2;
  11195. pLastMOV := hp2;
  11196. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11197. { Something different - drop out }
  11198. Exit;
  11199. { Otherwise, leave it for now }
  11200. end;
  11201. A_CMOVcc:
  11202. begin
  11203. if taicpu(hp2).condition = inverted_condition then
  11204. begin
  11205. { We found what we're looking for }
  11206. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11207. begin
  11208. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11209. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11210. begin
  11211. pCMOV := hp2;
  11212. Break;
  11213. end
  11214. else
  11215. { Unsafe reference - drop out }
  11216. Exit;
  11217. end;
  11218. end
  11219. else if taicpu(hp2).condition <> condition then
  11220. { Something weird - drop out }
  11221. Exit;
  11222. end;
  11223. else
  11224. { Invalid }
  11225. Exit;
  11226. end;
  11227. end;
  11228. if not Assigned(pCMOV) then
  11229. { No complementary CMOV found }
  11230. Exit;
  11231. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11232. begin
  11233. { Don't need to do anything special or search for a matching MOV }
  11234. Asml.Remove(pCMOV);
  11235. if RegInInstruction(TargetReg, pCond) then
  11236. { Make sure we don't overwrite the register if it's being used in the condition }
  11237. Asml.InsertAfter(pCMOV, pCond)
  11238. else
  11239. Asml.InsertBefore(pCMOV, pCond);
  11240. taicpu(pCMOV).opcode := A_MOV;
  11241. taicpu(pCMOV).condition := C_None;
  11242. { Don't need to worry about allocating new registers in these cases }
  11243. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11244. Result := True;
  11245. Exit;
  11246. end
  11247. else
  11248. begin
  11249. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11250. FoundMOV := False;
  11251. { Search for the MOV that sets the target register }
  11252. hp2 := pFirstMov;
  11253. repeat
  11254. if (taicpu(hp2).opcode = A_MOV) and
  11255. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11256. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11257. begin
  11258. { Change the destination }
  11259. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11260. if not FoundMOV then
  11261. begin
  11262. FoundMOV := True;
  11263. { Make sure the register is allocated }
  11264. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11265. end;
  11266. hp1 := tai(hp2.Previous);
  11267. Asml.Remove(hp2);
  11268. if RegInInstruction(TargetReg, pCond) then
  11269. { Make sure we don't overwrite the register if it's being used in the condition }
  11270. Asml.InsertAfter(hp2, pCond)
  11271. else
  11272. Asml.InsertBefore(hp2, pCond);
  11273. if (hp2 = pLastMov) then
  11274. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11275. Break;
  11276. hp2 := hp1;
  11277. end;
  11278. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11279. if FoundMOV then
  11280. { Delete the CMOV }
  11281. RemoveInstruction(pCMOV)
  11282. else
  11283. begin
  11284. { If no MOV was found, we have to actually move and transmute the CMOV }
  11285. Asml.Remove(pCMOV);
  11286. if RegInInstruction(TargetReg, pCond) then
  11287. { Make sure we don't overwrite the register if it's being used in the condition }
  11288. Asml.InsertAfter(pCMOV, pCond)
  11289. else
  11290. Asml.InsertBefore(pCMOV, pCond);
  11291. taicpu(pCMOV).opcode := A_MOV;
  11292. taicpu(pCMOV).condition := C_None;
  11293. end;
  11294. Result := True;
  11295. Exit;
  11296. end;
  11297. end;
  11298. end;
  11299. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11300. var
  11301. hp1, hp2, pCond: tai;
  11302. begin
  11303. Result := False;
  11304. { Search ahead for CMOV instructions }
  11305. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11306. begin
  11307. hp1 := p;
  11308. hp2 := p;
  11309. pCond := nil; { To prevent compiler warnings }
  11310. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11311. DEFAULTFLAGS }
  11312. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11313. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11314. pCond := p;
  11315. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11316. begin
  11317. if (hp1.typ <> ait_instruction) then
  11318. { Break out on markers and labels etc. }
  11319. Break;
  11320. case taicpu(hp1).opcode of
  11321. A_MOV:
  11322. { Ignore regular MOVs unless they are obviously not related
  11323. to a CMOV block }
  11324. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11325. Break;
  11326. A_CMOVcc:
  11327. if TryCmpCMovOpts(pCond, hp1) then
  11328. begin
  11329. hp1 := hp2;
  11330. { p itself isn't changed, and we're still inside a
  11331. while loop to catch subsequent CMOVs, so just flag
  11332. a new iteration }
  11333. Include(OptsToCheck, aoc_ForceNewIteration);
  11334. Continue;
  11335. end;
  11336. else
  11337. { Drop out if we find anything else }
  11338. Break;
  11339. end;
  11340. hp2 := hp1;
  11341. end;
  11342. end;
  11343. end;
  11344. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11345. var
  11346. hp1, hp2, pCond: tai;
  11347. SourceReg, TargetReg: TRegister;
  11348. begin
  11349. Result := False;
  11350. { In some situations, we end up with an inefficient arrangement of
  11351. instructions in the form of:
  11352. or %reg1,%reg2
  11353. (%reg1 deallocated)
  11354. test %reg2,%reg2
  11355. mov x,%reg2
  11356. we may be able to swap and rearrange the registers to produce:
  11357. or %reg2,%reg1
  11358. mov x,%reg2
  11359. test %reg1,%reg1
  11360. (%reg1 deallocated)
  11361. }
  11362. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11363. (taicpu(p).oper[1]^.typ = top_reg) and
  11364. (
  11365. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11366. MatchOperand(taicpu(p).oper[0]^, -1)
  11367. ) and
  11368. GetNextInstruction(p, hp1) and
  11369. MatchInstruction(hp1, A_MOV, []) and
  11370. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11371. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11372. begin
  11373. TargetReg := taicpu(p).oper[1]^.reg;
  11374. { Now look backwards to find a simple commutative operation: ADD,
  11375. IMUL (2-register version), OR, AND or XOR - whose destination
  11376. register is the same as TEST }
  11377. hp2 := p;
  11378. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11379. if RegInInstruction(TargetReg, hp2) then
  11380. begin
  11381. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11382. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11383. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11384. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11385. begin
  11386. SourceReg := taicpu(hp2).oper[0]^.reg;
  11387. if
  11388. { Make sure the MOV doesn't use the other register }
  11389. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11390. { And make sure the source register is not used afterwards }
  11391. not RegInUsedRegs(SourceReg, UsedRegs) then
  11392. begin
  11393. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11394. taicpu(hp2).oper[0]^.reg := TargetReg;
  11395. taicpu(hp2).oper[1]^.reg := SourceReg;
  11396. if taicpu(p).oper[0]^.typ = top_reg then
  11397. taicpu(p).oper[0]^.reg := SourceReg;
  11398. taicpu(p).oper[1]^.reg := SourceReg;
  11399. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11400. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11401. Include(OptsToCheck, aoc_ForceNewIteration);
  11402. { We can still check the following optimisations since
  11403. the instruction is still a TEST }
  11404. end;
  11405. end;
  11406. Break;
  11407. end;
  11408. end;
  11409. { Search ahead3 for CMOV instructions }
  11410. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11411. begin
  11412. hp1 := p;
  11413. hp2 := p;
  11414. pCond := nil; { To prevent compiler warnings }
  11415. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11416. DEFAULTFLAGS }
  11417. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11418. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11419. pCond := p;
  11420. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11421. begin
  11422. if (hp1.typ <> ait_instruction) then
  11423. { Break out on markers and labels etc. }
  11424. Break;
  11425. case taicpu(hp1).opcode of
  11426. A_MOV:
  11427. { Ignore regular MOVs unless they are obviously not related
  11428. to a CMOV block }
  11429. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11430. Break;
  11431. A_CMOVcc:
  11432. if TryCmpCMovOpts(pCond, hp1) then
  11433. begin
  11434. hp1 := hp2;
  11435. { p itself isn't changed, and we're still inside a
  11436. while loop to catch subsequent CMOVs, so just flag
  11437. a new iteration }
  11438. Include(OptsToCheck, aoc_ForceNewIteration);
  11439. Continue;
  11440. end;
  11441. else
  11442. { Drop out if we find anything else }
  11443. Break;
  11444. end;
  11445. hp2 := hp1;
  11446. end;
  11447. end;
  11448. end;
  11449. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11450. var
  11451. hp1: tai;
  11452. Count: Integer;
  11453. OrigLabel: TAsmLabel;
  11454. begin
  11455. result := False;
  11456. { Sometimes, the optimisations below can permit this }
  11457. RemoveDeadCodeAfterJump(p);
  11458. 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
  11459. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11460. begin
  11461. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11462. { Also a side-effect of optimisations }
  11463. if CollapseZeroDistJump(p, OrigLabel) then
  11464. begin
  11465. Result := True;
  11466. Exit;
  11467. end;
  11468. hp1 := GetLabelWithSym(OrigLabel);
  11469. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11470. begin
  11471. if taicpu(hp1).opcode = A_RET then
  11472. begin
  11473. {
  11474. change
  11475. jmp .L1
  11476. ...
  11477. .L1:
  11478. ret
  11479. into
  11480. ret
  11481. }
  11482. begin
  11483. ConvertJumpToRET(p, hp1);
  11484. result:=true;
  11485. end;
  11486. end
  11487. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11488. not (cs_opt_size in current_settings.optimizerswitches) and
  11489. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11490. begin
  11491. Result := True;
  11492. Exit;
  11493. end;
  11494. end;
  11495. end;
  11496. end;
  11497. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11498. begin
  11499. Result := assigned(p) and
  11500. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11501. (taicpu(p).oper[1]^.typ = top_reg) and
  11502. (
  11503. (taicpu(p).oper[0]^.typ = top_reg) or
  11504. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11505. it is not expected that this can cause a seg. violation }
  11506. (
  11507. (taicpu(p).oper[0]^.typ = top_ref) and
  11508. { TODO: Can we detect which references become constants at this
  11509. stage so we don't have to do a blanket ban? }
  11510. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11511. (
  11512. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11513. (
  11514. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11515. not RefModified and
  11516. { If the reference also appears in the condition, then we know it's safe, otherwise
  11517. any kind of access violation would have occurred already }
  11518. Assigned(cond_p) and
  11519. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11520. (cond_p.typ = ait_instruction) and
  11521. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11522. { Just consider 2-operand comparison instructions for now to be safe }
  11523. (taicpu(cond_p).ops = 2) and
  11524. (
  11525. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11526. (
  11527. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11528. { Don't risk identical registers but different offsets, as we may have constructs
  11529. such as buffer streams with things like length fields that indicate whether
  11530. any more data follows. And there are probably some contrived examples where
  11531. writing to offsets behind the one being read also lead to access violations }
  11532. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11533. (
  11534. { Check that we're not modifying a register that appears in the reference }
  11535. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11536. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11537. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11538. )
  11539. )
  11540. )
  11541. )
  11542. )
  11543. )
  11544. );
  11545. end;
  11546. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11547. begin
  11548. { Update integer registers, ignoring deallocations }
  11549. repeat
  11550. while assigned(p) and
  11551. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11552. (p.typ = ait_label) or
  11553. ((p.typ = ait_marker) and
  11554. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11555. p := tai(p.next);
  11556. while assigned(p) and
  11557. (p.typ=ait_RegAlloc) Do
  11558. begin
  11559. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11560. begin
  11561. case tai_regalloc(p).ratype of
  11562. ra_alloc :
  11563. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11564. else
  11565. ;
  11566. end;
  11567. end;
  11568. p := tai(p.next);
  11569. end;
  11570. until not(assigned(p)) or
  11571. (not(p.typ in SkipInstr) and
  11572. not((p.typ = ait_label) and
  11573. labelCanBeSkipped(tai_label(p))));
  11574. end;
  11575. {$ifndef 8086}
  11576. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11577. begin
  11578. Result := False;
  11579. EndJump := nil;
  11580. BlockStop := nil;
  11581. while (BlockStart <> fOptimizer.BlockEnd) and
  11582. { stop on labels }
  11583. (BlockStart.typ <> ait_label) do
  11584. begin
  11585. { Keep track of all integer registers that are used }
  11586. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11587. if BlockStart.typ = ait_instruction then
  11588. begin
  11589. if (taicpu(BlockStart).opcode = A_JMP) then
  11590. begin
  11591. if not IsJumpToLabel(taicpu(BlockStart)) or
  11592. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11593. Exit;
  11594. EndJump := BlockStart;
  11595. Break;
  11596. end
  11597. { Check to see if we have a valid MOV instruction instead }
  11598. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11599. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11600. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11601. begin
  11602. Exit;
  11603. end
  11604. else
  11605. { This will be a valid MOV }
  11606. fAllocationRange := BlockStart;
  11607. end;
  11608. OneBeforeBlock := BlockStart;
  11609. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11610. end;
  11611. if (BlockStart = fOptimizer.BlockEnd) then
  11612. Exit;
  11613. BlockStop := BlockStart;
  11614. Result := True;
  11615. end;
  11616. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11617. var
  11618. hp1: tai;
  11619. RefModified: Boolean;
  11620. begin
  11621. Result := 0;
  11622. hp1 := BlockStart;
  11623. RefModified := False; { As long as the condition is inverted, this can be reset }
  11624. while assigned(hp1) and
  11625. (hp1 <> BlockStop) do
  11626. begin
  11627. case hp1.typ of
  11628. ait_instruction:
  11629. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11630. begin
  11631. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11632. begin
  11633. Inc(Result);
  11634. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11635. Assigned(fCondition) and
  11636. { Will have 2 operands }
  11637. (
  11638. (
  11639. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11640. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11641. ) or
  11642. (
  11643. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11644. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11645. )
  11646. ) then
  11647. { It is no longer safe to use the reference in the condition.
  11648. this prevents problems such as:
  11649. mov (%reg),%reg
  11650. mov (%reg),...
  11651. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11652. (fixes #40165)
  11653. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11654. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11655. }
  11656. RefModified := True;
  11657. end
  11658. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11659. { CMOV with constants grows the code size }
  11660. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11661. begin
  11662. { Register was reserved by TryCMOVConst and
  11663. stored on ConstRegs }
  11664. end
  11665. else
  11666. begin
  11667. Result := -1;
  11668. Exit;
  11669. end;
  11670. end
  11671. else
  11672. begin
  11673. Result := -1;
  11674. Exit;
  11675. end;
  11676. else
  11677. { Most likely an align };
  11678. end;
  11679. fOptimizer.GetNextInstruction(hp1, hp1);
  11680. end;
  11681. end;
  11682. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11683. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11684. (this is done as a separate stage because the double types are extensions of the branching type,
  11685. but we can't discount the conditional jump until the last step) }
  11686. procedure EvaluateBranchingType;
  11687. begin
  11688. Inc(CMOVScore);
  11689. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11690. { Too many instructions to be worthwhile }
  11691. fState := tsInvalid;
  11692. end;
  11693. var
  11694. hp1: tai;
  11695. Count: Integer;
  11696. begin
  11697. { Table of valid CMOV block types
  11698. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11699. ---------- --------- --------- --------- --------- ---------
  11700. tsSimple X Yes X X X
  11701. tsDetour = 1st X X X X
  11702. tsBranching <> Mid Yes X X X
  11703. tsDouble End-label Yes * Yes X Yes
  11704. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11705. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11706. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11707. * Only one reference allowed
  11708. }
  11709. hp1 := nil; { To prevent compiler warnings }
  11710. Optimizer.CopyUsedRegs(RegisterTracking);
  11711. fOptimizer := Optimizer;
  11712. fLabel := AFirstLabel;
  11713. CMOVScore := 0;
  11714. ConstCount := 0;
  11715. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11716. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11717. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11718. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11719. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11720. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11721. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11722. fInsertionPoint := p_initialjump;
  11723. fCondition := nil;
  11724. fInitialJump := p_initialjump;
  11725. fFirstMovBlock := p_initialmov;
  11726. fFirstMovBlockStop := nil;
  11727. fSecondJump := nil;
  11728. fSecondMovBlock := nil;
  11729. fSecondMovBlockStop := nil;
  11730. fMidLabel := nil;
  11731. fSecondJump := nil;
  11732. fSecondMovBlock := nil;
  11733. fEndLabel := nil;
  11734. fAllocationRange := nil;
  11735. { Assume it all goes horribly wrong! }
  11736. fState := tsInvalid;
  11737. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11738. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11739. 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
  11740. begin
  11741. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11742. for Count := 0 to 1 do
  11743. with taicpu(fCondition).oper[Count]^ do
  11744. case typ of
  11745. top_reg:
  11746. if getregtype(reg) = R_INTREGISTER then
  11747. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11748. top_ref:
  11749. begin
  11750. if
  11751. {$ifdef x86_64}
  11752. (ref^.base <> NR_RIP) and
  11753. {$endif x86_64}
  11754. (ref^.base <> NR_NO) then
  11755. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11756. if (ref^.index <> NR_NO) then
  11757. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11758. end
  11759. else
  11760. ;
  11761. end;
  11762. { When inserting instructions before hp_prev, try to insert them
  11763. before the allocation of the FLAGS register }
  11764. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11765. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11766. { If not found, set it equal to the condition so it's something sensible }
  11767. fInsertionPoint := fCondition;
  11768. { When dealing with a comparison against zero, take note of the
  11769. instruction before it to see if we can move instructions further
  11770. back in order to benefit PostPeepholeOptTestOr.
  11771. }
  11772. if (
  11773. (
  11774. (taicpu(fCondition).opcode = A_CMP) and
  11775. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11776. ) or
  11777. (
  11778. (taicpu(fCondition).opcode = A_TEST) and
  11779. (
  11780. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11781. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11782. )
  11783. )
  11784. ) and
  11785. Optimizer.GetLastInstruction(fCondition, hp1) then
  11786. begin
  11787. { These instructions set the zero flag if the result is zero }
  11788. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11789. begin
  11790. fInsertionPoint := hp1;
  11791. { Also mark all the registers in this previous instruction
  11792. as 'in use', even if they've just been deallocated }
  11793. for Count := 0 to 1 do
  11794. with taicpu(hp1).oper[Count]^ do
  11795. case typ of
  11796. top_reg:
  11797. if getregtype(reg) = R_INTREGISTER then
  11798. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11799. top_ref:
  11800. begin
  11801. if
  11802. {$ifdef x86_64}
  11803. (ref^.base <> NR_RIP) and
  11804. {$endif x86_64}
  11805. (ref^.base <> NR_NO) then
  11806. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11807. if (ref^.index <> NR_NO) then
  11808. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11809. end
  11810. else
  11811. ;
  11812. end;
  11813. end;
  11814. end;
  11815. end
  11816. else
  11817. fCondition := nil;
  11818. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11819. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11820. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11821. { If not found, set it equal to p so it's something sensible }
  11822. fInsertionPoint := hp1;
  11823. hp1 := p_initialmov;
  11824. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11825. Exit;
  11826. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11827. if (hp1.typ <> ait_label) then { should be on a jump }
  11828. begin
  11829. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11830. { Need a label afterwards }
  11831. Exit;
  11832. end
  11833. else
  11834. fMidLabel := hp1;
  11835. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11836. { Not the correct label }
  11837. fMidLabel := nil;
  11838. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11839. { If there's neither a 2nd jump nor correct label, then it's invalid
  11840. (see above table) }
  11841. Exit;
  11842. { Analyse the first block of MOVs more closely }
  11843. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11844. if Assigned(fSecondJump) then
  11845. begin
  11846. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11847. begin
  11848. fState := tsDetour
  11849. end
  11850. else
  11851. begin
  11852. { Need the correct mid-label for this one }
  11853. if not Assigned(fMidLabel) then
  11854. Exit;
  11855. fState := tsBranching;
  11856. end;
  11857. end
  11858. else
  11859. { No jump. but mid-label is present }
  11860. fState := tsSimple;
  11861. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11862. begin
  11863. { Invalid or too many instructions to be worthwhile }
  11864. fState := tsInvalid;
  11865. Exit;
  11866. end;
  11867. { check further for
  11868. jCC xxx
  11869. <several movs 1>
  11870. jmp yyy
  11871. xxx:
  11872. <several movs 2>
  11873. yyy:
  11874. etc.
  11875. }
  11876. if (fState = tsBranching) and
  11877. { Estimate for required savings for extra jump }
  11878. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11879. { Only one reference is allowed for double blocks }
  11880. (AFirstLabel.getrefs = 1) then
  11881. begin
  11882. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11883. fSecondMovBlock := hp1;
  11884. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11885. begin
  11886. EvaluateBranchingType;
  11887. Exit;
  11888. end;
  11889. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11890. if (hp1.typ <> ait_label) then { should be on a jump }
  11891. begin
  11892. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11893. begin
  11894. { Need a label afterwards }
  11895. EvaluateBranchingType;
  11896. Exit;
  11897. end;
  11898. end
  11899. else
  11900. fEndLabel := hp1;
  11901. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11902. { Second jump doesn't go to the end }
  11903. fEndLabel := nil;
  11904. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11905. begin
  11906. { If there's neither a 3rd jump nor correct end label, then it's
  11907. not a invalid double block, but is a valid single branching
  11908. block (see above table) }
  11909. EvaluateBranchingType;
  11910. Exit;
  11911. end;
  11912. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11913. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11914. { Invalid or too many instructions to be worthwhile }
  11915. Exit;
  11916. Inc(CMOVScore, Count);
  11917. if Assigned(fThirdJump) then
  11918. begin
  11919. if not Assigned(fSecondJump) then
  11920. fState := tsDoubleSecondBranching
  11921. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11922. fState := tsDoubleBranchSame
  11923. else
  11924. fState := tsDoubleBranchDifferent;
  11925. end
  11926. else
  11927. fState := tsDouble;
  11928. end;
  11929. if fState = tsBranching then
  11930. EvaluateBranchingType;
  11931. end;
  11932. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11933. new register to store the constant }
  11934. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11935. var
  11936. RegSize: TSubRegister;
  11937. CurrentVal: TCGInt;
  11938. ANewReg: TRegister;
  11939. X: ShortInt;
  11940. begin
  11941. Result := False;
  11942. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11943. Exit;
  11944. if ConstCount >= MAX_CMOV_REGISTERS then
  11945. { Arrays are full }
  11946. Exit;
  11947. { Remember that CMOV can't encode 8-bit registers }
  11948. case taicpu(p).opsize of
  11949. S_W:
  11950. RegSize := R_SUBW;
  11951. S_L:
  11952. RegSize := R_SUBD;
  11953. {$ifdef x86_64}
  11954. S_Q:
  11955. RegSize := R_SUBQ;
  11956. {$endif x86_64}
  11957. else
  11958. InternalError(2021100401);
  11959. end;
  11960. { See if the value has already been reserved for another CMOV instruction }
  11961. CurrentVal := taicpu(p).oper[0]^.val;
  11962. for X := 0 to ConstCount - 1 do
  11963. if ConstVals[X] = CurrentVal then
  11964. begin
  11965. ConstRegs[ConstCount] := ConstRegs[X];
  11966. ConstSizes[ConstCount] := RegSize;
  11967. ConstVals[ConstCount] := CurrentVal;
  11968. Inc(ConstCount);
  11969. Inc(Count);
  11970. Result := True;
  11971. Exit;
  11972. end;
  11973. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11974. if ANewReg = NR_NO then
  11975. { No free registers }
  11976. Exit;
  11977. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11978. up vying for the same register }
  11979. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11980. ConstRegs[ConstCount] := ANewReg;
  11981. ConstSizes[ConstCount] := RegSize;
  11982. ConstVals[ConstCount] := CurrentVal;
  11983. Inc(ConstCount);
  11984. Inc(Count);
  11985. Result := True;
  11986. end;
  11987. destructor TCMOVTracking.Done;
  11988. begin
  11989. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11990. end;
  11991. procedure TCMOVTracking.Process(out new_p: tai);
  11992. var
  11993. Count, Writes: LongInt;
  11994. RegMatch: Boolean;
  11995. hp1, hp_new: tai;
  11996. inverted_condition, condition: TAsmCond;
  11997. begin
  11998. if (fState in [tsInvalid, tsProcessed]) then
  11999. InternalError(2023110701);
  12000. { Repurpose RegisterTracking to mark registers that we've defined }
  12001. RegisterTracking[R_INTREGISTER].Clear;
  12002. Count := 0;
  12003. Writes := 0;
  12004. condition := taicpu(fInitialJump).condition;
  12005. inverted_condition := inverse_cond(condition);
  12006. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12007. doesn't get CMOVs in this case }
  12008. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12009. begin
  12010. { Include the jump in the flag tracking }
  12011. if Assigned(fThirdJump) then
  12012. begin
  12013. if (fState = tsDoubleBranchSame) then
  12014. begin
  12015. { Will be an unconditional jump, so track to the instruction before it }
  12016. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12017. InternalError(2023110710);
  12018. end
  12019. else
  12020. hp1 := fThirdJump;
  12021. end
  12022. else
  12023. hp1 := fSecondMovBlockStop;
  12024. end
  12025. else
  12026. begin
  12027. { Include a conditional jump in the flag tracking }
  12028. if Assigned(fSecondJump) then
  12029. begin
  12030. if (fState = tsDetour) then
  12031. begin
  12032. { Will be an unconditional jump, so track to the instruction before it }
  12033. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12034. InternalError(2023110711);
  12035. end
  12036. else
  12037. hp1 := fSecondJump;
  12038. end
  12039. else
  12040. hp1 := fFirstMovBlockStop;
  12041. end;
  12042. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12043. { Process the second set of MOVs first, because if a destination
  12044. register is shared between the first and second MOV sets, it is more
  12045. efficient to turn the first one into a MOV instruction and place it
  12046. before the CMP if possible, but we won't know which registers are
  12047. shared until we've processed at least one list, so we might as well
  12048. make it the second one since that won't be modified again. }
  12049. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12050. begin
  12051. hp1 := fSecondMovBlock;
  12052. repeat
  12053. if not Assigned(hp1) then
  12054. InternalError(2018062902);
  12055. if (hp1.typ = ait_instruction) then
  12056. begin
  12057. { Extra safeguard }
  12058. if (taicpu(hp1).opcode <> A_MOV) then
  12059. InternalError(2018062903);
  12060. { Note: tsDoubleBranchDifferent is essentially identical to
  12061. tsBranching and the 2nd block is best left largely
  12062. untouched, but we need to evaluate which registers the MOVs
  12063. write to in order to track what would be complementary CMOV
  12064. pairs that can be further optimised. [Kit] }
  12065. if fState <> tsDoubleBranchDifferent then
  12066. begin
  12067. if taicpu(hp1).oper[0]^.typ = top_const then
  12068. begin
  12069. RegMatch := False;
  12070. for Count := 0 to ConstCount - 1 do
  12071. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12072. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12073. begin
  12074. RegMatch := True;
  12075. { If it's in RegisterTracking, then this register
  12076. is being used more than once and hence has
  12077. already had its value defined (it gets added to
  12078. UsedRegs through AllocRegBetween below) }
  12079. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12080. begin
  12081. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12082. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12083. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12084. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12085. ConstMovs[Count] := hp_new;
  12086. end
  12087. else
  12088. { We just need an instruction between hp_prev and hp1
  12089. where we know the register is marked as in use }
  12090. hp_new := fSecondMovBlock;
  12091. { Keep track of largest write for this register so it can be optimised later }
  12092. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12093. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12094. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12095. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12096. Break;
  12097. end;
  12098. if not RegMatch then
  12099. InternalError(2021100411);
  12100. end;
  12101. taicpu(hp1).opcode := A_CMOVcc;
  12102. taicpu(hp1).condition := condition;
  12103. end;
  12104. { Store these writes to search for duplicates later on }
  12105. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12106. Inc(Writes);
  12107. end;
  12108. fOptimizer.GetNextInstruction(hp1, hp1);
  12109. until (hp1 = fSecondMovBlockStop);
  12110. end;
  12111. { Now do the first set of MOVs }
  12112. hp1 := fFirstMovBlock;
  12113. repeat
  12114. if not Assigned(hp1) then
  12115. InternalError(2018062904);
  12116. if (hp1.typ = ait_instruction) then
  12117. begin
  12118. RegMatch := False;
  12119. { Extra safeguard }
  12120. if (taicpu(hp1).opcode <> A_MOV) then
  12121. InternalError(2018062905);
  12122. { Search through the RegWrites list to see if there are any
  12123. opposing CMOV pairs that write to the same register }
  12124. for Count := 0 to Writes - 1 do
  12125. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12126. begin
  12127. { We have a match. Keep this as a MOV }
  12128. { Move ahead in preparation }
  12129. fOptimizer.GetNextInstruction(hp1, hp1);
  12130. RegMatch := True;
  12131. Break;
  12132. end;
  12133. if RegMatch then
  12134. Continue;
  12135. if taicpu(hp1).oper[0]^.typ = top_const then
  12136. begin
  12137. for Count := 0 to ConstCount - 1 do
  12138. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12139. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12140. begin
  12141. RegMatch := True;
  12142. { If it's in RegisterTracking, then this register is
  12143. being used more than once and hence has already had
  12144. its value defined (it gets added to UsedRegs through
  12145. AllocRegBetween below) }
  12146. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12147. begin
  12148. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12149. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12150. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12151. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12152. ConstMovs[Count] := hp_new;
  12153. end
  12154. else
  12155. { We just need an instruction between hp_prev and hp1
  12156. where we know the register is marked as in use }
  12157. hp_new := fFirstMovBlock;
  12158. { Keep track of largest write for this register so it can be optimised later }
  12159. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12160. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12161. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12162. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12163. Break;
  12164. end;
  12165. if not RegMatch then
  12166. InternalError(2021100412);
  12167. end;
  12168. taicpu(hp1).opcode := A_CMOVcc;
  12169. taicpu(hp1).condition := inverted_condition;
  12170. if (fState = tsDoubleBranchDifferent) then
  12171. begin
  12172. { Store these writes to search for duplicates later on }
  12173. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12174. Inc(Writes);
  12175. end;
  12176. end;
  12177. fOptimizer.GetNextInstruction(hp1, hp1);
  12178. until (hp1 = fFirstMovBlockStop);
  12179. { Update initialisation MOVs to the smallest possible size }
  12180. for Count := 0 to ConstCount - 1 do
  12181. if Assigned(ConstMovs[Count]) then
  12182. begin
  12183. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12184. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12185. end;
  12186. case fState of
  12187. tsSimple:
  12188. begin
  12189. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12190. { No branch to delete }
  12191. end;
  12192. tsDetour:
  12193. begin
  12194. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12195. { Preserve jump }
  12196. end;
  12197. tsBranching, tsDoubleBranchDifferent:
  12198. begin
  12199. if (fState = tsBranching) then
  12200. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12201. else
  12202. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12203. taicpu(fSecondJump).opcode := A_JCC;
  12204. taicpu(fSecondJump).condition := inverted_condition;
  12205. end;
  12206. tsDouble, tsDoubleBranchSame:
  12207. begin
  12208. if (fState = tsDouble) then
  12209. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12210. else
  12211. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12212. { Delete second jump }
  12213. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12214. fOptimizer.RemoveInstruction(fSecondJump);
  12215. end;
  12216. tsDoubleSecondBranching:
  12217. begin
  12218. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12219. { Delete second jump, preserve third jump as conditional }
  12220. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12221. fOptimizer.RemoveInstruction(fSecondJump);
  12222. taicpu(fThirdJump).opcode := A_JCC;
  12223. taicpu(fThirdJump).condition := condition;
  12224. end;
  12225. else
  12226. InternalError(2023110720);
  12227. end;
  12228. { Now we can safely decrement the reference count }
  12229. tasmlabel(fLabel).decrefs;
  12230. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12231. { Remove the original jump }
  12232. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12233. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12234. fState := tsProcessed;
  12235. end;
  12236. {$endif 8086}
  12237. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12238. var
  12239. hp1,hp2: tai;
  12240. carryadd_opcode : TAsmOp;
  12241. symbol: TAsmSymbol;
  12242. increg, tmpreg: TRegister;
  12243. {$ifndef i8086}
  12244. CMOVTracking: PCMOVTracking;
  12245. hp3,hp4,hp5: tai;
  12246. {$endif i8086}
  12247. TempBool: Boolean;
  12248. begin
  12249. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12250. DoJumpOptimizations(p, TempBool) then
  12251. Exit(True);
  12252. result:=false;
  12253. if GetNextInstruction(p,hp1) then
  12254. begin
  12255. if (hp1.typ=ait_label) then
  12256. begin
  12257. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12258. Exit;
  12259. end
  12260. else if (hp1.typ<>ait_instruction) then
  12261. Exit;
  12262. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12263. if (
  12264. (
  12265. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12266. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12267. (Taicpu(hp1).oper[0]^.val=1)
  12268. ) or
  12269. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12270. ) and
  12271. GetNextInstruction(hp1,hp2) and
  12272. (hp2.typ = ait_label) and
  12273. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12274. { jb @@1 cmc
  12275. inc/dec operand --> adc/sbb operand,0
  12276. @@1:
  12277. ... and ...
  12278. jnb @@1
  12279. inc/dec operand --> adc/sbb operand,0
  12280. @@1: }
  12281. begin
  12282. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12283. begin
  12284. case taicpu(hp1).opcode of
  12285. A_INC,
  12286. A_ADD:
  12287. carryadd_opcode:=A_ADC;
  12288. A_DEC,
  12289. A_SUB:
  12290. carryadd_opcode:=A_SBB;
  12291. else
  12292. InternalError(2021011001);
  12293. end;
  12294. Taicpu(p).clearop(0);
  12295. Taicpu(p).ops:=0;
  12296. Taicpu(p).is_jmp:=false;
  12297. Taicpu(p).opcode:=A_CMC;
  12298. Taicpu(p).condition:=C_NONE;
  12299. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12300. Taicpu(hp1).ops:=2;
  12301. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12302. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12303. else
  12304. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12305. Taicpu(hp1).loadconst(0,0);
  12306. Taicpu(hp1).opcode:=carryadd_opcode;
  12307. result:=true;
  12308. exit;
  12309. end
  12310. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12311. begin
  12312. case taicpu(hp1).opcode of
  12313. A_INC,
  12314. A_ADD:
  12315. carryadd_opcode:=A_ADC;
  12316. A_DEC,
  12317. A_SUB:
  12318. carryadd_opcode:=A_SBB;
  12319. else
  12320. InternalError(2021011002);
  12321. end;
  12322. Taicpu(hp1).ops:=2;
  12323. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12324. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12325. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12326. else
  12327. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12328. Taicpu(hp1).loadconst(0,0);
  12329. Taicpu(hp1).opcode:=carryadd_opcode;
  12330. RemoveCurrentP(p, hp1);
  12331. result:=true;
  12332. exit;
  12333. end
  12334. {
  12335. jcc @@1 setcc tmpreg
  12336. inc/dec/add/sub operand -> (movzx tmpreg)
  12337. @@1: add/sub tmpreg,operand
  12338. While this increases code size slightly, it makes the code much faster if the
  12339. jump is unpredictable
  12340. }
  12341. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12342. begin
  12343. { search for an available register which is volatile }
  12344. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12345. if increg <> NR_NO then
  12346. begin
  12347. { We don't need to check if tmpreg is in hp1 or not, because
  12348. it will be marked as in use at p (if not, this is
  12349. indictive of a compiler bug). }
  12350. TAsmLabel(symbol).decrefs;
  12351. Taicpu(p).clearop(0);
  12352. Taicpu(p).ops:=1;
  12353. Taicpu(p).is_jmp:=false;
  12354. Taicpu(p).opcode:=A_SETcc;
  12355. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12356. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12357. Taicpu(p).loadreg(0,increg);
  12358. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12359. begin
  12360. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12361. R_SUBW:
  12362. begin
  12363. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12364. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12365. end;
  12366. R_SUBD:
  12367. begin
  12368. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12369. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12370. end;
  12371. {$ifdef x86_64}
  12372. R_SUBQ:
  12373. begin
  12374. { MOVZX doesn't have a 64-bit variant, because
  12375. the 32-bit version implicitly zeroes the
  12376. upper 32-bits of the destination register }
  12377. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12378. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12379. setsubreg(tmpreg, R_SUBQ);
  12380. end;
  12381. {$endif x86_64}
  12382. else
  12383. Internalerror(2020030601);
  12384. end;
  12385. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12386. asml.InsertAfter(hp2,p);
  12387. end
  12388. else
  12389. tmpreg := increg;
  12390. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12391. begin
  12392. Taicpu(hp1).ops:=2;
  12393. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12394. end;
  12395. Taicpu(hp1).loadreg(0,tmpreg);
  12396. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12397. Result := True;
  12398. { p is no longer a Jcc instruction, so exit }
  12399. Exit;
  12400. end;
  12401. end;
  12402. end;
  12403. { Detect the following:
  12404. jmp<cond> @Lbl1
  12405. jmp @Lbl2
  12406. ...
  12407. @Lbl1:
  12408. ret
  12409. Change to:
  12410. jmp<inv_cond> @Lbl2
  12411. ret
  12412. }
  12413. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12414. begin
  12415. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12416. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12417. MatchInstruction(hp2,A_RET,[S_NO]) then
  12418. begin
  12419. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12420. { Change label address to that of the unconditional jump }
  12421. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12422. TAsmLabel(symbol).DecRefs;
  12423. taicpu(hp1).opcode := A_RET;
  12424. taicpu(hp1).is_jmp := false;
  12425. taicpu(hp1).ops := taicpu(hp2).ops;
  12426. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12427. case taicpu(hp2).ops of
  12428. 0:
  12429. taicpu(hp1).clearop(0);
  12430. 1:
  12431. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12432. else
  12433. internalerror(2016041302);
  12434. end;
  12435. end;
  12436. {$ifndef i8086}
  12437. end
  12438. {
  12439. convert
  12440. j<c> .L1
  12441. mov 1,reg
  12442. jmp .L2
  12443. .L1
  12444. mov 0,reg
  12445. .L2
  12446. into
  12447. mov 0,reg
  12448. set<not(c)> reg
  12449. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12450. would destroy the flag contents
  12451. }
  12452. else if MatchInstruction(hp1,A_MOV,[]) and
  12453. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12454. {$ifdef i386}
  12455. (
  12456. { Under i386, ESI, EDI, EBP and ESP
  12457. don't have an 8-bit representation }
  12458. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12459. ) and
  12460. {$endif i386}
  12461. (taicpu(hp1).oper[0]^.val=1) and
  12462. GetNextInstruction(hp1,hp2) and
  12463. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12464. GetNextInstruction(hp2,hp3) and
  12465. (hp3.typ=ait_label) and
  12466. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12467. (tai_label(hp3).labsym.getrefs=1) and
  12468. GetNextInstruction(hp3,hp4) and
  12469. MatchInstruction(hp4,A_MOV,[]) and
  12470. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12471. (taicpu(hp4).oper[0]^.val=0) and
  12472. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12473. GetNextInstruction(hp4,hp5) and
  12474. (hp5.typ=ait_label) and
  12475. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12476. (tai_label(hp5).labsym.getrefs=1) then
  12477. begin
  12478. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12479. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12480. { remove last label }
  12481. RemoveInstruction(hp5);
  12482. { remove second label }
  12483. RemoveInstruction(hp3);
  12484. { remove jmp }
  12485. RemoveInstruction(hp2);
  12486. if taicpu(hp1).opsize=S_B then
  12487. RemoveInstruction(hp1)
  12488. else
  12489. taicpu(hp1).loadconst(0,0);
  12490. taicpu(hp4).opcode:=A_SETcc;
  12491. taicpu(hp4).opsize:=S_B;
  12492. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12493. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12494. taicpu(hp4).opercnt:=1;
  12495. taicpu(hp4).ops:=1;
  12496. taicpu(hp4).freeop(1);
  12497. RemoveCurrentP(p);
  12498. Result:=true;
  12499. exit;
  12500. end
  12501. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12502. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12503. begin
  12504. { check for
  12505. jCC xxx
  12506. <several movs>
  12507. xxx:
  12508. Also spot:
  12509. Jcc xxx
  12510. <several movs>
  12511. jmp xxx
  12512. Change to:
  12513. <several cmovs with inverted condition>
  12514. jmp xxx (only for the 2nd case)
  12515. }
  12516. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12517. if CMOVTracking^.State <> tsInvalid then
  12518. begin
  12519. CMovTracking^.Process(p);
  12520. Result := True;
  12521. end;
  12522. CMOVTracking^.Done;
  12523. {$endif i8086}
  12524. end;
  12525. end;
  12526. end;
  12527. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12528. var
  12529. hp1,hp2,hp3: tai;
  12530. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12531. NewSize: TOpSize;
  12532. NewRegSize: TSubRegister;
  12533. Limit: TCgInt;
  12534. SwapOper: POper;
  12535. begin
  12536. result:=false;
  12537. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12538. GetNextInstruction(p,hp1) and
  12539. (hp1.typ = ait_instruction);
  12540. if reg_and_hp1_is_instr and
  12541. (
  12542. (taicpu(hp1).opcode <> A_LEA) or
  12543. { If the LEA instruction can be converted into an arithmetic instruction,
  12544. it may be possible to then fold it. }
  12545. (
  12546. { If the flags register is in use, don't change the instruction
  12547. to an ADD otherwise this will scramble the flags. [Kit] }
  12548. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12549. ConvertLEA(taicpu(hp1))
  12550. )
  12551. ) and
  12552. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12553. GetNextInstruction(hp1,hp2) and
  12554. MatchInstruction(hp2,A_MOV,[]) and
  12555. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12556. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12557. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12558. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12559. {$ifdef i386}
  12560. { not all registers have byte size sub registers on i386 }
  12561. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12562. {$endif i386}
  12563. (((taicpu(hp1).ops=2) and
  12564. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12565. ((taicpu(hp1).ops=1) and
  12566. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12567. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12568. begin
  12569. { change movsX/movzX reg/ref, reg2
  12570. add/sub/or/... reg3/$const, reg2
  12571. mov reg2 reg/ref
  12572. to add/sub/or/... reg3/$const, reg/ref }
  12573. { by example:
  12574. movswl %si,%eax movswl %si,%eax p
  12575. decl %eax addl %edx,%eax hp1
  12576. movw %ax,%si movw %ax,%si hp2
  12577. ->
  12578. movswl %si,%eax movswl %si,%eax p
  12579. decw %eax addw %edx,%eax hp1
  12580. movw %ax,%si movw %ax,%si hp2
  12581. }
  12582. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12583. {
  12584. ->
  12585. movswl %si,%eax movswl %si,%eax p
  12586. decw %si addw %dx,%si hp1
  12587. movw %ax,%si movw %ax,%si hp2
  12588. }
  12589. case taicpu(hp1).ops of
  12590. 1:
  12591. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12592. 2:
  12593. begin
  12594. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12595. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12596. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12597. end;
  12598. else
  12599. internalerror(2008042702);
  12600. end;
  12601. {
  12602. ->
  12603. decw %si addw %dx,%si p
  12604. }
  12605. DebugMsg(SPeepholeOptimization + 'var3',p);
  12606. RemoveCurrentP(p, hp1);
  12607. RemoveInstruction(hp2);
  12608. Result := True;
  12609. Exit;
  12610. end;
  12611. if reg_and_hp1_is_instr and
  12612. (taicpu(hp1).opcode = A_MOV) and
  12613. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12614. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12615. {$ifdef x86_64}
  12616. { check for implicit extension to 64 bit }
  12617. or
  12618. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12619. (taicpu(hp1).opsize=S_Q) and
  12620. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12621. )
  12622. {$endif x86_64}
  12623. )
  12624. then
  12625. begin
  12626. { change
  12627. movx %reg1,%reg2
  12628. mov %reg2,%reg3
  12629. dealloc %reg2
  12630. into
  12631. movx %reg,%reg3
  12632. }
  12633. TransferUsedRegs(TmpUsedRegs);
  12634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12635. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12636. begin
  12637. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12638. {$ifdef x86_64}
  12639. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12640. (taicpu(hp1).opsize=S_Q) then
  12641. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12642. else
  12643. {$endif x86_64}
  12644. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12645. RemoveInstruction(hp1);
  12646. Result := True;
  12647. Exit;
  12648. end;
  12649. end;
  12650. if reg_and_hp1_is_instr and
  12651. ((taicpu(hp1).opcode=A_MOV) or
  12652. (taicpu(hp1).opcode=A_ADD) or
  12653. (taicpu(hp1).opcode=A_SUB) or
  12654. (taicpu(hp1).opcode=A_CMP) or
  12655. (taicpu(hp1).opcode=A_OR) or
  12656. (taicpu(hp1).opcode=A_XOR) or
  12657. (taicpu(hp1).opcode=A_AND)
  12658. ) and
  12659. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12660. begin
  12661. AndTest := (taicpu(hp1).opcode=A_AND) and
  12662. GetNextInstruction(hp1, hp2) and
  12663. (hp2.typ = ait_instruction) and
  12664. (
  12665. (
  12666. (taicpu(hp2).opcode=A_TEST) and
  12667. (
  12668. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12669. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12670. (
  12671. { If the AND and TEST instructions share a constant, this is also valid }
  12672. (taicpu(hp1).oper[0]^.typ = top_const) and
  12673. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12674. )
  12675. ) and
  12676. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12677. ) or
  12678. (
  12679. (taicpu(hp2).opcode=A_CMP) and
  12680. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12681. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12682. )
  12683. );
  12684. { change
  12685. movx (oper),%reg2
  12686. and $x,%reg2
  12687. test %reg2,%reg2
  12688. dealloc %reg2
  12689. into
  12690. op %reg1,%reg3
  12691. if the second op accesses only the bits stored in reg1
  12692. }
  12693. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12694. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12695. (taicpu(hp1).oper[0]^.typ = top_const) and
  12696. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12697. AndTest then
  12698. begin
  12699. { Check if the AND constant is in range }
  12700. case taicpu(p).opsize of
  12701. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12702. begin
  12703. NewSize := S_B;
  12704. Limit := $FF;
  12705. end;
  12706. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12707. begin
  12708. NewSize := S_W;
  12709. Limit := $FFFF;
  12710. end;
  12711. {$ifdef x86_64}
  12712. S_LQ:
  12713. begin
  12714. NewSize := S_L;
  12715. Limit := $FFFFFFFF;
  12716. end;
  12717. {$endif x86_64}
  12718. else
  12719. InternalError(2021120303);
  12720. end;
  12721. if (
  12722. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12723. { Check for negative operands }
  12724. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12725. ) and
  12726. GetNextInstruction(hp2,hp3) and
  12727. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12728. (taicpu(hp3).condition in [C_E,C_NE]) then
  12729. begin
  12730. TransferUsedRegs(TmpUsedRegs);
  12731. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12732. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12733. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12734. begin
  12735. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12736. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12737. taicpu(hp1).opcode := A_TEST;
  12738. taicpu(hp1).opsize := NewSize;
  12739. RemoveInstruction(hp2);
  12740. RemoveCurrentP(p, hp1);
  12741. Result:=true;
  12742. exit;
  12743. end;
  12744. end;
  12745. end;
  12746. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12747. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12748. (taicpu(hp1).opsize=S_B)) or
  12749. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12750. (taicpu(hp1).opsize=S_W))
  12751. {$ifdef x86_64}
  12752. or ((taicpu(p).opsize=S_LQ) and
  12753. (taicpu(hp1).opsize=S_L))
  12754. {$endif x86_64}
  12755. ) and
  12756. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12757. begin
  12758. { change
  12759. movx %reg1,%reg2
  12760. op %reg2,%reg3
  12761. dealloc %reg2
  12762. into
  12763. op %reg1,%reg3
  12764. if the second op accesses only the bits stored in reg1
  12765. }
  12766. TransferUsedRegs(TmpUsedRegs);
  12767. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12768. if AndTest then
  12769. begin
  12770. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12771. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12772. end
  12773. else
  12774. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12775. if not RegUsed then
  12776. begin
  12777. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12778. if taicpu(p).oper[0]^.typ=top_reg then
  12779. begin
  12780. case taicpu(hp1).opsize of
  12781. S_B:
  12782. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12783. S_W:
  12784. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12785. S_L:
  12786. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12787. else
  12788. Internalerror(2020102301);
  12789. end;
  12790. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12791. end
  12792. else
  12793. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12794. RemoveCurrentP(p);
  12795. if AndTest then
  12796. RemoveInstruction(hp2);
  12797. result:=true;
  12798. exit;
  12799. end;
  12800. end
  12801. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12802. (
  12803. { Bitwise operations only }
  12804. (taicpu(hp1).opcode=A_AND) or
  12805. (taicpu(hp1).opcode=A_TEST) or
  12806. (
  12807. (taicpu(hp1).oper[0]^.typ = top_const) and
  12808. (
  12809. (taicpu(hp1).opcode=A_OR) or
  12810. (taicpu(hp1).opcode=A_XOR)
  12811. )
  12812. )
  12813. ) and
  12814. (
  12815. (taicpu(hp1).oper[0]^.typ = top_const) or
  12816. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12817. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12818. ) then
  12819. begin
  12820. { change
  12821. movx %reg2,%reg2
  12822. op const,%reg2
  12823. into
  12824. op const,%reg2 (smaller version)
  12825. movx %reg2,%reg2
  12826. also change
  12827. movx %reg1,%reg2
  12828. and/test (oper),%reg2
  12829. dealloc %reg2
  12830. into
  12831. and/test (oper),%reg1
  12832. }
  12833. case taicpu(p).opsize of
  12834. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12835. begin
  12836. NewSize := S_B;
  12837. NewRegSize := R_SUBL;
  12838. Limit := $FF;
  12839. end;
  12840. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12841. begin
  12842. NewSize := S_W;
  12843. NewRegSize := R_SUBW;
  12844. Limit := $FFFF;
  12845. end;
  12846. {$ifdef x86_64}
  12847. S_LQ:
  12848. begin
  12849. NewSize := S_L;
  12850. NewRegSize := R_SUBD;
  12851. Limit := $FFFFFFFF;
  12852. end;
  12853. {$endif x86_64}
  12854. else
  12855. Internalerror(2021120302);
  12856. end;
  12857. TransferUsedRegs(TmpUsedRegs);
  12858. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12859. if AndTest then
  12860. begin
  12861. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12862. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12863. end
  12864. else
  12865. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12866. if
  12867. (
  12868. (taicpu(p).opcode = A_MOVZX) and
  12869. (
  12870. (taicpu(hp1).opcode=A_AND) or
  12871. (taicpu(hp1).opcode=A_TEST)
  12872. ) and
  12873. not (
  12874. { If both are references, then the final instruction will have
  12875. both operands as references, which is not allowed }
  12876. (taicpu(p).oper[0]^.typ = top_ref) and
  12877. (taicpu(hp1).oper[0]^.typ = top_ref)
  12878. ) and
  12879. not RegUsed
  12880. ) or
  12881. (
  12882. (
  12883. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12884. not RegUsed
  12885. ) and
  12886. (taicpu(p).oper[0]^.typ = top_reg) and
  12887. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12888. (taicpu(hp1).oper[0]^.typ = top_const) and
  12889. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12890. ) then
  12891. begin
  12892. {$if defined(i386) or defined(i8086)}
  12893. { If the target size is 8-bit, make sure we can actually encode it }
  12894. 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
  12895. Exit;
  12896. {$endif i386 or i8086}
  12897. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12898. taicpu(hp1).opsize := NewSize;
  12899. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12900. if AndTest then
  12901. begin
  12902. RemoveInstruction(hp2);
  12903. if not RegUsed then
  12904. begin
  12905. taicpu(hp1).opcode := A_TEST;
  12906. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12907. begin
  12908. { Make sure the reference is the second operand }
  12909. SwapOper := taicpu(hp1).oper[0];
  12910. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12911. taicpu(hp1).oper[1] := SwapOper;
  12912. end;
  12913. end;
  12914. end;
  12915. case taicpu(hp1).oper[0]^.typ of
  12916. top_reg:
  12917. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12918. top_const:
  12919. { For the AND/TEST case }
  12920. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12921. else
  12922. ;
  12923. end;
  12924. if RegUsed then
  12925. begin
  12926. AsmL.Remove(p);
  12927. AsmL.InsertAfter(p, hp1);
  12928. p := hp1;
  12929. end
  12930. else
  12931. RemoveCurrentP(p, hp1);
  12932. result:=true;
  12933. exit;
  12934. end;
  12935. end;
  12936. end;
  12937. if reg_and_hp1_is_instr and
  12938. (taicpu(p).oper[0]^.typ = top_reg) and
  12939. (
  12940. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12941. ) and
  12942. (taicpu(hp1).oper[0]^.typ = top_const) and
  12943. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12944. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12945. { Minimum shift value allowed is the bit difference between the sizes }
  12946. (taicpu(hp1).oper[0]^.val >=
  12947. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12948. 8 * (
  12949. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12950. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12951. )
  12952. ) then
  12953. begin
  12954. { For:
  12955. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12956. shl/sal ##, %reg1
  12957. Remove the movsx/movzx instruction if the shift overwrites the
  12958. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12959. }
  12960. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12961. RemoveCurrentP(p, hp1);
  12962. Result := True;
  12963. Exit;
  12964. end
  12965. else if reg_and_hp1_is_instr and
  12966. (taicpu(p).oper[0]^.typ = top_reg) and
  12967. (
  12968. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12969. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12970. ) and
  12971. (taicpu(hp1).oper[0]^.typ = top_const) and
  12972. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12973. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12974. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12975. (taicpu(hp1).oper[0]^.val <
  12976. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12977. 8 * (
  12978. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12979. )
  12980. ) then
  12981. begin
  12982. { For:
  12983. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12984. sar ##, %reg1 shr ##, %reg1
  12985. Move the shift to before the movx instruction if the shift value
  12986. is not too large.
  12987. }
  12988. asml.Remove(hp1);
  12989. asml.InsertBefore(hp1, p);
  12990. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12991. case taicpu(p).opsize of
  12992. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12993. taicpu(hp1).opsize := S_B;
  12994. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12995. taicpu(hp1).opsize := S_W;
  12996. {$ifdef x86_64}
  12997. S_LQ:
  12998. taicpu(hp1).opsize := S_L;
  12999. {$endif}
  13000. else
  13001. InternalError(2020112401);
  13002. end;
  13003. if (taicpu(hp1).opcode = A_SHR) then
  13004. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13005. else
  13006. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13007. Result := True;
  13008. end;
  13009. if reg_and_hp1_is_instr and
  13010. (taicpu(p).oper[0]^.typ = top_reg) and
  13011. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13012. (
  13013. (taicpu(hp1).opcode = taicpu(p).opcode)
  13014. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13015. {$ifdef x86_64}
  13016. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13017. {$endif x86_64}
  13018. ) then
  13019. begin
  13020. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13021. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13022. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13023. begin
  13024. {
  13025. For example:
  13026. movzbw %al,%ax
  13027. movzwl %ax,%eax
  13028. Compress into:
  13029. movzbl %al,%eax
  13030. }
  13031. RegUsed := False;
  13032. case taicpu(p).opsize of
  13033. S_BW:
  13034. case taicpu(hp1).opsize of
  13035. S_WL:
  13036. begin
  13037. taicpu(p).opsize := S_BL;
  13038. RegUsed := True;
  13039. end;
  13040. {$ifdef x86_64}
  13041. S_WQ:
  13042. begin
  13043. if taicpu(p).opcode = A_MOVZX then
  13044. begin
  13045. taicpu(p).opsize := S_BL;
  13046. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13047. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13048. end
  13049. else
  13050. taicpu(p).opsize := S_BQ;
  13051. RegUsed := True;
  13052. end;
  13053. {$endif x86_64}
  13054. else
  13055. ;
  13056. end;
  13057. {$ifdef x86_64}
  13058. S_BL:
  13059. case taicpu(hp1).opsize of
  13060. S_LQ:
  13061. begin
  13062. if taicpu(p).opcode = A_MOVZX then
  13063. begin
  13064. taicpu(p).opsize := S_BL;
  13065. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13066. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13067. end
  13068. else
  13069. taicpu(p).opsize := S_BQ;
  13070. RegUsed := True;
  13071. end;
  13072. else
  13073. ;
  13074. end;
  13075. S_WL:
  13076. case taicpu(hp1).opsize of
  13077. S_LQ:
  13078. begin
  13079. if taicpu(p).opcode = A_MOVZX then
  13080. begin
  13081. taicpu(p).opsize := S_WL;
  13082. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13083. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13084. end
  13085. else
  13086. taicpu(p).opsize := S_WQ;
  13087. RegUsed := True;
  13088. end;
  13089. else
  13090. ;
  13091. end;
  13092. {$endif x86_64}
  13093. else
  13094. ;
  13095. end;
  13096. if RegUsed then
  13097. begin
  13098. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13099. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13100. RemoveInstruction(hp1);
  13101. Result := True;
  13102. Exit;
  13103. end;
  13104. end;
  13105. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13106. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13107. GetNextInstruction(hp1, hp2) and
  13108. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13109. (
  13110. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13111. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13112. {$ifdef x86_64}
  13113. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13114. {$endif x86_64}
  13115. ) and
  13116. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13117. (
  13118. (
  13119. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13120. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13121. ) or
  13122. (
  13123. { Only allow the operands in reverse order for TEST instructions }
  13124. (taicpu(hp2).opcode = A_TEST) and
  13125. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13126. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13127. )
  13128. ) then
  13129. begin
  13130. {
  13131. For example:
  13132. movzbl %al,%eax
  13133. movzbl (ref),%edx
  13134. andl %edx,%eax
  13135. (%edx deallocated)
  13136. Change to:
  13137. andb (ref),%al
  13138. movzbl %al,%eax
  13139. Rules are:
  13140. - First two instructions have the same opcode and opsize
  13141. - First instruction's operands are the same super-register
  13142. - Second instruction operates on a different register
  13143. - Third instruction is AND, OR, XOR or TEST
  13144. - Third instruction's operands are the destination registers of the first two instructions
  13145. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13146. - Second instruction's destination register is deallocated afterwards
  13147. }
  13148. TransferUsedRegs(TmpUsedRegs);
  13149. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13150. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13151. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13152. begin
  13153. case taicpu(p).opsize of
  13154. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13155. NewSize := S_B;
  13156. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13157. NewSize := S_W;
  13158. {$ifdef x86_64}
  13159. S_LQ:
  13160. NewSize := S_L;
  13161. {$endif x86_64}
  13162. else
  13163. InternalError(2021120301);
  13164. end;
  13165. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13166. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13167. taicpu(hp2).opsize := NewSize;
  13168. RemoveInstruction(hp1);
  13169. { With TEST, it's best to keep the MOVX instruction at the top }
  13170. if (taicpu(hp2).opcode <> A_TEST) then
  13171. begin
  13172. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13173. asml.Remove(p);
  13174. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13175. asml.InsertAfter(p, hp2);
  13176. p := hp2;
  13177. end
  13178. else
  13179. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13180. Result := True;
  13181. Exit;
  13182. end;
  13183. end;
  13184. end;
  13185. if taicpu(p).opcode=A_MOVZX then
  13186. begin
  13187. { removes superfluous And's after movzx's }
  13188. if reg_and_hp1_is_instr and
  13189. (taicpu(hp1).opcode = A_AND) and
  13190. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13191. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13192. {$ifdef x86_64}
  13193. { check for implicit extension to 64 bit }
  13194. or
  13195. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13196. (taicpu(hp1).opsize=S_Q) and
  13197. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13198. )
  13199. {$endif x86_64}
  13200. )
  13201. then
  13202. begin
  13203. case taicpu(p).opsize Of
  13204. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13205. if (taicpu(hp1).oper[0]^.val = $ff) then
  13206. begin
  13207. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13208. RemoveInstruction(hp1);
  13209. Result:=true;
  13210. exit;
  13211. end;
  13212. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13213. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13214. begin
  13215. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13216. RemoveInstruction(hp1);
  13217. Result:=true;
  13218. exit;
  13219. end;
  13220. {$ifdef x86_64}
  13221. S_LQ:
  13222. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13223. begin
  13224. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13225. RemoveInstruction(hp1);
  13226. Result:=true;
  13227. exit;
  13228. end;
  13229. {$endif x86_64}
  13230. else
  13231. ;
  13232. end;
  13233. { we cannot get rid of the and, but can we get rid of the movz ?}
  13234. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13235. begin
  13236. case taicpu(p).opsize Of
  13237. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13238. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13239. begin
  13240. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13241. RemoveCurrentP(p,hp1);
  13242. Result:=true;
  13243. exit;
  13244. end;
  13245. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13246. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13247. begin
  13248. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13249. RemoveCurrentP(p,hp1);
  13250. Result:=true;
  13251. exit;
  13252. end;
  13253. {$ifdef x86_64}
  13254. S_LQ:
  13255. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13256. begin
  13257. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13258. RemoveCurrentP(p,hp1);
  13259. Result:=true;
  13260. exit;
  13261. end;
  13262. {$endif x86_64}
  13263. else
  13264. ;
  13265. end;
  13266. end;
  13267. end;
  13268. { changes some movzx constructs to faster synonyms (all examples
  13269. are given with eax/ax, but are also valid for other registers)}
  13270. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13271. begin
  13272. case taicpu(p).opsize of
  13273. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13274. (the machine code is equivalent to movzbl %al,%eax), but the
  13275. code generator still generates that assembler instruction and
  13276. it is silently converted. This should probably be checked.
  13277. [Kit] }
  13278. S_BW:
  13279. begin
  13280. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13281. (
  13282. not IsMOVZXAcceptable
  13283. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13284. or (
  13285. (cs_opt_size in current_settings.optimizerswitches) and
  13286. (taicpu(p).oper[1]^.reg = NR_AX)
  13287. )
  13288. ) then
  13289. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13290. begin
  13291. DebugMsg(SPeepholeOptimization + 'var7',p);
  13292. taicpu(p).opcode := A_AND;
  13293. taicpu(p).changeopsize(S_W);
  13294. taicpu(p).loadConst(0,$ff);
  13295. Result := True;
  13296. end
  13297. else if not IsMOVZXAcceptable and
  13298. GetNextInstruction(p, hp1) and
  13299. (tai(hp1).typ = ait_instruction) and
  13300. (taicpu(hp1).opcode = A_AND) and
  13301. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13302. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13303. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13304. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13305. begin
  13306. DebugMsg(SPeepholeOptimization + 'var8',p);
  13307. taicpu(p).opcode := A_MOV;
  13308. taicpu(p).changeopsize(S_W);
  13309. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13310. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13311. Result := True;
  13312. end;
  13313. end;
  13314. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13315. S_BL:
  13316. if not IsMOVZXAcceptable then
  13317. begin
  13318. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13319. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13320. begin
  13321. DebugMsg(SPeepholeOptimization + 'var9',p);
  13322. taicpu(p).opcode := A_AND;
  13323. taicpu(p).changeopsize(S_L);
  13324. taicpu(p).loadConst(0,$ff);
  13325. Result := True;
  13326. end
  13327. else if GetNextInstruction(p, hp1) and
  13328. (tai(hp1).typ = ait_instruction) and
  13329. (taicpu(hp1).opcode = A_AND) and
  13330. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13331. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13332. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13333. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13334. begin
  13335. DebugMsg(SPeepholeOptimization + 'var10',p);
  13336. taicpu(p).opcode := A_MOV;
  13337. taicpu(p).changeopsize(S_L);
  13338. { do not use R_SUBWHOLE
  13339. as movl %rdx,%eax
  13340. is invalid in assembler PM }
  13341. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13342. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13343. Result := True;
  13344. end;
  13345. end;
  13346. {$endif i8086}
  13347. S_WL:
  13348. if not IsMOVZXAcceptable then
  13349. begin
  13350. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13351. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13352. begin
  13353. DebugMsg(SPeepholeOptimization + 'var11',p);
  13354. taicpu(p).opcode := A_AND;
  13355. taicpu(p).changeopsize(S_L);
  13356. taicpu(p).loadConst(0,$ffff);
  13357. Result := True;
  13358. end
  13359. else if GetNextInstruction(p, hp1) and
  13360. (tai(hp1).typ = ait_instruction) and
  13361. (taicpu(hp1).opcode = A_AND) and
  13362. (taicpu(hp1).oper[0]^.typ = top_const) and
  13363. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13364. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13365. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13366. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13367. begin
  13368. DebugMsg(SPeepholeOptimization + 'var12',p);
  13369. taicpu(p).opcode := A_MOV;
  13370. taicpu(p).changeopsize(S_L);
  13371. { do not use R_SUBWHOLE
  13372. as movl %rdx,%eax
  13373. is invalid in assembler PM }
  13374. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13375. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13376. Result := True;
  13377. end;
  13378. end;
  13379. else
  13380. InternalError(2017050705);
  13381. end;
  13382. end
  13383. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13384. begin
  13385. if GetNextInstruction(p, hp1) and
  13386. (tai(hp1).typ = ait_instruction) and
  13387. (taicpu(hp1).opcode = A_AND) and
  13388. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13389. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13390. begin
  13391. case taicpu(p).opsize Of
  13392. S_BL:
  13393. if (taicpu(hp1).opsize <> S_L) or
  13394. (taicpu(hp1).oper[0]^.val > $FF) then
  13395. begin
  13396. DebugMsg(SPeepholeOptimization + 'var13',p);
  13397. taicpu(hp1).changeopsize(S_L);
  13398. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13399. Include(OptsToCheck, aoc_ForceNewIteration);
  13400. end;
  13401. S_WL:
  13402. if (taicpu(hp1).opsize <> S_L) or
  13403. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13404. begin
  13405. DebugMsg(SPeepholeOptimization + 'var14',p);
  13406. taicpu(hp1).changeopsize(S_L);
  13407. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13408. Include(OptsToCheck, aoc_ForceNewIteration);
  13409. end;
  13410. S_BW:
  13411. if (taicpu(hp1).opsize <> S_W) or
  13412. (taicpu(hp1).oper[0]^.val > $FF) then
  13413. begin
  13414. DebugMsg(SPeepholeOptimization + 'var15',p);
  13415. taicpu(hp1).changeopsize(S_W);
  13416. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13417. Include(OptsToCheck, aoc_ForceNewIteration);
  13418. end;
  13419. else
  13420. Internalerror(2017050704)
  13421. end;
  13422. end;
  13423. end;
  13424. end;
  13425. end;
  13426. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13427. var
  13428. hp1, hp2 : tai;
  13429. MaskLength : Cardinal;
  13430. MaskedBits : TCgInt;
  13431. ActiveReg : TRegister;
  13432. begin
  13433. Result:=false;
  13434. { There are no optimisations for reference targets }
  13435. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13436. Exit;
  13437. while GetNextInstruction(p, hp1) and
  13438. (hp1.typ = ait_instruction) do
  13439. begin
  13440. if (taicpu(p).oper[0]^.typ = top_const) then
  13441. begin
  13442. case taicpu(hp1).opcode of
  13443. A_AND:
  13444. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13445. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13446. { the second register must contain the first one, so compare their subreg types }
  13447. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13448. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13449. { change
  13450. and const1, reg
  13451. and const2, reg
  13452. to
  13453. and (const1 and const2), reg
  13454. }
  13455. begin
  13456. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13457. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13458. RemoveCurrentP(p, hp1);
  13459. Result:=true;
  13460. exit;
  13461. end;
  13462. A_CMP:
  13463. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13464. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13465. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13466. { Just check that the condition on the next instruction is compatible }
  13467. GetNextInstruction(hp1, hp2) and
  13468. (hp2.typ = ait_instruction) and
  13469. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13470. then
  13471. { change
  13472. and 2^n, reg
  13473. cmp 2^n, reg
  13474. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13475. to
  13476. and 2^n, reg
  13477. test reg, reg
  13478. j(~c) / set(~c) / cmov(~c)
  13479. }
  13480. begin
  13481. { Keep TEST instruction in, rather than remove it, because
  13482. it may trigger other optimisations such as MovAndTest2Test }
  13483. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13484. taicpu(hp1).opcode := A_TEST;
  13485. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13486. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13487. Result := True;
  13488. Exit;
  13489. end
  13490. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13491. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13492. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13493. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13494. { change
  13495. and $ff/$ff/$ffff, reg
  13496. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13497. dealloc reg
  13498. to
  13499. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13500. }
  13501. begin
  13502. TransferUsedRegs(TmpUsedRegs);
  13503. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13504. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13505. begin
  13506. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13507. case taicpu(p).oper[0]^.val of
  13508. $ff:
  13509. begin
  13510. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13511. taicpu(hp1).opsize:=S_B;
  13512. end;
  13513. $ffff:
  13514. begin
  13515. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13516. taicpu(hp1).opsize:=S_W;
  13517. end;
  13518. $ffffffff:
  13519. begin
  13520. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13521. taicpu(hp1).opsize:=S_L;
  13522. end;
  13523. else
  13524. Internalerror(2023030401);
  13525. end;
  13526. RemoveCurrentP(p);
  13527. Result := True;
  13528. Exit;
  13529. end;
  13530. end;
  13531. A_MOVZX:
  13532. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13533. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13534. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13535. (
  13536. (
  13537. (taicpu(p).opsize=S_W) and
  13538. (taicpu(hp1).opsize=S_BW)
  13539. ) or
  13540. (
  13541. (taicpu(p).opsize=S_L) and
  13542. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13543. )
  13544. {$ifdef x86_64}
  13545. or
  13546. (
  13547. (taicpu(p).opsize=S_Q) and
  13548. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13549. )
  13550. {$endif x86_64}
  13551. ) then
  13552. begin
  13553. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13554. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13555. ) or
  13556. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13557. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13558. then
  13559. begin
  13560. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13561. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13562. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13563. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13564. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13565. }
  13566. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13567. RemoveInstruction(hp1);
  13568. { See if there are other optimisations possible }
  13569. Continue;
  13570. end;
  13571. end;
  13572. A_SHL:
  13573. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13574. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13575. begin
  13576. {$ifopt R+}
  13577. {$define RANGE_WAS_ON}
  13578. {$R-}
  13579. {$endif}
  13580. { get length of potential and mask }
  13581. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13582. { really a mask? }
  13583. {$ifdef RANGE_WAS_ON}
  13584. {$R+}
  13585. {$endif}
  13586. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13587. { unmasked part shifted out? }
  13588. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13589. begin
  13590. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13591. RemoveCurrentP(p, hp1);
  13592. Result:=true;
  13593. exit;
  13594. end;
  13595. end;
  13596. A_SHR:
  13597. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13598. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13599. (taicpu(hp1).oper[0]^.val <= 63) then
  13600. begin
  13601. { Does SHR combined with the AND cover all the bits?
  13602. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13603. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13604. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13605. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13606. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13607. begin
  13608. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13609. RemoveCurrentP(p, hp1);
  13610. Result := True;
  13611. Exit;
  13612. end;
  13613. end;
  13614. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13615. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13616. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13617. begin
  13618. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13619. (
  13620. (
  13621. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13622. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13623. ) or (
  13624. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13625. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13626. {$ifdef x86_64}
  13627. ) or (
  13628. (taicpu(hp1).opsize = S_LQ) and
  13629. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13630. {$endif x86_64}
  13631. )
  13632. ) then
  13633. begin
  13634. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13635. begin
  13636. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13637. RemoveInstruction(hp1);
  13638. { See if there are other optimisations possible }
  13639. Continue;
  13640. end;
  13641. { The super-registers are the same though.
  13642. Note that this change by itself doesn't improve
  13643. code speed, but it opens up other optimisations. }
  13644. {$ifdef x86_64}
  13645. { Convert 64-bit register to 32-bit }
  13646. case taicpu(hp1).opsize of
  13647. S_BQ:
  13648. begin
  13649. taicpu(hp1).opsize := S_BL;
  13650. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13651. end;
  13652. S_WQ:
  13653. begin
  13654. taicpu(hp1).opsize := S_WL;
  13655. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13656. end
  13657. else
  13658. ;
  13659. end;
  13660. {$endif x86_64}
  13661. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13662. taicpu(hp1).opcode := A_MOVZX;
  13663. { See if there are other optimisations possible }
  13664. Continue;
  13665. end;
  13666. end;
  13667. else
  13668. ;
  13669. end;
  13670. end
  13671. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13672. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13673. begin
  13674. {$ifdef x86_64}
  13675. if (taicpu(p).opsize = S_Q) then
  13676. begin
  13677. { Never necessary }
  13678. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13679. RemoveCurrentP(p, hp1);
  13680. Result := True;
  13681. Exit;
  13682. end;
  13683. {$endif x86_64}
  13684. { Forward check to determine necessity of and %reg,%reg }
  13685. TransferUsedRegs(TmpUsedRegs);
  13686. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13687. { Saves on a bunch of dereferences }
  13688. ActiveReg := taicpu(p).oper[1]^.reg;
  13689. case taicpu(hp1).opcode of
  13690. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13691. if (
  13692. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13693. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13694. ) and
  13695. (
  13696. (taicpu(hp1).opcode <> A_MOV) or
  13697. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13698. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13699. ) and
  13700. not (
  13701. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13702. (taicpu(hp1).opcode = A_MOV) and
  13703. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13704. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13705. ) and
  13706. (
  13707. (
  13708. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13709. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13710. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13711. ) or
  13712. (
  13713. {$ifdef x86_64}
  13714. (
  13715. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13716. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13717. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13718. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13719. ) and
  13720. {$endif x86_64}
  13721. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13722. )
  13723. ) then
  13724. begin
  13725. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13726. RemoveCurrentP(p, hp1);
  13727. Result := True;
  13728. Exit;
  13729. end;
  13730. A_ADD,
  13731. A_AND,
  13732. A_BSF,
  13733. A_BSR,
  13734. A_BTC,
  13735. A_BTR,
  13736. A_BTS,
  13737. A_OR,
  13738. A_SUB,
  13739. A_XOR:
  13740. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13741. if (
  13742. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13743. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13744. ) and
  13745. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13746. begin
  13747. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13748. RemoveCurrentP(p, hp1);
  13749. Result := True;
  13750. Exit;
  13751. end;
  13752. A_CMP,
  13753. A_TEST:
  13754. if (
  13755. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13756. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13757. ) and
  13758. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13759. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13760. begin
  13761. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13762. RemoveCurrentP(p, hp1);
  13763. Result := True;
  13764. Exit;
  13765. end;
  13766. A_BSWAP,
  13767. A_NEG,
  13768. A_NOT:
  13769. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13770. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13771. begin
  13772. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13773. RemoveCurrentP(p, hp1);
  13774. Result := True;
  13775. Exit;
  13776. end;
  13777. else
  13778. ;
  13779. end;
  13780. end;
  13781. if (taicpu(hp1).is_jmp) and
  13782. (taicpu(hp1).opcode<>A_JMP) and
  13783. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13784. begin
  13785. { change
  13786. and x, reg
  13787. jxx
  13788. to
  13789. test x, reg
  13790. jxx
  13791. if reg is deallocated before the
  13792. jump, but only if it's a conditional jump (PFV)
  13793. }
  13794. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13795. taicpu(p).opcode := A_TEST;
  13796. Exit;
  13797. end;
  13798. Break;
  13799. end;
  13800. { Lone AND tests }
  13801. if (taicpu(p).oper[0]^.typ = top_const) then
  13802. begin
  13803. {
  13804. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13805. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13806. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13807. }
  13808. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13809. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13810. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13811. begin
  13812. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13813. if taicpu(p).opsize = S_L then
  13814. begin
  13815. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13816. Result := True;
  13817. end;
  13818. end;
  13819. end;
  13820. { Backward check to determine necessity of and %reg,%reg }
  13821. if (taicpu(p).oper[0]^.typ = top_reg) and
  13822. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13823. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13824. GetLastInstruction(p, hp2) and
  13825. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13826. { Check size of adjacent instruction to determine if the AND is
  13827. effectively a null operation }
  13828. (
  13829. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13830. { Note: Don't include S_Q }
  13831. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13832. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13833. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13834. ) then
  13835. begin
  13836. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13837. { If GetNextInstruction returned False, hp1 will be nil }
  13838. RemoveCurrentP(p, hp1);
  13839. Result := True;
  13840. Exit;
  13841. end;
  13842. end;
  13843. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13844. var
  13845. hp1, hp2: tai;
  13846. NewRef: TReference;
  13847. Distance: Cardinal;
  13848. TempTracking: TAllUsedRegs;
  13849. { This entire nested function is used in an if-statement below, but we
  13850. want to avoid all the used reg transfers and GetNextInstruction calls
  13851. until we really have to check }
  13852. function MemRegisterNotUsedLater: Boolean; inline;
  13853. var
  13854. hp2: tai;
  13855. begin
  13856. TransferUsedRegs(TmpUsedRegs);
  13857. hp2 := p;
  13858. repeat
  13859. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13860. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13861. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13862. end;
  13863. begin
  13864. Result := False;
  13865. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13866. (taicpu(p).oper[1]^.typ = top_reg) then
  13867. begin
  13868. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13869. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13870. (hp1.typ <> ait_instruction) or
  13871. not
  13872. (
  13873. (cs_opt_level3 in current_settings.optimizerswitches) or
  13874. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13875. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13876. ) then
  13877. Exit;
  13878. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13879. addq $x, %rax
  13880. movq %rax, %rdx
  13881. sarq $63, %rdx
  13882. (%rax still in use)
  13883. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13884. leaq $x(%rax),%rdx
  13885. addq $x, %rax
  13886. sarq $63, %rdx
  13887. ...which is okay since it breaks the dependency chain between
  13888. addq and movq, but if OptPass2MOV is called first:
  13889. addq $x, %rax
  13890. cqto
  13891. ...which is better in all ways, taking only 2 cycles to execute
  13892. and much smaller in code size.
  13893. }
  13894. { The extra register tracking is quite strenuous }
  13895. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13896. MatchInstruction(hp1, A_MOV, []) then
  13897. begin
  13898. { Update the register tracking to the MOV instruction }
  13899. CopyUsedRegs(TempTracking);
  13900. hp2 := p;
  13901. repeat
  13902. UpdateUsedRegs(tai(hp2.Next));
  13903. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13904. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13905. OptPass2ADD get called again }
  13906. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13907. begin
  13908. { Reset the tracking to the current instruction }
  13909. RestoreUsedRegs(TempTracking);
  13910. ReleaseUsedRegs(TempTracking);
  13911. Result := True;
  13912. Exit;
  13913. end;
  13914. { Reset the tracking to the current instruction }
  13915. RestoreUsedRegs(TempTracking);
  13916. ReleaseUsedRegs(TempTracking);
  13917. { If OptPass2MOV returned True, we don't need to set Result to
  13918. True if hp1 didn't change because the ADD instruction didn't
  13919. get modified and we'll be evaluating hp1 again when the
  13920. peephole optimizer reaches it }
  13921. end;
  13922. { Change:
  13923. add %reg2,%reg1
  13924. (%reg2 not modified in between)
  13925. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13926. To:
  13927. mov/s/z #(%reg1,%reg2),%reg1
  13928. }
  13929. if (taicpu(p).oper[0]^.typ = top_reg) and
  13930. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13931. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13932. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13933. (
  13934. (
  13935. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13936. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13937. { r/esp cannot be an index }
  13938. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13939. ) or (
  13940. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13941. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13942. )
  13943. ) and (
  13944. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13945. (
  13946. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13947. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13948. MemRegisterNotUsedLater
  13949. )
  13950. ) then
  13951. begin
  13952. if (
  13953. { Instructions are guaranteed to be adjacent on -O2 and under }
  13954. (cs_opt_level3 in current_settings.optimizerswitches) and
  13955. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13956. ) then
  13957. begin
  13958. { If the other register is used in between, move the MOV
  13959. instruction to right after the ADD instruction so a
  13960. saving can still be made }
  13961. Asml.Remove(hp1);
  13962. Asml.InsertAfter(hp1, p);
  13963. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13964. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13965. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13966. RemoveCurrentp(p, hp1);
  13967. end
  13968. else
  13969. begin
  13970. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13971. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13972. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13973. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13974. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13975. { hp1 may not be the immediate next instruction under -O3 }
  13976. RemoveCurrentp(p)
  13977. else
  13978. RemoveCurrentp(p, hp1);
  13979. end;
  13980. Result := True;
  13981. Exit;
  13982. end;
  13983. { Change:
  13984. addl/q $x,%reg1
  13985. movl/q %reg1,%reg2
  13986. To:
  13987. leal/q $x(%reg1),%reg2
  13988. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13989. Breaks the dependency chain.
  13990. }
  13991. if (taicpu(p).oper[0]^.typ = top_const) and
  13992. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13993. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13994. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13995. (
  13996. { Instructions are guaranteed to be adjacent on -O2 and under }
  13997. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13998. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13999. ) then
  14000. begin
  14001. TransferUsedRegs(TmpUsedRegs);
  14002. hp2 := p;
  14003. repeat
  14004. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14005. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14006. if (
  14007. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14008. not (cs_opt_size in current_settings.optimizerswitches) or
  14009. (
  14010. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14011. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14012. )
  14013. ) then
  14014. begin
  14015. { Change the MOV instruction to a LEA instruction, and update the
  14016. first operand }
  14017. reference_reset(NewRef, 1, []);
  14018. NewRef.base := taicpu(p).oper[1]^.reg;
  14019. NewRef.scalefactor := 1;
  14020. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14021. taicpu(hp1).opcode := A_LEA;
  14022. taicpu(hp1).loadref(0, NewRef);
  14023. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14024. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14025. begin
  14026. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14027. { Move what is now the LEA instruction to before the ADD instruction }
  14028. Asml.Remove(hp1);
  14029. Asml.InsertBefore(hp1, p);
  14030. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14031. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14032. p := hp1;
  14033. end
  14034. else
  14035. begin
  14036. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14037. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14038. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14039. { hp1 may not be the immediate next instruction under -O3 }
  14040. RemoveCurrentp(p)
  14041. else
  14042. RemoveCurrentp(p, hp1);
  14043. end;
  14044. Result := True;
  14045. end;
  14046. end;
  14047. end;
  14048. end;
  14049. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14050. var
  14051. SubReg: TSubRegister;
  14052. hp1, hp2: tai;
  14053. CallJmp: Boolean;
  14054. begin
  14055. Result := False;
  14056. CallJmp := False;
  14057. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14058. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14059. with taicpu(p).oper[0]^.ref^ do
  14060. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14061. if (offset = 0) then
  14062. begin
  14063. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14064. begin
  14065. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14066. taicpu(p).opcode := A_ADD;
  14067. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14068. Result := True;
  14069. end
  14070. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14071. begin
  14072. if (base <> NR_NO) then
  14073. begin
  14074. if (scalefactor <= 1) then
  14075. begin
  14076. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14077. taicpu(p).opcode := A_ADD;
  14078. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14079. Result := True;
  14080. end;
  14081. end
  14082. else
  14083. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14084. if (scalefactor in [2, 4, 8]) then
  14085. begin
  14086. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14087. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14088. taicpu(p).opcode := A_SHL;
  14089. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14090. Result := True;
  14091. end;
  14092. end;
  14093. end
  14094. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14095. lot of latency, so break off the offset if %reg3 is used soon
  14096. afterwards }
  14097. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14098. { If 3-component addresses don't have additional latency, don't
  14099. perform this optimisation }
  14100. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14101. GetNextInstruction(p, hp1) and
  14102. (
  14103. (
  14104. { Permit jumps and calls since they have a larger degree of overhead }
  14105. (
  14106. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14107. (
  14108. { ... unless the register specifies the location }
  14109. (taicpu(hp1).ops > 0) and
  14110. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14111. )
  14112. ) and
  14113. (
  14114. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14115. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14116. )
  14117. )
  14118. or
  14119. (
  14120. { Check up to two instructions ahead }
  14121. GetNextInstruction(hp1, hp2) and
  14122. (
  14123. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14124. (
  14125. { Same as above }
  14126. (taicpu(hp2).ops > 0) and
  14127. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14128. )
  14129. ) and
  14130. (
  14131. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14132. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14133. )
  14134. )
  14135. ) then
  14136. begin
  14137. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14138. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14139. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14140. offset := 0;
  14141. if Assigned(symbol) or Assigned(relsymbol) then
  14142. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14143. else
  14144. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14145. { Inserting before the next instruction rather than after the
  14146. current instruction gives more accurate register tracking }
  14147. asml.InsertBefore(hp2, hp1);
  14148. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14149. Result := True;
  14150. end;
  14151. end;
  14152. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14153. var
  14154. hp1, hp2: tai;
  14155. NewRef: TReference;
  14156. Distance: Cardinal;
  14157. TempTracking: TAllUsedRegs;
  14158. begin
  14159. Result := False;
  14160. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14161. MatchOpType(taicpu(p),top_const,top_reg) then
  14162. begin
  14163. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14164. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14165. (hp1.typ <> ait_instruction) or
  14166. not
  14167. (
  14168. (cs_opt_level3 in current_settings.optimizerswitches) or
  14169. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14170. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14171. ) then
  14172. Exit;
  14173. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14174. subq $x, %rax
  14175. movq %rax, %rdx
  14176. sarq $63, %rdx
  14177. (%rax still in use)
  14178. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14179. leaq $-x(%rax),%rdx
  14180. movq $x, %rax
  14181. sarq $63, %rdx
  14182. ...which is okay since it breaks the dependency chain between
  14183. subq and movq, but if OptPass2MOV is called first:
  14184. subq $x, %rax
  14185. cqto
  14186. ...which is better in all ways, taking only 2 cycles to execute
  14187. and much smaller in code size.
  14188. }
  14189. { The extra register tracking is quite strenuous }
  14190. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14191. MatchInstruction(hp1, A_MOV, []) then
  14192. begin
  14193. { Update the register tracking to the MOV instruction }
  14194. CopyUsedRegs(TempTracking);
  14195. hp2 := p;
  14196. repeat
  14197. UpdateUsedRegs(tai(hp2.Next));
  14198. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14199. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14200. OptPass2SUB get called again }
  14201. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14202. begin
  14203. { Reset the tracking to the current instruction }
  14204. RestoreUsedRegs(TempTracking);
  14205. ReleaseUsedRegs(TempTracking);
  14206. Result := True;
  14207. Exit;
  14208. end;
  14209. { Reset the tracking to the current instruction }
  14210. RestoreUsedRegs(TempTracking);
  14211. ReleaseUsedRegs(TempTracking);
  14212. { If OptPass2MOV returned True, we don't need to set Result to
  14213. True if hp1 didn't change because the SUB instruction didn't
  14214. get modified and we'll be evaluating hp1 again when the
  14215. peephole optimizer reaches it }
  14216. end;
  14217. { Change:
  14218. subl/q $x,%reg1
  14219. movl/q %reg1,%reg2
  14220. To:
  14221. leal/q $-x(%reg1),%reg2
  14222. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14223. Breaks the dependency chain and potentially permits the removal of
  14224. a CMP instruction if one follows.
  14225. }
  14226. if 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. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14233. ) then
  14234. begin
  14235. TransferUsedRegs(TmpUsedRegs);
  14236. hp2 := p;
  14237. repeat
  14238. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14239. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14240. if (
  14241. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14242. not (cs_opt_size in current_settings.optimizerswitches) or
  14243. (
  14244. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14245. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14246. )
  14247. ) then
  14248. begin
  14249. { Change the MOV instruction to a LEA instruction, and update the
  14250. first operand }
  14251. reference_reset(NewRef, 1, []);
  14252. NewRef.base := taicpu(p).oper[1]^.reg;
  14253. NewRef.scalefactor := 1;
  14254. NewRef.offset := -taicpu(p).oper[0]^.val;
  14255. taicpu(hp1).opcode := A_LEA;
  14256. taicpu(hp1).loadref(0, NewRef);
  14257. TransferUsedRegs(TmpUsedRegs);
  14258. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14259. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14260. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14261. begin
  14262. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14263. { Move what is now the LEA instruction to before the SUB instruction }
  14264. Asml.Remove(hp1);
  14265. Asml.InsertBefore(hp1, p);
  14266. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14267. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14268. p := hp1;
  14269. end
  14270. else
  14271. begin
  14272. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14273. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14274. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14275. { hp1 may not be the immediate next instruction under -O3 }
  14276. RemoveCurrentp(p)
  14277. else
  14278. RemoveCurrentp(p, hp1);
  14279. end;
  14280. Result := True;
  14281. end;
  14282. end;
  14283. end;
  14284. end;
  14285. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14286. begin
  14287. { we can skip all instructions not messing with the stack pointer }
  14288. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14289. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14290. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14291. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14292. ({(taicpu(hp1).ops=0) or }
  14293. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14294. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14295. ) and }
  14296. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14297. )
  14298. ) do
  14299. GetNextInstruction(hp1,hp1);
  14300. Result:=assigned(hp1);
  14301. end;
  14302. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14303. var
  14304. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14305. begin
  14306. Result:=false;
  14307. hp5:=nil;
  14308. hp6:=nil;
  14309. hp7:=nil;
  14310. hp8:=nil;
  14311. { replace
  14312. leal(q) x(<stackpointer>),<stackpointer>
  14313. <optional .seh_stackalloc ...>
  14314. <optional .seh_endprologue ...>
  14315. call procname
  14316. <optional NOP>
  14317. leal(q) -x(<stackpointer>),<stackpointer>
  14318. <optional VZEROUPPER>
  14319. ret
  14320. by
  14321. jmp procname
  14322. but do it only on level 4 because it destroys stack back traces
  14323. }
  14324. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14325. MatchOpType(taicpu(p),top_ref,top_reg) and
  14326. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14327. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14328. { the -8, -24, -40 are not required, but bail out early if possible,
  14329. higher values are unlikely }
  14330. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14331. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14332. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14333. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14334. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14335. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14336. GetNextInstruction(p, hp1) and
  14337. { Take a copy of hp1 }
  14338. SetAndTest(hp1, hp4) and
  14339. { trick to skip label }
  14340. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14341. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14342. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14343. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14344. SkipSimpleInstructions(hp1) and
  14345. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14346. GetNextInstruction(hp1, hp2) and
  14347. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14348. { skip nop instruction on win64 }
  14349. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14350. SetAndTest(hp2,hp6) and
  14351. GetNextInstruction(hp2,hp2) and
  14352. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14353. ) and
  14354. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14355. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14356. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14357. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14358. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14359. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14360. { Segment register will be NR_NO }
  14361. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14362. GetNextInstruction(hp2, hp3) and
  14363. { trick to skip label }
  14364. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14365. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14366. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14367. SetAndTest(hp3,hp5) and
  14368. GetNextInstruction(hp3,hp3) and
  14369. MatchInstruction(hp3,A_RET,[S_NO])
  14370. )
  14371. ) and
  14372. (taicpu(hp3).ops=0) then
  14373. begin
  14374. taicpu(hp1).opcode := A_JMP;
  14375. taicpu(hp1).is_jmp := true;
  14376. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14377. { search for the stackalloc directive and remove it }
  14378. hp7:=tai(p.next);
  14379. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14380. begin
  14381. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14382. begin
  14383. { sanity check }
  14384. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14385. Internalerror(2024012201);
  14386. hp8:=tai(hp7.next);
  14387. RemoveInstruction(tai(hp7));
  14388. hp7:=hp8;
  14389. break;
  14390. end
  14391. else
  14392. hp7:=tai(hp7.next);
  14393. end;
  14394. RemoveCurrentP(p, hp4);
  14395. RemoveInstruction(hp2);
  14396. RemoveInstruction(hp3);
  14397. { if there is a vzeroupper instruction then move it before the jmp }
  14398. if Assigned(hp5) then
  14399. begin
  14400. AsmL.Remove(hp5);
  14401. ASmL.InsertBefore(hp5,hp1)
  14402. end;
  14403. { remove nop on win64 }
  14404. if Assigned(hp6) then
  14405. RemoveInstruction(hp6);
  14406. Result:=true;
  14407. end;
  14408. end;
  14409. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14410. {$ifdef x86_64}
  14411. var
  14412. hp1, hp2, hp3, hp4, hp5: tai;
  14413. {$endif x86_64}
  14414. begin
  14415. Result:=false;
  14416. {$ifdef x86_64}
  14417. hp5:=nil;
  14418. { replace
  14419. push %rax
  14420. call procname
  14421. pop %rcx
  14422. ret
  14423. by
  14424. jmp procname
  14425. but do it only on level 4 because it destroys stack back traces
  14426. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14427. for all supported calling conventions
  14428. }
  14429. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14430. MatchOpType(taicpu(p),top_reg) and
  14431. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14432. GetNextInstruction(p, hp1) and
  14433. { Take a copy of hp1 }
  14434. SetAndTest(hp1, hp4) and
  14435. { trick to skip label }
  14436. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14437. SkipSimpleInstructions(hp1) and
  14438. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14439. GetNextInstruction(hp1, hp2) and
  14440. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14441. MatchOpType(taicpu(hp2),top_reg) and
  14442. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14443. GetNextInstruction(hp2, hp3) and
  14444. { trick to skip label }
  14445. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14446. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14447. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14448. SetAndTest(hp3,hp5) and
  14449. GetNextInstruction(hp3,hp3) and
  14450. MatchInstruction(hp3,A_RET,[S_NO])
  14451. )
  14452. ) and
  14453. (taicpu(hp3).ops=0) then
  14454. begin
  14455. taicpu(hp1).opcode := A_JMP;
  14456. taicpu(hp1).is_jmp := true;
  14457. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14458. RemoveCurrentP(p, hp4);
  14459. RemoveInstruction(hp2);
  14460. RemoveInstruction(hp3);
  14461. if Assigned(hp5) then
  14462. begin
  14463. AsmL.Remove(hp5);
  14464. ASmL.InsertBefore(hp5,hp1)
  14465. end;
  14466. Result:=true;
  14467. end;
  14468. {$endif x86_64}
  14469. end;
  14470. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14471. var
  14472. Value, RegName: string;
  14473. hp1: tai;
  14474. begin
  14475. Result:=false;
  14476. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14477. begin
  14478. case taicpu(p).oper[0]^.val of
  14479. 0:
  14480. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14481. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14482. (
  14483. { See if we can still convert the instruction }
  14484. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14485. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14486. ) then
  14487. begin
  14488. { change "mov $0,%reg" into "xor %reg,%reg" }
  14489. taicpu(p).opcode := A_XOR;
  14490. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14491. Result := True;
  14492. {$ifdef x86_64}
  14493. end
  14494. else if (taicpu(p).opsize = S_Q) then
  14495. begin
  14496. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14497. { The actual optimization }
  14498. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14499. taicpu(p).changeopsize(S_L);
  14500. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14501. Result := True;
  14502. end;
  14503. $1..$FFFFFFFF:
  14504. begin
  14505. { Code size reduction by J. Gareth "Kit" Moreton }
  14506. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14507. case taicpu(p).opsize of
  14508. S_Q:
  14509. begin
  14510. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14511. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14512. { The actual optimization }
  14513. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14514. taicpu(p).changeopsize(S_L);
  14515. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14516. Result := True;
  14517. end;
  14518. else
  14519. { Do nothing };
  14520. end;
  14521. {$endif x86_64}
  14522. end;
  14523. -1:
  14524. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14525. if (cs_opt_size in current_settings.optimizerswitches) and
  14526. (taicpu(p).opsize <> S_B) and
  14527. (
  14528. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14529. (
  14530. { See if we can still convert the instruction }
  14531. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14532. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14533. )
  14534. ) then
  14535. begin
  14536. { change "mov $-1,%reg" into "or $-1,%reg" }
  14537. { NOTES:
  14538. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14539. - This operation creates a false dependency on the register, so only do it when optimising for size
  14540. - 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
  14541. }
  14542. taicpu(p).opcode := A_OR;
  14543. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14544. Result := True;
  14545. end;
  14546. else
  14547. { Do nothing };
  14548. end;
  14549. end;
  14550. end;
  14551. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14552. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14553. begin
  14554. Result := False;
  14555. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14556. Exit;
  14557. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14558. so don't bother optimising }
  14559. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14560. Exit;
  14561. if (taicpu(p).oper[0]^.typ <> top_const) or
  14562. { If the value can fit into an 8-bit signed integer, a smaller
  14563. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14564. falls within this range }
  14565. (
  14566. (taicpu(p).oper[0]^.val > -128) and
  14567. (taicpu(p).oper[0]^.val <= 127)
  14568. ) then
  14569. Exit;
  14570. { If we're optimising for size, this is acceptable }
  14571. if (cs_opt_size in current_settings.optimizerswitches) then
  14572. Exit(True);
  14573. if (taicpu(p).oper[1]^.typ = top_reg) and
  14574. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14575. Exit(True);
  14576. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14577. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14578. Exit(True);
  14579. end;
  14580. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14581. var
  14582. hp1: tai;
  14583. Value: TCGInt;
  14584. begin
  14585. Result := False;
  14586. if MatchOpType(taicpu(p), top_const, top_reg) then
  14587. begin
  14588. { Detect:
  14589. andw x, %ax (0 <= x < $8000)
  14590. ...
  14591. movzwl %ax,%eax
  14592. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14593. }
  14594. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14595. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14596. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14597. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14598. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14599. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14600. begin
  14601. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14602. taicpu(hp1).opcode := A_CWDE;
  14603. taicpu(hp1).clearop(0);
  14604. taicpu(hp1).clearop(1);
  14605. taicpu(hp1).ops := 0;
  14606. { A change was made, but not with p, so don't set Result, but
  14607. notify the compiler that a change was made }
  14608. Include(OptsToCheck, aoc_ForceNewIteration);
  14609. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14610. end;
  14611. end;
  14612. { If "not x" is a power of 2 (popcnt = 1), change:
  14613. and $x, %reg/ref
  14614. To:
  14615. btr lb(x), %reg/ref
  14616. }
  14617. if IsBTXAcceptable(p) and
  14618. (
  14619. { Make sure a TEST doesn't follow that plays with the register }
  14620. not GetNextInstruction(p, hp1) or
  14621. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14622. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14623. ) then
  14624. begin
  14625. {$push}{$R-}{$Q-}
  14626. { Value is a sign-extended 32-bit integer - just correct it
  14627. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14628. checks to see if this operand is an immediate. }
  14629. Value := not taicpu(p).oper[0]^.val;
  14630. {$pop}
  14631. {$ifdef x86_64}
  14632. if taicpu(p).opsize = S_L then
  14633. {$endif x86_64}
  14634. Value := Value and $FFFFFFFF;
  14635. if (PopCnt(QWord(Value)) = 1) then
  14636. begin
  14637. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14638. taicpu(p).opcode := A_BTR;
  14639. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14640. Result := True;
  14641. Exit;
  14642. end;
  14643. end;
  14644. end;
  14645. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14646. begin
  14647. Result := False;
  14648. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14649. Exit;
  14650. { Convert:
  14651. movswl %ax,%eax -> cwtl
  14652. movslq %eax,%rax -> cdqe
  14653. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14654. refer to the same opcode and depends only on the assembler's
  14655. current operand-size attribute. [Kit]
  14656. }
  14657. with taicpu(p) do
  14658. case opsize of
  14659. S_WL:
  14660. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14661. begin
  14662. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14663. opcode := A_CWDE;
  14664. clearop(0);
  14665. clearop(1);
  14666. ops := 0;
  14667. Result := True;
  14668. end;
  14669. {$ifdef x86_64}
  14670. S_LQ:
  14671. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14672. begin
  14673. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14674. opcode := A_CDQE;
  14675. clearop(0);
  14676. clearop(1);
  14677. ops := 0;
  14678. Result := True;
  14679. end;
  14680. {$endif x86_64}
  14681. else
  14682. ;
  14683. end;
  14684. end;
  14685. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14686. var
  14687. hp1, hp2: tai;
  14688. IdentityMask, Shift: TCGInt;
  14689. LimitSize: Topsize;
  14690. DoNotMerge: Boolean;
  14691. begin
  14692. Result := False;
  14693. { All these optimisations work on "shr const,%reg" }
  14694. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14695. Exit;
  14696. DoNotMerge := False;
  14697. Shift := taicpu(p).oper[0]^.val;
  14698. LimitSize := taicpu(p).opsize;
  14699. hp1 := p;
  14700. repeat
  14701. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14702. Break;
  14703. { Detect:
  14704. shr x, %reg
  14705. and y, %reg
  14706. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14707. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14708. }
  14709. case taicpu(hp1).opcode of
  14710. A_AND:
  14711. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14712. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14713. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14714. begin
  14715. { Make sure the FLAGS register isn't in use }
  14716. TransferUsedRegs(TmpUsedRegs);
  14717. hp2 := p;
  14718. repeat
  14719. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14720. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14721. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14722. begin
  14723. { Generate the identity mask }
  14724. case taicpu(p).opsize of
  14725. S_B:
  14726. IdentityMask := $FF shr Shift;
  14727. S_W:
  14728. IdentityMask := $FFFF shr Shift;
  14729. S_L:
  14730. IdentityMask := $FFFFFFFF shr Shift;
  14731. {$ifdef x86_64}
  14732. S_Q:
  14733. { We need to force the operands to be unsigned 64-bit
  14734. integers otherwise the wrong value is generated }
  14735. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14736. {$endif x86_64}
  14737. else
  14738. InternalError(2022081501);
  14739. end;
  14740. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14741. begin
  14742. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14743. { All the possible 1 bits are covered, so we can remove the AND }
  14744. hp2 := tai(hp1.Previous);
  14745. RemoveInstruction(hp1);
  14746. { p wasn't actually changed, so don't set Result to True,
  14747. but a change was nonetheless made elsewhere }
  14748. Include(OptsToCheck, aoc_ForceNewIteration);
  14749. { Do another pass in case other AND or MOVZX instructions
  14750. follow }
  14751. hp1 := hp2;
  14752. Continue;
  14753. end;
  14754. end;
  14755. end;
  14756. A_TEST, A_CMP, A_Jcc:
  14757. { Skip over conditional jumps and relevant comparisons }
  14758. Continue;
  14759. A_MOVZX:
  14760. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14761. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14762. begin
  14763. { Since the original register is being read as is, subsequent
  14764. SHRs must not be merged at this point }
  14765. DoNotMerge := True;
  14766. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14767. begin
  14768. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14769. begin
  14770. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14771. { All the possible 1 bits are covered, so we can remove the AND }
  14772. hp2 := tai(hp1.Previous);
  14773. RemoveInstruction(hp1);
  14774. hp1 := hp2;
  14775. end
  14776. else { Different register target }
  14777. begin
  14778. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14779. taicpu(hp1).opcode := A_MOV;
  14780. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14781. case taicpu(hp1).opsize of
  14782. S_BW:
  14783. taicpu(hp1).opsize := S_W;
  14784. S_BL, S_WL:
  14785. taicpu(hp1).opsize := S_L;
  14786. else
  14787. InternalError(2022081503);
  14788. end;
  14789. end;
  14790. end
  14791. else if (Shift > 0) and
  14792. (taicpu(p).opsize = S_W) and
  14793. (taicpu(hp1).opsize = S_WL) and
  14794. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14795. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14796. begin
  14797. { Detect:
  14798. shr x, %ax (x > 0)
  14799. ...
  14800. movzwl %ax,%eax
  14801. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14802. }
  14803. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14804. taicpu(hp1).opcode := A_CWDE;
  14805. taicpu(hp1).clearop(0);
  14806. taicpu(hp1).clearop(1);
  14807. taicpu(hp1).ops := 0;
  14808. end;
  14809. { Move onto the next instruction }
  14810. Continue;
  14811. end;
  14812. A_SHL, A_SAL, A_SHR:
  14813. if (taicpu(hp1).opsize <= LimitSize) and
  14814. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14815. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14816. begin
  14817. { Make sure the sizes don't exceed the register size limit
  14818. (measured by the shift value falling below the limit) }
  14819. if taicpu(hp1).opsize < LimitSize then
  14820. LimitSize := taicpu(hp1).opsize;
  14821. if taicpu(hp1).opcode = A_SHR then
  14822. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14823. else
  14824. begin
  14825. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14826. DoNotMerge := True;
  14827. end;
  14828. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14829. Break;
  14830. { Since we've established that the combined shift is within
  14831. limits, we can actually combine the adjacent SHR
  14832. instructions even if they're different sizes }
  14833. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14834. begin
  14835. hp2 := tai(hp1.Previous);
  14836. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14837. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14838. RemoveInstruction(hp1);
  14839. hp1 := hp2;
  14840. end;
  14841. { Move onto the next instruction }
  14842. Continue;
  14843. end;
  14844. else
  14845. ;
  14846. end;
  14847. Break;
  14848. until False;
  14849. { Detect the following (looking backwards):
  14850. shr %cl,%reg
  14851. shr x, %reg
  14852. Swap the two SHR instructions to minimise a pipeline stall.
  14853. }
  14854. if GetLastInstruction(p, hp1) and
  14855. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14856. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14857. { First operand will be %cl }
  14858. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14859. { Just to be sure }
  14860. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14861. begin
  14862. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14863. { Moving the entries this way ensures the register tracking remains correct }
  14864. Asml.Remove(p);
  14865. Asml.InsertBefore(p, hp1);
  14866. p := hp1;
  14867. { Don't set Result to True because the current instruction is now
  14868. "shr %cl,%reg" and there's nothing more we can do with it }
  14869. end;
  14870. end;
  14871. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14872. var
  14873. hp1, hp2: tai;
  14874. Opposite, SecondOpposite: TAsmOp;
  14875. NewCond: TAsmCond;
  14876. begin
  14877. Result := False;
  14878. { Change:
  14879. add/sub 128,(dest)
  14880. To:
  14881. sub/add -128,(dest)
  14882. This generaally takes fewer bytes to encode because -128 can be stored
  14883. in a signed byte, whereas +128 cannot.
  14884. }
  14885. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14886. begin
  14887. if taicpu(p).opcode = A_ADD then
  14888. Opposite := A_SUB
  14889. else
  14890. Opposite := A_ADD;
  14891. { Be careful if the flags are in use, because the CF flag inverts
  14892. when changing from ADD to SUB and vice versa }
  14893. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14894. GetNextInstruction(p, hp1) then
  14895. begin
  14896. TransferUsedRegs(TmpUsedRegs);
  14897. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14898. hp2 := hp1;
  14899. { Scan ahead to check if everything's safe }
  14900. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14901. begin
  14902. if (hp1.typ <> ait_instruction) then
  14903. { Probably unsafe since the flags are still in use }
  14904. Exit;
  14905. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14906. { Stop searching at an unconditional jump }
  14907. Break;
  14908. if not
  14909. (
  14910. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14911. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14912. ) and
  14913. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14914. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14915. Exit;
  14916. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14917. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14918. { Move to the next instruction }
  14919. GetNextInstruction(hp1, hp1);
  14920. end;
  14921. while Assigned(hp2) and (hp2 <> hp1) do
  14922. begin
  14923. NewCond := C_None;
  14924. case taicpu(hp2).condition of
  14925. C_A, C_NBE:
  14926. NewCond := C_BE;
  14927. C_B, C_C, C_NAE:
  14928. NewCond := C_AE;
  14929. C_AE, C_NB, C_NC:
  14930. NewCond := C_B;
  14931. C_BE, C_NA:
  14932. NewCond := C_A;
  14933. else
  14934. { No change needed };
  14935. end;
  14936. if NewCond <> C_None then
  14937. begin
  14938. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14939. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14940. taicpu(hp2).condition := NewCond;
  14941. end
  14942. else
  14943. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14944. begin
  14945. { Because of the flipping of the carry bit, to ensure
  14946. the operation remains equivalent, ADC becomes SBB
  14947. and vice versa, and the constant is not-inverted.
  14948. If multiple ADCs or SBBs appear in a row, each one
  14949. changed causes the carry bit to invert, so they all
  14950. need to be flipped }
  14951. if taicpu(hp2).opcode = A_ADC then
  14952. SecondOpposite := A_SBB
  14953. else
  14954. SecondOpposite := A_ADC;
  14955. if taicpu(hp2).oper[0]^.typ <> top_const then
  14956. { Should have broken out of this optimisation already }
  14957. InternalError(2021112901);
  14958. 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]^) + ' -> ' +
  14959. 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);
  14960. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14961. taicpu(hp2).opcode := SecondOpposite;
  14962. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14963. end;
  14964. { Move to the next instruction }
  14965. GetNextInstruction(hp2, hp2);
  14966. end;
  14967. if (hp2 <> hp1) then
  14968. InternalError(2021111501);
  14969. end;
  14970. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14971. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14972. taicpu(p).opcode := Opposite;
  14973. taicpu(p).oper[0]^.val := -128;
  14974. { No further optimisations can be made on this instruction, so move
  14975. onto the next one to save time }
  14976. p := tai(p.Next);
  14977. UpdateUsedRegs(p);
  14978. Result := True;
  14979. Exit;
  14980. end;
  14981. { Detect:
  14982. add/sub %reg2,(dest)
  14983. add/sub x, (dest)
  14984. (dest can be a register or a reference)
  14985. Swap the instructions to minimise a pipeline stall. This reverses the
  14986. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14987. optimisations could be made.
  14988. }
  14989. if (taicpu(p).oper[0]^.typ = top_reg) and
  14990. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14991. (
  14992. (
  14993. (taicpu(p).oper[1]^.typ = top_reg) and
  14994. { We can try searching further ahead if we're writing to a register }
  14995. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14996. ) or
  14997. (
  14998. (taicpu(p).oper[1]^.typ = top_ref) and
  14999. GetNextInstruction(p, hp1)
  15000. )
  15001. ) and
  15002. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15003. (taicpu(hp1).oper[0]^.typ = top_const) and
  15004. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15005. begin
  15006. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15007. TransferUsedRegs(TmpUsedRegs);
  15008. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15009. hp2 := p;
  15010. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15011. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15012. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15013. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15014. begin
  15015. asml.remove(hp1);
  15016. asml.InsertBefore(hp1, p);
  15017. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15018. Result := True;
  15019. end;
  15020. end;
  15021. end;
  15022. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15023. var
  15024. hp1: tai;
  15025. begin
  15026. Result:=false;
  15027. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15028. while GetNextInstruction(p, hp1) and
  15029. TrySwapMovCmp(p, hp1) do
  15030. begin
  15031. if MatchInstruction(hp1, A_MOV, []) then
  15032. begin
  15033. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15034. begin
  15035. { A little hacky, but since CMP doesn't read the flags, only
  15036. modify them, it's safe if they get scrambled by MOV -> XOR }
  15037. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15038. Result := PostPeepholeOptMov(hp1);
  15039. {$ifdef x86_64}
  15040. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15041. { Used to shrink instruction size }
  15042. PostPeepholeOptXor(hp1);
  15043. {$endif x86_64}
  15044. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15045. end
  15046. else
  15047. begin
  15048. Result := PostPeepholeOptMov(hp1);
  15049. {$ifdef x86_64}
  15050. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15051. { Used to shrink instruction size }
  15052. PostPeepholeOptXor(hp1);
  15053. {$endif x86_64}
  15054. end;
  15055. end;
  15056. { Enabling this flag is actually a null operation, but it marks
  15057. the code as 'modified' during this pass }
  15058. Include(OptsToCheck, aoc_ForceNewIteration);
  15059. end;
  15060. { change "cmp $0, %reg" to "test %reg, %reg" }
  15061. if MatchOpType(taicpu(p),top_const,top_reg) and
  15062. (taicpu(p).oper[0]^.val = 0) then
  15063. begin
  15064. taicpu(p).opcode := A_TEST;
  15065. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15066. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15067. Result:=true;
  15068. end;
  15069. end;
  15070. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15071. var
  15072. IsTestConstX, IsValid : Boolean;
  15073. hp1,hp2 : tai;
  15074. begin
  15075. Result:=false;
  15076. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15077. if (taicpu(p).opcode = A_TEST) then
  15078. while GetNextInstruction(p, hp1) and
  15079. TrySwapMovCmp(p, hp1) do
  15080. begin
  15081. if MatchInstruction(hp1, A_MOV, []) then
  15082. begin
  15083. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15084. begin
  15085. { A little hacky, but since TEST doesn't read the flags, only
  15086. modify them, it's safe if they get scrambled by MOV -> XOR }
  15087. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15088. Result := PostPeepholeOptMov(hp1);
  15089. {$ifdef x86_64}
  15090. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15091. { Used to shrink instruction size }
  15092. PostPeepholeOptXor(hp1);
  15093. {$endif x86_64}
  15094. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15095. end
  15096. else
  15097. begin
  15098. Result := PostPeepholeOptMov(hp1);
  15099. {$ifdef x86_64}
  15100. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15101. { Used to shrink instruction size }
  15102. PostPeepholeOptXor(hp1);
  15103. {$endif x86_64}
  15104. end;
  15105. end;
  15106. { Enabling this flag is actually a null operation, but it marks
  15107. the code as 'modified' during this pass }
  15108. Include(OptsToCheck, aoc_ForceNewIteration);
  15109. end;
  15110. { If x is a power of 2 (popcnt = 1), change:
  15111. or $x, %reg/ref
  15112. To:
  15113. bts lb(x), %reg/ref
  15114. }
  15115. if (taicpu(p).opcode = A_OR) and
  15116. IsBTXAcceptable(p) and
  15117. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15118. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15119. (
  15120. { Don't optimise if a test instruction follows }
  15121. not GetNextInstruction(p, hp1) or
  15122. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15123. ) then
  15124. begin
  15125. 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);
  15126. taicpu(p).opcode := A_BTS;
  15127. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15128. Result := True;
  15129. Exit;
  15130. end;
  15131. { If x is a power of 2 (popcnt = 1), change:
  15132. test $x, %reg/ref
  15133. je / sete / cmove (or jne / setne)
  15134. To:
  15135. bt lb(x), %reg/ref
  15136. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15137. }
  15138. if (taicpu(p).opcode = A_TEST) and
  15139. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15140. (taicpu(p).oper[0]^.typ = top_const) and
  15141. (
  15142. (cs_opt_size in current_settings.optimizerswitches) or
  15143. (
  15144. (taicpu(p).oper[1]^.typ = top_reg) and
  15145. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15146. ) or
  15147. (
  15148. (taicpu(p).oper[1]^.typ <> top_reg) and
  15149. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15150. )
  15151. ) and
  15152. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15153. { For sizes less than S_L, the byte size is equal or larger with BT,
  15154. so don't bother optimising }
  15155. (taicpu(p).opsize >= S_L) then
  15156. begin
  15157. IsValid := True;
  15158. { Check the next set of instructions, watching the FLAGS register
  15159. and the conditions used }
  15160. TransferUsedRegs(TmpUsedRegs);
  15161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15162. hp1 := p;
  15163. hp2 := nil;
  15164. while GetNextInstruction(hp1, hp1) do
  15165. begin
  15166. if not Assigned(hp2) then
  15167. { The first instruction after TEST }
  15168. hp2 := hp1;
  15169. if (hp1.typ <> ait_instruction) then
  15170. begin
  15171. { If the flags are no longer in use, everything is fine }
  15172. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15173. IsValid := False;
  15174. Break;
  15175. end;
  15176. case taicpu(hp1).condition of
  15177. C_None:
  15178. begin
  15179. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15180. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15181. { Something is not quite normal, so play safe and don't change }
  15182. IsValid := False;
  15183. Break;
  15184. end;
  15185. C_E, C_Z, C_NE, C_NZ:
  15186. { This is fine };
  15187. else
  15188. begin
  15189. { Unsupported condition }
  15190. IsValid := False;
  15191. Break;
  15192. end;
  15193. end;
  15194. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15195. end;
  15196. if IsValid then
  15197. begin
  15198. while hp2 <> hp1 do
  15199. begin
  15200. case taicpu(hp2).condition of
  15201. C_Z, C_E:
  15202. taicpu(hp2).condition := C_NC;
  15203. C_NZ, C_NE:
  15204. taicpu(hp2).condition := C_C;
  15205. else
  15206. { Should not get this by this point }
  15207. InternalError(2022110701);
  15208. end;
  15209. GetNextInstruction(hp2, hp2);
  15210. end;
  15211. 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);
  15212. taicpu(p).opcode := A_BT;
  15213. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15214. Result := True;
  15215. Exit;
  15216. end;
  15217. end;
  15218. { removes the line marked with (x) from the sequence
  15219. and/or/xor/add/sub/... $x, %y
  15220. test/or %y, %y | test $-1, %y (x)
  15221. j(n)z _Label
  15222. as the first instruction already adjusts the ZF
  15223. %y operand may also be a reference }
  15224. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15225. MatchOperand(taicpu(p).oper[0]^,-1);
  15226. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15227. GetLastInstruction(p, hp1) and
  15228. (tai(hp1).typ = ait_instruction) and
  15229. GetNextInstruction(p,hp2) and
  15230. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15231. case taicpu(hp1).opcode Of
  15232. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15233. { These two instructions set the zero flag if the result is zero }
  15234. A_POPCNT, A_LZCNT:
  15235. begin
  15236. if (
  15237. { With POPCNT, an input of zero will set the zero flag
  15238. because the population count of zero is zero }
  15239. (taicpu(hp1).opcode = A_POPCNT) and
  15240. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15241. (
  15242. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15243. { Faster than going through the second half of the 'or'
  15244. condition below }
  15245. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15246. )
  15247. ) or (
  15248. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15249. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15250. { and in case of carry for A(E)/B(E)/C/NC }
  15251. (
  15252. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15253. (
  15254. (taicpu(hp1).opcode <> A_ADD) and
  15255. (taicpu(hp1).opcode <> A_SUB) and
  15256. (taicpu(hp1).opcode <> A_LZCNT)
  15257. )
  15258. )
  15259. ) then
  15260. begin
  15261. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15262. RemoveCurrentP(p, hp2);
  15263. Result:=true;
  15264. Exit;
  15265. end;
  15266. end;
  15267. A_SHL, A_SAL, A_SHR, A_SAR:
  15268. begin
  15269. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15270. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15271. { therefore, it's only safe to do this optimization for }
  15272. { shifts by a (nonzero) constant }
  15273. (taicpu(hp1).oper[0]^.typ = top_const) and
  15274. (taicpu(hp1).oper[0]^.val <> 0) and
  15275. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15276. { and in case of carry for A(E)/B(E)/C/NC }
  15277. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15278. begin
  15279. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15280. RemoveCurrentP(p, hp2);
  15281. Result:=true;
  15282. Exit;
  15283. end;
  15284. end;
  15285. A_DEC, A_INC, A_NEG:
  15286. begin
  15287. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15288. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15289. { and in case of carry for A(E)/B(E)/C/NC }
  15290. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15291. begin
  15292. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15293. RemoveCurrentP(p, hp2);
  15294. Result:=true;
  15295. Exit;
  15296. end;
  15297. end;
  15298. A_ANDN, A_BZHI:
  15299. begin
  15300. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15301. { Only the zero and sign flags are consistent with what the result is }
  15302. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15303. begin
  15304. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15305. RemoveCurrentP(p, hp2);
  15306. Result:=true;
  15307. Exit;
  15308. end;
  15309. end;
  15310. A_BEXTR:
  15311. begin
  15312. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15313. { Only the zero flag is set }
  15314. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15315. begin
  15316. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15317. RemoveCurrentP(p, hp2);
  15318. Result:=true;
  15319. Exit;
  15320. end;
  15321. end;
  15322. else
  15323. ;
  15324. end; { case }
  15325. { change "test $-1,%reg" into "test %reg,%reg" }
  15326. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15327. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15328. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15329. if MatchInstruction(p, A_OR, []) and
  15330. { Can only match if they're both registers }
  15331. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15332. begin
  15333. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15334. taicpu(p).opcode := A_TEST;
  15335. { No need to set Result to True, as we've done all the optimisations we can }
  15336. end;
  15337. end;
  15338. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15339. var
  15340. hp1,hp3 : tai;
  15341. {$ifndef x86_64}
  15342. hp2 : taicpu;
  15343. {$endif x86_64}
  15344. begin
  15345. Result:=false;
  15346. hp3:=nil;
  15347. {$ifndef x86_64}
  15348. { don't do this on modern CPUs, this really hurts them due to
  15349. broken call/ret pairing }
  15350. if (current_settings.optimizecputype < cpu_Pentium2) and
  15351. not(cs_create_pic in current_settings.moduleswitches) and
  15352. GetNextInstruction(p, hp1) and
  15353. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15354. MatchOpType(taicpu(hp1),top_ref) and
  15355. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15356. begin
  15357. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15358. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15359. InsertLLItem(p.previous, p, hp2);
  15360. taicpu(p).opcode := A_JMP;
  15361. taicpu(p).is_jmp := true;
  15362. RemoveInstruction(hp1);
  15363. Result:=true;
  15364. end
  15365. else
  15366. {$endif x86_64}
  15367. { replace
  15368. call procname
  15369. ret
  15370. by
  15371. jmp procname
  15372. but do it only on level 4 because it destroys stack back traces
  15373. else if the subroutine is marked as no return, remove the ret
  15374. }
  15375. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15376. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15377. GetNextInstruction(p, hp1) and
  15378. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15379. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15380. SetAndTest(hp1,hp3) and
  15381. GetNextInstruction(hp1,hp1) and
  15382. MatchInstruction(hp1,A_RET,[S_NO])
  15383. )
  15384. ) and
  15385. (taicpu(hp1).ops=0) then
  15386. begin
  15387. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15388. { we might destroy stack alignment here if we do not do a call }
  15389. (target_info.stackalign<=sizeof(SizeUInt)) then
  15390. begin
  15391. taicpu(p).opcode := A_JMP;
  15392. taicpu(p).is_jmp := true;
  15393. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15394. end
  15395. else
  15396. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15397. RemoveInstruction(hp1);
  15398. if Assigned(hp3) then
  15399. begin
  15400. AsmL.Remove(hp3);
  15401. AsmL.InsertBefore(hp3,p)
  15402. end;
  15403. Result:=true;
  15404. end;
  15405. end;
  15406. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15407. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15408. begin
  15409. case OpSize of
  15410. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15411. Result := (Val <= $FF) and (Val >= -128);
  15412. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15413. Result := (Val <= $FFFF) and (Val >= -32768);
  15414. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15415. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15416. else
  15417. Result := True;
  15418. end;
  15419. end;
  15420. var
  15421. hp1, hp2 : tai;
  15422. SizeChange: Boolean;
  15423. PreMessage: string;
  15424. begin
  15425. Result := False;
  15426. if (taicpu(p).oper[0]^.typ = top_reg) and
  15427. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15428. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15429. begin
  15430. { Change (using movzbl %al,%eax as an example):
  15431. movzbl %al, %eax movzbl %al, %eax
  15432. cmpl x, %eax testl %eax,%eax
  15433. To:
  15434. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15435. movzbl %al, %eax movzbl %al, %eax
  15436. Smaller instruction and minimises pipeline stall as the CPU
  15437. doesn't have to wait for the register to get zero-extended. [Kit]
  15438. Also allow if the smaller of the two registers is being checked,
  15439. as this still removes the false dependency.
  15440. }
  15441. if
  15442. (
  15443. (
  15444. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15445. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15446. ) or (
  15447. { If MatchOperand returns True, they must both be registers }
  15448. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15449. )
  15450. ) and
  15451. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15452. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15453. begin
  15454. 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);
  15455. asml.Remove(hp1);
  15456. asml.InsertBefore(hp1, p);
  15457. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15458. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15459. begin
  15460. taicpu(hp1).opcode := A_TEST;
  15461. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15462. end;
  15463. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15464. case taicpu(p).opsize of
  15465. S_BW, S_BL:
  15466. begin
  15467. SizeChange := taicpu(hp1).opsize <> S_B;
  15468. taicpu(hp1).changeopsize(S_B);
  15469. end;
  15470. S_WL:
  15471. begin
  15472. SizeChange := taicpu(hp1).opsize <> S_W;
  15473. taicpu(hp1).changeopsize(S_W);
  15474. end
  15475. else
  15476. InternalError(2020112701);
  15477. end;
  15478. UpdateUsedRegs(tai(p.Next));
  15479. { Check if the register is used aferwards - if not, we can
  15480. remove the movzx instruction completely }
  15481. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15482. begin
  15483. { Hp1 is a better position than p for debugging purposes }
  15484. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15485. RemoveCurrentp(p, hp1);
  15486. Result := True;
  15487. end;
  15488. if SizeChange then
  15489. DebugMsg(SPeepholeOptimization + PreMessage +
  15490. 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)
  15491. else
  15492. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15493. Exit;
  15494. end;
  15495. { Change (using movzwl %ax,%eax as an example):
  15496. movzwl %ax, %eax
  15497. movb %al, (dest) (Register is smaller than read register in movz)
  15498. To:
  15499. movb %al, (dest) (Move one back to avoid a false dependency)
  15500. movzwl %ax, %eax
  15501. }
  15502. if (taicpu(hp1).opcode = A_MOV) and
  15503. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15504. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15505. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15506. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15507. begin
  15508. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15509. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15510. asml.Remove(hp1);
  15511. asml.InsertBefore(hp1, p);
  15512. if taicpu(hp1).oper[1]^.typ = top_reg then
  15513. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15514. { Check if the register is used aferwards - if not, we can
  15515. remove the movzx instruction completely }
  15516. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15517. begin
  15518. { Hp1 is a better position than p for debugging purposes }
  15519. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15520. RemoveCurrentp(p, hp1);
  15521. Result := True;
  15522. end;
  15523. Exit;
  15524. end;
  15525. end;
  15526. end;
  15527. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15528. var
  15529. hp1: tai;
  15530. {$ifdef x86_64}
  15531. PreMessage, RegName: string;
  15532. {$endif x86_64}
  15533. begin
  15534. Result := False;
  15535. { If x is a power of 2 (popcnt = 1), change:
  15536. xor $x, %reg/ref
  15537. To:
  15538. btc lb(x), %reg/ref
  15539. }
  15540. if IsBTXAcceptable(p) and
  15541. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15542. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15543. (
  15544. { Don't optimise if a test instruction follows }
  15545. not GetNextInstruction(p, hp1) or
  15546. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15547. ) then
  15548. begin
  15549. 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);
  15550. taicpu(p).opcode := A_BTC;
  15551. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15552. Result := True;
  15553. Exit;
  15554. end;
  15555. {$ifdef x86_64}
  15556. { Code size reduction by J. Gareth "Kit" Moreton }
  15557. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15558. as this removes the REX prefix }
  15559. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15560. Exit;
  15561. if taicpu(p).oper[0]^.typ <> top_reg then
  15562. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15563. InternalError(2018011500);
  15564. case taicpu(p).opsize of
  15565. S_Q:
  15566. begin
  15567. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15568. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15569. { The actual optimization }
  15570. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15571. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15572. taicpu(p).changeopsize(S_L);
  15573. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15574. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15575. end;
  15576. else
  15577. ;
  15578. end;
  15579. {$endif x86_64}
  15580. end;
  15581. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15582. var
  15583. XReg: TRegister;
  15584. begin
  15585. Result := False;
  15586. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15587. Smaller encoding and slightly faster on some platforms (also works for
  15588. ZMM-sized registers) }
  15589. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15590. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15591. begin
  15592. XReg := taicpu(p).oper[0]^.reg;
  15593. if (taicpu(p).oper[1]^.reg = XReg) then
  15594. begin
  15595. taicpu(p).changeopsize(S_XMM);
  15596. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15597. if (cs_opt_size in current_settings.optimizerswitches) then
  15598. begin
  15599. { Change input registers to %xmm0 to reduce size. Note that
  15600. there's a risk of a false dependency doing this, so only
  15601. optimise for size here }
  15602. XReg := NR_XMM0;
  15603. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15604. end
  15605. else
  15606. begin
  15607. setsubreg(XReg, R_SUBMMX);
  15608. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15609. end;
  15610. taicpu(p).oper[0]^.reg := XReg;
  15611. taicpu(p).oper[1]^.reg := XReg;
  15612. Result := True;
  15613. end;
  15614. end;
  15615. end;
  15616. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15617. var
  15618. OperIdx: Integer;
  15619. begin
  15620. for OperIdx := 0 to p.ops - 1 do
  15621. if p.oper[OperIdx]^.typ = top_ref then
  15622. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15623. end;
  15624. end.