aoptx86.pas 713 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass1STCCLC(var p: tai): Boolean;
  147. function OptPass2Movx(var p : tai): Boolean;
  148. function OptPass2MOV(var p : tai) : boolean;
  149. function OptPass2Imul(var p : tai) : boolean;
  150. function OptPass2Jmp(var p : tai) : boolean;
  151. function OptPass2Jcc(var p : tai) : boolean;
  152. function OptPass2Lea(var p: tai): Boolean;
  153. function OptPass2SUB(var p: tai): Boolean;
  154. function OptPass2ADD(var p : tai): Boolean;
  155. function OptPass2SETcc(var p : tai) : boolean;
  156. function OptPass2Cmp(var p: tai): Boolean;
  157. function OptPass2Test(var p: tai): Boolean;
  158. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  159. function PostPeepholeOptMov(var p : tai) : Boolean;
  160. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  161. function PostPeepholeOptXor(var p : tai) : Boolean;
  162. function PostPeepholeOptAnd(var p : tai) : boolean;
  163. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  164. function PostPeepholeOptCmp(var p : tai) : Boolean;
  165. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  166. function PostPeepholeOptCall(var p : tai) : Boolean;
  167. function PostPeepholeOptLea(var p : tai) : Boolean;
  168. function PostPeepholeOptPush(var p: tai): Boolean;
  169. function PostPeepholeOptShr(var p : tai) : boolean;
  170. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  171. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  172. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  173. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  174. function TrySwapMovOp(var p, hp1: tai): Boolean;
  175. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  176. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  177. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  178. { Processor-dependent reference optimisation }
  179. class procedure OptimizeRefs(var p: taicpu); static;
  180. end;
  181. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  182. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  183. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  184. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  185. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  186. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  187. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  188. {$if max_operands>2}
  189. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  190. {$endif max_operands>2}
  191. function RefsEqual(const r1, r2: treference): boolean;
  192. { Note that Result is set to True if the references COULD overlap but the
  193. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  194. might still overlap because %reg2 could be equal to %reg1-4 }
  195. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  196. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  197. { returns true, if ref is a reference using only the registers passed as base and index
  198. and having an offset }
  199. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  200. implementation
  201. uses
  202. cutils,verbose,
  203. systems,
  204. globals,
  205. cpuinfo,
  206. procinfo,
  207. paramgr,
  208. aasmbase,
  209. aoptbase,aoptutils,
  210. symconst,symsym,
  211. cgx86,
  212. itcpugas;
  213. {$ifndef 8086}
  214. const
  215. MAX_CMOV_INSTRUCTIONS = 4;
  216. MAX_CMOV_REGISTERS = 8;
  217. type
  218. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  219. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  220. tsProcessed);
  221. { For OptPass2Jcc }
  222. TCMOVTracking = object
  223. private
  224. CMOVScore, ConstCount: LongInt;
  225. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  226. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  227. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  228. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  229. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  230. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  231. fOptimizer: TX86AsmOptimizer;
  232. fLabel: TAsmSymbol;
  233. fInsertionPoint,
  234. fCondition,
  235. fInitialJump,
  236. fFirstMovBlock,
  237. fFirstMovBlockStop,
  238. fSecondJump,
  239. fThirdJump,
  240. fSecondMovBlock,
  241. fSecondMovBlockStop,
  242. fMidLabel,
  243. fEndLabel,
  244. fAllocationRange: tai;
  245. fState: TCMovTrackingState;
  246. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  247. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  248. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  249. public
  250. RegisterTracking: TAllUsedRegs;
  251. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  252. destructor Done;
  253. procedure Process(out new_p: tai);
  254. property State: TCMovTrackingState read fState;
  255. end;
  256. PCMOVTracking = ^TCMOVTracking;
  257. {$endif 8086}
  258. {$ifdef DEBUG_AOPTCPU}
  259. const
  260. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  261. {$else DEBUG_AOPTCPU}
  262. { Empty strings help the optimizer to remove string concatenations that won't
  263. ever appear to the user on release builds. [Kit] }
  264. const
  265. SPeepholeOptimization = '';
  266. {$endif DEBUG_AOPTCPU}
  267. LIST_STEP_SIZE = 4;
  268. type
  269. TJumpTrackingItem = class(TLinkedListItem)
  270. private
  271. FSymbol: TAsmSymbol;
  272. FRefs: LongInt;
  273. public
  274. constructor Create(ASymbol: TAsmSymbol);
  275. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  276. property Symbol: TAsmSymbol read FSymbol;
  277. property Refs: LongInt read FRefs;
  278. end;
  279. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  280. begin
  281. inherited Create;
  282. FSymbol := ASymbol;
  283. FRefs := 0;
  284. end;
  285. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. begin
  287. Inc(FRefs);
  288. end;
  289. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  290. begin
  291. result :=
  292. (instr.typ = ait_instruction) and
  293. (taicpu(instr).opcode = op) and
  294. ((opsize = []) or (taicpu(instr).opsize in opsize));
  295. end;
  296. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  297. begin
  298. result :=
  299. (instr.typ = ait_instruction) and
  300. ((taicpu(instr).opcode = op1) or
  301. (taicpu(instr).opcode = op2)
  302. ) and
  303. ((opsize = []) or (taicpu(instr).opsize in opsize));
  304. end;
  305. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  306. begin
  307. result :=
  308. (instr.typ = ait_instruction) and
  309. ((taicpu(instr).opcode = op1) or
  310. (taicpu(instr).opcode = op2) or
  311. (taicpu(instr).opcode = op3)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  316. const opsize : topsizes) : boolean;
  317. var
  318. op : TAsmOp;
  319. begin
  320. result:=false;
  321. if (instr.typ <> ait_instruction) or
  322. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  323. exit;
  324. for op in ops do
  325. begin
  326. if taicpu(instr).opcode = op then
  327. begin
  328. result:=true;
  329. exit;
  330. end;
  331. end;
  332. end;
  333. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  334. begin
  335. result := (oper.typ = top_reg) and (oper.reg = reg);
  336. end;
  337. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  338. begin
  339. result := (oper.typ = top_const) and (oper.val = a);
  340. end;
  341. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  342. begin
  343. result := oper1.typ = oper2.typ;
  344. if result then
  345. case oper1.typ of
  346. top_const:
  347. Result:=oper1.val = oper2.val;
  348. top_reg:
  349. Result:=oper1.reg = oper2.reg;
  350. top_ref:
  351. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  352. else
  353. internalerror(2013102801);
  354. end
  355. end;
  356. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  357. begin
  358. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  359. if result then
  360. case oper1.typ of
  361. top_const:
  362. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  363. top_reg:
  364. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  365. top_ref:
  366. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  367. else
  368. internalerror(2020052401);
  369. end
  370. end;
  371. function RefsEqual(const r1, r2: treference): boolean;
  372. begin
  373. RefsEqual :=
  374. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  375. (r1.relsymbol = r2.relsymbol) and
  376. (r1.segment = r2.segment) and (r1.base = r2.base) and
  377. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  378. (r1.offset = r2.offset) and
  379. (r1.volatility + r2.volatility = []);
  380. end;
  381. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  382. begin
  383. if (r1.symbol<>r2.symbol) then
  384. { If the index registers are different, there's a chance one could
  385. be set so it equals the other symbol }
  386. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  387. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  388. (r1.relsymbol = r2.relsymbol) and
  389. (r1.segment = r2.segment) and (r1.base = r2.base) and
  390. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  391. (r1.volatility + r2.volatility = []) then
  392. { In this case, it all depends on the offsets }
  393. Exit(abs(r1.offset - r2.offset) < Range);
  394. { There's a chance things MIGHT overlap, so take no chances }
  395. Result := True;
  396. end;
  397. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  398. begin
  399. Result:=(ref.offset=0) and
  400. (ref.scalefactor in [0,1]) and
  401. (ref.segment=NR_NO) and
  402. (ref.symbol=nil) and
  403. (ref.relsymbol=nil) and
  404. ((base=NR_INVALID) or
  405. (ref.base=base)) and
  406. ((index=NR_INVALID) or
  407. (ref.index=index)) and
  408. (ref.volatility=[]);
  409. end;
  410. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  411. begin
  412. Result:=(ref.scalefactor in [0,1]) and
  413. (ref.segment=NR_NO) and
  414. (ref.symbol=nil) and
  415. (ref.relsymbol=nil) and
  416. ((base=NR_INVALID) or
  417. (ref.base=base)) and
  418. ((index=NR_INVALID) or
  419. (ref.index=index)) and
  420. (ref.volatility=[]);
  421. end;
  422. function InstrReadsFlags(p: tai): boolean;
  423. begin
  424. InstrReadsFlags := true;
  425. case p.typ of
  426. ait_instruction:
  427. if InsProp[taicpu(p).opcode].Ch*
  428. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  429. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  430. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  431. exit;
  432. ait_label:
  433. exit;
  434. else
  435. ;
  436. end;
  437. InstrReadsFlags := false;
  438. end;
  439. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  440. begin
  441. Next:=Current;
  442. repeat
  443. Result:=GetNextInstruction(Next,Next);
  444. until not (Result) or
  445. not(cs_opt_level3 in current_settings.optimizerswitches) or
  446. (Next.typ<>ait_instruction) or
  447. RegInInstruction(reg,Next) or
  448. is_calljmp(taicpu(Next).opcode);
  449. end;
  450. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  451. var
  452. GetNextResult: Boolean;
  453. begin
  454. Result:=0;
  455. Next:=Current;
  456. repeat
  457. GetNextResult := GetNextInstruction(Next,Next);
  458. if GetNextResult then
  459. Inc(Result)
  460. else
  461. { Must return zero upon hitting the end of the linked list without a match }
  462. Result := 0;
  463. until not (GetNextResult) or
  464. not(cs_opt_level3 in current_settings.optimizerswitches) or
  465. (Next.typ<>ait_instruction) or
  466. RegInInstruction(reg,Next) or
  467. is_calljmp(taicpu(Next).opcode);
  468. end;
  469. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  470. procedure TrackJump(Symbol: TAsmSymbol);
  471. var
  472. Search: TJumpTrackingItem;
  473. begin
  474. { See if an entry already exists in our jump tracking list
  475. (faster to search backwards due to the higher chance of
  476. matching destinations) }
  477. Search := TJumpTrackingItem(JumpTracking.Last);
  478. while Assigned(Search) do
  479. begin
  480. if Search.Symbol = Symbol then
  481. begin
  482. { Found it - remove it so it can be pushed to the front }
  483. JumpTracking.Remove(Search);
  484. Break;
  485. end;
  486. Search := TJumpTrackingItem(Search.Previous);
  487. end;
  488. if not Assigned(Search) then
  489. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  490. JumpTracking.Concat(Search);
  491. Search.IncRefs;
  492. end;
  493. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  494. var
  495. Search: TJumpTrackingItem;
  496. begin
  497. Result := False;
  498. { See if this label appears in the tracking list }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - let's see what we can discover }
  505. if Search.Symbol.getrefs = Search.Refs then
  506. begin
  507. { Success - all the references are accounted for }
  508. JumpTracking.Remove(Search);
  509. Search.Free;
  510. { It is logically impossible for CrossJump to be false here
  511. because we must have run into a conditional jump for
  512. this label at some point }
  513. if not CrossJump then
  514. InternalError(2022041710);
  515. if JumpTracking.First = nil then
  516. { Tracking list is now empty - no more cross jumps }
  517. CrossJump := False;
  518. Result := True;
  519. Exit;
  520. end;
  521. { If the references don't match, it's possible to enter
  522. this label through other means, so drop out }
  523. Exit;
  524. end;
  525. Search := TJumpTrackingItem(Search.Previous);
  526. end;
  527. end;
  528. var
  529. Next_Label: tai;
  530. begin
  531. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  532. Next := Current;
  533. repeat
  534. Result := GetNextInstruction(Next,Next);
  535. if not Result then
  536. Break;
  537. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  538. if is_calljmpuncondret(taicpu(Next).opcode) then
  539. begin
  540. if (taicpu(Next).opcode = A_JMP) and
  541. { Remove dead code now to save time }
  542. RemoveDeadCodeAfterJump(taicpu(Next)) then
  543. { A jump was removed, but not the current instruction, and
  544. Result doesn't necessarily translate into an optimisation
  545. routine's Result, so use the "Force New Iteration" flag so
  546. mark a new pass }
  547. Include(OptsToCheck, aoc_ForceNewIteration);
  548. if not Assigned(JumpTracking) then
  549. begin
  550. { Cross-label optimisations often causes other optimisations
  551. to perform worse because they're not given the chance to
  552. optimise locally. In this case, don't do the cross-label
  553. optimisations yet, but flag them as a potential possibility
  554. for the next iteration of Pass 1 }
  555. if not NotFirstIteration then
  556. Include(OptsToCheck, aoc_ForceNewIteration);
  557. end
  558. else if IsJumpToLabel(taicpu(Next)) and
  559. GetNextInstruction(Next, Next_Label) then
  560. begin
  561. { If we have JMP .lbl, and the label after it has all of its
  562. references tracked, then this is probably an if-else style of
  563. block and we can keep tracking. If the label for this jump
  564. then appears later and is fully tracked, then it's the end
  565. of the if-else blocks and the code paths converge (thus
  566. marking the end of the cross-jump) }
  567. if (Next_Label.typ = ait_label) then
  568. begin
  569. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  570. begin
  571. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  572. Next := Next_Label;
  573. { CrossJump gets set to false by LabelAccountedFor if the
  574. list is completely emptied (as it indicates that all
  575. code paths have converged). We could avoid this nuance
  576. by moving the TrackJump call to before the
  577. LabelAccountedFor call, but this is slower in situations
  578. where LabelAccountedFor would return False due to the
  579. creation of a new object that is not used and destroyed
  580. soon after. }
  581. CrossJump := True;
  582. Continue;
  583. end;
  584. end
  585. else if (Next_Label.typ <> ait_marker) then
  586. { We just did a RemoveDeadCodeAfterJump, so either we find
  587. a label, the end of the procedure or some kind of marker}
  588. InternalError(2022041720);
  589. end;
  590. Result := False;
  591. Exit;
  592. end
  593. else
  594. begin
  595. if not Assigned(JumpTracking) then
  596. begin
  597. { Cross-label optimisations often causes other optimisations
  598. to perform worse because they're not given the chance to
  599. optimise locally. In this case, don't do the cross-label
  600. optimisations yet, but flag them as a potential possibility
  601. for the next iteration of Pass 1 }
  602. if not NotFirstIteration then
  603. Include(OptsToCheck, aoc_ForceNewIteration);
  604. end
  605. else if IsJumpToLabel(taicpu(Next)) then
  606. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  607. else
  608. { Conditional jumps should always be a jump to label }
  609. InternalError(2022041701);
  610. CrossJump := True;
  611. Continue;
  612. end;
  613. if Next.typ = ait_label then
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if LabelAccountedFor(tai_label(Next).labsym) then
  626. Continue;
  627. { If we reach here, we're at a label that hasn't been seen before
  628. (or JumpTracking was nil) }
  629. Break;
  630. end;
  631. until not Result or
  632. not (cs_opt_level3 in current_settings.optimizerswitches) or
  633. not (Next.typ in [ait_label, ait_instruction]) or
  634. RegInInstruction(reg,Next);
  635. end;
  636. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  637. begin
  638. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  639. begin
  640. Result:=GetNextInstruction(Current,Next);
  641. exit;
  642. end;
  643. Next:=tai(Current.Next);
  644. Result:=false;
  645. while assigned(Next) do
  646. begin
  647. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  648. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  649. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  650. exit
  651. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  652. begin
  653. Result:=true;
  654. exit;
  655. end;
  656. Next:=tai(Next.Next);
  657. end;
  658. end;
  659. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  660. begin
  661. Result:=RegReadByInstruction(reg,hp);
  662. end;
  663. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  664. var
  665. p: taicpu;
  666. opcount: longint;
  667. begin
  668. RegReadByInstruction := false;
  669. if hp.typ <> ait_instruction then
  670. exit;
  671. p := taicpu(hp);
  672. case p.opcode of
  673. A_CALL:
  674. regreadbyinstruction := true;
  675. A_IMUL:
  676. case p.ops of
  677. 1:
  678. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  679. (
  680. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  681. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  682. );
  683. 2,3:
  684. regReadByInstruction :=
  685. reginop(reg,p.oper[0]^) or
  686. reginop(reg,p.oper[1]^);
  687. else
  688. InternalError(2019112801);
  689. end;
  690. A_MUL:
  691. begin
  692. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  693. (
  694. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  695. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  696. );
  697. end;
  698. A_IDIV,A_DIV:
  699. begin
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. (getregtype(reg)=R_INTREGISTER) and
  703. (
  704. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  705. )
  706. );
  707. end;
  708. else
  709. begin
  710. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  711. begin
  712. RegReadByInstruction := false;
  713. exit;
  714. end;
  715. for opcount := 0 to p.ops-1 do
  716. if (p.oper[opCount]^.typ = top_ref) and
  717. RegInRef(reg,p.oper[opcount]^.ref^) then
  718. begin
  719. RegReadByInstruction := true;
  720. exit
  721. end;
  722. { special handling for SSE MOVSD }
  723. if (p.opcode=A_MOVSD) and (p.ops>0) then
  724. begin
  725. if p.ops<>2 then
  726. internalerror(2017042702);
  727. regReadByInstruction := reginop(reg,p.oper[0]^) or
  728. (
  729. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  730. );
  731. exit;
  732. end;
  733. with insprop[p.opcode] do
  734. begin
  735. case getregtype(reg) of
  736. R_INTREGISTER:
  737. begin
  738. case getsupreg(reg) of
  739. RS_EAX:
  740. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  741. begin
  742. RegReadByInstruction := true;
  743. exit
  744. end;
  745. RS_ECX:
  746. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  747. begin
  748. RegReadByInstruction := true;
  749. exit
  750. end;
  751. RS_EDX:
  752. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  753. begin
  754. RegReadByInstruction := true;
  755. exit
  756. end;
  757. RS_EBX:
  758. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  759. begin
  760. RegReadByInstruction := true;
  761. exit
  762. end;
  763. RS_ESP:
  764. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  765. begin
  766. RegReadByInstruction := true;
  767. exit
  768. end;
  769. RS_EBP:
  770. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  771. begin
  772. RegReadByInstruction := true;
  773. exit
  774. end;
  775. RS_ESI:
  776. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  777. begin
  778. RegReadByInstruction := true;
  779. exit
  780. end;
  781. RS_EDI:
  782. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  783. begin
  784. RegReadByInstruction := true;
  785. exit
  786. end;
  787. end;
  788. end;
  789. R_MMREGISTER:
  790. begin
  791. case getsupreg(reg) of
  792. RS_XMM0:
  793. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  794. begin
  795. RegReadByInstruction := true;
  796. exit
  797. end;
  798. end;
  799. end;
  800. else
  801. ;
  802. end;
  803. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  804. begin
  805. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  806. begin
  807. case p.condition of
  808. C_A,C_NBE, { CF=0 and ZF=0 }
  809. C_BE,C_NA: { CF=1 or ZF=1 }
  810. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  811. C_AE,C_NB,C_NC, { CF=0 }
  812. C_B,C_NAE,C_C: { CF=1 }
  813. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  814. C_NE,C_NZ, { ZF=0 }
  815. C_E,C_Z: { ZF=1 }
  816. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  817. C_G,C_NLE, { ZF=0 and SF=OF }
  818. C_LE,C_NG: { ZF=1 or SF<>OF }
  819. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  820. C_GE,C_NL, { SF=OF }
  821. C_L,C_NGE: { SF<>OF }
  822. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  823. C_NO, { OF=0 }
  824. C_O: { OF=1 }
  825. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  826. C_NP,C_PO, { PF=0 }
  827. C_P,C_PE: { PF=1 }
  828. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  829. C_NS, { SF=0 }
  830. C_S: { SF=1 }
  831. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  832. else
  833. internalerror(2017042701);
  834. end;
  835. if RegReadByInstruction then
  836. exit;
  837. end;
  838. case getsubreg(reg) of
  839. R_SUBW,R_SUBD,R_SUBQ:
  840. RegReadByInstruction :=
  841. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  842. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  843. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  844. R_SUBFLAGCARRY:
  845. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  846. R_SUBFLAGPARITY:
  847. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGAUXILIARY:
  849. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGZERO:
  851. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGSIGN:
  853. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGOVERFLOW:
  855. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGINTERRUPT:
  857. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGDIRECTION:
  859. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. else
  861. internalerror(2017042601);
  862. end;
  863. exit;
  864. end;
  865. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  866. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  867. (p.oper[0]^.reg=p.oper[1]^.reg) then
  868. exit;
  869. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  870. begin
  871. RegReadByInstruction := true;
  872. exit
  873. end;
  874. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  875. begin
  876. RegReadByInstruction := true;
  877. exit
  878. end;
  879. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  880. begin
  881. RegReadByInstruction := true;
  882. exit
  883. end;
  884. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  885. begin
  886. RegReadByInstruction := true;
  887. exit
  888. end;
  889. end;
  890. end;
  891. end;
  892. end;
  893. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  894. begin
  895. result:=false;
  896. if p1.typ<>ait_instruction then
  897. exit;
  898. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  899. exit(true);
  900. if (getregtype(reg)=R_INTREGISTER) and
  901. { change information for xmm movsd are not correct }
  902. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  903. begin
  904. { Handle instructions that behave differently depending on the size and operand count }
  905. case taicpu(p1).opcode of
  906. A_MUL, A_DIV, A_IDIV:
  907. if taicpu(p1).opsize = S_B then
  908. Result := (getsupreg(Reg) = RS_EAX)
  909. else
  910. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  911. A_IMUL:
  912. if taicpu(p1).ops = 1 then
  913. begin
  914. if taicpu(p1).opsize = S_B then
  915. Result := (getsupreg(Reg) = RS_EAX)
  916. else
  917. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  918. end;
  919. { If ops are greater than 1, call inherited method }
  920. else
  921. case getsupreg(reg) of
  922. { RS_EAX = RS_RAX on x86-64 }
  923. RS_EAX:
  924. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  925. RS_ECX:
  926. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_EDX:
  928. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_EBX:
  930. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_ESP:
  932. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBP:
  934. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESI:
  936. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EDI:
  938. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. else
  940. ;
  941. end;
  942. end;
  943. if result then
  944. exit;
  945. end
  946. else if getregtype(reg)=R_MMREGISTER then
  947. begin
  948. case getsupreg(reg) of
  949. RS_XMM0:
  950. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. else
  952. ;
  953. end;
  954. if result then
  955. exit;
  956. end
  957. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  958. begin
  959. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  960. exit(true);
  961. case getsubreg(reg) of
  962. R_SUBFLAGCARRY:
  963. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  964. R_SUBFLAGPARITY:
  965. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGAUXILIARY:
  967. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGZERO:
  969. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGSIGN:
  971. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGOVERFLOW:
  973. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGINTERRUPT:
  975. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGDIRECTION:
  977. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBW,R_SUBD,R_SUBQ:
  979. { Everything except the direction bits }
  980. Result:=
  981. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  982. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  983. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  984. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  985. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  986. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  987. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. else
  989. ;
  990. end;
  991. if result then
  992. exit;
  993. end
  994. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  995. exit(true);
  996. Result:=inherited RegInInstruction(Reg, p1);
  997. end;
  998. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  999. const
  1000. WriteOps: array[0..3] of set of TInsChange =
  1001. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1002. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1003. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1004. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1005. var
  1006. OperIdx: Integer;
  1007. begin
  1008. Result := False;
  1009. if p1.typ <> ait_instruction then
  1010. exit;
  1011. with insprop[taicpu(p1).opcode] do
  1012. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1013. begin
  1014. case getsubreg(reg) of
  1015. R_SUBW,R_SUBD,R_SUBQ:
  1016. Result :=
  1017. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1018. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1019. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1020. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1021. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1022. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1023. R_SUBFLAGCARRY:
  1024. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGPARITY:
  1026. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGAUXILIARY:
  1028. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGZERO:
  1030. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGSIGN:
  1032. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGOVERFLOW:
  1034. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGINTERRUPT:
  1036. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGDIRECTION:
  1038. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. else
  1040. internalerror(2017042602);
  1041. end;
  1042. exit;
  1043. end;
  1044. case taicpu(p1).opcode of
  1045. A_CALL:
  1046. { We could potentially set Result to False if the register in
  1047. question is non-volatile for the subroutine's calling convention,
  1048. but this would require detecting the calling convention in use and
  1049. also assuming that the routine doesn't contain malformed assembly
  1050. language, for example... so it could only be done under -O4 as it
  1051. would be considered a side-effect. [Kit] }
  1052. Result := True;
  1053. A_MOVSD:
  1054. { special handling for SSE MOVSD }
  1055. if (taicpu(p1).ops>0) then
  1056. begin
  1057. if taicpu(p1).ops<>2 then
  1058. internalerror(2017042703);
  1059. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1060. end;
  1061. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1062. so fix it here (FK)
  1063. }
  1064. A_VMOVSS,
  1065. A_VMOVSD:
  1066. begin
  1067. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1068. exit;
  1069. end;
  1070. A_MUL, A_DIV, A_IDIV:
  1071. begin
  1072. if taicpu(p1).opsize = S_B then
  1073. Result := (getsupreg(Reg) = RS_EAX)
  1074. else
  1075. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1076. end;
  1077. A_IMUL:
  1078. begin
  1079. if taicpu(p1).ops = 1 then
  1080. begin
  1081. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1082. end
  1083. else
  1084. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1085. Exit;
  1086. end;
  1087. else
  1088. ;
  1089. end;
  1090. if Result then
  1091. exit;
  1092. with insprop[taicpu(p1).opcode] do
  1093. begin
  1094. if getregtype(reg)=R_INTREGISTER then
  1095. begin
  1096. case getsupreg(reg) of
  1097. RS_EAX:
  1098. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1099. begin
  1100. Result := True;
  1101. exit
  1102. end;
  1103. RS_ECX:
  1104. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1105. begin
  1106. Result := True;
  1107. exit
  1108. end;
  1109. RS_EDX:
  1110. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1111. begin
  1112. Result := True;
  1113. exit
  1114. end;
  1115. RS_EBX:
  1116. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1117. begin
  1118. Result := True;
  1119. exit
  1120. end;
  1121. RS_ESP:
  1122. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1123. begin
  1124. Result := True;
  1125. exit
  1126. end;
  1127. RS_EBP:
  1128. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1129. begin
  1130. Result := True;
  1131. exit
  1132. end;
  1133. RS_ESI:
  1134. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1135. begin
  1136. Result := True;
  1137. exit
  1138. end;
  1139. RS_EDI:
  1140. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1141. begin
  1142. Result := True;
  1143. exit
  1144. end;
  1145. end;
  1146. end;
  1147. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1148. if (WriteOps[OperIdx]*Ch<>[]) and
  1149. { The register doesn't get modified inside a reference }
  1150. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1151. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1152. begin
  1153. Result := true;
  1154. exit
  1155. end;
  1156. end;
  1157. end;
  1158. {$ifdef DEBUG_AOPTCPU}
  1159. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1160. begin
  1161. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1162. end;
  1163. function debug_tostr(i: tcgint): string; inline;
  1164. begin
  1165. Result := tostr(i);
  1166. end;
  1167. function debug_hexstr(i: tcgint): string;
  1168. begin
  1169. Result := '0x';
  1170. case i of
  1171. 0..$FF:
  1172. Result := Result + hexstr(i, 2);
  1173. $100..$FFFF:
  1174. Result := Result + hexstr(i, 4);
  1175. $10000..$FFFFFF:
  1176. Result := Result + hexstr(i, 6);
  1177. $1000000..$FFFFFFFF:
  1178. Result := Result + hexstr(i, 8);
  1179. else
  1180. Result := Result + hexstr(i, 16);
  1181. end;
  1182. end;
  1183. function debug_regname(r: TRegister): string; inline;
  1184. begin
  1185. Result := '%' + std_regname(r);
  1186. end;
  1187. { Debug output function - creates a string representation of an operator }
  1188. function debug_operstr(oper: TOper): string;
  1189. begin
  1190. case oper.typ of
  1191. top_const:
  1192. Result := '$' + debug_tostr(oper.val);
  1193. top_reg:
  1194. Result := debug_regname(oper.reg);
  1195. top_ref:
  1196. begin
  1197. if oper.ref^.offset <> 0 then
  1198. Result := debug_tostr(oper.ref^.offset) + '('
  1199. else
  1200. Result := '(';
  1201. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1202. begin
  1203. Result := Result + debug_regname(oper.ref^.base);
  1204. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1205. Result := Result + ',' + debug_regname(oper.ref^.index);
  1206. end
  1207. else
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + debug_regname(oper.ref^.index);
  1210. if (oper.ref^.scalefactor > 1) then
  1211. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1212. else
  1213. Result := Result + ')';
  1214. end;
  1215. else
  1216. Result := '[UNKNOWN]';
  1217. end;
  1218. end;
  1219. function debug_op2str(opcode: tasmop): string; inline;
  1220. begin
  1221. Result := std_op2str[opcode];
  1222. end;
  1223. function debug_opsize2str(opsize: topsize): string; inline;
  1224. begin
  1225. Result := gas_opsize2str[opsize];
  1226. end;
  1227. {$else DEBUG_AOPTCPU}
  1228. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1229. begin
  1230. end;
  1231. function debug_tostr(i: tcgint): string; inline;
  1232. begin
  1233. Result := '';
  1234. end;
  1235. function debug_hexstr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_regname(r: TRegister): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_operstr(oper: TOper): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_op2str(opcode: tasmop): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_opsize2str(opsize: topsize): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. {$endif DEBUG_AOPTCPU}
  1256. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1257. begin
  1258. {$ifdef x86_64}
  1259. { Always fine on x86-64 }
  1260. Result := True;
  1261. {$else x86_64}
  1262. Result :=
  1263. {$ifdef i8086}
  1264. (current_settings.cputype >= cpu_386) and
  1265. {$endif i8086}
  1266. (
  1267. { Always accept if optimising for size }
  1268. (cs_opt_size in current_settings.optimizerswitches) or
  1269. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1270. (current_settings.optimizecputype >= cpu_Pentium2)
  1271. );
  1272. {$endif x86_64}
  1273. end;
  1274. { Attempts to allocate a volatile integer register for use between p and hp,
  1275. using AUsedRegs for the current register usage information. Returns NR_NO
  1276. if no free register could be found }
  1277. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1278. var
  1279. RegSet: TCPURegisterSet;
  1280. CurrentSuperReg: Integer;
  1281. CurrentReg: TRegister;
  1282. Currentp: tai;
  1283. Breakout: Boolean;
  1284. begin
  1285. Result := NR_NO;
  1286. RegSet :=
  1287. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1288. current_procinfo.saved_regs_int;
  1289. (*
  1290. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1291. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1292. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1293. *)
  1294. for CurrentSuperReg in RegSet do
  1295. begin
  1296. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1297. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1298. {$if defined(i386) or defined(i8086)}
  1299. { If the target size is 8-bit, make sure we can actually encode it }
  1300. and (
  1301. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1302. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1303. )
  1304. {$endif i386 or i8086}
  1305. then
  1306. begin
  1307. Currentp := p;
  1308. Breakout := False;
  1309. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1310. begin
  1311. case Currentp.typ of
  1312. ait_instruction:
  1313. begin
  1314. if RegInInstruction(CurrentReg, Currentp) then
  1315. begin
  1316. Breakout := True;
  1317. Break;
  1318. end;
  1319. { Cannot allocate across an unconditional jump }
  1320. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1321. Exit;
  1322. end;
  1323. ait_marker:
  1324. { Don't try anything more if a marker is hit }
  1325. Exit;
  1326. ait_regalloc:
  1327. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1328. begin
  1329. Breakout := True;
  1330. Break;
  1331. end;
  1332. else
  1333. ;
  1334. end;
  1335. end;
  1336. if Breakout then
  1337. { Try the next register }
  1338. Continue;
  1339. { We have a free register available }
  1340. Result := CurrentReg;
  1341. if not DontAlloc then
  1342. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1343. Exit;
  1344. end;
  1345. end;
  1346. end;
  1347. { Attempts to allocate a volatile MM register for use between p and hp,
  1348. using AUsedRegs for the current register usage information. Returns NR_NO
  1349. if no free register could be found }
  1350. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1351. var
  1352. RegSet: TCPURegisterSet;
  1353. CurrentSuperReg: Integer;
  1354. CurrentReg: TRegister;
  1355. Currentp: tai;
  1356. Breakout: Boolean;
  1357. begin
  1358. Result := NR_NO;
  1359. RegSet :=
  1360. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1361. current_procinfo.saved_regs_mm;
  1362. for CurrentSuperReg in RegSet do
  1363. begin
  1364. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1365. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1366. begin
  1367. Currentp := p;
  1368. Breakout := False;
  1369. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1370. begin
  1371. case Currentp.typ of
  1372. ait_instruction:
  1373. begin
  1374. if RegInInstruction(CurrentReg, Currentp) then
  1375. begin
  1376. Breakout := True;
  1377. Break;
  1378. end;
  1379. { Cannot allocate across an unconditional jump }
  1380. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1381. Exit;
  1382. end;
  1383. ait_marker:
  1384. { Don't try anything more if a marker is hit }
  1385. Exit;
  1386. ait_regalloc:
  1387. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1388. begin
  1389. Breakout := True;
  1390. Break;
  1391. end;
  1392. else
  1393. ;
  1394. end;
  1395. end;
  1396. if Breakout then
  1397. { Try the next register }
  1398. Continue;
  1399. { We have a free register available }
  1400. Result := CurrentReg;
  1401. if not DontAlloc then
  1402. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1403. Exit;
  1404. end;
  1405. end;
  1406. end;
  1407. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1408. begin
  1409. if not SuperRegistersEqual(reg1,reg2) then
  1410. exit(false);
  1411. if getregtype(reg1)<>R_INTREGISTER then
  1412. exit(true); {because SuperRegisterEqual is true}
  1413. case getsubreg(reg1) of
  1414. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1415. higher, it preserves the high bits, so the new value depends on
  1416. reg2's previous value. In other words, it is equivalent to doing:
  1417. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1418. R_SUBL:
  1419. exit(getsubreg(reg2)=R_SUBL);
  1420. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1421. higher, it actually does a:
  1422. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1423. R_SUBH:
  1424. exit(getsubreg(reg2)=R_SUBH);
  1425. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1426. bits of reg2:
  1427. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1428. R_SUBW:
  1429. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1430. { a write to R_SUBD always overwrites every other subregister,
  1431. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1432. R_SUBD,
  1433. R_SUBQ:
  1434. exit(true);
  1435. else
  1436. internalerror(2017042801);
  1437. end;
  1438. end;
  1439. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1440. begin
  1441. if not SuperRegistersEqual(reg1,reg2) then
  1442. exit(false);
  1443. if getregtype(reg1)<>R_INTREGISTER then
  1444. exit(true); {because SuperRegisterEqual is true}
  1445. case getsubreg(reg1) of
  1446. R_SUBL:
  1447. exit(getsubreg(reg2)<>R_SUBH);
  1448. R_SUBH:
  1449. exit(getsubreg(reg2)<>R_SUBL);
  1450. R_SUBW,
  1451. R_SUBD,
  1452. R_SUBQ:
  1453. exit(true);
  1454. else
  1455. internalerror(2017042802);
  1456. end;
  1457. end;
  1458. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1459. var
  1460. hp1 : tai;
  1461. l : TCGInt;
  1462. begin
  1463. result:=false;
  1464. if not(GetNextInstruction(p, hp1)) then
  1465. exit;
  1466. { changes the code sequence
  1467. shr/sar const1, x
  1468. shl const2, x
  1469. to
  1470. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1471. if (taicpu(p).oper[0]^.typ = top_const) and
  1472. MatchInstruction(hp1,A_SHL,[]) and
  1473. (taicpu(hp1).oper[0]^.typ = top_const) and
  1474. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1475. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1476. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1477. begin
  1478. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1479. not(cs_opt_size in current_settings.optimizerswitches) then
  1480. begin
  1481. { shr/sar const1, %reg
  1482. shl const2, %reg
  1483. with const1 > const2 }
  1484. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1485. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1486. taicpu(hp1).opcode := A_AND;
  1487. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1488. case taicpu(p).opsize Of
  1489. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1490. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1491. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1492. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1493. else
  1494. Internalerror(2017050703)
  1495. end;
  1496. end
  1497. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1498. not(cs_opt_size in current_settings.optimizerswitches) then
  1499. begin
  1500. { shr/sar const1, %reg
  1501. shl const2, %reg
  1502. with const1 < const2 }
  1503. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1504. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1505. taicpu(p).opcode := A_AND;
  1506. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1507. case taicpu(p).opsize Of
  1508. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1509. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1510. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1511. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1512. else
  1513. Internalerror(2017050702)
  1514. end;
  1515. end
  1516. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1517. begin
  1518. { shr/sar const1, %reg
  1519. shl const2, %reg
  1520. with const1 = const2 }
  1521. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1522. taicpu(p).opcode := A_AND;
  1523. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1524. case taicpu(p).opsize Of
  1525. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1526. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1527. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1528. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1529. else
  1530. Internalerror(2017050701)
  1531. end;
  1532. RemoveInstruction(hp1);
  1533. end;
  1534. end;
  1535. end;
  1536. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1537. var
  1538. opsize : topsize;
  1539. hp1, hp2 : tai;
  1540. tmpref : treference;
  1541. ShiftValue : Cardinal;
  1542. BaseValue : TCGInt;
  1543. begin
  1544. result:=false;
  1545. opsize:=taicpu(p).opsize;
  1546. { changes certain "imul const, %reg"'s to lea sequences }
  1547. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1548. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1549. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1550. if (taicpu(p).oper[0]^.val = 1) then
  1551. if (taicpu(p).ops = 2) then
  1552. { remove "imul $1, reg" }
  1553. begin
  1554. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1555. Result := RemoveCurrentP(p);
  1556. end
  1557. else
  1558. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1559. begin
  1560. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1561. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1562. asml.InsertAfter(hp1, p);
  1563. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1564. RemoveCurrentP(p, hp1);
  1565. Result := True;
  1566. end
  1567. else if ((taicpu(p).ops <= 2) or
  1568. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1569. not(cs_opt_size in current_settings.optimizerswitches) and
  1570. (not(GetNextInstruction(p, hp1)) or
  1571. not((tai(hp1).typ = ait_instruction) and
  1572. ((taicpu(hp1).opcode=A_Jcc) and
  1573. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1574. begin
  1575. {
  1576. imul X, reg1, reg2 to
  1577. lea (reg1,reg1,Y), reg2
  1578. shl ZZ,reg2
  1579. imul XX, reg1 to
  1580. lea (reg1,reg1,YY), reg1
  1581. shl ZZ,reg2
  1582. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1583. it does not exist as a separate optimization target in FPC though.
  1584. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1585. at most two zeros
  1586. }
  1587. reference_reset(tmpref,1,[]);
  1588. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1589. begin
  1590. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1591. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1592. TmpRef.base := taicpu(p).oper[1]^.reg;
  1593. TmpRef.index := taicpu(p).oper[1]^.reg;
  1594. if not(BaseValue in [3,5,9]) then
  1595. Internalerror(2018110101);
  1596. TmpRef.ScaleFactor := BaseValue-1;
  1597. if (taicpu(p).ops = 2) then
  1598. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1599. else
  1600. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1601. AsmL.InsertAfter(hp1,p);
  1602. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1603. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1604. RemoveCurrentP(p, hp1);
  1605. if ShiftValue>0 then
  1606. begin
  1607. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1608. AsmL.InsertAfter(hp2,hp1);
  1609. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1610. end;
  1611. Result := True;
  1612. end;
  1613. end;
  1614. end;
  1615. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1616. begin
  1617. Result := False;
  1618. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1619. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1620. begin
  1621. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1622. taicpu(p).opcode := A_MOV;
  1623. Result := True;
  1624. end;
  1625. end;
  1626. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1627. var
  1628. p: taicpu absolute hp; { Implicit typecast }
  1629. i: Integer;
  1630. begin
  1631. Result := False;
  1632. if not assigned(hp) or
  1633. (hp.typ <> ait_instruction) then
  1634. Exit;
  1635. Prefetch(insprop[p.opcode]);
  1636. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1637. with insprop[p.opcode] do
  1638. begin
  1639. case getsubreg(reg) of
  1640. R_SUBW,R_SUBD,R_SUBQ:
  1641. Result:=
  1642. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1643. uncommon flags are checked first }
  1644. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1645. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1646. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1647. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1648. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1650. R_SUBFLAGCARRY:
  1651. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1652. R_SUBFLAGPARITY:
  1653. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGAUXILIARY:
  1655. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGZERO:
  1657. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGSIGN:
  1659. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGOVERFLOW:
  1661. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGINTERRUPT:
  1663. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGDIRECTION:
  1665. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1666. else
  1667. internalerror(2017050501);
  1668. end;
  1669. exit;
  1670. end;
  1671. { Handle special cases first }
  1672. case p.opcode of
  1673. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1674. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1675. begin
  1676. Result :=
  1677. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1678. (p.oper[1]^.typ = top_reg) and
  1679. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1680. (
  1681. (p.oper[0]^.typ = top_const) or
  1682. (
  1683. (p.oper[0]^.typ = top_reg) and
  1684. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1685. ) or (
  1686. (p.oper[0]^.typ = top_ref) and
  1687. not RegInRef(reg,p.oper[0]^.ref^)
  1688. )
  1689. );
  1690. end;
  1691. A_MUL, A_IMUL:
  1692. Result :=
  1693. (
  1694. (p.ops=3) and { IMUL only }
  1695. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1696. (
  1697. (
  1698. (p.oper[1]^.typ=top_reg) and
  1699. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1700. ) or (
  1701. (p.oper[1]^.typ=top_ref) and
  1702. not RegInRef(reg,p.oper[1]^.ref^)
  1703. )
  1704. )
  1705. ) or (
  1706. (
  1707. (p.ops=1) and
  1708. (
  1709. (
  1710. (
  1711. (p.oper[0]^.typ=top_reg) and
  1712. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1713. )
  1714. ) or (
  1715. (p.oper[0]^.typ=top_ref) and
  1716. not RegInRef(reg,p.oper[0]^.ref^)
  1717. )
  1718. ) and (
  1719. (
  1720. (p.opsize=S_B) and
  1721. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1722. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1723. ) or (
  1724. (p.opsize=S_W) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1726. ) or (
  1727. (p.opsize=S_L) and
  1728. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1729. {$ifdef x86_64}
  1730. ) or (
  1731. (p.opsize=S_Q) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1733. {$endif x86_64}
  1734. )
  1735. )
  1736. )
  1737. );
  1738. A_CBW:
  1739. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1740. {$ifndef x86_64}
  1741. A_LDS:
  1742. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1743. A_LES:
  1744. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1745. {$endif not x86_64}
  1746. A_LFS:
  1747. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1748. A_LGS:
  1749. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LSS:
  1751. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1753. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1754. A_LODSB:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1756. A_LODSW:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1758. {$ifdef x86_64}
  1759. A_LODSQ:
  1760. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1761. {$endif x86_64}
  1762. A_LODSD:
  1763. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1764. A_FSTSW, A_FNSTSW:
  1765. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1766. else
  1767. begin
  1768. with insprop[p.opcode] do
  1769. begin
  1770. if (
  1771. { xor %reg,%reg etc. is classed as a new value }
  1772. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1773. MatchOpType(p, top_reg, top_reg) and
  1774. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1775. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1776. ) then
  1777. begin
  1778. Result := True;
  1779. Exit;
  1780. end;
  1781. { Make sure the entire register is overwritten }
  1782. if (getregtype(reg) = R_INTREGISTER) then
  1783. begin
  1784. if (p.ops > 0) then
  1785. begin
  1786. if RegInOp(reg, p.oper[0]^) then
  1787. begin
  1788. if (p.oper[0]^.typ = top_ref) then
  1789. begin
  1790. if RegInRef(reg, p.oper[0]^.ref^) then
  1791. begin
  1792. Result := False;
  1793. Exit;
  1794. end;
  1795. end
  1796. else if (p.oper[0]^.typ = top_reg) then
  1797. begin
  1798. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1799. begin
  1800. Result := False;
  1801. Exit;
  1802. end
  1803. else if ([Ch_WOp1]*Ch<>[]) then
  1804. begin
  1805. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1806. Result := True
  1807. else
  1808. begin
  1809. Result := False;
  1810. Exit;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. if (p.ops > 1) then
  1816. begin
  1817. if RegInOp(reg, p.oper[1]^) then
  1818. begin
  1819. if (p.oper[1]^.typ = top_ref) then
  1820. begin
  1821. if RegInRef(reg, p.oper[1]^.ref^) then
  1822. begin
  1823. Result := False;
  1824. Exit;
  1825. end;
  1826. end
  1827. else if (p.oper[1]^.typ = top_reg) then
  1828. begin
  1829. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1830. begin
  1831. Result := False;
  1832. Exit;
  1833. end
  1834. else if ([Ch_WOp2]*Ch<>[]) then
  1835. begin
  1836. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1837. Result := True
  1838. else
  1839. begin
  1840. Result := False;
  1841. Exit;
  1842. end;
  1843. end;
  1844. end;
  1845. end;
  1846. if (p.ops > 2) then
  1847. begin
  1848. if RegInOp(reg, p.oper[2]^) then
  1849. begin
  1850. if (p.oper[2]^.typ = top_ref) then
  1851. begin
  1852. if RegInRef(reg, p.oper[2]^.ref^) then
  1853. begin
  1854. Result := False;
  1855. Exit;
  1856. end;
  1857. end
  1858. else if (p.oper[2]^.typ = top_reg) then
  1859. begin
  1860. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1861. begin
  1862. Result := False;
  1863. Exit;
  1864. end
  1865. else if ([Ch_WOp3]*Ch<>[]) then
  1866. begin
  1867. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1868. Result := True
  1869. else
  1870. begin
  1871. Result := False;
  1872. Exit;
  1873. end;
  1874. end;
  1875. end;
  1876. end;
  1877. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1878. begin
  1879. if (p.oper[3]^.typ = top_ref) then
  1880. begin
  1881. if RegInRef(reg, p.oper[3]^.ref^) then
  1882. begin
  1883. Result := False;
  1884. Exit;
  1885. end;
  1886. end
  1887. else if (p.oper[3]^.typ = top_reg) then
  1888. begin
  1889. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1890. begin
  1891. Result := False;
  1892. Exit;
  1893. end
  1894. else if ([Ch_WOp4]*Ch<>[]) then
  1895. begin
  1896. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1897. Result := True
  1898. else
  1899. begin
  1900. Result := False;
  1901. Exit;
  1902. end;
  1903. end;
  1904. end;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1910. case getsupreg(reg) of
  1911. RS_EAX:
  1912. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1913. begin
  1914. Result := True;
  1915. Exit;
  1916. end;
  1917. RS_ECX:
  1918. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1919. begin
  1920. Result := True;
  1921. Exit;
  1922. end;
  1923. RS_EDX:
  1924. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1925. begin
  1926. Result := True;
  1927. Exit;
  1928. end;
  1929. RS_EBX:
  1930. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1931. begin
  1932. Result := True;
  1933. Exit;
  1934. end;
  1935. RS_ESP:
  1936. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1937. begin
  1938. Result := True;
  1939. Exit;
  1940. end;
  1941. RS_EBP:
  1942. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1943. begin
  1944. Result := True;
  1945. Exit;
  1946. end;
  1947. RS_ESI:
  1948. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1949. begin
  1950. Result := True;
  1951. Exit;
  1952. end;
  1953. RS_EDI:
  1954. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1955. begin
  1956. Result := True;
  1957. Exit;
  1958. end;
  1959. else
  1960. ;
  1961. end;
  1962. end;
  1963. end;
  1964. end;
  1965. end;
  1966. end;
  1967. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1968. var
  1969. hp2,hp3 : tai;
  1970. begin
  1971. { some x86-64 issue a NOP before the real exit code }
  1972. if MatchInstruction(p,A_NOP,[]) then
  1973. GetNextInstruction(p,p);
  1974. result:=assigned(p) and (p.typ=ait_instruction) and
  1975. ((taicpu(p).opcode = A_RET) or
  1976. ((taicpu(p).opcode=A_LEAVE) and
  1977. GetNextInstruction(p,hp2) and
  1978. MatchInstruction(hp2,A_RET,[S_NO])
  1979. ) or
  1980. (((taicpu(p).opcode=A_LEA) and
  1981. MatchOpType(taicpu(p),top_ref,top_reg) and
  1982. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1983. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1984. ) and
  1985. GetNextInstruction(p,hp2) and
  1986. MatchInstruction(hp2,A_RET,[S_NO])
  1987. ) or
  1988. ((((taicpu(p).opcode=A_MOV) and
  1989. MatchOpType(taicpu(p),top_reg,top_reg) and
  1990. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1991. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1992. ((taicpu(p).opcode=A_LEA) and
  1993. MatchOpType(taicpu(p),top_ref,top_reg) and
  1994. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1996. )
  1997. ) and
  1998. GetNextInstruction(p,hp2) and
  1999. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2000. MatchOpType(taicpu(hp2),top_reg) and
  2001. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2002. GetNextInstruction(hp2,hp3) and
  2003. MatchInstruction(hp3,A_RET,[S_NO])
  2004. )
  2005. );
  2006. end;
  2007. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2008. begin
  2009. isFoldableArithOp := False;
  2010. case hp1.opcode of
  2011. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2012. isFoldableArithOp :=
  2013. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2014. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2015. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2016. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2017. (taicpu(hp1).oper[1]^.reg = reg);
  2018. A_INC,A_DEC,A_NEG,A_NOT:
  2019. isFoldableArithOp :=
  2020. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[0]^.reg = reg);
  2022. else
  2023. ;
  2024. end;
  2025. end;
  2026. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2027. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2028. var
  2029. hp2: tai;
  2030. begin
  2031. hp2 := p;
  2032. repeat
  2033. hp2 := tai(hp2.previous);
  2034. if assigned(hp2) and
  2035. (hp2.typ = ait_regalloc) and
  2036. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2037. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2038. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2039. begin
  2040. RemoveInstruction(hp2);
  2041. break;
  2042. end;
  2043. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2044. end;
  2045. begin
  2046. case current_procinfo.procdef.returndef.typ of
  2047. arraydef,recorddef,pointerdef,
  2048. stringdef,enumdef,procdef,objectdef,errordef,
  2049. filedef,setdef,procvardef,
  2050. classrefdef,forwarddef:
  2051. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2052. orddef:
  2053. if current_procinfo.procdef.returndef.size <> 0 then
  2054. begin
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. { for int64/qword }
  2057. if current_procinfo.procdef.returndef.size = 8 then
  2058. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2059. end;
  2060. else
  2061. ;
  2062. end;
  2063. end;
  2064. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2065. var
  2066. hp1,hp2 : tai;
  2067. begin
  2068. result:=false;
  2069. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2070. begin
  2071. { vmova* reg1,reg1
  2072. =>
  2073. <nop> }
  2074. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2075. begin
  2076. RemoveCurrentP(p);
  2077. result:=true;
  2078. exit;
  2079. end;
  2080. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2081. (hp1.typ = ait_instruction) and
  2082. (
  2083. { Under -O2 and below, the instructions are always adjacent }
  2084. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2085. (taicpu(hp1).ops <= 1) or
  2086. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2087. { If reg1 = reg3, reg1 must not be modified in between }
  2088. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2089. ) then
  2090. begin
  2091. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2092. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2093. begin
  2094. { vmova* reg1,reg2
  2095. ...
  2096. vmova* reg2,reg3
  2097. dealloc reg2
  2098. =>
  2099. vmova* reg1,reg3 }
  2100. TransferUsedRegs(TmpUsedRegs);
  2101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2102. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2103. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2104. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2105. begin
  2106. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2107. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2108. TransferUsedRegs(TmpUsedRegs);
  2109. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2110. RemoveInstruction(hp1);
  2111. result:=true;
  2112. exit;
  2113. end;
  2114. { special case:
  2115. vmova* reg1,<op>
  2116. ...
  2117. vmova* <op>,reg1
  2118. =>
  2119. vmova* reg1,<op> }
  2120. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2121. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2122. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2123. ) then
  2124. begin
  2125. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2126. RemoveInstruction(hp1);
  2127. result:=true;
  2128. exit;
  2129. end
  2130. end
  2131. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2132. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2133. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2134. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2135. ) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmovs* reg2,<op>
  2141. dealloc reg2
  2142. =>
  2143. vmovs* reg1,<op> }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2146. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2147. begin
  2148. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2149. taicpu(p).opcode:=taicpu(hp1).opcode;
  2150. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2151. TransferUsedRegs(TmpUsedRegs);
  2152. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2153. RemoveInstruction(hp1);
  2154. result:=true;
  2155. exit;
  2156. end
  2157. end;
  2158. if MatchInstruction(hp1,[A_VFMADDPD,
  2159. A_VFMADD132PD,
  2160. A_VFMADD132PS,
  2161. A_VFMADD132SD,
  2162. A_VFMADD132SS,
  2163. A_VFMADD213PD,
  2164. A_VFMADD213PS,
  2165. A_VFMADD213SD,
  2166. A_VFMADD213SS,
  2167. A_VFMADD231PD,
  2168. A_VFMADD231PS,
  2169. A_VFMADD231SD,
  2170. A_VFMADD231SS,
  2171. A_VFMADDSUB132PD,
  2172. A_VFMADDSUB132PS,
  2173. A_VFMADDSUB213PD,
  2174. A_VFMADDSUB213PS,
  2175. A_VFMADDSUB231PD,
  2176. A_VFMADDSUB231PS,
  2177. A_VFMSUB132PD,
  2178. A_VFMSUB132PS,
  2179. A_VFMSUB132SD,
  2180. A_VFMSUB132SS,
  2181. A_VFMSUB213PD,
  2182. A_VFMSUB213PS,
  2183. A_VFMSUB213SD,
  2184. A_VFMSUB213SS,
  2185. A_VFMSUB231PD,
  2186. A_VFMSUB231PS,
  2187. A_VFMSUB231SD,
  2188. A_VFMSUB231SS,
  2189. A_VFMSUBADD132PD,
  2190. A_VFMSUBADD132PS,
  2191. A_VFMSUBADD213PD,
  2192. A_VFMSUBADD213PS,
  2193. A_VFMSUBADD231PD,
  2194. A_VFMSUBADD231PS,
  2195. A_VFNMADD132PD,
  2196. A_VFNMADD132PS,
  2197. A_VFNMADD132SD,
  2198. A_VFNMADD132SS,
  2199. A_VFNMADD213PD,
  2200. A_VFNMADD213PS,
  2201. A_VFNMADD213SD,
  2202. A_VFNMADD213SS,
  2203. A_VFNMADD231PD,
  2204. A_VFNMADD231PS,
  2205. A_VFNMADD231SD,
  2206. A_VFNMADD231SS,
  2207. A_VFNMSUB132PD,
  2208. A_VFNMSUB132PS,
  2209. A_VFNMSUB132SD,
  2210. A_VFNMSUB132SS,
  2211. A_VFNMSUB213PD,
  2212. A_VFNMSUB213PS,
  2213. A_VFNMSUB213SD,
  2214. A_VFNMSUB213SS,
  2215. A_VFNMSUB231PD,
  2216. A_VFNMSUB231PS,
  2217. A_VFNMSUB231SD,
  2218. A_VFNMSUB231SS],[S_NO]) and
  2219. { we mix single and double opperations here because we assume that the compiler
  2220. generates vmovapd only after double operations and vmovaps only after single operations }
  2221. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2222. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2223. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2224. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2225. begin
  2226. TransferUsedRegs(TmpUsedRegs);
  2227. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2228. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2229. begin
  2230. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2231. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2232. RemoveCurrentP(p)
  2233. else
  2234. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2235. RemoveInstruction(hp2);
  2236. end;
  2237. end
  2238. else if (hp1.typ = ait_instruction) and
  2239. (((taicpu(p).opcode=A_MOVAPS) and
  2240. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2241. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2242. ((taicpu(p).opcode=A_MOVAPD) and
  2243. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2244. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2245. ) and
  2246. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2247. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2248. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2249. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2250. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2251. { change
  2252. movapX reg,reg2
  2253. addsX/subsX/... reg3, reg2
  2254. movapX reg2,reg
  2255. to
  2256. addsX/subsX/... reg3,reg
  2257. }
  2258. begin
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2261. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2264. debug_op2str(taicpu(p).opcode)+' '+
  2265. debug_op2str(taicpu(hp1).opcode)+' '+
  2266. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2267. { we cannot eliminate the first move if
  2268. the operations uses the same register for source and dest }
  2269. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2270. { Remember that hp1 is not necessarily the immediate
  2271. next instruction }
  2272. RemoveCurrentP(p);
  2273. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2274. RemoveInstruction(hp2);
  2275. result:=true;
  2276. end;
  2277. end
  2278. else if (hp1.typ = ait_instruction) and
  2279. (((taicpu(p).opcode=A_VMOVAPD) and
  2280. (taicpu(hp1).opcode=A_VCOMISD)) or
  2281. ((taicpu(p).opcode=A_VMOVAPS) and
  2282. ((taicpu(hp1).opcode=A_VCOMISS))
  2283. )
  2284. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2285. { change
  2286. movapX reg,reg1
  2287. vcomisX reg1,reg1
  2288. to
  2289. vcomisX reg,reg
  2290. }
  2291. begin
  2292. TransferUsedRegs(TmpUsedRegs);
  2293. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2294. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2295. begin
  2296. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2297. debug_op2str(taicpu(p).opcode)+' '+
  2298. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2299. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2300. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2301. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2302. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2303. RemoveCurrentP(p);
  2304. result:=true;
  2305. exit;
  2306. end;
  2307. end
  2308. end;
  2309. end;
  2310. end;
  2311. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2312. var
  2313. hp1 : tai;
  2314. begin
  2315. result:=false;
  2316. { replace
  2317. V<Op>X %mreg1,%mreg2,%mreg3
  2318. VMovX %mreg3,%mreg4
  2319. dealloc %mreg3
  2320. by
  2321. V<Op>X %mreg1,%mreg2,%mreg4
  2322. ?
  2323. }
  2324. if GetNextInstruction(p,hp1) and
  2325. { we mix single and double operations here because we assume that the compiler
  2326. generates vmovapd only after double operations and vmovaps only after single operations }
  2327. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2328. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2329. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2330. begin
  2331. TransferUsedRegs(TmpUsedRegs);
  2332. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2333. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2334. begin
  2335. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2336. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2337. RemoveInstruction(hp1);
  2338. result:=true;
  2339. end;
  2340. end;
  2341. end;
  2342. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2343. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2344. begin
  2345. Result := False;
  2346. { For safety reasons, only check for exact register matches }
  2347. { Check base register }
  2348. if (ref.base = AOldReg) then
  2349. begin
  2350. ref.base := ANewReg;
  2351. Result := True;
  2352. end;
  2353. { Check index register }
  2354. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2355. begin
  2356. ref.index := ANewReg;
  2357. Result := True;
  2358. end;
  2359. end;
  2360. { Replaces all references to AOldReg in an operand to ANewReg }
  2361. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2362. var
  2363. OldSupReg, NewSupReg: TSuperRegister;
  2364. OldSubReg, NewSubReg: TSubRegister;
  2365. OldRegType: TRegisterType;
  2366. ThisOper: POper;
  2367. begin
  2368. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2369. Result := False;
  2370. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2371. InternalError(2020011801);
  2372. OldSupReg := getsupreg(AOldReg);
  2373. OldSubReg := getsubreg(AOldReg);
  2374. OldRegType := getregtype(AOldReg);
  2375. NewSupReg := getsupreg(ANewReg);
  2376. NewSubReg := getsubreg(ANewReg);
  2377. if OldRegType <> getregtype(ANewReg) then
  2378. InternalError(2020011802);
  2379. if OldSubReg <> NewSubReg then
  2380. InternalError(2020011803);
  2381. case ThisOper^.typ of
  2382. top_reg:
  2383. if (
  2384. (ThisOper^.reg = AOldReg) or
  2385. (
  2386. (OldRegType = R_INTREGISTER) and
  2387. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2388. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2389. (
  2390. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2391. {$ifndef x86_64}
  2392. and (
  2393. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2394. don't have an 8-bit representation }
  2395. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2396. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2397. )
  2398. {$endif x86_64}
  2399. )
  2400. )
  2401. ) then
  2402. begin
  2403. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2404. Result := True;
  2405. end;
  2406. top_ref:
  2407. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2408. Result := True;
  2409. else
  2410. ;
  2411. end;
  2412. end;
  2413. { Replaces all references to AOldReg in an instruction to ANewReg }
  2414. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2415. const
  2416. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2417. var
  2418. OperIdx: Integer;
  2419. begin
  2420. Result := False;
  2421. for OperIdx := 0 to p.ops - 1 do
  2422. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2423. begin
  2424. { The shift and rotate instructions can only use CL }
  2425. if not (
  2426. (OperIdx = 0) and
  2427. { This second condition just helps to avoid unnecessarily
  2428. calling MatchInstruction for 10 different opcodes }
  2429. (p.oper[0]^.reg = NR_CL) and
  2430. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2431. ) then
  2432. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2433. end
  2434. else if p.oper[OperIdx]^.typ = top_ref then
  2435. { It's okay to replace registers in references that get written to }
  2436. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2437. end;
  2438. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2439. begin
  2440. Result :=
  2441. (ref^.index = NR_NO) and
  2442. (
  2443. {$ifdef x86_64}
  2444. (
  2445. (ref^.base = NR_RIP) and
  2446. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2447. ) or
  2448. {$endif x86_64}
  2449. (ref^.refaddr = addr_full) or
  2450. (ref^.base = NR_STACK_POINTER_REG) or
  2451. (ref^.base = current_procinfo.framepointer)
  2452. );
  2453. end;
  2454. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2455. var
  2456. l: asizeint;
  2457. begin
  2458. Result := False;
  2459. { Should have been checked previously }
  2460. if p.opcode <> A_LEA then
  2461. InternalError(2020072501);
  2462. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2463. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2464. not(cs_opt_size in current_settings.optimizerswitches) then
  2465. exit;
  2466. with p.oper[0]^.ref^ do
  2467. begin
  2468. if (base <> p.oper[1]^.reg) or
  2469. (index <> NR_NO) or
  2470. assigned(symbol) then
  2471. exit;
  2472. l:=offset;
  2473. if (l=1) and UseIncDec then
  2474. begin
  2475. p.opcode:=A_INC;
  2476. p.loadreg(0,p.oper[1]^.reg);
  2477. p.ops:=1;
  2478. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2479. end
  2480. else if (l=-1) and UseIncDec then
  2481. begin
  2482. p.opcode:=A_DEC;
  2483. p.loadreg(0,p.oper[1]^.reg);
  2484. p.ops:=1;
  2485. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2486. end
  2487. else
  2488. begin
  2489. if (l<0) and (l<>-2147483648) then
  2490. begin
  2491. p.opcode:=A_SUB;
  2492. p.loadConst(0,-l);
  2493. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2494. end
  2495. else
  2496. begin
  2497. p.opcode:=A_ADD;
  2498. p.loadConst(0,l);
  2499. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2500. end;
  2501. end;
  2502. end;
  2503. Result := True;
  2504. end;
  2505. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2506. var
  2507. CurrentReg, ReplaceReg: TRegister;
  2508. begin
  2509. Result := False;
  2510. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2511. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2512. case hp.opcode of
  2513. A_FSTSW, A_FNSTSW,
  2514. A_IN, A_INS, A_OUT, A_OUTS,
  2515. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2516. { These routines have explicit operands, but they are restricted in
  2517. what they can be (e.g. IN and OUT can only read from AL, AX or
  2518. EAX. }
  2519. Exit;
  2520. A_IMUL:
  2521. begin
  2522. { The 1-operand version writes to implicit registers
  2523. The 2-operand version reads from the first operator, and reads
  2524. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2525. the 3-operand version reads from a register that it doesn't write to
  2526. }
  2527. case hp.ops of
  2528. 1:
  2529. if (
  2530. (
  2531. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2532. ) or
  2533. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2534. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2535. begin
  2536. Result := True;
  2537. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2538. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2539. end;
  2540. 2:
  2541. { Only modify the first parameter }
  2542. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2543. begin
  2544. Result := True;
  2545. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2546. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2547. end;
  2548. 3:
  2549. { Only modify the second parameter }
  2550. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2551. begin
  2552. Result := True;
  2553. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2554. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2555. end;
  2556. else
  2557. InternalError(2020012901);
  2558. end;
  2559. end;
  2560. else
  2561. if (hp.ops > 0) and
  2562. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2563. begin
  2564. Result := True;
  2565. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2566. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2567. end;
  2568. end;
  2569. end;
  2570. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2571. var
  2572. hp2: tai;
  2573. p_SourceReg, p_TargetReg: TRegister;
  2574. begin
  2575. Result := False;
  2576. { Backward optimisation. If we have:
  2577. func. %reg1,%reg2
  2578. mov %reg2,%reg3
  2579. (dealloc %reg2)
  2580. Change to:
  2581. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2582. Perform similar optimisations with 1, 3 and 4-operand instructions
  2583. that only have one output.
  2584. }
  2585. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2586. begin
  2587. p_SourceReg := taicpu(p).oper[0]^.reg;
  2588. p_TargetReg := taicpu(p).oper[1]^.reg;
  2589. TransferUsedRegs(TmpUsedRegs);
  2590. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2591. GetLastInstruction(p, hp2) and
  2592. (hp2.typ = ait_instruction) and
  2593. { Have to make sure it's an instruction that only reads from
  2594. the first operands and only writes (not reads or modifies) to
  2595. the last one; in essence, a pure function such as BSR, POPCNT
  2596. or ANDN }
  2597. (
  2598. (
  2599. (taicpu(hp2).ops = 1) and
  2600. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2601. ) or
  2602. (
  2603. (taicpu(hp2).ops = 2) and
  2604. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2605. ) or
  2606. (
  2607. (taicpu(hp2).ops = 3) and
  2608. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2609. ) or
  2610. (
  2611. (taicpu(hp2).ops = 4) and
  2612. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2613. )
  2614. ) and
  2615. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2616. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2617. begin
  2618. case taicpu(hp2).opcode of
  2619. A_FSTSW, A_FNSTSW,
  2620. A_IN, A_INS, A_OUT, A_OUTS,
  2621. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2622. { These routines have explicit operands, but they are restricted in
  2623. what they can be (e.g. IN and OUT can only read from AL, AX or
  2624. EAX. }
  2625. ;
  2626. else
  2627. begin
  2628. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2629. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2630. if not RegInInstruction(p_TargetReg, hp2) then
  2631. begin
  2632. { Since we're allocating from an earlier point, we
  2633. need to remove the register from the tracking }
  2634. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2635. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2636. end;
  2637. RemoveCurrentp(p, hp1);
  2638. { If the Func was another MOV instruction, we might get
  2639. "mov %reg,%reg" that doesn't get removed in Pass 2
  2640. otherwise, so deal with it here (also do something
  2641. similar with lea (%reg),%reg}
  2642. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2643. begin
  2644. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2645. if p = hp2 then
  2646. RemoveCurrentp(p)
  2647. else
  2648. RemoveInstruction(hp2);
  2649. end;
  2650. Result := True;
  2651. Exit;
  2652. end;
  2653. end;
  2654. end;
  2655. end;
  2656. end;
  2657. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2658. begin
  2659. Result := False;
  2660. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2661. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2662. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2663. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2664. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2665. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2666. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2667. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2668. begin
  2669. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2670. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2671. Result := True;
  2672. end;
  2673. end;
  2674. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2675. var
  2676. hp1, hp2, hp3, hp4: tai;
  2677. DoOptimisation, TempBool: Boolean;
  2678. {$ifdef x86_64}
  2679. NewConst: TCGInt;
  2680. {$endif x86_64}
  2681. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2682. begin
  2683. if taicpu(hp1).opcode = signed_movop then
  2684. begin
  2685. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2686. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2687. end
  2688. else
  2689. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2690. end;
  2691. function TryConstMerge(var p1, p2: tai): Boolean;
  2692. var
  2693. ThisRef: TReference;
  2694. begin
  2695. Result := False;
  2696. ThisRef := taicpu(p2).oper[1]^.ref^;
  2697. { Only permit writes to the stack, since we can guarantee alignment with that }
  2698. if (ThisRef.index = NR_NO) and
  2699. (
  2700. (ThisRef.base = NR_STACK_POINTER_REG) or
  2701. (ThisRef.base = current_procinfo.framepointer)
  2702. ) then
  2703. begin
  2704. case taicpu(p).opsize of
  2705. S_B:
  2706. begin
  2707. { Word writes must be on a 2-byte boundary }
  2708. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2709. begin
  2710. { Reduce offset of second reference to see if it is sequential with the first }
  2711. Dec(ThisRef.offset, 1);
  2712. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2713. begin
  2714. { Make sure the constants aren't represented as a
  2715. negative number, as these won't merge properly }
  2716. taicpu(p1).opsize := S_W;
  2717. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2718. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2719. RemoveInstruction(p2);
  2720. Result := True;
  2721. end;
  2722. end;
  2723. end;
  2724. S_W:
  2725. begin
  2726. { Longword writes must be on a 4-byte boundary }
  2727. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2728. begin
  2729. { Reduce offset of second reference to see if it is sequential with the first }
  2730. Dec(ThisRef.offset, 2);
  2731. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2732. begin
  2733. { Make sure the constants aren't represented as a
  2734. negative number, as these won't merge properly }
  2735. taicpu(p1).opsize := S_L;
  2736. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2737. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2738. RemoveInstruction(p2);
  2739. Result := True;
  2740. end;
  2741. end;
  2742. end;
  2743. {$ifdef x86_64}
  2744. S_L:
  2745. begin
  2746. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2747. see if the constants can be encoded this way. }
  2748. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2749. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2750. { Quadword writes must be on an 8-byte boundary }
  2751. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2752. begin
  2753. { Reduce offset of second reference to see if it is sequential with the first }
  2754. Dec(ThisRef.offset, 4);
  2755. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2756. begin
  2757. { Make sure the constants aren't represented as a
  2758. negative number, as these won't merge properly }
  2759. taicpu(p1).opsize := S_Q;
  2760. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2761. taicpu(p1).oper[0]^.val := NewConst;
  2762. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2763. RemoveInstruction(p2);
  2764. Result := True;
  2765. end;
  2766. end;
  2767. end;
  2768. {$endif x86_64}
  2769. else
  2770. ;
  2771. end;
  2772. end;
  2773. end;
  2774. var
  2775. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2776. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2777. NewSize: topsize; NewOffset: asizeint;
  2778. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2779. SourceRef, TargetRef: TReference;
  2780. MovAligned, MovUnaligned: TAsmOp;
  2781. ThisRef: TReference;
  2782. JumpTracking: TLinkedList;
  2783. begin
  2784. Result:=false;
  2785. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2786. { remove mov reg1,reg1? }
  2787. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2788. then
  2789. begin
  2790. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2791. { take care of the register (de)allocs following p }
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. { All the next optimisations require a next instruction }
  2797. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2798. Exit;
  2799. { Prevent compiler warnings }
  2800. p_TargetReg := NR_NO;
  2801. if taicpu(p).oper[1]^.typ = top_reg then
  2802. begin
  2803. { Saves on a large number of dereferences }
  2804. p_TargetReg := taicpu(p).oper[1]^.reg;
  2805. { Look for:
  2806. mov %reg1,%reg2
  2807. ??? %reg2,r/m
  2808. Change to:
  2809. mov %reg1,%reg2
  2810. ??? %reg1,r/m
  2811. }
  2812. if taicpu(p).oper[0]^.typ = top_reg then
  2813. begin
  2814. if RegReadByInstruction(p_TargetReg, hp1) and
  2815. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2816. begin
  2817. { A change has occurred, just not in p }
  2818. Result := True;
  2819. TransferUsedRegs(TmpUsedRegs);
  2820. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2821. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2822. { Just in case something didn't get modified (e.g. an
  2823. implicit register) }
  2824. not RegReadByInstruction(p_TargetReg, hp1) then
  2825. begin
  2826. { We can remove the original MOV }
  2827. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2828. RemoveCurrentp(p, hp1);
  2829. { UsedRegs got updated by RemoveCurrentp }
  2830. Result := True;
  2831. Exit;
  2832. end;
  2833. { If we know a MOV instruction has become a null operation, we might as well
  2834. get rid of it now to save time. }
  2835. if (taicpu(hp1).opcode = A_MOV) and
  2836. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2837. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2838. { Just being a register is enough to confirm it's a null operation }
  2839. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2840. begin
  2841. Result := True;
  2842. { Speed-up to reduce a pipeline stall... if we had something like...
  2843. movl %eax,%edx
  2844. movw %dx,%ax
  2845. ... the second instruction would change to movw %ax,%ax, but
  2846. given that it is now %ax that's active rather than %eax,
  2847. penalties might occur due to a partial register write, so instead,
  2848. change it to a MOVZX instruction when optimising for speed.
  2849. }
  2850. if not (cs_opt_size in current_settings.optimizerswitches) and
  2851. IsMOVZXAcceptable and
  2852. (taicpu(hp1).opsize < taicpu(p).opsize)
  2853. {$ifdef x86_64}
  2854. { operations already implicitly set the upper 64 bits to zero }
  2855. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2856. {$endif x86_64}
  2857. then
  2858. begin
  2859. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2860. case taicpu(p).opsize of
  2861. S_W:
  2862. if taicpu(hp1).opsize = S_B then
  2863. taicpu(hp1).opsize := S_BL
  2864. else
  2865. InternalError(2020012911);
  2866. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2867. case taicpu(hp1).opsize of
  2868. S_B:
  2869. taicpu(hp1).opsize := S_BL;
  2870. S_W:
  2871. taicpu(hp1).opsize := S_WL;
  2872. else
  2873. InternalError(2020012912);
  2874. end;
  2875. else
  2876. InternalError(2020012910);
  2877. end;
  2878. taicpu(hp1).opcode := A_MOVZX;
  2879. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2880. end
  2881. else
  2882. begin
  2883. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2884. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2885. RemoveInstruction(hp1);
  2886. { The instruction after what was hp1 is now the immediate next instruction,
  2887. so we can continue to make optimisations if it's present }
  2888. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2889. Exit;
  2890. hp1 := hp2;
  2891. end;
  2892. end;
  2893. end;
  2894. end;
  2895. end;
  2896. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2897. overwrites the original destination register. e.g.
  2898. movl ###,%reg2d
  2899. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2900. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2901. }
  2902. if (taicpu(p).oper[1]^.typ = top_reg) and
  2903. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2904. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2905. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2906. begin
  2907. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2908. begin
  2909. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2910. case taicpu(p).oper[0]^.typ of
  2911. top_const:
  2912. { We have something like:
  2913. movb $x, %regb
  2914. movzbl %regb,%regd
  2915. Change to:
  2916. movl $x, %regd
  2917. }
  2918. begin
  2919. case taicpu(hp1).opsize of
  2920. S_BW:
  2921. begin
  2922. convert_mov_value(A_MOVSX, $FF);
  2923. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2924. taicpu(p).opsize := S_W;
  2925. end;
  2926. S_BL:
  2927. begin
  2928. convert_mov_value(A_MOVSX, $FF);
  2929. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2930. taicpu(p).opsize := S_L;
  2931. end;
  2932. S_WL:
  2933. begin
  2934. convert_mov_value(A_MOVSX, $FFFF);
  2935. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2936. taicpu(p).opsize := S_L;
  2937. end;
  2938. {$ifdef x86_64}
  2939. S_BQ:
  2940. begin
  2941. convert_mov_value(A_MOVSX, $FF);
  2942. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2943. taicpu(p).opsize := S_Q;
  2944. end;
  2945. S_WQ:
  2946. begin
  2947. convert_mov_value(A_MOVSX, $FFFF);
  2948. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2949. taicpu(p).opsize := S_Q;
  2950. end;
  2951. S_LQ:
  2952. begin
  2953. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2954. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2955. taicpu(p).opsize := S_Q;
  2956. end;
  2957. {$endif x86_64}
  2958. else
  2959. { If hp1 was a MOV instruction, it should have been
  2960. optimised already }
  2961. InternalError(2020021001);
  2962. end;
  2963. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result := True;
  2966. Exit;
  2967. end;
  2968. top_ref:
  2969. begin
  2970. { We have something like:
  2971. movb mem, %regb
  2972. movzbl %regb,%regd
  2973. Change to:
  2974. movzbl mem, %regd
  2975. }
  2976. ThisRef := taicpu(p).oper[0]^.ref^;
  2977. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2978. begin
  2979. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2980. taicpu(hp1).loadref(0, ThisRef);
  2981. { Make sure any registers in the references are properly tracked }
  2982. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2983. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2984. if (ThisRef.index <> NR_NO) then
  2985. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2986. RemoveCurrentP(p, hp1);
  2987. Result := True;
  2988. Exit;
  2989. end;
  2990. end;
  2991. else
  2992. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2993. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2994. Exit;
  2995. end;
  2996. end
  2997. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2998. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2999. optimised }
  3000. else
  3001. begin
  3002. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3003. RemoveCurrentP(p, hp1);
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. end;
  3008. if (taicpu(hp1).opcode = A_AND) and
  3009. (taicpu(p).oper[1]^.typ = top_reg) and
  3010. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3011. begin
  3012. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3013. begin
  3014. case taicpu(p).opsize of
  3015. S_L:
  3016. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3017. begin
  3018. { Optimize out:
  3019. mov x, %reg
  3020. and ffffffffh, %reg
  3021. }
  3022. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3023. RemoveInstruction(hp1);
  3024. Result:=true;
  3025. exit;
  3026. end;
  3027. S_Q: { TODO: Confirm if this is even possible }
  3028. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3029. begin
  3030. { Optimize out:
  3031. mov x, %reg
  3032. and ffffffffffffffffh, %reg
  3033. }
  3034. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3035. RemoveInstruction(hp1);
  3036. Result:=true;
  3037. exit;
  3038. end;
  3039. else
  3040. ;
  3041. end;
  3042. if (
  3043. (taicpu(p).oper[0]^.typ=top_reg) or
  3044. (
  3045. (taicpu(p).oper[0]^.typ=top_ref) and
  3046. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3047. )
  3048. ) and
  3049. GetNextInstruction(hp1,hp2) and
  3050. MatchInstruction(hp2,A_TEST,[]) and
  3051. (
  3052. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3053. (
  3054. { If the register being tested is smaller than the one
  3055. that received a bitwise AND, permit it if the constant
  3056. fits into the smaller size }
  3057. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3058. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3059. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3060. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3061. (
  3062. (
  3063. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3064. (taicpu(hp1).oper[0]^.val <= $FF)
  3065. ) or
  3066. (
  3067. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3068. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3069. {$ifdef x86_64}
  3070. ) or
  3071. (
  3072. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3073. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3074. {$endif x86_64}
  3075. )
  3076. )
  3077. )
  3078. ) and
  3079. (
  3080. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3081. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3082. ) and
  3083. GetNextInstruction(hp2,hp3) and
  3084. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3085. (taicpu(hp3).condition in [C_E,C_NE]) then
  3086. begin
  3087. TransferUsedRegs(TmpUsedRegs);
  3088. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3089. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3090. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3091. begin
  3092. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3093. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3094. taicpu(hp1).opcode:=A_TEST;
  3095. { Shrink the TEST instruction down to the smallest possible size }
  3096. case taicpu(hp1).oper[0]^.val of
  3097. 0..255:
  3098. if (taicpu(hp1).opsize <> S_B)
  3099. {$ifndef x86_64}
  3100. and (
  3101. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3102. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3103. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3104. )
  3105. {$endif x86_64}
  3106. then
  3107. begin
  3108. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3109. { Only print debug message if the TEST instruction
  3110. is a different size before and after }
  3111. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3112. taicpu(hp1).opsize := S_B;
  3113. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3114. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3115. end;
  3116. 256..65535:
  3117. if (taicpu(hp1).opsize <> S_W) then
  3118. begin
  3119. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3120. { Only print debug message if the TEST instruction
  3121. is a different size before and after }
  3122. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3123. taicpu(hp1).opsize := S_W;
  3124. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3126. end;
  3127. {$ifdef x86_64}
  3128. 65536..$7FFFFFFF:
  3129. if (taicpu(hp1).opsize <> S_L) then
  3130. begin
  3131. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3132. { Only print debug message if the TEST instruction
  3133. is a different size before and after }
  3134. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3135. taicpu(hp1).opsize := S_L;
  3136. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3137. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3138. end;
  3139. {$endif x86_64}
  3140. else
  3141. ;
  3142. end;
  3143. RemoveInstruction(hp2);
  3144. RemoveCurrentP(p, hp1);
  3145. Result:=true;
  3146. exit;
  3147. end;
  3148. end;
  3149. end
  3150. else if IsMOVZXAcceptable and
  3151. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3152. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3153. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3154. then
  3155. begin
  3156. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3157. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3158. case taicpu(p).opsize of
  3159. S_B:
  3160. if (taicpu(hp1).oper[0]^.val = $ff) then
  3161. begin
  3162. { Convert:
  3163. movb x, %regl movb x, %regl
  3164. andw ffh, %regw andl ffh, %regd
  3165. To:
  3166. movzbw x, %regd movzbl x, %regd
  3167. (Identical registers, just different sizes)
  3168. }
  3169. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3170. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3171. case taicpu(hp1).opsize of
  3172. S_W: NewSize := S_BW;
  3173. S_L: NewSize := S_BL;
  3174. {$ifdef x86_64}
  3175. S_Q: NewSize := S_BQ;
  3176. {$endif x86_64}
  3177. else
  3178. InternalError(2018011510);
  3179. end;
  3180. end
  3181. else
  3182. NewSize := S_NO;
  3183. S_W:
  3184. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3185. begin
  3186. { Convert:
  3187. movw x, %regw
  3188. andl ffffh, %regd
  3189. To:
  3190. movzwl x, %regd
  3191. (Identical registers, just different sizes)
  3192. }
  3193. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3194. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3195. case taicpu(hp1).opsize of
  3196. S_L: NewSize := S_WL;
  3197. {$ifdef x86_64}
  3198. S_Q: NewSize := S_WQ;
  3199. {$endif x86_64}
  3200. else
  3201. InternalError(2018011511);
  3202. end;
  3203. end
  3204. else
  3205. NewSize := S_NO;
  3206. else
  3207. NewSize := S_NO;
  3208. end;
  3209. if NewSize <> S_NO then
  3210. begin
  3211. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3212. { The actual optimization }
  3213. taicpu(p).opcode := A_MOVZX;
  3214. taicpu(p).changeopsize(NewSize);
  3215. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3216. { Safeguard if "and" is followed by a conditional command }
  3217. TransferUsedRegs(TmpUsedRegs);
  3218. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3219. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3220. begin
  3221. { At this point, the "and" command is effectively equivalent to
  3222. "test %reg,%reg". This will be handled separately by the
  3223. Peephole Optimizer. [Kit] }
  3224. DebugMsg(SPeepholeOptimization + PreMessage +
  3225. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3226. end
  3227. else
  3228. begin
  3229. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3230. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3231. RemoveInstruction(hp1);
  3232. end;
  3233. Result := True;
  3234. Exit;
  3235. end;
  3236. end;
  3237. end;
  3238. if (taicpu(hp1).opcode = A_OR) and
  3239. (taicpu(p).oper[1]^.typ = top_reg) and
  3240. MatchOperand(taicpu(p).oper[0]^, 0) and
  3241. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3242. begin
  3243. { mov 0, %reg
  3244. or ###,%reg
  3245. Change to (only if the flags are not used):
  3246. mov ###,%reg
  3247. }
  3248. TransferUsedRegs(TmpUsedRegs);
  3249. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3250. DoOptimisation := True;
  3251. { Even if the flags are used, we might be able to do the optimisation
  3252. if the conditions are predictable }
  3253. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3254. begin
  3255. { Only perform if ### = %reg (the same register) or equal to 0,
  3256. so %reg is guaranteed to still have a value of zero }
  3257. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3258. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3259. begin
  3260. hp2 := hp1;
  3261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3262. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3263. GetNextInstruction(hp2, hp3) do
  3264. begin
  3265. { Don't continue modifying if the flags state is getting changed }
  3266. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3267. Break;
  3268. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3269. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3270. begin
  3271. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3272. begin
  3273. { Condition is always true }
  3274. case taicpu(hp3).opcode of
  3275. A_Jcc:
  3276. begin
  3277. { Check for jump shortcuts before we destroy the condition }
  3278. hp4 := hp3;
  3279. DoJumpOptimizations(hp3, TempBool);
  3280. { Make sure hp3 hasn't changed }
  3281. if (hp4 = hp3) then
  3282. begin
  3283. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3284. MakeUnconditional(taicpu(hp3));
  3285. end;
  3286. Result := True;
  3287. end;
  3288. A_CMOVcc:
  3289. begin
  3290. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3291. taicpu(hp3).opcode := A_MOV;
  3292. taicpu(hp3).condition := C_None;
  3293. Result := True;
  3294. end;
  3295. A_SETcc:
  3296. begin
  3297. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3298. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3299. taicpu(hp3).opcode := A_MOV;
  3300. taicpu(hp3).ops := 2;
  3301. taicpu(hp3).condition := C_None;
  3302. taicpu(hp3).opsize := S_B;
  3303. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3304. taicpu(hp3).loadconst(0, 1);
  3305. Result := True;
  3306. end;
  3307. else
  3308. InternalError(2021090701);
  3309. end;
  3310. end
  3311. 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
  3312. begin
  3313. { Condition is always false }
  3314. case taicpu(hp3).opcode of
  3315. A_Jcc:
  3316. begin
  3317. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3318. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3319. RemoveInstruction(hp3);
  3320. Result := True;
  3321. { Since hp3 was deleted, hp2 must not be updated }
  3322. Continue;
  3323. end;
  3324. A_CMOVcc:
  3325. begin
  3326. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3327. RemoveInstruction(hp3);
  3328. Result := True;
  3329. { Since hp3 was deleted, hp2 must not be updated }
  3330. Continue;
  3331. end;
  3332. A_SETcc:
  3333. begin
  3334. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3335. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3336. taicpu(hp3).opcode := A_MOV;
  3337. taicpu(hp3).ops := 2;
  3338. taicpu(hp3).condition := C_None;
  3339. taicpu(hp3).opsize := S_B;
  3340. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3341. taicpu(hp3).loadconst(0, 0);
  3342. Result := True;
  3343. end;
  3344. else
  3345. InternalError(2021090702);
  3346. end;
  3347. end
  3348. else
  3349. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3350. DoOptimisation := False;
  3351. end;
  3352. hp2 := hp3;
  3353. end;
  3354. { Flags are still in use - don't optimise }
  3355. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3356. DoOptimisation := False;
  3357. end
  3358. else
  3359. DoOptimisation := False;
  3360. end;
  3361. if DoOptimisation then
  3362. begin
  3363. {$ifdef x86_64}
  3364. { OR only supports 32-bit sign-extended constants for 64-bit
  3365. instructions, so compensate for this if the constant is
  3366. encoded as a value greater than or equal to 2^31 }
  3367. if (taicpu(hp1).opsize = S_Q) and
  3368. (taicpu(hp1).oper[0]^.typ = top_const) and
  3369. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3370. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3371. {$endif x86_64}
  3372. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3373. taicpu(hp1).opcode := A_MOV;
  3374. RemoveCurrentP(p, hp1);
  3375. Result := True;
  3376. Exit;
  3377. end;
  3378. end;
  3379. { Next instruction is also a MOV ? }
  3380. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3381. begin
  3382. if MatchOpType(taicpu(p), top_const, top_ref) and
  3383. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3384. TryConstMerge(p, hp1) then
  3385. begin
  3386. Result := True;
  3387. { In case we have four byte writes in a row, check for 2 more
  3388. right now so we don't have to wait for another iteration of
  3389. pass 1
  3390. }
  3391. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3392. case taicpu(p).opsize of
  3393. S_W:
  3394. begin
  3395. if GetNextInstruction(p, hp1) and
  3396. MatchInstruction(hp1, A_MOV, [S_B]) and
  3397. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3398. GetNextInstruction(hp1, hp2) and
  3399. MatchInstruction(hp2, A_MOV, [S_B]) and
  3400. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3401. { Try to merge the two bytes }
  3402. TryConstMerge(hp1, hp2) then
  3403. { Now try to merge the two words (hp2 will get deleted) }
  3404. TryConstMerge(p, hp1);
  3405. end;
  3406. S_L:
  3407. begin
  3408. { Though this only really benefits x86_64 and not i386, it
  3409. gets a potential optimisation done faster and hence
  3410. reduces the number of times OptPass1MOV is entered }
  3411. if GetNextInstruction(p, hp1) and
  3412. MatchInstruction(hp1, A_MOV, [S_W]) and
  3413. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3414. GetNextInstruction(hp1, hp2) and
  3415. MatchInstruction(hp2, A_MOV, [S_W]) and
  3416. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3417. { Try to merge the two words }
  3418. TryConstMerge(hp1, hp2) then
  3419. { This will always fail on i386, so don't bother
  3420. calling it unless we're doing x86_64 }
  3421. {$ifdef x86_64}
  3422. { Now try to merge the two longwords (hp2 will get deleted) }
  3423. TryConstMerge(p, hp1)
  3424. {$endif x86_64}
  3425. ;
  3426. end;
  3427. else
  3428. ;
  3429. end;
  3430. Exit;
  3431. end;
  3432. if (taicpu(p).oper[1]^.typ = top_reg) and
  3433. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3434. begin
  3435. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3436. TransferUsedRegs(TmpUsedRegs);
  3437. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3438. { we have
  3439. mov x, %treg
  3440. mov %treg, y
  3441. }
  3442. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3443. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3444. { we've got
  3445. mov x, %treg
  3446. mov %treg, y
  3447. with %treg is not used after }
  3448. case taicpu(p).oper[0]^.typ Of
  3449. { top_reg is covered by DeepMOVOpt }
  3450. top_const:
  3451. begin
  3452. { change
  3453. mov const, %treg
  3454. mov %treg, y
  3455. to
  3456. mov const, y
  3457. }
  3458. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3459. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3460. begin
  3461. if taicpu(hp1).oper[1]^.typ=top_reg then
  3462. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3463. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3464. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3465. RemoveInstruction(hp1);
  3466. Result:=true;
  3467. Exit;
  3468. end;
  3469. end;
  3470. top_ref:
  3471. case taicpu(hp1).oper[1]^.typ of
  3472. top_reg:
  3473. begin
  3474. { change
  3475. mov mem, %treg
  3476. mov %treg, %reg
  3477. to
  3478. mov mem, %reg"
  3479. }
  3480. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3481. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3482. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3483. RemoveInstruction(hp1);
  3484. Result:=true;
  3485. Exit;
  3486. end;
  3487. top_ref:
  3488. begin
  3489. {$ifdef x86_64}
  3490. { Look for the following to simplify:
  3491. mov x(mem1), %reg
  3492. mov %reg, y(mem2)
  3493. mov x+8(mem1), %reg
  3494. mov %reg, y+8(mem2)
  3495. Change to:
  3496. movdqu x(mem1), %xmmreg
  3497. movdqu %xmmreg, y(mem2)
  3498. ...but only as long as the memory blocks don't overlap
  3499. }
  3500. SourceRef := taicpu(p).oper[0]^.ref^;
  3501. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3502. if (taicpu(p).opsize = S_Q) and
  3503. GetNextInstruction(hp1, hp2) and
  3504. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3505. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3506. begin
  3507. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3509. Inc(SourceRef.offset, 8);
  3510. if UseAVX then
  3511. begin
  3512. MovAligned := A_VMOVDQA;
  3513. MovUnaligned := A_VMOVDQU;
  3514. end
  3515. else
  3516. begin
  3517. MovAligned := A_MOVDQA;
  3518. MovUnaligned := A_MOVDQU;
  3519. end;
  3520. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3521. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3522. begin
  3523. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3524. Inc(TargetRef.offset, 8);
  3525. if GetNextInstruction(hp2, hp3) and
  3526. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3527. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3528. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3529. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3530. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3531. begin
  3532. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3533. if NewMMReg <> NR_NO then
  3534. begin
  3535. { Remember that the offsets are 8 ahead }
  3536. if ((SourceRef.offset mod 16) = 8) and
  3537. (
  3538. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3539. (SourceRef.base = current_procinfo.framepointer) or
  3540. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3541. ) then
  3542. taicpu(p).opcode := MovAligned
  3543. else
  3544. taicpu(p).opcode := MovUnaligned;
  3545. taicpu(p).opsize := S_XMM;
  3546. taicpu(p).oper[1]^.reg := NewMMReg;
  3547. if ((TargetRef.offset mod 16) = 8) and
  3548. (
  3549. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3550. (TargetRef.base = current_procinfo.framepointer) or
  3551. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3552. ) then
  3553. taicpu(hp1).opcode := MovAligned
  3554. else
  3555. taicpu(hp1).opcode := MovUnaligned;
  3556. taicpu(hp1).opsize := S_XMM;
  3557. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3558. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3559. RemoveInstruction(hp2);
  3560. RemoveInstruction(hp3);
  3561. Result := True;
  3562. Exit;
  3563. end;
  3564. end;
  3565. end
  3566. else
  3567. begin
  3568. { See if the next references are 8 less rather than 8 greater }
  3569. Dec(SourceRef.offset, 16); { -8 the other way }
  3570. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3571. begin
  3572. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3573. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3574. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3575. GetNextInstruction(hp2, hp3) and
  3576. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3577. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3578. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3579. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3580. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3581. begin
  3582. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3583. if NewMMReg <> NR_NO then
  3584. begin
  3585. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3586. if ((SourceRef.offset mod 16) = 0) and
  3587. (
  3588. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3589. (SourceRef.base = current_procinfo.framepointer) or
  3590. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3591. ) then
  3592. taicpu(hp2).opcode := MovAligned
  3593. else
  3594. taicpu(hp2).opcode := MovUnaligned;
  3595. taicpu(hp2).opsize := S_XMM;
  3596. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3597. if ((TargetRef.offset mod 16) = 0) and
  3598. (
  3599. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3600. (TargetRef.base = current_procinfo.framepointer) or
  3601. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3602. ) then
  3603. taicpu(hp3).opcode := MovAligned
  3604. else
  3605. taicpu(hp3).opcode := MovUnaligned;
  3606. taicpu(hp3).opsize := S_XMM;
  3607. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3608. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3609. RemoveInstruction(hp1);
  3610. RemoveCurrentP(p, hp2);
  3611. Result := True;
  3612. Exit;
  3613. end;
  3614. end;
  3615. end;
  3616. end;
  3617. end;
  3618. {$endif x86_64}
  3619. end;
  3620. else
  3621. { The write target should be a reg or a ref }
  3622. InternalError(2021091601);
  3623. end;
  3624. else
  3625. ;
  3626. end
  3627. else
  3628. { %treg is used afterwards, but all eventualities
  3629. other than the first MOV instruction being a constant
  3630. are covered by DeepMOVOpt, so only check for that }
  3631. if (taicpu(p).oper[0]^.typ = top_const) and
  3632. (
  3633. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3634. not (cs_opt_size in current_settings.optimizerswitches) or
  3635. (taicpu(hp1).opsize = S_B)
  3636. ) and
  3637. (
  3638. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3639. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3640. ) then
  3641. begin
  3642. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3643. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3644. end;
  3645. end;
  3646. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3647. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3648. { mov reg1, mem1 or mov mem1, reg1
  3649. mov mem2, reg2 mov reg2, mem2}
  3650. begin
  3651. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3652. { mov reg1, mem1 or mov mem1, reg1
  3653. mov mem2, reg1 mov reg2, mem1}
  3654. begin
  3655. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3656. { Removes the second statement from
  3657. mov reg1, mem1/reg2
  3658. mov mem1/reg2, reg1 }
  3659. begin
  3660. if taicpu(p).oper[0]^.typ=top_reg then
  3661. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3662. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3663. RemoveInstruction(hp1);
  3664. Result:=true;
  3665. exit;
  3666. end
  3667. else
  3668. begin
  3669. TransferUsedRegs(TmpUsedRegs);
  3670. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3671. if (taicpu(p).oper[1]^.typ = top_ref) and
  3672. { mov reg1, mem1
  3673. mov mem2, reg1 }
  3674. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3675. GetNextInstruction(hp1, hp2) and
  3676. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3677. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3678. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3679. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3680. { change to
  3681. mov reg1, mem1 mov reg1, mem1
  3682. mov mem2, reg1 cmp reg1, mem2
  3683. cmp mem1, reg1
  3684. }
  3685. begin
  3686. RemoveInstruction(hp2);
  3687. taicpu(hp1).opcode := A_CMP;
  3688. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3689. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3690. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3691. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3692. end;
  3693. end;
  3694. end
  3695. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3696. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3697. begin
  3698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3699. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3700. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3701. end
  3702. else
  3703. begin
  3704. TransferUsedRegs(TmpUsedRegs);
  3705. if GetNextInstruction(hp1, hp2) and
  3706. MatchOpType(taicpu(p),top_ref,top_reg) and
  3707. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3708. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3709. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3710. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3711. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3712. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3713. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3714. { mov mem1, %reg1
  3715. mov %reg1, mem2
  3716. mov mem2, reg2
  3717. to:
  3718. mov mem1, reg2
  3719. mov reg2, mem2}
  3720. begin
  3721. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3722. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3723. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3724. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3725. RemoveInstruction(hp2);
  3726. Result := True;
  3727. end
  3728. {$ifdef i386}
  3729. { this is enabled for i386 only, as the rules to create the reg sets below
  3730. are too complicated for x86-64, so this makes this code too error prone
  3731. on x86-64
  3732. }
  3733. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3734. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3735. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3736. { mov mem1, reg1 mov mem1, reg1
  3737. mov reg1, mem2 mov reg1, mem2
  3738. mov mem2, reg2 mov mem2, reg1
  3739. to: to:
  3740. mov mem1, reg1 mov mem1, reg1
  3741. mov mem1, reg2 mov reg1, mem2
  3742. mov reg1, mem2
  3743. or (if mem1 depends on reg1
  3744. and/or if mem2 depends on reg2)
  3745. to:
  3746. mov mem1, reg1
  3747. mov reg1, mem2
  3748. mov reg1, reg2
  3749. }
  3750. begin
  3751. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3752. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3753. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3754. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3755. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3756. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3757. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3758. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3759. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3760. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3761. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3762. end
  3763. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3764. begin
  3765. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3766. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3767. end
  3768. else
  3769. begin
  3770. RemoveInstruction(hp2);
  3771. end
  3772. {$endif i386}
  3773. ;
  3774. end;
  3775. end
  3776. { movl [mem1],reg1
  3777. movl [mem1],reg2
  3778. to
  3779. movl [mem1],reg1
  3780. movl reg1,reg2
  3781. }
  3782. else if not CheckMovMov2MovMov2(p, hp1) and
  3783. { movl const1,[mem1]
  3784. movl [mem1],reg1
  3785. to
  3786. movl const1,reg1
  3787. movl reg1,[mem1]
  3788. }
  3789. MatchOpType(Taicpu(p),top_const,top_ref) and
  3790. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3792. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3793. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3794. begin
  3795. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3796. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3797. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3798. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3799. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3800. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3801. Result:=true;
  3802. exit;
  3803. end;
  3804. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3805. { Change:
  3806. movl %reg1,%reg2
  3807. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3808. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3809. To:
  3810. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3811. movl x(%reg1),%reg1
  3812. movl %reg1,%regX
  3813. }
  3814. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3815. begin
  3816. p_SourceReg := taicpu(p).oper[0]^.reg;
  3817. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3818. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3819. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3820. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3821. GetNextInstruction(hp1, hp2) and
  3822. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3823. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3824. begin
  3825. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3826. if RegInRef(p_TargetReg, SourceRef) and
  3827. { If %reg1 also appears in the second reference, then it will
  3828. not refer to the same memory block as the first reference }
  3829. not RegInRef(p_SourceReg, SourceRef) then
  3830. begin
  3831. { Check to see if the references match if %reg2 is changed to %reg1 }
  3832. if SourceRef.base = p_TargetReg then
  3833. SourceRef.base := p_SourceReg;
  3834. if SourceRef.index = p_TargetReg then
  3835. SourceRef.index := p_SourceReg;
  3836. { RefsEqual also checks to ensure both references are non-volatile }
  3837. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3838. begin
  3839. taicpu(hp2).loadreg(0, p_SourceReg);
  3840. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3841. Result := True;
  3842. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3843. begin
  3844. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3845. RemoveCurrentP(p, hp1);
  3846. Exit;
  3847. end
  3848. else
  3849. begin
  3850. { Check to see if %reg2 is no longer in use }
  3851. TransferUsedRegs(TmpUsedRegs);
  3852. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3853. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3854. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3855. begin
  3856. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3857. RemoveCurrentP(p, hp1);
  3858. Exit;
  3859. end;
  3860. end;
  3861. { If we reach this point, p and hp1 weren't actually modified,
  3862. so we can do a bit more work on this pass }
  3863. end;
  3864. end;
  3865. end;
  3866. end;
  3867. end;
  3868. {$ifdef x86_64}
  3869. { Change:
  3870. movl %reg1l,%reg2l
  3871. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3872. To:
  3873. movl %reg1l,%reg2l
  3874. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3875. If %reg1 = %reg3, convert to:
  3876. movl %reg1l,%reg2l
  3877. andl %reg1l,%reg1l
  3878. }
  3879. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3880. MatchOpType(taicpu(p), top_reg, top_reg) and
  3881. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3882. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3883. begin
  3884. TransferUsedRegs(TmpUsedRegs);
  3885. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3886. taicpu(hp1).opsize := S_L;
  3887. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3888. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3889. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3890. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3891. begin
  3892. { %reg1 = %reg3 }
  3893. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3894. taicpu(hp1).opcode := A_AND;
  3895. end
  3896. else
  3897. begin
  3898. { %reg1 <> %reg3 }
  3899. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3900. end;
  3901. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3902. begin
  3903. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3904. RemoveCurrentP(p, hp1);
  3905. Result := True;
  3906. Exit;
  3907. end
  3908. else
  3909. begin
  3910. { Initial instruction wasn't actually changed }
  3911. Include(OptsToCheck, aoc_ForceNewIteration);
  3912. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3913. appears below since %reg1 has technically changed }
  3914. if taicpu(hp1).opcode = A_AND then
  3915. Exit;
  3916. end;
  3917. end;
  3918. {$endif x86_64}
  3919. { search further than the next instruction for a mov (as long as it's not a jump) }
  3920. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3921. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3922. (taicpu(p).oper[1]^.typ = top_reg) and
  3923. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3924. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3925. begin
  3926. { we work with hp2 here, so hp1 can be still used later on when
  3927. checking for GetNextInstruction_p }
  3928. hp3 := hp1;
  3929. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3930. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3931. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3932. TransferUsedRegs(TmpUsedRegs);
  3933. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3934. if NotFirstIteration then
  3935. JumpTracking := TLinkedList.Create
  3936. else
  3937. JumpTracking := nil;
  3938. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3939. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3940. (hp2.typ=ait_instruction) do
  3941. begin
  3942. case taicpu(hp2).opcode of
  3943. A_POP:
  3944. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3945. begin
  3946. if not CrossJump and
  3947. not RegUsedBetween(p_TargetReg, p, hp2) then
  3948. begin
  3949. { We can remove the original MOV since the register
  3950. wasn't used between it and its popping from the stack }
  3951. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3952. RemoveCurrentp(p, hp1);
  3953. Result := True;
  3954. JumpTracking.Free;
  3955. Exit;
  3956. end;
  3957. { Can't go any further }
  3958. Break;
  3959. end;
  3960. A_MOV:
  3961. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3962. ((taicpu(p).oper[0]^.typ=top_const) or
  3963. ((taicpu(p).oper[0]^.typ=top_reg) and
  3964. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3965. )
  3966. ) then
  3967. begin
  3968. { we have
  3969. mov x, %treg
  3970. mov %treg, y
  3971. }
  3972. { We don't need to call UpdateUsedRegs for every instruction between
  3973. p and hp2 because the register we're concerned about will not
  3974. become deallocated (otherwise GetNextInstructionUsingReg would
  3975. have stopped at an earlier instruction). [Kit] }
  3976. TempRegUsed :=
  3977. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3978. RegReadByInstruction(p_TargetReg, hp3) or
  3979. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3980. case taicpu(p).oper[0]^.typ Of
  3981. top_reg:
  3982. begin
  3983. { change
  3984. mov %reg, %treg
  3985. mov %treg, y
  3986. to
  3987. mov %reg, y
  3988. }
  3989. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3990. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3991. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3992. begin
  3993. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3994. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3995. if TempRegUsed then
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3998. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3999. { Set the start of the next GetNextInstructionUsingRegCond search
  4000. to start at the entry right before hp2 (which is about to be removed) }
  4001. hp3 := tai(hp2.Previous);
  4002. RemoveInstruction(hp2);
  4003. Include(OptsToCheck, aoc_ForceNewIteration);
  4004. { See if there's more we can optimise }
  4005. Continue;
  4006. end
  4007. else
  4008. begin
  4009. RemoveInstruction(hp2);
  4010. { We can remove the original MOV too }
  4011. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4012. RemoveCurrentP(p, hp1);
  4013. Result:=true;
  4014. JumpTracking.Free;
  4015. Exit;
  4016. end;
  4017. end
  4018. else
  4019. begin
  4020. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4021. taicpu(hp2).loadReg(0, p_SourceReg);
  4022. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4023. { Check to see if the register also appears in the reference }
  4024. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4025. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4026. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4027. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4028. begin
  4029. { Don't remove the first instruction if the temporary register is in use }
  4030. if not TempRegUsed then
  4031. begin
  4032. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4033. RemoveCurrentP(p, hp1);
  4034. Result:=true;
  4035. JumpTracking.Free;
  4036. Exit;
  4037. end;
  4038. { No need to set Result to True here. If there's another instruction later
  4039. on that can be optimised, it will be detected when the main Pass 1 loop
  4040. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4041. hp3 := hp2;
  4042. Continue;
  4043. end;
  4044. end;
  4045. end;
  4046. top_const:
  4047. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4048. begin
  4049. { change
  4050. mov const, %treg
  4051. mov %treg, y
  4052. to
  4053. mov const, y
  4054. }
  4055. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4056. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4057. begin
  4058. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4059. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4060. if TempRegUsed then
  4061. begin
  4062. { Don't remove the first instruction if the temporary register is in use }
  4063. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4064. { No need to set Result to True. If there's another instruction later on
  4065. that can be optimised, it will be detected when the main Pass 1 loop
  4066. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4067. end
  4068. else
  4069. begin
  4070. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4071. RemoveCurrentP(p, hp1);
  4072. Result:=true;
  4073. Exit;
  4074. end;
  4075. end;
  4076. end;
  4077. else
  4078. Internalerror(2019103001);
  4079. end;
  4080. end
  4081. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4082. begin
  4083. if not CrossJump and
  4084. not RegUsedBetween(p_TargetReg, p, hp2) and
  4085. not RegReadByInstruction(p_TargetReg, hp2) then
  4086. begin
  4087. { Register is not used before it is overwritten }
  4088. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4089. RemoveCurrentp(p, hp1);
  4090. Result := True;
  4091. Exit;
  4092. end;
  4093. if (taicpu(p).oper[0]^.typ = top_const) and
  4094. (taicpu(hp2).oper[0]^.typ = top_const) then
  4095. begin
  4096. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4097. begin
  4098. { Same value - register hasn't changed }
  4099. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4100. RemoveInstruction(hp2);
  4101. Include(OptsToCheck, aoc_ForceNewIteration);
  4102. { See if there's more we can optimise }
  4103. Continue;
  4104. end;
  4105. end;
  4106. {$ifdef x86_64}
  4107. end
  4108. { Change:
  4109. movl %reg1l,%reg2l
  4110. ...
  4111. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4112. To:
  4113. movl %reg1l,%reg2l
  4114. ...
  4115. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4116. If %reg1 = %reg3, convert to:
  4117. movl %reg1l,%reg2l
  4118. ...
  4119. andl %reg1l,%reg1l
  4120. }
  4121. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4122. (taicpu(p).oper[0]^.typ = top_reg) and
  4123. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4124. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4125. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4126. begin
  4127. TempRegUsed :=
  4128. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4129. RegReadByInstruction(p_TargetReg, hp3) or
  4130. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4131. taicpu(hp2).opsize := S_L;
  4132. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4133. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4134. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4135. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4136. begin
  4137. { %reg1 = %reg3 }
  4138. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4139. taicpu(hp2).opcode := A_AND;
  4140. end
  4141. else
  4142. begin
  4143. { %reg1 <> %reg3 }
  4144. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4145. end;
  4146. if not TempRegUsed then
  4147. begin
  4148. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4149. RemoveCurrentP(p, hp1);
  4150. Result := True;
  4151. Exit;
  4152. end
  4153. else
  4154. begin
  4155. { Initial instruction wasn't actually changed }
  4156. Include(OptsToCheck, aoc_ForceNewIteration);
  4157. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4158. appears below since %reg1 has technically changed }
  4159. if taicpu(hp2).opcode = A_AND then
  4160. Break;
  4161. end;
  4162. {$endif x86_64}
  4163. end
  4164. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4165. GetNextInstruction(hp2, hp4) and
  4166. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4167. { Optimise the following first:
  4168. movl [mem1],reg1
  4169. movl [mem1],reg2
  4170. to
  4171. movl [mem1],reg1
  4172. movl reg1,reg2
  4173. If [mem1] contains the target register and reg1 is the
  4174. the source register, this optimisation will get missed
  4175. and produce less efficient code later on.
  4176. }
  4177. if CheckMovMov2MovMov2(hp2, hp4) then
  4178. { Initial instruction wasn't actually changed }
  4179. Include(OptsToCheck, aoc_ForceNewIteration);
  4180. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4181. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4182. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4183. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4184. begin
  4185. {
  4186. Change from:
  4187. mov ###, %reg
  4188. ...
  4189. movs/z %reg,%reg (Same register, just different sizes)
  4190. To:
  4191. movs/z ###, %reg (Longer version)
  4192. ...
  4193. (remove)
  4194. }
  4195. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4196. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4197. { Keep the first instruction as mov if ### is a constant }
  4198. if taicpu(p).oper[0]^.typ = top_const then
  4199. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4200. else
  4201. begin
  4202. taicpu(p).opcode := taicpu(hp2).opcode;
  4203. taicpu(p).opsize := taicpu(hp2).opsize;
  4204. end;
  4205. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4206. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4207. RemoveInstruction(hp2);
  4208. Result := True;
  4209. JumpTracking.Free;
  4210. Exit;
  4211. end;
  4212. else
  4213. { Move down to the if-block below };
  4214. end;
  4215. { Also catches MOV/S/Z instructions that aren't modified }
  4216. if taicpu(p).oper[0]^.typ = top_reg then
  4217. begin
  4218. p_SourceReg := taicpu(p).oper[0]^.reg;
  4219. if
  4220. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4221. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4222. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4223. begin
  4224. Result := True;
  4225. { Just in case something didn't get modified (e.g. an
  4226. implicit register). Also, if it does read from this
  4227. register, then there's no longer an advantage to
  4228. changing the register on subsequent instructions.}
  4229. if not RegReadByInstruction(p_TargetReg, hp2) then
  4230. begin
  4231. { If a conditional jump was crossed, do not delete
  4232. the original MOV no matter what }
  4233. if not CrossJump and
  4234. { RegEndOfLife returns True if the register is
  4235. deallocated before the next instruction or has
  4236. been loaded with a new value }
  4237. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4238. begin
  4239. { We can remove the original MOV }
  4240. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4241. RemoveCurrentp(p, hp1);
  4242. JumpTracking.Free;
  4243. Result := True;
  4244. Exit;
  4245. end;
  4246. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4247. begin
  4248. { See if there's more we can optimise }
  4249. hp3 := hp2;
  4250. Continue;
  4251. end;
  4252. end;
  4253. end;
  4254. end;
  4255. { Break out of the while loop under normal circumstances }
  4256. Break;
  4257. end;
  4258. JumpTracking.Free;
  4259. end;
  4260. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4261. (taicpu(p).oper[1]^.typ = top_reg) and
  4262. (taicpu(p).opsize = S_L) and
  4263. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4264. (hp2.typ = ait_instruction) and
  4265. (taicpu(hp2).opcode = A_AND) and
  4266. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4267. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4268. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4269. ) then
  4270. begin
  4271. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4272. begin
  4273. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4274. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4275. begin
  4276. { Optimize out:
  4277. mov x, %reg
  4278. and ffffffffh, %reg
  4279. }
  4280. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4281. RemoveInstruction(hp2);
  4282. Result:=true;
  4283. exit;
  4284. end;
  4285. end;
  4286. end;
  4287. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4288. x >= RetOffset) as it doesn't do anything (it writes either to a
  4289. parameter or to the temporary storage room for the function
  4290. result)
  4291. }
  4292. if IsExitCode(hp1) and
  4293. (taicpu(p).oper[1]^.typ = top_ref) and
  4294. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4295. (
  4296. (
  4297. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4298. not (
  4299. assigned(current_procinfo.procdef.funcretsym) and
  4300. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4301. )
  4302. ) or
  4303. { Also discard writes to the stack that are below the base pointer,
  4304. as this is temporary storage rather than a function result on the
  4305. stack, say. }
  4306. (
  4307. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4308. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4309. )
  4310. ) then
  4311. begin
  4312. RemoveCurrentp(p, hp1);
  4313. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4314. RemoveLastDeallocForFuncRes(p);
  4315. Result:=true;
  4316. exit;
  4317. end;
  4318. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4319. begin
  4320. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4321. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4322. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4323. begin
  4324. { change
  4325. mov reg1, mem1
  4326. test/cmp x, mem1
  4327. to
  4328. mov reg1, mem1
  4329. test/cmp x, reg1
  4330. }
  4331. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4332. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4334. Result := True;
  4335. Exit;
  4336. end;
  4337. if DoMovCmpMemOpt(p, hp1) then
  4338. begin
  4339. Result := True;
  4340. Exit;
  4341. end;
  4342. end;
  4343. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4344. { If the flags register is in use, don't change the instruction to an
  4345. ADD otherwise this will scramble the flags. [Kit] }
  4346. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4347. begin
  4348. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4349. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4350. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4351. ) or
  4352. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4353. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4354. )
  4355. ) then
  4356. { mov reg1,ref
  4357. lea reg2,[reg1,reg2]
  4358. to
  4359. add reg2,ref}
  4360. begin
  4361. TransferUsedRegs(TmpUsedRegs);
  4362. { reg1 may not be used afterwards }
  4363. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4364. begin
  4365. Taicpu(hp1).opcode:=A_ADD;
  4366. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4367. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4368. RemoveCurrentp(p, hp1);
  4369. result:=true;
  4370. exit;
  4371. end;
  4372. end;
  4373. { If the LEA instruction can be converted into an arithmetic instruction,
  4374. it may be possible to then fold it in the next optimisation, otherwise
  4375. there's nothing more that can be optimised here. }
  4376. if not ConvertLEA(taicpu(hp1)) then
  4377. Exit;
  4378. end;
  4379. if (taicpu(p).oper[1]^.typ = top_reg) and
  4380. (hp1.typ = ait_instruction) and
  4381. GetNextInstruction(hp1, hp2) and
  4382. MatchInstruction(hp2,A_MOV,[]) and
  4383. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4384. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4385. (
  4386. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4387. {$ifdef x86_64}
  4388. or
  4389. (
  4390. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4391. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4392. )
  4393. {$endif x86_64}
  4394. ) then
  4395. begin
  4396. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4397. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4398. { change movsX/movzX reg/ref, reg2
  4399. add/sub/or/... reg3/$const, reg2
  4400. mov reg2 reg/ref
  4401. dealloc reg2
  4402. to
  4403. add/sub/or/... reg3/$const, reg/ref }
  4404. begin
  4405. TransferUsedRegs(TmpUsedRegs);
  4406. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4407. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4408. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4409. begin
  4410. { by example:
  4411. movswl %si,%eax movswl %si,%eax p
  4412. decl %eax addl %edx,%eax hp1
  4413. movw %ax,%si movw %ax,%si hp2
  4414. ->
  4415. movswl %si,%eax movswl %si,%eax p
  4416. decw %eax addw %edx,%eax hp1
  4417. movw %ax,%si movw %ax,%si hp2
  4418. }
  4419. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4420. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4421. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4422. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4423. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4424. {
  4425. ->
  4426. movswl %si,%eax movswl %si,%eax p
  4427. decw %si addw %dx,%si hp1
  4428. movw %ax,%si movw %ax,%si hp2
  4429. }
  4430. case taicpu(hp1).ops of
  4431. 1:
  4432. begin
  4433. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4434. if taicpu(hp1).oper[0]^.typ=top_reg then
  4435. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4436. end;
  4437. 2:
  4438. begin
  4439. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4440. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4441. (taicpu(hp1).opcode<>A_SHL) and
  4442. (taicpu(hp1).opcode<>A_SHR) and
  4443. (taicpu(hp1).opcode<>A_SAR) then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. else
  4447. internalerror(2008042701);
  4448. end;
  4449. {
  4450. ->
  4451. decw %si addw %dx,%si p
  4452. }
  4453. RemoveInstruction(hp2);
  4454. RemoveCurrentP(p, hp1);
  4455. Result:=True;
  4456. Exit;
  4457. end;
  4458. end;
  4459. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4460. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4461. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4462. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4463. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4464. )
  4465. {$ifdef i386}
  4466. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4467. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4468. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4469. {$endif i386}
  4470. then
  4471. { change movsX/movzX reg/ref, reg2
  4472. add/sub/or/... regX/$const, reg2
  4473. mov reg2, reg3
  4474. dealloc reg2
  4475. to
  4476. movsX/movzX reg/ref, reg3
  4477. add/sub/or/... reg3/$const, reg3
  4478. }
  4479. begin
  4480. TransferUsedRegs(TmpUsedRegs);
  4481. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4482. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4483. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4484. begin
  4485. { by example:
  4486. movswl %si,%eax movswl %si,%eax p
  4487. decl %eax addl %edx,%eax hp1
  4488. movw %ax,%si movw %ax,%si hp2
  4489. ->
  4490. movswl %si,%eax movswl %si,%eax p
  4491. decw %eax addw %edx,%eax hp1
  4492. movw %ax,%si movw %ax,%si hp2
  4493. }
  4494. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4495. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4496. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4497. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4498. { limit size of constants as well to avoid assembler errors, but
  4499. check opsize to avoid overflow when left shifting the 1 }
  4500. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4501. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4502. {$ifdef x86_64}
  4503. { Be careful of, for example:
  4504. movl %reg1,%reg2
  4505. addl %reg3,%reg2
  4506. movq %reg2,%reg4
  4507. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4508. }
  4509. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4510. begin
  4511. taicpu(hp2).changeopsize(S_L);
  4512. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4513. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4514. end;
  4515. {$endif x86_64}
  4516. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4517. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4518. if taicpu(p).oper[0]^.typ=top_reg then
  4519. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4520. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4521. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4522. {
  4523. ->
  4524. movswl %si,%eax movswl %si,%eax p
  4525. decw %si addw %dx,%si hp1
  4526. movw %ax,%si movw %ax,%si hp2
  4527. }
  4528. case taicpu(hp1).ops of
  4529. 1:
  4530. begin
  4531. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4532. if taicpu(hp1).oper[0]^.typ=top_reg then
  4533. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4534. end;
  4535. 2:
  4536. begin
  4537. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4538. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4539. (taicpu(hp1).opcode<>A_SHL) and
  4540. (taicpu(hp1).opcode<>A_SHR) and
  4541. (taicpu(hp1).opcode<>A_SAR) then
  4542. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4543. end;
  4544. else
  4545. internalerror(2018111801);
  4546. end;
  4547. {
  4548. ->
  4549. decw %si addw %dx,%si p
  4550. }
  4551. RemoveInstruction(hp2);
  4552. end;
  4553. end;
  4554. end;
  4555. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4556. GetNextInstruction(hp1, hp2) and
  4557. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4558. MatchOperand(Taicpu(p).oper[0]^,0) and
  4559. (Taicpu(p).oper[1]^.typ = top_reg) and
  4560. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4561. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4562. { mov reg1,0
  4563. bts reg1,operand1 --> mov reg1,operand2
  4564. or reg1,operand2 bts reg1,operand1}
  4565. begin
  4566. Taicpu(hp2).opcode:=A_MOV;
  4567. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4568. asml.remove(hp1);
  4569. insertllitem(hp2,hp2.next,hp1);
  4570. RemoveCurrentp(p, hp1);
  4571. Result:=true;
  4572. exit;
  4573. end;
  4574. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4575. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4576. GetNextInstruction(hp1, hp2) and
  4577. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4578. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4579. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4580. { change
  4581. mov reg1,reg2
  4582. sub reg3,reg2
  4583. cmp reg3,reg1
  4584. into
  4585. mov reg1,reg2
  4586. sub reg3,reg2
  4587. }
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4590. RemoveInstruction(hp2);
  4591. Result:=true;
  4592. exit;
  4593. end;
  4594. {
  4595. mov ref,reg0
  4596. <op> reg0,reg1
  4597. dealloc reg0
  4598. to
  4599. <op> ref,reg1
  4600. }
  4601. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4602. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4603. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4604. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4605. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4606. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4607. begin
  4608. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4609. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4610. RemoveCurrentp(p, hp1);
  4611. Result:=true;
  4612. exit;
  4613. end;
  4614. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4615. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4616. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4617. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4618. begin
  4619. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4620. {$ifdef x86_64}
  4621. { Convert:
  4622. movq x(ref),%reg64
  4623. shrq y,%reg64
  4624. To:
  4625. movl x+4(ref),%reg32
  4626. shrl y-32,%reg32 (Remove if y = 32)
  4627. }
  4628. if (taicpu(p).opsize = S_Q) and
  4629. (taicpu(hp1).opcode = A_SHR) and
  4630. (taicpu(hp1).oper[0]^.val >= 32) then
  4631. begin
  4632. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4633. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4634. { Convert to 32-bit }
  4635. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4636. taicpu(p).opsize := S_L;
  4637. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4638. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4639. if (taicpu(hp1).oper[0]^.val = 32) then
  4640. begin
  4641. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4642. RemoveInstruction(hp1);
  4643. end
  4644. else
  4645. begin
  4646. { This will potentially open up more arithmetic operations since
  4647. the peephole optimizer now has a big hint that only the lower
  4648. 32 bits are currently in use (and opcodes are smaller in size) }
  4649. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4650. taicpu(hp1).opsize := S_L;
  4651. Dec(taicpu(hp1).oper[0]^.val, 32);
  4652. DebugMsg(SPeepholeOptimization + PreMessage +
  4653. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4654. end;
  4655. Result := True;
  4656. Exit;
  4657. end;
  4658. {$endif x86_64}
  4659. { Convert:
  4660. movl x(ref),%reg
  4661. shrl $24,%reg
  4662. To:
  4663. movzbl x+3(ref),%reg
  4664. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4665. Also accept sar instead of shr, but convert to movsx instead of movzx
  4666. }
  4667. if taicpu(hp1).opcode = A_SHR then
  4668. MovUnaligned := A_MOVZX
  4669. else
  4670. MovUnaligned := A_MOVSX;
  4671. NewSize := S_NO;
  4672. NewOffset := 0;
  4673. case taicpu(p).opsize of
  4674. S_B:
  4675. { No valid combinations };
  4676. S_W:
  4677. if (taicpu(hp1).oper[0]^.val = 8) then
  4678. begin
  4679. NewSize := S_BW;
  4680. NewOffset := 1;
  4681. end;
  4682. S_L:
  4683. case taicpu(hp1).oper[0]^.val of
  4684. 16:
  4685. begin
  4686. NewSize := S_WL;
  4687. NewOffset := 2;
  4688. end;
  4689. 24:
  4690. begin
  4691. NewSize := S_BL;
  4692. NewOffset := 3;
  4693. end;
  4694. else
  4695. ;
  4696. end;
  4697. {$ifdef x86_64}
  4698. S_Q:
  4699. case taicpu(hp1).oper[0]^.val of
  4700. 32:
  4701. begin
  4702. if taicpu(hp1).opcode = A_SAR then
  4703. begin
  4704. { 32-bit to 64-bit is a distinct instruction }
  4705. MovUnaligned := A_MOVSXD;
  4706. NewSize := S_LQ;
  4707. NewOffset := 4;
  4708. end
  4709. else
  4710. { Should have been handled by MovShr2Mov above }
  4711. InternalError(2022081811);
  4712. end;
  4713. 48:
  4714. begin
  4715. NewSize := S_WQ;
  4716. NewOffset := 6;
  4717. end;
  4718. 56:
  4719. begin
  4720. NewSize := S_BQ;
  4721. NewOffset := 7;
  4722. end;
  4723. else
  4724. ;
  4725. end;
  4726. {$endif x86_64}
  4727. else
  4728. InternalError(2022081810);
  4729. end;
  4730. if (NewSize <> S_NO) and
  4731. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4732. begin
  4733. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4734. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4735. debug_op2str(MovUnaligned);
  4736. {$ifdef x86_64}
  4737. if MovUnaligned <> A_MOVSXD then
  4738. { Don't add size suffix for MOVSXD }
  4739. {$endif x86_64}
  4740. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4741. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4742. taicpu(p).opcode := MovUnaligned;
  4743. taicpu(p).opsize := NewSize;
  4744. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4745. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4746. RemoveInstruction(hp1);
  4747. Result := True;
  4748. Exit;
  4749. end;
  4750. end;
  4751. { Backward optimisation shared with OptPass2MOV }
  4752. if FuncMov2Func(p, hp1) then
  4753. begin
  4754. Result := True;
  4755. Exit;
  4756. end;
  4757. end;
  4758. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4759. var
  4760. hp1 : tai;
  4761. begin
  4762. Result:=false;
  4763. if taicpu(p).ops <> 2 then
  4764. exit;
  4765. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4766. GetNextInstruction(p,hp1) then
  4767. begin
  4768. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4769. (taicpu(hp1).ops = 2) then
  4770. begin
  4771. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4772. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4773. { movXX reg1, mem1 or movXX mem1, reg1
  4774. movXX mem2, reg2 movXX reg2, mem2}
  4775. begin
  4776. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4777. { movXX reg1, mem1 or movXX mem1, reg1
  4778. movXX mem2, reg1 movXX reg2, mem1}
  4779. begin
  4780. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4781. begin
  4782. { Removes the second statement from
  4783. movXX reg1, mem1/reg2
  4784. movXX mem1/reg2, reg1
  4785. }
  4786. if taicpu(p).oper[0]^.typ=top_reg then
  4787. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4788. { Removes the second statement from
  4789. movXX mem1/reg1, reg2
  4790. movXX reg2, mem1/reg1
  4791. }
  4792. if (taicpu(p).oper[1]^.typ=top_reg) and
  4793. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4794. begin
  4795. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4796. RemoveInstruction(hp1);
  4797. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4798. Result:=true;
  4799. exit;
  4800. end
  4801. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4802. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4803. begin
  4804. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4805. RemoveInstruction(hp1);
  4806. Result:=true;
  4807. exit;
  4808. end;
  4809. end
  4810. end;
  4811. end;
  4812. end;
  4813. end;
  4814. end;
  4815. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4816. var
  4817. hp1 : tai;
  4818. begin
  4819. result:=false;
  4820. { replace
  4821. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4822. MovX %mreg2,%mreg1
  4823. dealloc %mreg2
  4824. by
  4825. <Op>X %mreg2,%mreg1
  4826. ?
  4827. }
  4828. if GetNextInstruction(p,hp1) and
  4829. { we mix single and double opperations here because we assume that the compiler
  4830. generates vmovapd only after double operations and vmovaps only after single operations }
  4831. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4832. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4833. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4834. (taicpu(p).oper[0]^.typ=top_reg) then
  4835. begin
  4836. TransferUsedRegs(TmpUsedRegs);
  4837. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4838. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4839. begin
  4840. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4841. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4842. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4843. RemoveInstruction(hp1);
  4844. result:=true;
  4845. end;
  4846. end;
  4847. end;
  4848. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4849. var
  4850. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4851. JumpLabel, JumpLabel_dist: TAsmLabel;
  4852. FirstValue, SecondValue: TCGInt;
  4853. function OptimizeJump(var InputP: tai): Boolean;
  4854. var
  4855. TempBool: Boolean;
  4856. begin
  4857. Result := False;
  4858. TempBool := True;
  4859. if DoJumpOptimizations(InputP, TempBool) or
  4860. not TempBool then
  4861. begin
  4862. Result := True;
  4863. if Assigned(InputP) then
  4864. begin
  4865. { CollapseZeroDistJump will be set to the label or an align
  4866. before it after the jump if it optimises, whether or not
  4867. the label is live or dead }
  4868. if (InputP.typ = ait_align) or
  4869. (
  4870. (InputP.typ = ait_label) and
  4871. not (tai_label(InputP).labsym.is_used)
  4872. ) then
  4873. GetNextInstruction(InputP, InputP);
  4874. end;
  4875. Exit;
  4876. end;
  4877. end;
  4878. begin
  4879. Result := False;
  4880. if (taicpu(p).oper[0]^.typ = top_const) and
  4881. (taicpu(p).oper[0]^.val <> -1) then
  4882. begin
  4883. { Convert unsigned maximum constants to -1 to aid optimisation }
  4884. case taicpu(p).opsize of
  4885. S_B:
  4886. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4887. begin
  4888. taicpu(p).oper[0]^.val := -1;
  4889. Result := True;
  4890. Exit;
  4891. end;
  4892. S_W:
  4893. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4894. begin
  4895. taicpu(p).oper[0]^.val := -1;
  4896. Result := True;
  4897. Exit;
  4898. end;
  4899. S_L:
  4900. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4901. begin
  4902. taicpu(p).oper[0]^.val := -1;
  4903. Result := True;
  4904. Exit;
  4905. end;
  4906. {$ifdef x86_64}
  4907. S_Q:
  4908. { Storing anything greater than $7FFFFFFF is not possible so do
  4909. nothing };
  4910. {$endif x86_64}
  4911. else
  4912. InternalError(2021121001);
  4913. end;
  4914. end;
  4915. if GetNextInstruction(p, hp1) and
  4916. TrySwapMovCmp(p, hp1) then
  4917. begin
  4918. Result := True;
  4919. Exit;
  4920. end;
  4921. p_label := nil;
  4922. JumpLabel := nil;
  4923. if MatchInstruction(hp1, A_Jcc, []) then
  4924. begin
  4925. if OptimizeJump(hp1) then
  4926. begin
  4927. Result := True;
  4928. if Assigned(hp1) then
  4929. begin
  4930. { CollapseZeroDistJump will be set to the label or an align
  4931. before it after the jump if it optimises, whether or not
  4932. the label is live or dead }
  4933. if (hp1.typ = ait_align) or
  4934. (
  4935. (hp1.typ = ait_label) and
  4936. not (tai_label(hp1).labsym.is_used)
  4937. ) then
  4938. GetNextInstruction(hp1, hp1);
  4939. end;
  4940. TransferUsedRegs(TmpUsedRegs);
  4941. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4942. if not Assigned(hp1) or
  4943. (
  4944. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4945. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4946. ) then
  4947. begin
  4948. { No more conditional jumps; conditional statement is no longer required }
  4949. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4950. RemoveCurrentP(p);
  4951. end;
  4952. Exit;
  4953. end;
  4954. if IsJumpToLabel(taicpu(hp1)) then
  4955. begin
  4956. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4957. if Assigned(JumpLabel) then
  4958. p_label := getlabelwithsym(JumpLabel);
  4959. end;
  4960. end;
  4961. { Search for:
  4962. test $x,(reg/ref)
  4963. jne @lbl1
  4964. test $y,(reg/ref) (same register or reference)
  4965. jne @lbl1
  4966. Change to:
  4967. test $(x or y),(reg/ref)
  4968. jne @lbl1
  4969. (Note, this doesn't work with je instead of jne)
  4970. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4971. Also search for:
  4972. test $x,(reg/ref)
  4973. je @lbl1
  4974. ...
  4975. test $y,(reg/ref)
  4976. je/jne @lbl2
  4977. If (x or y) = x, then the second jump is deterministic
  4978. }
  4979. if (
  4980. (
  4981. (taicpu(p).oper[0]^.typ = top_const) or
  4982. (
  4983. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4984. (taicpu(p).oper[0]^.typ = top_reg) and
  4985. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4986. )
  4987. ) and
  4988. MatchInstruction(hp1, A_JCC, [])
  4989. ) then
  4990. begin
  4991. if (taicpu(p).oper[0]^.typ = top_reg) and
  4992. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4993. FirstValue := -1
  4994. else
  4995. FirstValue := taicpu(p).oper[0]^.val;
  4996. { If we have several test/jne's in a row, it might be the case that
  4997. the second label doesn't go to the same location, but the one
  4998. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4999. so accommodate for this with a while loop.
  5000. }
  5001. hp1_last := hp1;
  5002. while (
  5003. (
  5004. (taicpu(p).oper[1]^.typ = top_reg) and
  5005. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5006. ) or GetNextInstruction(hp1_last, p_dist)
  5007. ) and (p_dist.typ = ait_instruction) do
  5008. begin
  5009. if (
  5010. (
  5011. (taicpu(p_dist).opcode = A_TEST) and
  5012. (
  5013. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5014. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5015. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5016. )
  5017. ) or
  5018. (
  5019. { cmp 0,%reg = test %reg,%reg }
  5020. (taicpu(p_dist).opcode = A_CMP) and
  5021. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5022. )
  5023. ) and
  5024. { Make sure the destination operands are actually the same }
  5025. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5026. GetNextInstruction(p_dist, hp1_dist) and
  5027. MatchInstruction(hp1_dist, A_JCC, []) then
  5028. begin
  5029. if OptimizeJump(hp1_dist) then
  5030. begin
  5031. Result := True;
  5032. Exit;
  5033. end;
  5034. if
  5035. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5036. (
  5037. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5038. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5039. ) then
  5040. SecondValue := -1
  5041. else
  5042. SecondValue := taicpu(p_dist).oper[0]^.val;
  5043. { If both of the TEST constants are identical, delete the
  5044. second TEST that is unnecessary (be careful though, just
  5045. in case the flags are modified in between) }
  5046. if (FirstValue = SecondValue) then
  5047. begin
  5048. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5049. begin
  5050. { Since the second jump's condition is a subset of the first, we
  5051. know it will never branch because the first jump dominates it.
  5052. Get it out of the way now rather than wait for the jump
  5053. optimisations for a speed boost. }
  5054. if IsJumpToLabel(taicpu(hp1_dist)) then
  5055. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5056. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5057. RemoveInstruction(hp1_dist);
  5058. Result := True;
  5059. end
  5060. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5061. begin
  5062. { If the inverse of the first condition is a subset of the second,
  5063. the second one will definitely branch if the first one doesn't }
  5064. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5065. { We can remove the TEST instruction too }
  5066. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5067. RemoveInstruction(p_dist);
  5068. MakeUnconditional(taicpu(hp1_dist));
  5069. RemoveDeadCodeAfterJump(hp1_dist);
  5070. { Since the jump is now unconditional, we can't
  5071. continue any further with this particular
  5072. optimisation. The original TEST is still intact
  5073. though, so there might be something else we can
  5074. do }
  5075. Include(OptsToCheck, aoc_ForceNewIteration);
  5076. Break;
  5077. end;
  5078. if Result or
  5079. { If a jump wasn't removed or made unconditional, only
  5080. remove the identical TEST instruction if the flags
  5081. weren't modified }
  5082. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5083. begin
  5084. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5085. RemoveInstruction(p_dist);
  5086. { If the jump was removed or made unconditional, we
  5087. don't need to allocate NR_DEFAULTFLAGS over the
  5088. entire range }
  5089. if not Result then
  5090. begin
  5091. { Mark the flags as 'in use' over the entire range }
  5092. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5093. { Speed gain - continue search from the Jcc instruction }
  5094. hp1_last := hp1_dist;
  5095. { Only the TEST instruction was removed, and the
  5096. original was unchanged, so we can safely do
  5097. another iteration of the while loop }
  5098. Include(OptsToCheck, aoc_ForceNewIteration);
  5099. Continue;
  5100. end;
  5101. Exit;
  5102. end;
  5103. end;
  5104. hp1_last := nil;
  5105. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5106. (
  5107. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5108. { Always adjacent under -O2 and under }
  5109. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5110. (
  5111. GetNextInstruction(hp1, hp1_last) and
  5112. (hp1_last = p_dist)
  5113. )
  5114. ) and
  5115. (
  5116. (
  5117. { Test the following variant:
  5118. test $x,(reg/ref)
  5119. jne @lbl1
  5120. test $y,(reg/ref)
  5121. je @lbl2
  5122. @lbl1:
  5123. Becomes:
  5124. test $(x or y),(reg/ref)
  5125. je @lbl2
  5126. @lbl1: (may become a dead label)
  5127. }
  5128. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5129. GetNextInstruction(hp1_dist, hp1_last) and
  5130. (hp1_last = p_label)
  5131. ) or
  5132. (
  5133. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5134. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5135. then the second jump will never branch, so it can also be
  5136. removed regardless of where it goes }
  5137. (
  5138. (FirstValue = -1) or
  5139. (SecondValue = -1) or
  5140. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5141. )
  5142. )
  5143. ) then
  5144. begin
  5145. { Same jump location... can be a register since nothing's changed }
  5146. { If any of the entries are equivalent to test %reg,%reg, then the
  5147. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5148. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5149. if (hp1_last = p_label) then
  5150. begin
  5151. { Variant }
  5152. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5153. RemoveInstruction(p_dist);
  5154. if Assigned(JumpLabel) then
  5155. JumpLabel.decrefs;
  5156. RemoveInstruction(hp1);
  5157. end
  5158. else
  5159. begin
  5160. { Only remove the second test if no jumps or other conditional instructions follow }
  5161. TransferUsedRegs(TmpUsedRegs);
  5162. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5163. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5164. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5165. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5168. RemoveInstruction(p_dist);
  5169. { Remove the first jump, not the second, to keep
  5170. any register deallocations between the second
  5171. TEST/JNE pair in the same place. Aids future
  5172. optimisation. }
  5173. if Assigned(JumpLabel) then
  5174. JumpLabel.decrefs;
  5175. RemoveInstruction(hp1);
  5176. end
  5177. else
  5178. begin
  5179. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5180. if IsJumpToLabel(taicpu(hp1_dist)) then
  5181. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5182. { Remove second jump in this instance }
  5183. RemoveInstruction(hp1_dist);
  5184. end;
  5185. end;
  5186. Result := True;
  5187. Exit;
  5188. end;
  5189. end;
  5190. if { If -O2 and under, it may stop on any old instruction }
  5191. (cs_opt_level3 in current_settings.optimizerswitches) and
  5192. (taicpu(p).oper[1]^.typ = top_reg) and
  5193. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5194. begin
  5195. hp1_last := p_dist;
  5196. Continue;
  5197. end;
  5198. Break;
  5199. end;
  5200. end;
  5201. { Search for:
  5202. test %reg,%reg
  5203. j(c1) @lbl1
  5204. ...
  5205. @lbl:
  5206. test %reg,%reg (same register)
  5207. j(c2) @lbl2
  5208. If c2 is a subset of c1, change to:
  5209. test %reg,%reg
  5210. j(c1) @lbl2
  5211. (@lbl1 may become a dead label as a result)
  5212. }
  5213. if (taicpu(p).oper[1]^.typ = top_reg) and
  5214. (taicpu(p).oper[0]^.typ = top_reg) and
  5215. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5216. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5217. Assigned(p_label) and
  5218. GetNextInstruction(p_label, p_dist) and
  5219. MatchInstruction(p_dist, A_TEST, []) and
  5220. { It's fine if the second test uses smaller sub-registers }
  5221. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5222. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5223. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5224. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5225. GetNextInstruction(p_dist, hp1_dist) and
  5226. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5227. begin
  5228. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5229. if JumpLabel = JumpLabel_dist then
  5230. { This is an infinite loop }
  5231. Exit;
  5232. { Best optimisation when the first condition is a subset (or equal) of the second }
  5233. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5234. begin
  5235. { Any registers used here will already be allocated }
  5236. if Assigned(JumpLabel) then
  5237. JumpLabel.DecRefs;
  5238. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5239. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5240. Result := True;
  5241. Exit;
  5242. end;
  5243. end;
  5244. end;
  5245. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5246. var
  5247. hp1, hp2: tai;
  5248. ActiveReg: TRegister;
  5249. OldOffset: asizeint;
  5250. ThisConst: TCGInt;
  5251. function RegDeallocated: Boolean;
  5252. begin
  5253. TransferUsedRegs(TmpUsedRegs);
  5254. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5255. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5256. end;
  5257. begin
  5258. result:=false;
  5259. hp1 := nil;
  5260. { replace
  5261. addX const,%reg1
  5262. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5263. dealloc %reg1
  5264. by
  5265. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5266. }
  5267. if MatchOpType(taicpu(p),top_const,top_reg) then
  5268. begin
  5269. ActiveReg := taicpu(p).oper[1]^.reg;
  5270. { Ensures the entire register was updated }
  5271. if (taicpu(p).opsize >= S_L) and
  5272. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5273. MatchInstruction(hp1,A_LEA,[]) and
  5274. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5275. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5276. (
  5277. { Cover the case where the register in the reference is also the destination register }
  5278. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5279. (
  5280. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5281. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5282. RegDeallocated
  5283. )
  5284. ) then
  5285. begin
  5286. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5287. {$push}
  5288. {$R-}{$Q-}
  5289. { Explicitly disable overflow checking for these offset calculation
  5290. as those do not matter for the final result }
  5291. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5292. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5293. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5295. {$pop}
  5296. {$ifdef x86_64}
  5297. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5298. begin
  5299. { Overflow; abort }
  5300. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5301. end
  5302. else
  5303. {$endif x86_64}
  5304. begin
  5305. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5306. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5307. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5308. RemoveCurrentP(p, hp1)
  5309. else
  5310. RemoveCurrentP(p);
  5311. result:=true;
  5312. Exit;
  5313. end;
  5314. end;
  5315. if (
  5316. { Save calling GetNextInstructionUsingReg again }
  5317. Assigned(hp1) or
  5318. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5319. ) and
  5320. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5321. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5322. begin
  5323. if taicpu(hp1).oper[0]^.typ = top_const then
  5324. begin
  5325. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5326. if taicpu(hp1).opcode = A_ADD then
  5327. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5328. else
  5329. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5330. Result := True;
  5331. { Handle any overflows }
  5332. case taicpu(p).opsize of
  5333. S_B:
  5334. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5335. S_W:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5337. S_L:
  5338. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5339. {$ifdef x86_64}
  5340. S_Q:
  5341. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5342. { Overflow; abort }
  5343. Result := False
  5344. else
  5345. taicpu(p).oper[0]^.val := ThisConst;
  5346. {$endif x86_64}
  5347. else
  5348. InternalError(2021102610);
  5349. end;
  5350. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5351. if Result then
  5352. begin
  5353. if (taicpu(p).oper[0]^.val < 0) and
  5354. (
  5355. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5356. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5357. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5358. ) then
  5359. begin
  5360. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5361. taicpu(p).opcode := A_SUB;
  5362. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5363. end
  5364. else
  5365. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5366. RemoveInstruction(hp1);
  5367. end;
  5368. end
  5369. else
  5370. begin
  5371. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. hp2 := p;
  5375. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5376. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5378. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5379. begin
  5380. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5381. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5382. Asml.Remove(p);
  5383. Asml.InsertAfter(p, hp1);
  5384. p := hp1;
  5385. Result := True;
  5386. Exit;
  5387. end;
  5388. end;
  5389. end;
  5390. if DoArithCombineOpt(p) then
  5391. Result:=true;
  5392. end;
  5393. end;
  5394. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5395. var
  5396. hp1, hp2: tai;
  5397. ref: Integer;
  5398. saveref: treference;
  5399. offsetcalc: Int64;
  5400. TempReg: TRegister;
  5401. Multiple: TCGInt;
  5402. Adjacent, IntermediateRegDiscarded: Boolean;
  5403. begin
  5404. Result:=false;
  5405. { play save and throw an error if LEA uses a seg register prefix,
  5406. this is most likely an error somewhere else }
  5407. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5408. internalerror(2022022001);
  5409. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5410. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5411. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5412. (
  5413. { do not mess with leas accessing the stack pointer
  5414. unless it's a null operation }
  5415. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5416. (
  5417. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5418. (taicpu(p).oper[0]^.ref^.offset = 0)
  5419. )
  5420. ) and
  5421. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5422. begin
  5423. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5424. begin
  5425. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5426. begin
  5427. taicpu(p).opcode := A_MOV;
  5428. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5429. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5430. end
  5431. else
  5432. begin
  5433. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5434. RemoveCurrentP(p);
  5435. end;
  5436. Result:=true;
  5437. exit;
  5438. end
  5439. else if (
  5440. { continue to use lea to adjust the stack pointer,
  5441. it is the recommended way, but only if not optimizing for size }
  5442. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5443. (cs_opt_size in current_settings.optimizerswitches)
  5444. ) and
  5445. { If the flags register is in use, don't change the instruction
  5446. to an ADD otherwise this will scramble the flags. [Kit] }
  5447. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5448. ConvertLEA(taicpu(p)) then
  5449. begin
  5450. Result:=true;
  5451. exit;
  5452. end;
  5453. end;
  5454. { Don't optimise if the stack or frame pointer is the destination register }
  5455. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5456. Exit;
  5457. if GetNextInstruction(p,hp1) and
  5458. (hp1.typ=ait_instruction) then
  5459. begin
  5460. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5461. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5462. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5463. begin
  5464. TransferUsedRegs(TmpUsedRegs);
  5465. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5466. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5467. begin
  5468. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5469. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5470. RemoveInstruction(hp1);
  5471. result:=true;
  5472. exit;
  5473. end;
  5474. end;
  5475. { changes
  5476. lea <ref1>, reg1
  5477. <op> ...,<ref. with reg1>,...
  5478. to
  5479. <op> ...,<ref1>,... }
  5480. { find a reference which uses reg1 }
  5481. 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
  5482. ref:=0
  5483. 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
  5484. ref:=1
  5485. else
  5486. ref:=-1;
  5487. if (ref<>-1) and
  5488. { reg1 must be either the base or the index }
  5489. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5490. begin
  5491. { reg1 can be removed from the reference }
  5492. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5493. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5494. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5495. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5496. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5497. else
  5498. Internalerror(2019111201);
  5499. { check if the can insert all data of the lea into the second instruction }
  5500. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5501. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5502. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5503. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5504. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5505. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5506. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5507. {$ifdef x86_64}
  5508. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5509. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5510. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5511. )
  5512. {$endif x86_64}
  5513. then
  5514. begin
  5515. { reg1 might not used by the second instruction after it is remove from the reference }
  5516. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5517. begin
  5518. TransferUsedRegs(TmpUsedRegs);
  5519. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5520. { reg1 is not updated so it might not be used afterwards }
  5521. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5522. begin
  5523. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5524. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5525. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5526. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5527. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5528. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5529. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5530. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5531. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5532. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5533. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5534. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5535. RemoveCurrentP(p, hp1);
  5536. result:=true;
  5537. exit;
  5538. end
  5539. end;
  5540. end;
  5541. { recover }
  5542. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5543. end;
  5544. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5545. if Adjacent or
  5546. { Check further ahead (up to 2 instructions ahead for -O2) }
  5547. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5548. begin
  5549. { Check common LEA/LEA conditions }
  5550. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5551. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5552. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5553. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5554. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5555. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5556. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5557. (
  5558. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5559. calling it (since it calls GetNextInstruction) }
  5560. Adjacent or
  5561. (
  5562. (
  5563. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5564. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5565. ) and (
  5566. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5567. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5568. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5569. )
  5570. )
  5571. ) then
  5572. begin
  5573. TransferUsedRegs(TmpUsedRegs);
  5574. hp2 := p;
  5575. repeat
  5576. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5577. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5578. IntermediateRegDiscarded :=
  5579. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5580. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5581. { changes
  5582. lea offset1(regX,scale), reg1
  5583. lea offset2(reg1,reg1), reg2
  5584. to
  5585. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5586. and
  5587. lea offset1(regX,scale1), reg1
  5588. lea offset2(reg1,scale2), reg2
  5589. to
  5590. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5591. and
  5592. lea offset1(regX,scale1), reg1
  5593. lea offset2(reg3,reg1,scale2), reg2
  5594. to
  5595. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5596. ... so long as the final scale does not exceed 8
  5597. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5598. }
  5599. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5600. (
  5601. { Don't optimise if size is a concern and the intermediate register remains in use }
  5602. IntermediateRegDiscarded or
  5603. not (cs_opt_size in current_settings.optimizerswitches)
  5604. ) and
  5605. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5606. (
  5607. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5608. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5609. ) and (
  5610. (
  5611. { lea (reg1,scale2), reg2 variant }
  5612. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5613. (
  5614. Adjacent or
  5615. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5616. ) and
  5617. (
  5618. (
  5619. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5620. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5621. ) or (
  5622. { lea (regX,regX), reg1 variant }
  5623. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5624. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5625. )
  5626. )
  5627. ) or (
  5628. { lea (reg1,reg1), reg1 variant }
  5629. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5630. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5631. )
  5632. ) then
  5633. begin
  5634. { Make everything homogeneous to make calculations easier }
  5635. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5636. begin
  5637. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5638. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5639. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5640. else
  5641. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5642. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5643. end;
  5644. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5645. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5646. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5647. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5648. begin
  5649. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5650. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5651. begin
  5652. { Put the register to change in the index register }
  5653. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5654. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5655. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5656. end;
  5657. { Change lea (reg,reg) to lea(,reg,2) }
  5658. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5659. begin
  5660. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5661. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5662. end;
  5663. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5664. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5665. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5666. { Just to prevent miscalculations }
  5667. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5668. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5669. else
  5670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5671. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5672. if IntermediateRegDiscarded then
  5673. begin
  5674. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5675. RemoveCurrentP(p);
  5676. end
  5677. else
  5678. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5679. result:=true;
  5680. exit;
  5681. end;
  5682. end;
  5683. { changes
  5684. lea offset1(regX), reg1
  5685. lea offset2(reg1), reg2
  5686. to
  5687. lea offset1+offset2(regX), reg2 }
  5688. if (
  5689. { Don't optimise if size is a concern and the intermediate register remains in use }
  5690. IntermediateRegDiscarded or
  5691. not (cs_opt_size in current_settings.optimizerswitches)
  5692. ) and
  5693. (
  5694. (
  5695. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5696. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5697. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5698. ) or (
  5699. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5700. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5701. (
  5702. (
  5703. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5704. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5705. ) or (
  5706. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5707. (
  5708. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5709. (
  5710. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5711. (
  5712. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5713. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5714. )
  5715. )
  5716. )
  5717. )
  5718. )
  5719. )
  5720. ) then
  5721. begin
  5722. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5723. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5724. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5725. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5726. begin
  5727. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5728. begin
  5729. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5730. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5731. { if the register is used as index and base, we have to increase for base as well
  5732. and adapt base }
  5733. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5734. begin
  5735. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5736. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5737. end;
  5738. end
  5739. else
  5740. begin
  5741. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5742. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5743. end;
  5744. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5745. begin
  5746. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5747. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5748. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5749. end;
  5750. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5751. if IntermediateRegDiscarded then
  5752. begin
  5753. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5754. RemoveCurrentP(p);
  5755. end
  5756. else
  5757. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5758. result:=true;
  5759. exit;
  5760. end;
  5761. end;
  5762. end;
  5763. { Change:
  5764. leal/q $x(%reg1),%reg2
  5765. ...
  5766. shll/q $y,%reg2
  5767. To:
  5768. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5769. }
  5770. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5771. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5772. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5773. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5774. (taicpu(hp1).oper[0]^.val <= 3) then
  5775. begin
  5776. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5777. TransferUsedRegs(TmpUsedRegs);
  5778. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5779. if
  5780. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5781. (this works even if scalefactor is zero) }
  5782. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5783. { Ensure offset doesn't go out of bounds }
  5784. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5785. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5786. (
  5787. (
  5788. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5789. (
  5790. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5791. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5792. (
  5793. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5794. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5795. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5796. )
  5797. )
  5798. ) or (
  5799. (
  5800. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5801. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5802. ) and
  5803. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5804. )
  5805. ) then
  5806. begin
  5807. repeat
  5808. with taicpu(p).oper[0]^.ref^ do
  5809. begin
  5810. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5811. if index = base then
  5812. begin
  5813. if Multiple > 4 then
  5814. { Optimisation will no longer work because resultant
  5815. scale factor will exceed 8 }
  5816. Break;
  5817. base := NR_NO;
  5818. scalefactor := 2;
  5819. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5820. end
  5821. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5822. begin
  5823. { Scale factor only works on the index register }
  5824. index := base;
  5825. base := NR_NO;
  5826. end;
  5827. { For safety }
  5828. if scalefactor <= 1 then
  5829. begin
  5830. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5831. scalefactor := Multiple;
  5832. end
  5833. else
  5834. begin
  5835. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5836. scalefactor := scalefactor * Multiple;
  5837. end;
  5838. offset := offset * Multiple;
  5839. end;
  5840. RemoveInstruction(hp1);
  5841. Result := True;
  5842. Exit;
  5843. { This repeat..until loop exists for the benefit of Break }
  5844. until True;
  5845. end;
  5846. end;
  5847. end;
  5848. end;
  5849. end;
  5850. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5851. var
  5852. hp1 : tai;
  5853. SubInstr: Boolean;
  5854. ThisConst: TCGInt;
  5855. const
  5856. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5857. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5858. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5859. begin
  5860. Result := False;
  5861. if taicpu(p).oper[0]^.typ <> top_const then
  5862. { Should have been confirmed before calling }
  5863. InternalError(2021102601);
  5864. SubInstr := (taicpu(p).opcode = A_SUB);
  5865. if GetLastInstruction(p, hp1) and
  5866. (hp1.typ = ait_instruction) and
  5867. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5868. begin
  5869. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5870. { Bad size }
  5871. InternalError(2022042001);
  5872. case taicpu(hp1).opcode Of
  5873. A_INC:
  5874. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5875. begin
  5876. if SubInstr then
  5877. ThisConst := taicpu(p).oper[0]^.val - 1
  5878. else
  5879. ThisConst := taicpu(p).oper[0]^.val + 1;
  5880. end
  5881. else
  5882. Exit;
  5883. A_DEC:
  5884. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5885. begin
  5886. if SubInstr then
  5887. ThisConst := taicpu(p).oper[0]^.val + 1
  5888. else
  5889. ThisConst := taicpu(p).oper[0]^.val - 1;
  5890. end
  5891. else
  5892. Exit;
  5893. A_SUB:
  5894. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5895. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5896. begin
  5897. if SubInstr then
  5898. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5899. else
  5900. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5901. end
  5902. else
  5903. Exit;
  5904. A_ADD:
  5905. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5906. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5907. begin
  5908. if SubInstr then
  5909. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5910. else
  5911. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5912. end
  5913. else
  5914. Exit;
  5915. else
  5916. Exit;
  5917. end;
  5918. { Check that the values are in range }
  5919. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5920. { Overflow; abort }
  5921. Exit;
  5922. if (ThisConst = 0) then
  5923. begin
  5924. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5925. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5926. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5927. RemoveInstruction(hp1);
  5928. hp1 := tai(p.next);
  5929. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5930. if not GetLastInstruction(hp1, p) then
  5931. p := hp1;
  5932. end
  5933. else
  5934. begin
  5935. if taicpu(hp1).opercnt=1 then
  5936. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5937. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5938. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5939. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5940. else
  5941. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5942. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5943. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5944. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5945. RemoveInstruction(hp1);
  5946. taicpu(p).loadconst(0, ThisConst);
  5947. end;
  5948. Result := True;
  5949. end;
  5950. end;
  5951. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5952. begin
  5953. Result := False;
  5954. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5955. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5956. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5957. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5958. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5959. (
  5960. (
  5961. (taicpu(hp1).opcode = A_TEST)
  5962. ) or (
  5963. (taicpu(hp1).opcode = A_CMP) and
  5964. { A sanity check more than anything }
  5965. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5966. )
  5967. ) then
  5968. begin
  5969. { change
  5970. mov mem, %reg
  5971. ...
  5972. cmp/test x, %reg / test %reg,%reg
  5973. (reg deallocated)
  5974. to
  5975. cmp/test x, mem / cmp 0, mem
  5976. }
  5977. TransferUsedRegs(TmpUsedRegs);
  5978. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5979. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5980. begin
  5981. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5982. if (taicpu(hp1).opcode = A_TEST) and
  5983. (
  5984. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5985. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5986. ) then
  5987. begin
  5988. taicpu(hp1).opcode := A_CMP;
  5989. taicpu(hp1).loadconst(0, 0);
  5990. end;
  5991. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5992. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5993. RemoveCurrentP(p);
  5994. if (p <> hp1) then
  5995. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5996. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5997. { Make sure the flags are allocated across the CMP instruction }
  5998. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5999. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6000. Result := True;
  6001. Exit;
  6002. end;
  6003. end;
  6004. end;
  6005. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6006. var
  6007. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6008. ThisReg, SecondReg: TRegister;
  6009. JumpLoc: TAsmLabel;
  6010. NewSize: TOpSize;
  6011. begin
  6012. Result := False;
  6013. {
  6014. Convert:
  6015. j<c> .L1
  6016. .L2:
  6017. mov 1,reg
  6018. jmp .L3 (or ret, although it might not be a RET yet)
  6019. .L1:
  6020. mov 0,reg
  6021. jmp .L3 (or ret)
  6022. ( As long as .L3 <> .L1 or .L2)
  6023. To:
  6024. mov 0,reg
  6025. set<not(c)> reg
  6026. jmp .L3 (or ret)
  6027. .L2:
  6028. mov 1,reg
  6029. jmp .L3 (or ret)
  6030. .L1:
  6031. mov 0,reg
  6032. jmp .L3 (or ret)
  6033. }
  6034. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6035. Exit;
  6036. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6037. if GetNextInstruction(hp_label, hp2) and
  6038. MatchInstruction(hp2,A_MOV,[]) and
  6039. (taicpu(hp2).oper[0]^.typ = top_const) and
  6040. (
  6041. (
  6042. (taicpu(hp2).oper[1]^.typ = top_reg)
  6043. {$ifdef i386}
  6044. { Under i386, ESI, EDI, EBP and ESP
  6045. don't have an 8-bit representation }
  6046. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6047. {$endif i386}
  6048. ) or (
  6049. {$ifdef i386}
  6050. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6051. {$endif i386}
  6052. (taicpu(hp2).opsize = S_B)
  6053. )
  6054. ) and
  6055. GetNextInstruction(hp2, hp3) and
  6056. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6057. (
  6058. (taicpu(hp3).opcode=A_RET) or
  6059. (
  6060. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6061. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6062. )
  6063. ) and
  6064. GetNextInstruction(hp3, hp4) and
  6065. (hp4.typ=ait_label) and
  6066. (tai_label(hp4).labsym=JumpLoc) and
  6067. (
  6068. not (cs_opt_size in current_settings.optimizerswitches) or
  6069. { If the initial jump is the label's only reference, then it will
  6070. become a dead label if the other conditions are met and hence
  6071. remove at least 2 instructions, including a jump }
  6072. (JumpLoc.getrefs = 1)
  6073. ) and
  6074. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6075. that will be optimised out }
  6076. GetNextInstruction(hp4, hp5) and
  6077. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6078. (taicpu(hp5).oper[0]^.typ = top_const) and
  6079. (
  6080. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6081. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6082. ) and
  6083. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6084. GetNextInstruction(hp5,hp6) and
  6085. (
  6086. (hp6.typ<>ait_label) or
  6087. SkipLabels(hp6, hp6)
  6088. ) and
  6089. (hp6.typ=ait_instruction) then
  6090. begin
  6091. { First, let's look at the two jumps that are hp3 and hp6 }
  6092. if not
  6093. (
  6094. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6095. (
  6096. (taicpu(hp6).opcode=A_RET) or
  6097. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6098. )
  6099. ) then
  6100. { If condition is False, then the JMP/RET instructions matched conventionally }
  6101. begin
  6102. { See if one of the jumps can be instantly converted into a RET }
  6103. if (taicpu(hp3).opcode=A_JMP) then
  6104. begin
  6105. { Reuse hp5 }
  6106. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6107. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6108. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6109. Exit;
  6110. if MatchInstruction(hp5, A_RET, []) then
  6111. begin
  6112. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6113. ConvertJumpToRET(hp3, hp5);
  6114. Result := True;
  6115. end
  6116. else
  6117. Exit;
  6118. end;
  6119. if (taicpu(hp6).opcode=A_JMP) then
  6120. begin
  6121. { Reuse hp5 }
  6122. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6123. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6124. Exit;
  6125. if MatchInstruction(hp5, A_RET, []) then
  6126. begin
  6127. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6128. ConvertJumpToRET(hp6, hp5);
  6129. Result := True;
  6130. end
  6131. else
  6132. Exit;
  6133. end;
  6134. if not
  6135. (
  6136. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6137. (
  6138. (taicpu(hp6).opcode=A_RET) or
  6139. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6140. )
  6141. ) then
  6142. { Still doesn't match }
  6143. Exit;
  6144. end;
  6145. if (taicpu(hp2).oper[0]^.val = 1) then
  6146. begin
  6147. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6148. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6149. end
  6150. else
  6151. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6152. if taicpu(hp2).opsize=S_B then
  6153. begin
  6154. if taicpu(hp2).oper[1]^.typ = top_reg then
  6155. begin
  6156. SecondReg := taicpu(hp2).oper[1]^.reg;
  6157. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6158. end
  6159. else
  6160. begin
  6161. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6162. SecondReg := NR_NO;
  6163. end;
  6164. hp_pos := p;
  6165. hp_allocstart := hp4;
  6166. end
  6167. else
  6168. begin
  6169. { Will be a register because the size can't be S_B otherwise }
  6170. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6171. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6172. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6173. if (cs_opt_size in current_settings.optimizerswitches) then
  6174. begin
  6175. { Favour using MOVZX when optimising for size }
  6176. case taicpu(hp2).opsize of
  6177. S_W:
  6178. NewSize := S_BW;
  6179. S_L:
  6180. NewSize := S_BL;
  6181. {$ifdef x86_64}
  6182. S_Q:
  6183. begin
  6184. NewSize := S_BL;
  6185. { Will implicitly zero-extend to 64-bit }
  6186. setsubreg(SecondReg, R_SUBD);
  6187. end;
  6188. {$endif x86_64}
  6189. else
  6190. InternalError(2022101301);
  6191. end;
  6192. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6193. { Inserting it right before p will guarantee that the flags are also tracked }
  6194. Asml.InsertBefore(hp5, p);
  6195. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6196. hp_pos := hp5;
  6197. hp_allocstart := hp4;
  6198. end
  6199. else
  6200. begin
  6201. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6202. { Inserting it right before p will guarantee that the flags are also tracked }
  6203. Asml.InsertBefore(hp5, p);
  6204. hp_pos := p;
  6205. hp_allocstart := hp5;
  6206. end;
  6207. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6208. end;
  6209. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6210. taicpu(hp4).condition := taicpu(p).condition;
  6211. asml.InsertBefore(hp4, hp_pos);
  6212. if taicpu(hp3).is_jmp then
  6213. begin
  6214. JumpLoc.decrefs;
  6215. MakeUnconditional(taicpu(p));
  6216. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6217. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6218. end
  6219. else
  6220. ConvertJumpToRET(p, hp3);
  6221. if SecondReg <> NR_NO then
  6222. { Ensure the destination register is allocated over this region }
  6223. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6224. if (JumpLoc.getrefs = 0) then
  6225. RemoveDeadCodeAfterJump(hp3);
  6226. Result:=true;
  6227. exit;
  6228. end;
  6229. end;
  6230. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6231. var
  6232. hp1, hp2: tai;
  6233. ActiveReg: TRegister;
  6234. OldOffset: asizeint;
  6235. ThisConst: TCGInt;
  6236. function RegDeallocated: Boolean;
  6237. begin
  6238. TransferUsedRegs(TmpUsedRegs);
  6239. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6240. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6241. end;
  6242. begin
  6243. Result:=false;
  6244. hp1 := nil;
  6245. { replace
  6246. subX const,%reg1
  6247. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6248. dealloc %reg1
  6249. by
  6250. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6251. }
  6252. if MatchOpType(taicpu(p),top_const,top_reg) then
  6253. begin
  6254. ActiveReg := taicpu(p).oper[1]^.reg;
  6255. { Ensures the entire register was updated }
  6256. if (taicpu(p).opsize >= S_L) and
  6257. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6258. MatchInstruction(hp1,A_LEA,[]) and
  6259. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6260. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6261. (
  6262. { Cover the case where the register in the reference is also the destination register }
  6263. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6264. (
  6265. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6266. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6267. RegDeallocated
  6268. )
  6269. ) then
  6270. begin
  6271. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6272. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6273. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6274. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6275. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6276. {$ifdef x86_64}
  6277. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6278. begin
  6279. { Overflow; abort }
  6280. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6281. end
  6282. else
  6283. {$endif x86_64}
  6284. begin
  6285. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6286. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6287. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6288. RemoveCurrentP(p, hp1)
  6289. else
  6290. RemoveCurrentP(p);
  6291. result:=true;
  6292. Exit;
  6293. end;
  6294. end;
  6295. if (
  6296. { Save calling GetNextInstructionUsingReg again }
  6297. Assigned(hp1) or
  6298. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6299. ) and
  6300. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6301. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6302. begin
  6303. if taicpu(hp1).oper[0]^.typ = top_const then
  6304. begin
  6305. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6306. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6307. Result := True;
  6308. { Handle any overflows }
  6309. case taicpu(p).opsize of
  6310. S_B:
  6311. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6312. S_W:
  6313. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6314. S_L:
  6315. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6316. {$ifdef x86_64}
  6317. S_Q:
  6318. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6319. { Overflow; abort }
  6320. Result := False
  6321. else
  6322. taicpu(p).oper[0]^.val := ThisConst;
  6323. {$endif x86_64}
  6324. else
  6325. InternalError(2021102611);
  6326. end;
  6327. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6328. if Result then
  6329. begin
  6330. if (taicpu(p).oper[0]^.val < 0) and
  6331. (
  6332. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6333. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6334. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6335. ) then
  6336. begin
  6337. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6338. taicpu(p).opcode := A_SUB;
  6339. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6340. end
  6341. else
  6342. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6343. RemoveInstruction(hp1);
  6344. end;
  6345. end
  6346. else
  6347. begin
  6348. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6349. TransferUsedRegs(TmpUsedRegs);
  6350. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6351. hp2 := p;
  6352. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6353. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6354. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6355. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6356. begin
  6357. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6358. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6359. Asml.Remove(p);
  6360. Asml.InsertAfter(p, hp1);
  6361. p := hp1;
  6362. Result := True;
  6363. Exit;
  6364. end;
  6365. end;
  6366. end;
  6367. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6368. { * change "sub/add const1, reg" or "dec reg" followed by
  6369. "sub const2, reg" to one "sub ..., reg" }
  6370. {$ifdef i386}
  6371. if (taicpu(p).oper[0]^.val = 2) and
  6372. (ActiveReg = NR_ESP) and
  6373. { Don't do the sub/push optimization if the sub }
  6374. { comes from setting up the stack frame (JM) }
  6375. (not(GetLastInstruction(p,hp1)) or
  6376. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6377. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6378. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6379. begin
  6380. hp1 := tai(p.next);
  6381. while Assigned(hp1) and
  6382. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6383. not RegReadByInstruction(NR_ESP,hp1) and
  6384. not RegModifiedByInstruction(NR_ESP,hp1) do
  6385. hp1 := tai(hp1.next);
  6386. if Assigned(hp1) and
  6387. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6388. begin
  6389. taicpu(hp1).changeopsize(S_L);
  6390. if taicpu(hp1).oper[0]^.typ=top_reg then
  6391. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6392. hp1 := tai(p.next);
  6393. RemoveCurrentp(p, hp1);
  6394. Result:=true;
  6395. exit;
  6396. end;
  6397. end;
  6398. {$endif i386}
  6399. if DoArithCombineOpt(p) then
  6400. Result:=true;
  6401. end;
  6402. end;
  6403. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6404. var
  6405. TmpBool1,TmpBool2 : Boolean;
  6406. tmpref : treference;
  6407. hp1,hp2: tai;
  6408. mask, shiftval: tcgint;
  6409. begin
  6410. Result:=false;
  6411. { All these optimisations work on "shl/sal const,%reg" }
  6412. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6413. Exit;
  6414. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6415. (taicpu(p).oper[0]^.val <= 3) then
  6416. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6417. begin
  6418. { should we check the next instruction? }
  6419. TmpBool1 := True;
  6420. { have we found an add/sub which could be
  6421. integrated in the lea? }
  6422. TmpBool2 := False;
  6423. reference_reset(tmpref,2,[]);
  6424. TmpRef.index := taicpu(p).oper[1]^.reg;
  6425. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6426. while TmpBool1 and
  6427. GetNextInstruction(p, hp1) and
  6428. (tai(hp1).typ = ait_instruction) and
  6429. ((((taicpu(hp1).opcode = A_ADD) or
  6430. (taicpu(hp1).opcode = A_SUB)) and
  6431. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6432. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6433. (((taicpu(hp1).opcode = A_INC) or
  6434. (taicpu(hp1).opcode = A_DEC)) and
  6435. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6436. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6437. ((taicpu(hp1).opcode = A_LEA) and
  6438. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6439. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6440. (not GetNextInstruction(hp1,hp2) or
  6441. not instrReadsFlags(hp2)) Do
  6442. begin
  6443. TmpBool1 := False;
  6444. if taicpu(hp1).opcode=A_LEA then
  6445. begin
  6446. if (TmpRef.base = NR_NO) and
  6447. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6448. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6449. { Segment register isn't a concern here }
  6450. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6451. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6452. begin
  6453. TmpBool1 := True;
  6454. TmpBool2 := True;
  6455. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6456. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6457. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6458. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6459. RemoveInstruction(hp1);
  6460. end
  6461. end
  6462. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6463. begin
  6464. TmpBool1 := True;
  6465. TmpBool2 := True;
  6466. case taicpu(hp1).opcode of
  6467. A_ADD:
  6468. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6469. A_SUB:
  6470. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6471. else
  6472. internalerror(2019050536);
  6473. end;
  6474. RemoveInstruction(hp1);
  6475. end
  6476. else
  6477. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6478. (((taicpu(hp1).opcode = A_ADD) and
  6479. (TmpRef.base = NR_NO)) or
  6480. (taicpu(hp1).opcode = A_INC) or
  6481. (taicpu(hp1).opcode = A_DEC)) then
  6482. begin
  6483. TmpBool1 := True;
  6484. TmpBool2 := True;
  6485. case taicpu(hp1).opcode of
  6486. A_ADD:
  6487. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6488. A_INC:
  6489. inc(TmpRef.offset);
  6490. A_DEC:
  6491. dec(TmpRef.offset);
  6492. else
  6493. internalerror(2019050535);
  6494. end;
  6495. RemoveInstruction(hp1);
  6496. end;
  6497. end;
  6498. if TmpBool2
  6499. {$ifndef x86_64}
  6500. or
  6501. ((current_settings.optimizecputype < cpu_Pentium2) and
  6502. (taicpu(p).oper[0]^.val <= 3) and
  6503. not(cs_opt_size in current_settings.optimizerswitches))
  6504. {$endif x86_64}
  6505. then
  6506. begin
  6507. if not(TmpBool2) and
  6508. (taicpu(p).oper[0]^.val=1) then
  6509. begin
  6510. taicpu(p).opcode := A_ADD;
  6511. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6512. end
  6513. else
  6514. begin
  6515. taicpu(p).opcode := A_LEA;
  6516. taicpu(p).loadref(0, TmpRef);
  6517. end;
  6518. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6519. Result := True;
  6520. end;
  6521. end
  6522. {$ifndef x86_64}
  6523. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6524. begin
  6525. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6526. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6527. (unlike shl, which is only Tairable in the U pipe) }
  6528. if taicpu(p).oper[0]^.val=1 then
  6529. begin
  6530. taicpu(p).opcode := A_ADD;
  6531. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6532. Result := True;
  6533. end
  6534. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6535. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6536. else if (taicpu(p).opsize = S_L) and
  6537. (taicpu(p).oper[0]^.val<= 3) then
  6538. begin
  6539. reference_reset(tmpref,2,[]);
  6540. TmpRef.index := taicpu(p).oper[1]^.reg;
  6541. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6542. taicpu(p).opcode := A_LEA;
  6543. taicpu(p).loadref(0, TmpRef);
  6544. Result := True;
  6545. end;
  6546. end
  6547. {$endif x86_64}
  6548. else if
  6549. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6550. (
  6551. (
  6552. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6553. SetAndTest(hp1, hp2)
  6554. {$ifdef x86_64}
  6555. ) or
  6556. (
  6557. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6558. GetNextInstruction(hp1, hp2) and
  6559. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6560. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6561. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6562. {$endif x86_64}
  6563. )
  6564. ) and
  6565. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6566. begin
  6567. { Change:
  6568. shl x, %reg1
  6569. mov -(1<<x), %reg2
  6570. and %reg2, %reg1
  6571. Or:
  6572. shl x, %reg1
  6573. and -(1<<x), %reg1
  6574. To just:
  6575. shl x, %reg1
  6576. Since the and operation only zeroes bits that are already zero from the shl operation
  6577. }
  6578. case taicpu(p).oper[0]^.val of
  6579. 8:
  6580. mask:=$FFFFFFFFFFFFFF00;
  6581. 16:
  6582. mask:=$FFFFFFFFFFFF0000;
  6583. 32:
  6584. mask:=$FFFFFFFF00000000;
  6585. 63:
  6586. { Constant pre-calculated to prevent overflow errors with Int64 }
  6587. mask:=$8000000000000000;
  6588. else
  6589. begin
  6590. if taicpu(p).oper[0]^.val >= 64 then
  6591. { Shouldn't happen realistically, since the register
  6592. is guaranteed to be set to zero at this point }
  6593. mask := 0
  6594. else
  6595. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6596. end;
  6597. end;
  6598. if taicpu(hp1).oper[0]^.val = mask then
  6599. begin
  6600. { Everything checks out, perform the optimisation, as long as
  6601. the FLAGS register isn't being used}
  6602. TransferUsedRegs(TmpUsedRegs);
  6603. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6604. {$ifdef x86_64}
  6605. if (hp1 <> hp2) then
  6606. begin
  6607. { "shl/mov/and" version }
  6608. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6609. { Don't do the optimisation if the FLAGS register is in use }
  6610. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6611. begin
  6612. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6613. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6614. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6615. begin
  6616. RemoveInstruction(hp1);
  6617. Result := True;
  6618. end;
  6619. { Only set Result to True if the 'mov' instruction was removed }
  6620. RemoveInstruction(hp2);
  6621. end;
  6622. end
  6623. else
  6624. {$endif x86_64}
  6625. begin
  6626. { "shl/and" version }
  6627. { Don't do the optimisation if the FLAGS register is in use }
  6628. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6629. begin
  6630. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6631. RemoveInstruction(hp1);
  6632. Result := True;
  6633. end;
  6634. end;
  6635. Exit;
  6636. end
  6637. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6638. begin
  6639. { Even if the mask doesn't allow for its removal, we might be
  6640. able to optimise the mask for the "shl/and" version, which
  6641. may permit other peephole optimisations }
  6642. {$ifdef DEBUG_AOPTCPU}
  6643. mask := taicpu(hp1).oper[0]^.val and mask;
  6644. if taicpu(hp1).oper[0]^.val <> mask then
  6645. begin
  6646. DebugMsg(
  6647. SPeepholeOptimization +
  6648. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6649. ' to $' + debug_tostr(mask) +
  6650. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6651. taicpu(hp1).oper[0]^.val := mask;
  6652. end;
  6653. {$else DEBUG_AOPTCPU}
  6654. { If debugging is off, just set the operand even if it's the same }
  6655. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6656. {$endif DEBUG_AOPTCPU}
  6657. end;
  6658. end;
  6659. {
  6660. change
  6661. shl/sal const,reg
  6662. <op> ...(...,reg,1),...
  6663. into
  6664. <op> ...(...,reg,1 shl const),...
  6665. if const in 1..3
  6666. }
  6667. if MatchOpType(taicpu(p), top_const, top_reg) and
  6668. (taicpu(p).oper[0]^.val in [1..3]) and
  6669. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6670. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6671. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6672. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6673. MatchOpType(taicpu(hp1),top_ref))
  6674. ) and
  6675. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6676. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6677. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6678. begin
  6679. TransferUsedRegs(TmpUsedRegs);
  6680. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6681. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6682. begin
  6683. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6684. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6685. RemoveCurrentP(p);
  6686. Result:=true;
  6687. exit;
  6688. end;
  6689. end;
  6690. if MatchOpType(taicpu(p), top_const, top_reg) and
  6691. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6692. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6693. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6694. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6695. begin
  6696. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6697. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6698. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6699. {$ifdef x86_64}
  6700. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6701. {$endif x86_64}
  6702. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6703. begin
  6704. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6705. taicpu(hp1).opcode:=A_MOV;
  6706. taicpu(hp1).oper[0]^.val:=0;
  6707. end
  6708. else
  6709. begin
  6710. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6711. taicpu(hp1).oper[0]^.val:=shiftval;
  6712. end;
  6713. RemoveCurrentP(p);
  6714. Result:=true;
  6715. exit;
  6716. end;
  6717. end;
  6718. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6719. begin
  6720. case shr_size of
  6721. S_B:
  6722. { No valid combinations }
  6723. Result := False;
  6724. S_W:
  6725. Result := (Shift >= 8) and (movz_size = S_BW);
  6726. S_L:
  6727. Result :=
  6728. (Shift >= 24) { Any opsize is valid for this shift } or
  6729. ((Shift >= 16) and (movz_size = S_WL));
  6730. {$ifdef x86_64}
  6731. S_Q:
  6732. Result :=
  6733. (Shift >= 56) { Any opsize is valid for this shift } or
  6734. ((Shift >= 48) and (movz_size = S_WL));
  6735. {$endif x86_64}
  6736. else
  6737. InternalError(2022081510);
  6738. end;
  6739. end;
  6740. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6741. var
  6742. hp1, hp2: tai;
  6743. Shift: TCGInt;
  6744. LimitSize: Topsize;
  6745. DoNotMerge: Boolean;
  6746. begin
  6747. Result := False;
  6748. { All these optimisations work on "shr const,%reg" }
  6749. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6750. Exit;
  6751. DoNotMerge := False;
  6752. Shift := taicpu(p).oper[0]^.val;
  6753. LimitSize := taicpu(p).opsize;
  6754. hp1 := p;
  6755. repeat
  6756. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6757. Exit;
  6758. case taicpu(hp1).opcode of
  6759. A_TEST, A_CMP, A_Jcc:
  6760. { Skip over conditional jumps and relevant comparisons }
  6761. Continue;
  6762. A_MOVZX:
  6763. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6764. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6765. begin
  6766. { Since the original register is being read as is, subsequent
  6767. SHRs must not be merged at this point }
  6768. DoNotMerge := True;
  6769. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6770. begin
  6771. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6772. begin
  6773. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6774. taicpu(hp1).opcode := A_MOV;
  6775. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6776. case taicpu(hp1).opsize of
  6777. S_BW:
  6778. taicpu(hp1).opsize := S_W;
  6779. S_BL, S_WL:
  6780. taicpu(hp1).opsize := S_L;
  6781. else
  6782. InternalError(2022081503);
  6783. end;
  6784. { p itself hasn't changed, so no need to set Result to True }
  6785. Include(OptsToCheck, aoc_ForceNewIteration);
  6786. { See if there's anything afterwards that can be
  6787. optimised, since the input register hasn't changed }
  6788. Continue;
  6789. end;
  6790. { NOTE: If the MOVZX instruction reads and writes the same
  6791. register, defer this to the post-peephole optimisation stage }
  6792. Exit;
  6793. end;
  6794. end;
  6795. A_SHL, A_SAL, A_SHR:
  6796. if (taicpu(hp1).opsize <= LimitSize) and
  6797. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6798. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6799. begin
  6800. { Make sure the sizes don't exceed the register size limit
  6801. (measured by the shift value falling below the limit) }
  6802. if taicpu(hp1).opsize < LimitSize then
  6803. LimitSize := taicpu(hp1).opsize;
  6804. if taicpu(hp1).opcode = A_SHR then
  6805. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6806. else
  6807. begin
  6808. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6809. DoNotMerge := True;
  6810. end;
  6811. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6812. Exit;
  6813. { Since we've established that the combined shift is within
  6814. limits, we can actually combine the adjacent SHR
  6815. instructions even if they're different sizes }
  6816. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6817. begin
  6818. hp2 := tai(hp1.Previous);
  6819. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6820. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6821. RemoveInstruction(hp1);
  6822. hp1 := hp2;
  6823. { Though p has changed, only the constant has, and its
  6824. effects can still be detected on the next iteration of
  6825. the repeat..until loop }
  6826. Include(OptsToCheck, aoc_ForceNewIteration);
  6827. end;
  6828. { Move onto the next instruction }
  6829. Continue;
  6830. end;
  6831. else
  6832. ;
  6833. end;
  6834. Break;
  6835. until False;
  6836. end;
  6837. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6838. var
  6839. CurrentRef: TReference;
  6840. FullReg: TRegister;
  6841. hp1, hp2: tai;
  6842. begin
  6843. Result := False;
  6844. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6845. Exit;
  6846. { We assume you've checked if the operand is actually a reference by
  6847. this point. If it isn't, you'll most likely get an access violation }
  6848. CurrentRef := first_mov.oper[1]^.ref^;
  6849. { Memory must be aligned }
  6850. if (CurrentRef.offset mod 4) <> 0 then
  6851. Exit;
  6852. Inc(CurrentRef.offset);
  6853. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6854. if MatchOperand(second_mov.oper[0]^, 0) and
  6855. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6856. GetNextInstruction(second_mov, hp1) and
  6857. (hp1.typ = ait_instruction) and
  6858. (taicpu(hp1).opcode = A_MOV) and
  6859. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6860. (taicpu(hp1).oper[0]^.val = 0) then
  6861. begin
  6862. Inc(CurrentRef.offset);
  6863. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6864. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6865. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6866. begin
  6867. case taicpu(hp1).opsize of
  6868. S_B:
  6869. if GetNextInstruction(hp1, hp2) and
  6870. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6871. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6872. (taicpu(hp2).oper[0]^.val = 0) then
  6873. begin
  6874. Inc(CurrentRef.offset);
  6875. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6876. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6877. (taicpu(hp2).opsize = S_B) then
  6878. begin
  6879. RemoveInstruction(hp1);
  6880. RemoveInstruction(hp2);
  6881. first_mov.opsize := S_L;
  6882. if first_mov.oper[0]^.typ = top_reg then
  6883. begin
  6884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6885. { Reuse second_mov as a MOVZX instruction }
  6886. second_mov.opcode := A_MOVZX;
  6887. second_mov.opsize := S_BL;
  6888. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6889. second_mov.loadreg(1, FullReg);
  6890. first_mov.oper[0]^.reg := FullReg;
  6891. asml.Remove(second_mov);
  6892. asml.InsertBefore(second_mov, first_mov);
  6893. end
  6894. else
  6895. { It's a value }
  6896. begin
  6897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6898. RemoveInstruction(second_mov);
  6899. end;
  6900. Result := True;
  6901. Exit;
  6902. end;
  6903. end;
  6904. S_W:
  6905. begin
  6906. RemoveInstruction(hp1);
  6907. first_mov.opsize := S_L;
  6908. if first_mov.oper[0]^.typ = top_reg then
  6909. begin
  6910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6911. { Reuse second_mov as a MOVZX instruction }
  6912. second_mov.opcode := A_MOVZX;
  6913. second_mov.opsize := S_BL;
  6914. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6915. second_mov.loadreg(1, FullReg);
  6916. first_mov.oper[0]^.reg := FullReg;
  6917. asml.Remove(second_mov);
  6918. asml.InsertBefore(second_mov, first_mov);
  6919. end
  6920. else
  6921. { It's a value }
  6922. begin
  6923. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6924. RemoveInstruction(second_mov);
  6925. end;
  6926. Result := True;
  6927. Exit;
  6928. end;
  6929. else
  6930. ;
  6931. end;
  6932. end;
  6933. end;
  6934. end;
  6935. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6936. { returns true if a "continue" should be done after this optimization }
  6937. var
  6938. hp1, hp2, hp3: tai;
  6939. begin
  6940. Result := false;
  6941. hp3 := nil;
  6942. if MatchOpType(taicpu(p),top_ref) and
  6943. GetNextInstruction(p, hp1) and
  6944. (hp1.typ = ait_instruction) and
  6945. (((taicpu(hp1).opcode = A_FLD) and
  6946. (taicpu(p).opcode = A_FSTP)) or
  6947. ((taicpu(p).opcode = A_FISTP) and
  6948. (taicpu(hp1).opcode = A_FILD))) and
  6949. MatchOpType(taicpu(hp1),top_ref) and
  6950. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6951. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6952. begin
  6953. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6954. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6955. GetNextInstruction(hp1, hp2) and
  6956. (((hp2.typ = ait_instruction) and
  6957. IsExitCode(hp2) and
  6958. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6959. not(assigned(current_procinfo.procdef.funcretsym) and
  6960. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6961. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6962. { fstp <temp>
  6963. fld <temp>
  6964. <dealloc> <temp>
  6965. }
  6966. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6967. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6968. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6969. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6970. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6971. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6972. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6973. )
  6974. )
  6975. ) then
  6976. begin
  6977. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6978. RemoveInstruction(hp1);
  6979. RemoveCurrentP(p, hp2);
  6980. { first case: exit code }
  6981. if hp2.typ = ait_instruction then
  6982. RemoveLastDeallocForFuncRes(p);
  6983. Result := true;
  6984. end
  6985. else
  6986. { we can do this only in fast math mode as fstp is rounding ...
  6987. ... still disabled as it breaks the compiler and/or rtl }
  6988. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6989. { ... or if another fstp equal to the first one follows }
  6990. GetNextInstruction(hp1,hp2) and
  6991. (hp2.typ = ait_instruction) and
  6992. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6993. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6994. begin
  6995. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6996. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6997. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6998. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6999. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7000. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7001. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7002. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7003. ) then
  7004. begin
  7005. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7006. RemoveCurrentP(p,hp2);
  7007. RemoveInstruction(hp1);
  7008. Result := true;
  7009. end
  7010. else if { fst can't store an extended/comp value }
  7011. (taicpu(p).opsize <> S_FX) and
  7012. (taicpu(p).opsize <> S_IQ) then
  7013. begin
  7014. if (taicpu(p).opcode = A_FSTP) then
  7015. taicpu(p).opcode := A_FST
  7016. else
  7017. taicpu(p).opcode := A_FIST;
  7018. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7019. RemoveInstruction(hp1);
  7020. Result := true;
  7021. end;
  7022. end;
  7023. end;
  7024. end;
  7025. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7026. var
  7027. hp1, hp2, hp3: tai;
  7028. begin
  7029. result:=false;
  7030. if MatchOpType(taicpu(p),top_reg) and
  7031. GetNextInstruction(p, hp1) and
  7032. (hp1.typ = Ait_Instruction) and
  7033. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7034. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7035. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7036. { change to
  7037. fld reg fxxx reg,st
  7038. fxxxp st, st1 (hp1)
  7039. Remark: non commutative operations must be reversed!
  7040. }
  7041. begin
  7042. case taicpu(hp1).opcode Of
  7043. A_FMULP,A_FADDP,
  7044. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7045. begin
  7046. case taicpu(hp1).opcode Of
  7047. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7048. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7049. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7050. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7051. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7052. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7053. else
  7054. internalerror(2019050534);
  7055. end;
  7056. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7057. taicpu(hp1).oper[1]^.reg := NR_ST;
  7058. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7059. RemoveCurrentP(p, hp1);
  7060. Result:=true;
  7061. exit;
  7062. end;
  7063. else
  7064. ;
  7065. end;
  7066. end
  7067. else
  7068. if MatchOpType(taicpu(p),top_ref) and
  7069. GetNextInstruction(p, hp2) and
  7070. (hp2.typ = Ait_Instruction) and
  7071. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7072. (taicpu(p).opsize in [S_FS, S_FL]) and
  7073. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7074. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7075. if GetLastInstruction(p, hp1) and
  7076. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7077. MatchOpType(taicpu(hp1),top_ref) and
  7078. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7079. if ((taicpu(hp2).opcode = A_FMULP) or
  7080. (taicpu(hp2).opcode = A_FADDP)) then
  7081. { change to
  7082. fld/fst mem1 (hp1) fld/fst mem1
  7083. fld mem1 (p) fadd/
  7084. faddp/ fmul st, st
  7085. fmulp st, st1 (hp2) }
  7086. begin
  7087. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7088. RemoveCurrentP(p, hp1);
  7089. if (taicpu(hp2).opcode = A_FADDP) then
  7090. taicpu(hp2).opcode := A_FADD
  7091. else
  7092. taicpu(hp2).opcode := A_FMUL;
  7093. taicpu(hp2).oper[1]^.reg := NR_ST;
  7094. end
  7095. else
  7096. { change to
  7097. fld/fst mem1 (hp1) fld/fst mem1
  7098. fld mem1 (p) fld st
  7099. }
  7100. begin
  7101. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7102. taicpu(p).changeopsize(S_FL);
  7103. taicpu(p).loadreg(0,NR_ST);
  7104. end
  7105. else
  7106. begin
  7107. case taicpu(hp2).opcode Of
  7108. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7109. { change to
  7110. fld/fst mem1 (hp1) fld/fst mem1
  7111. fld mem2 (p) fxxx mem2
  7112. fxxxp st, st1 (hp2) }
  7113. begin
  7114. case taicpu(hp2).opcode Of
  7115. A_FADDP: taicpu(p).opcode := A_FADD;
  7116. A_FMULP: taicpu(p).opcode := A_FMUL;
  7117. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7118. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7119. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7120. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7121. else
  7122. internalerror(2019050533);
  7123. end;
  7124. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7125. RemoveInstruction(hp2);
  7126. end
  7127. else
  7128. ;
  7129. end
  7130. end
  7131. end;
  7132. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7133. begin
  7134. Result := condition_in(cond1, cond2) or
  7135. { Not strictly subsets due to the actual flags checked, but because we're
  7136. comparing integers, E is a subset of AE and GE and their aliases }
  7137. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7138. end;
  7139. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7140. var
  7141. v: TCGInt;
  7142. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7143. FirstMatch, TempBool: Boolean;
  7144. NewReg: TRegister;
  7145. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7146. begin
  7147. Result:=false;
  7148. { All these optimisations need a next instruction }
  7149. if not GetNextInstruction(p, hp1) then
  7150. Exit;
  7151. { Search for:
  7152. cmp ###,###
  7153. j(c1) @lbl1
  7154. ...
  7155. @lbl:
  7156. cmp ###,### (same comparison as above)
  7157. j(c2) @lbl2
  7158. If c1 is a subset of c2, change to:
  7159. cmp ###,###
  7160. j(c1) @lbl2
  7161. (@lbl1 may become a dead label as a result)
  7162. }
  7163. { Also handle cases where there are multiple jumps in a row }
  7164. p_jump := hp1;
  7165. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7166. begin
  7167. if IsJumpToLabel(taicpu(p_jump)) then
  7168. begin
  7169. { Do jump optimisations first in case the condition becomes
  7170. unnecessary }
  7171. TempBool := True;
  7172. if DoJumpOptimizations(p_jump, TempBool) or
  7173. not TempBool then
  7174. begin
  7175. if Assigned(p_jump) then
  7176. begin
  7177. { CollapseZeroDistJump will be set to the label or an align
  7178. before it after the jump if it optimises, whether or not
  7179. the label is live or dead }
  7180. if (p_jump.typ = ait_align) or
  7181. (
  7182. (p_jump.typ = ait_label) and
  7183. not (tai_label(p_jump).labsym.is_used)
  7184. ) then
  7185. GetNextInstruction(p_jump, p_jump);
  7186. end;
  7187. TransferUsedRegs(TmpUsedRegs);
  7188. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7189. if not Assigned(p_jump) or
  7190. (
  7191. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7192. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7193. ) then
  7194. begin
  7195. { No more conditional jumps; conditional statement is no longer required }
  7196. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7197. RemoveCurrentP(p);
  7198. Result := True;
  7199. Exit;
  7200. end;
  7201. hp1 := p_jump;
  7202. Include(OptsToCheck, aoc_ForceNewIteration);
  7203. Continue;
  7204. end;
  7205. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7206. if GetNextInstruction(p_jump, hp2) and
  7207. (
  7208. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7209. not TempBool
  7210. ) then
  7211. begin
  7212. hp1 := p_jump;
  7213. Include(OptsToCheck, aoc_ForceNewIteration);
  7214. Continue;
  7215. end;
  7216. p_label := nil;
  7217. if Assigned(JumpLabel) then
  7218. p_label := getlabelwithsym(JumpLabel);
  7219. if Assigned(p_label) and
  7220. GetNextInstruction(p_label, p_dist) and
  7221. MatchInstruction(p_dist, A_CMP, []) and
  7222. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7223. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7224. GetNextInstruction(p_dist, hp1_dist) and
  7225. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7226. begin
  7227. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7228. if JumpLabel = JumpLabel_dist then
  7229. { This is an infinite loop }
  7230. Exit;
  7231. { Best optimisation when the first condition is a subset (or equal) of the second }
  7232. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7233. begin
  7234. { Any registers used here will already be allocated }
  7235. if Assigned(JumpLabel) then
  7236. JumpLabel.DecRefs;
  7237. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7238. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7239. Result := True;
  7240. { Don't exit yet. Since p and p_jump haven't actually been
  7241. removed, we can check for more on this iteration }
  7242. end
  7243. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7244. GetNextInstruction(hp1_dist, hp1_label) and
  7245. (hp1_label.typ = ait_label) then
  7246. begin
  7247. JumpLabel_far := tai_label(hp1_label).labsym;
  7248. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7249. { This is an infinite loop }
  7250. Exit;
  7251. if Assigned(JumpLabel_far) then
  7252. begin
  7253. { In this situation, if the first jump branches, the second one will never,
  7254. branch so change the destination label to after the second jump }
  7255. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7256. if Assigned(JumpLabel) then
  7257. JumpLabel.DecRefs;
  7258. JumpLabel_far.IncRefs;
  7259. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7260. Result := True;
  7261. { Don't exit yet. Since p and p_jump haven't actually been
  7262. removed, we can check for more on this iteration }
  7263. Continue;
  7264. end;
  7265. end;
  7266. end;
  7267. end;
  7268. { Search for:
  7269. cmp ###,###
  7270. j(c1) @lbl1
  7271. cmp ###,### (same as first)
  7272. Remove second cmp
  7273. }
  7274. if GetNextInstruction(p_jump, hp2) and
  7275. (
  7276. (
  7277. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7278. (
  7279. (
  7280. MatchOpType(taicpu(p), top_const, top_reg) and
  7281. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7282. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7283. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7284. ) or (
  7285. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7286. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7287. )
  7288. )
  7289. ) or (
  7290. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7291. MatchOperand(taicpu(p).oper[0]^, 0) and
  7292. (taicpu(p).oper[1]^.typ = top_reg) and
  7293. MatchInstruction(hp2, A_TEST, []) and
  7294. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7295. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7296. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7297. )
  7298. ) then
  7299. begin
  7300. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7301. RemoveInstruction(hp2);
  7302. Result := True;
  7303. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7304. end;
  7305. GetNextInstruction(p_jump, p_jump);
  7306. end;
  7307. if (
  7308. { Don't call GetNextInstruction again if we already have it }
  7309. (hp1 = p_jump) or
  7310. GetNextInstruction(p, hp1)
  7311. ) and
  7312. MatchInstruction(hp1, A_Jcc, []) and
  7313. IsJumpToLabel(taicpu(hp1)) and
  7314. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7315. GetNextInstruction(hp1, hp2) then
  7316. begin
  7317. {
  7318. cmp x, y (or "cmp y, x")
  7319. je @lbl
  7320. mov x, y
  7321. @lbl:
  7322. (x and y can be constants, registers or references)
  7323. Change to:
  7324. mov x, y (x and y will always be equal in the end)
  7325. @lbl: (may beceome a dead label)
  7326. Also:
  7327. cmp x, y (or "cmp y, x")
  7328. jne @lbl
  7329. mov x, y
  7330. @lbl:
  7331. (x and y can be constants, registers or references)
  7332. Change to:
  7333. Absolutely nothing! (Except @lbl if it's still live)
  7334. }
  7335. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7336. (
  7337. (
  7338. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7339. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7340. ) or (
  7341. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7342. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7343. )
  7344. ) and
  7345. GetNextInstruction(hp2, hp1_label) and
  7346. (hp1_label.typ = ait_label) and
  7347. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7348. begin
  7349. tai_label(hp1_label).labsym.DecRefs;
  7350. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7351. begin
  7352. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7353. RemoveInstruction(hp2);
  7354. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7355. end
  7356. else
  7357. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7358. RemoveInstruction(hp1);
  7359. RemoveCurrentp(p, hp2);
  7360. Result := True;
  7361. Exit;
  7362. end;
  7363. {
  7364. Try to optimise the following:
  7365. cmp $x,### ($x and $y can be registers or constants)
  7366. je @lbl1 (only reference)
  7367. cmp $y,### (### are identical)
  7368. @Lbl:
  7369. sete %reg1
  7370. Change to:
  7371. cmp $x,###
  7372. sete %reg2 (allocate new %reg2)
  7373. cmp $y,###
  7374. sete %reg1
  7375. orb %reg2,%reg1
  7376. (dealloc %reg2)
  7377. This adds an instruction (so don't perform under -Os), but it removes
  7378. a conditional branch.
  7379. }
  7380. if not (cs_opt_size in current_settings.optimizerswitches) and
  7381. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7382. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7383. { The first operand of CMP instructions can only be a register or
  7384. immediate anyway, so no need to check }
  7385. GetNextInstruction(hp2, p_label) and
  7386. (p_label.typ = ait_label) and
  7387. (tai_label(p_label).labsym.getrefs = 1) and
  7388. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7389. GetNextInstruction(p_label, p_dist) and
  7390. MatchInstruction(p_dist, A_SETcc, []) and
  7391. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7392. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7393. begin
  7394. TransferUsedRegs(TmpUsedRegs);
  7395. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7396. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7397. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7398. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7399. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7400. { Get the instruction after the SETcc instruction so we can
  7401. allocate a new register over the entire range }
  7402. GetNextInstruction(p_dist, hp1_dist) then
  7403. begin
  7404. { Register can appear in p if it's not used afterwards, so only
  7405. allocate between hp1 and hp1_dist }
  7406. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7407. if NewReg <> NR_NO then
  7408. begin
  7409. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7410. { Change the jump instruction into a SETcc instruction }
  7411. taicpu(hp1).opcode := A_SETcc;
  7412. taicpu(hp1).opsize := S_B;
  7413. taicpu(hp1).loadreg(0, NewReg);
  7414. { This is now a dead label }
  7415. tai_label(p_label).labsym.decrefs;
  7416. { Prefer adding before the next instruction so the FLAGS
  7417. register is deallicated first }
  7418. AsmL.InsertBefore(
  7419. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7420. hp1_dist
  7421. );
  7422. Result := True;
  7423. { Don't exit yet, as p wasn't changed and hp1, while
  7424. modified, is still intact and might be optimised by the
  7425. SETcc optimisation below }
  7426. end;
  7427. end;
  7428. end;
  7429. end;
  7430. if taicpu(p).oper[0]^.typ = top_const then
  7431. begin
  7432. if (taicpu(p).oper[0]^.val = 0) and
  7433. (taicpu(p).oper[1]^.typ = top_reg) and
  7434. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7435. begin
  7436. hp2 := p;
  7437. FirstMatch := True;
  7438. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7439. anything meaningful once it's converted to "test %reg,%reg";
  7440. additionally, some jumps will always (or never) branch, so
  7441. evaluate every jump immediately following the
  7442. comparison, optimising the conditions if possible.
  7443. Similarly with SETcc... those that are always set to 0 or 1
  7444. are changed to MOV instructions }
  7445. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7446. (
  7447. GetNextInstruction(hp2, hp1) and
  7448. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7449. ) do
  7450. begin
  7451. FirstMatch := False;
  7452. case taicpu(hp1).condition of
  7453. C_B, C_C, C_NAE, C_O:
  7454. { For B/NAE:
  7455. Will never branch since an unsigned integer can never be below zero
  7456. For C/O:
  7457. Result cannot overflow because 0 is being subtracted
  7458. }
  7459. begin
  7460. if taicpu(hp1).opcode = A_Jcc then
  7461. begin
  7462. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7463. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7464. RemoveInstruction(hp1);
  7465. { Since hp1 was deleted, hp2 must not be updated }
  7466. Continue;
  7467. end
  7468. else
  7469. begin
  7470. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7471. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7472. taicpu(hp1).opcode := A_MOV;
  7473. taicpu(hp1).ops := 2;
  7474. taicpu(hp1).condition := C_None;
  7475. taicpu(hp1).opsize := S_B;
  7476. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7477. taicpu(hp1).loadconst(0, 0);
  7478. end;
  7479. end;
  7480. C_BE, C_NA:
  7481. begin
  7482. { Will only branch if equal to zero }
  7483. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7484. taicpu(hp1).condition := C_E;
  7485. end;
  7486. C_A, C_NBE:
  7487. begin
  7488. { Will only branch if not equal to zero }
  7489. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7490. taicpu(hp1).condition := C_NE;
  7491. end;
  7492. C_AE, C_NB, C_NC, C_NO:
  7493. begin
  7494. { Will always branch }
  7495. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7496. if taicpu(hp1).opcode = A_Jcc then
  7497. begin
  7498. MakeUnconditional(taicpu(hp1));
  7499. { Any jumps/set that follow will now be dead code }
  7500. RemoveDeadCodeAfterJump(taicpu(hp1));
  7501. Break;
  7502. end
  7503. else
  7504. begin
  7505. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7506. taicpu(hp1).opcode := A_MOV;
  7507. taicpu(hp1).ops := 2;
  7508. taicpu(hp1).condition := C_None;
  7509. taicpu(hp1).opsize := S_B;
  7510. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7511. taicpu(hp1).loadconst(0, 1);
  7512. end;
  7513. end;
  7514. C_None:
  7515. InternalError(2020012201);
  7516. C_P, C_PE, C_NP, C_PO:
  7517. { We can't handle parity checks and they should never be generated
  7518. after a general-purpose CMP (it's used in some floating-point
  7519. comparisons that don't use CMP) }
  7520. InternalError(2020012202);
  7521. else
  7522. { Zero/Equality, Sign, their complements and all of the
  7523. signed comparisons do not need to be converted };
  7524. end;
  7525. hp2 := hp1;
  7526. end;
  7527. { Convert the instruction to a TEST }
  7528. taicpu(p).opcode := A_TEST;
  7529. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7530. Result := True;
  7531. Exit;
  7532. end
  7533. else if (taicpu(p).oper[0]^.val = 1) and
  7534. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7535. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7536. begin
  7537. { Convert; To:
  7538. cmp $1,r/m cmp $0,r/m
  7539. jl @lbl jle @lbl
  7540. (Also do inverted conditions)
  7541. }
  7542. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7543. taicpu(p).oper[0]^.val := 0;
  7544. if taicpu(hp1).condition in [C_L, C_NGE] then
  7545. taicpu(hp1).condition := C_LE
  7546. else
  7547. taicpu(hp1).condition := C_NLE;
  7548. { If the instruction is now "cmp $0,%reg", convert it to a
  7549. TEST (and effectively do the work of the "cmp $0,%reg" in
  7550. the block above)
  7551. }
  7552. if (taicpu(p).oper[1]^.typ = top_reg) then
  7553. begin
  7554. taicpu(p).opcode := A_TEST;
  7555. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7556. end;
  7557. Result := True;
  7558. Exit;
  7559. end
  7560. else if (taicpu(p).oper[1]^.typ = top_reg)
  7561. {$ifdef x86_64}
  7562. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7563. {$endif x86_64}
  7564. then
  7565. begin
  7566. { cmp register,$8000 neg register
  7567. je target --> jo target
  7568. .... only if register is deallocated before jump.}
  7569. case Taicpu(p).opsize of
  7570. S_B: v:=$80;
  7571. S_W: v:=$8000;
  7572. S_L: v:=qword($80000000);
  7573. else
  7574. internalerror(2013112905);
  7575. end;
  7576. if (taicpu(p).oper[0]^.val=v) and
  7577. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7578. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7579. begin
  7580. TransferUsedRegs(TmpUsedRegs);
  7581. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7582. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7583. begin
  7584. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7585. Taicpu(p).opcode:=A_NEG;
  7586. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7587. Taicpu(p).clearop(1);
  7588. Taicpu(p).ops:=1;
  7589. if Taicpu(hp1).condition=C_E then
  7590. Taicpu(hp1).condition:=C_O
  7591. else
  7592. Taicpu(hp1).condition:=C_NO;
  7593. Result:=true;
  7594. exit;
  7595. end;
  7596. end;
  7597. end;
  7598. end;
  7599. if TrySwapMovCmp(p, hp1) then
  7600. begin
  7601. Result := True;
  7602. Exit;
  7603. end;
  7604. end;
  7605. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7606. var
  7607. hp1: tai;
  7608. begin
  7609. {
  7610. remove the second (v)pxor from
  7611. pxor reg,reg
  7612. ...
  7613. pxor reg,reg
  7614. }
  7615. Result:=false;
  7616. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7617. MatchOpType(taicpu(p),top_reg,top_reg) and
  7618. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7619. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7620. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7621. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7622. begin
  7623. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7624. RemoveInstruction(hp1);
  7625. Result:=true;
  7626. Exit;
  7627. end
  7628. {
  7629. replace
  7630. pxor reg1,reg1
  7631. movapd/s reg1,reg2
  7632. dealloc reg1
  7633. by
  7634. pxor reg2,reg2
  7635. }
  7636. else if GetNextInstruction(p,hp1) and
  7637. { we mix single and double opperations here because we assume that the compiler
  7638. generates vmovapd only after double operations and vmovaps only after single operations }
  7639. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7640. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7641. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7642. (taicpu(p).oper[0]^.typ=top_reg) then
  7643. begin
  7644. TransferUsedRegs(TmpUsedRegs);
  7645. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7646. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7647. begin
  7648. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7649. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7650. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7651. RemoveInstruction(hp1);
  7652. result:=true;
  7653. end;
  7654. end;
  7655. end;
  7656. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7657. var
  7658. hp1: tai;
  7659. begin
  7660. {
  7661. remove the second (v)pxor from
  7662. (v)pxor reg,reg
  7663. ...
  7664. (v)pxor reg,reg
  7665. }
  7666. Result:=false;
  7667. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7668. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7669. begin
  7670. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7671. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7672. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7673. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7674. begin
  7675. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7676. RemoveInstruction(hp1);
  7677. Result:=true;
  7678. Exit;
  7679. end;
  7680. {$ifdef x86_64}
  7681. {
  7682. replace
  7683. vpxor reg1,reg1,reg1
  7684. vmov reg,mem
  7685. by
  7686. movq $0,mem
  7687. }
  7688. if GetNextInstruction(p,hp1) and
  7689. MatchInstruction(hp1,A_VMOVSD,[]) and
  7690. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7691. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7692. begin
  7693. TransferUsedRegs(TmpUsedRegs);
  7694. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7695. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7696. begin
  7697. taicpu(hp1).loadconst(0,0);
  7698. taicpu(hp1).opcode:=A_MOV;
  7699. taicpu(hp1).opsize:=S_Q;
  7700. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7701. RemoveCurrentP(p);
  7702. result:=true;
  7703. Exit;
  7704. end;
  7705. end;
  7706. {$endif x86_64}
  7707. end
  7708. {
  7709. replace
  7710. vpxor reg1,reg1,reg2
  7711. by
  7712. vpxor reg2,reg2,reg2
  7713. to avoid unncessary data dependencies
  7714. }
  7715. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7716. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7717. begin
  7718. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7719. { avoid unncessary data dependency }
  7720. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7721. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7722. result:=true;
  7723. exit;
  7724. end;
  7725. Result:=OptPass1VOP(p);
  7726. end;
  7727. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7728. var
  7729. hp1 : tai;
  7730. begin
  7731. result:=false;
  7732. { replace
  7733. IMul const,%mreg1,%mreg2
  7734. Mov %reg2,%mreg3
  7735. dealloc %mreg3
  7736. by
  7737. Imul const,%mreg1,%mreg23
  7738. }
  7739. if (taicpu(p).ops=3) and
  7740. GetNextInstruction(p,hp1) and
  7741. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7742. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7743. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7744. begin
  7745. TransferUsedRegs(TmpUsedRegs);
  7746. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7747. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7748. begin
  7749. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7750. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7751. RemoveInstruction(hp1);
  7752. result:=true;
  7753. end;
  7754. end;
  7755. end;
  7756. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7757. var
  7758. hp1 : tai;
  7759. begin
  7760. result:=false;
  7761. { replace
  7762. IMul %reg0,%reg1,%reg2
  7763. Mov %reg2,%reg3
  7764. dealloc %reg2
  7765. by
  7766. Imul %reg0,%reg1,%reg3
  7767. }
  7768. if GetNextInstruction(p,hp1) and
  7769. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7770. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7771. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7772. begin
  7773. TransferUsedRegs(TmpUsedRegs);
  7774. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7775. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7776. begin
  7777. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7778. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7779. RemoveInstruction(hp1);
  7780. result:=true;
  7781. end;
  7782. end;
  7783. end;
  7784. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7785. var
  7786. hp1: tai;
  7787. begin
  7788. Result:=false;
  7789. { get rid of
  7790. (v)cvtss2sd reg0,<reg1,>reg2
  7791. (v)cvtss2sd reg2,<reg2,>reg0
  7792. }
  7793. if GetNextInstruction(p,hp1) and
  7794. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7795. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7796. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7797. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7798. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7799. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7800. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7801. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7802. )
  7803. ) then
  7804. begin
  7805. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7806. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7807. begin
  7808. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7809. RemoveCurrentP(p);
  7810. RemoveInstruction(hp1);
  7811. end
  7812. else
  7813. begin
  7814. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7815. if taicpu(hp1).opcode=A_CVTSD2SS then
  7816. begin
  7817. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7818. taicpu(p).opcode:=A_MOVAPS;
  7819. end
  7820. else
  7821. begin
  7822. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7823. taicpu(p).opcode:=A_VMOVAPS;
  7824. end;
  7825. taicpu(p).ops:=2;
  7826. RemoveInstruction(hp1);
  7827. end;
  7828. Result:=true;
  7829. Exit;
  7830. end;
  7831. end;
  7832. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7833. var
  7834. hp1, hp2, hp3, hp4, hp5: tai;
  7835. ThisReg: TRegister;
  7836. begin
  7837. Result := False;
  7838. if not GetNextInstruction(p,hp1) then
  7839. Exit;
  7840. {
  7841. convert
  7842. j<c> .L1
  7843. mov 1,reg
  7844. jmp .L2
  7845. .L1
  7846. mov 0,reg
  7847. .L2
  7848. into
  7849. mov 0,reg
  7850. set<not(c)> reg
  7851. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7852. would destroy the flag contents
  7853. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7854. executed at the same time as a previous comparison.
  7855. set<not(c)> reg
  7856. movzx reg, reg
  7857. }
  7858. if MatchInstruction(hp1,A_MOV,[]) and
  7859. (taicpu(hp1).oper[0]^.typ = top_const) and
  7860. (
  7861. (
  7862. (taicpu(hp1).oper[1]^.typ = top_reg)
  7863. {$ifdef i386}
  7864. { Under i386, ESI, EDI, EBP and ESP
  7865. don't have an 8-bit representation }
  7866. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7867. {$endif i386}
  7868. ) or (
  7869. {$ifdef i386}
  7870. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7871. {$endif i386}
  7872. (taicpu(hp1).opsize = S_B)
  7873. )
  7874. ) and
  7875. GetNextInstruction(hp1,hp2) and
  7876. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7877. GetNextInstruction(hp2,hp3) and
  7878. (hp3.typ=ait_label) and
  7879. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7880. GetNextInstruction(hp3,hp4) and
  7881. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7882. (taicpu(hp4).oper[0]^.typ = top_const) and
  7883. (
  7884. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7885. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7886. ) and
  7887. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7888. GetNextInstruction(hp4,hp5) and
  7889. (hp5.typ=ait_label) and
  7890. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7891. begin
  7892. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7893. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7894. tai_label(hp3).labsym.DecRefs;
  7895. { If this isn't the only reference to the middle label, we can
  7896. still make a saving - only that the first jump and everything
  7897. that follows will remain. }
  7898. if (tai_label(hp3).labsym.getrefs = 0) then
  7899. begin
  7900. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7901. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7902. else
  7903. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7904. { remove jump, first label and second MOV (also catching any aligns) }
  7905. repeat
  7906. if not GetNextInstruction(hp2, hp3) then
  7907. InternalError(2021040810);
  7908. RemoveInstruction(hp2);
  7909. hp2 := hp3;
  7910. until hp2 = hp5;
  7911. { Don't decrement reference count before the removal loop
  7912. above, otherwise GetNextInstruction won't stop on the
  7913. the label }
  7914. tai_label(hp5).labsym.DecRefs;
  7915. end
  7916. else
  7917. begin
  7918. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7919. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7920. else
  7921. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7922. end;
  7923. taicpu(p).opcode:=A_SETcc;
  7924. taicpu(p).opsize:=S_B;
  7925. taicpu(p).is_jmp:=False;
  7926. if taicpu(hp1).opsize=S_B then
  7927. begin
  7928. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7929. if taicpu(hp1).oper[1]^.typ = top_reg then
  7930. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7931. RemoveInstruction(hp1);
  7932. end
  7933. else
  7934. begin
  7935. { Will be a register because the size can't be S_B otherwise }
  7936. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7937. taicpu(p).loadreg(0, ThisReg);
  7938. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7939. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7940. begin
  7941. case taicpu(hp1).opsize of
  7942. S_W:
  7943. taicpu(hp1).opsize := S_BW;
  7944. S_L:
  7945. taicpu(hp1).opsize := S_BL;
  7946. {$ifdef x86_64}
  7947. S_Q:
  7948. begin
  7949. taicpu(hp1).opsize := S_BL;
  7950. { Change the destination register to 32-bit }
  7951. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7952. end;
  7953. {$endif x86_64}
  7954. else
  7955. InternalError(2021040820);
  7956. end;
  7957. taicpu(hp1).opcode := A_MOVZX;
  7958. taicpu(hp1).loadreg(0, ThisReg);
  7959. end
  7960. else
  7961. begin
  7962. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7963. { hp1 is already a MOV instruction with the correct register }
  7964. taicpu(hp1).loadconst(0, 0);
  7965. { Inserting it right before p will guarantee that the flags are also tracked }
  7966. asml.Remove(hp1);
  7967. asml.InsertBefore(hp1, p);
  7968. end;
  7969. end;
  7970. Result:=true;
  7971. exit;
  7972. end
  7973. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  7974. Result := TryJccStcClcOpt(p, hp1)
  7975. else if (hp1.typ = ait_label) then
  7976. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7977. end;
  7978. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7979. var
  7980. hp1, hp2, hp3: tai;
  7981. SourceRef, TargetRef: TReference;
  7982. CurrentReg: TRegister;
  7983. begin
  7984. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7985. if not UseAVX then
  7986. InternalError(2021100501);
  7987. Result := False;
  7988. { Look for the following to simplify:
  7989. vmovdqa/u x(mem1), %xmmreg
  7990. vmovdqa/u %xmmreg, y(mem2)
  7991. vmovdqa/u x+16(mem1), %xmmreg
  7992. vmovdqa/u %xmmreg, y+16(mem2)
  7993. Change to:
  7994. vmovdqa/u x(mem1), %ymmreg
  7995. vmovdqa/u %ymmreg, y(mem2)
  7996. vpxor %ymmreg, %ymmreg, %ymmreg
  7997. ( The VPXOR instruction is to zero the upper half, thus removing the
  7998. need to call the potentially expensive VZEROUPPER instruction. Other
  7999. peephole optimisations can remove VPXOR if it's unnecessary )
  8000. }
  8001. TransferUsedRegs(TmpUsedRegs);
  8002. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8003. { NOTE: In the optimisations below, if the references dictate that an
  8004. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8005. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8006. if (taicpu(p).opsize = S_XMM) and
  8007. MatchOpType(taicpu(p), top_ref, top_reg) and
  8008. GetNextInstruction(p, hp1) and
  8009. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8010. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8011. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8012. begin
  8013. SourceRef := taicpu(p).oper[0]^.ref^;
  8014. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8015. if GetNextInstruction(hp1, hp2) and
  8016. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8017. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8018. begin
  8019. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8020. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8021. Inc(SourceRef.offset, 16);
  8022. { Reuse the register in the first block move }
  8023. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8024. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8025. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8026. begin
  8027. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8028. Inc(TargetRef.offset, 16);
  8029. if GetNextInstruction(hp2, hp3) and
  8030. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8031. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8032. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8033. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8034. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8035. begin
  8036. { Update the register tracking to the new size }
  8037. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8038. { Remember that the offsets are 16 ahead }
  8039. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8040. if not (
  8041. ((SourceRef.offset mod 32) = 16) and
  8042. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8043. ) then
  8044. taicpu(p).opcode := A_VMOVDQU;
  8045. taicpu(p).opsize := S_YMM;
  8046. taicpu(p).oper[1]^.reg := CurrentReg;
  8047. if not (
  8048. ((TargetRef.offset mod 32) = 16) and
  8049. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8050. ) then
  8051. taicpu(hp1).opcode := A_VMOVDQU;
  8052. taicpu(hp1).opsize := S_YMM;
  8053. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8054. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8055. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8056. if (pi_uses_ymm in current_procinfo.flags) then
  8057. RemoveInstruction(hp2)
  8058. else
  8059. begin
  8060. taicpu(hp2).opcode := A_VPXOR;
  8061. taicpu(hp2).opsize := S_YMM;
  8062. taicpu(hp2).loadreg(0, CurrentReg);
  8063. taicpu(hp2).loadreg(1, CurrentReg);
  8064. taicpu(hp2).loadreg(2, CurrentReg);
  8065. taicpu(hp2).ops := 3;
  8066. end;
  8067. RemoveInstruction(hp3);
  8068. Result := True;
  8069. Exit;
  8070. end;
  8071. end
  8072. else
  8073. begin
  8074. { See if the next references are 16 less rather than 16 greater }
  8075. Dec(SourceRef.offset, 32); { -16 the other way }
  8076. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8077. begin
  8078. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8079. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8080. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8081. GetNextInstruction(hp2, hp3) and
  8082. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8083. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8084. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8085. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8086. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8087. begin
  8088. { Update the register tracking to the new size }
  8089. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8090. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8091. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8092. if not(
  8093. ((SourceRef.offset mod 32) = 0) and
  8094. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8095. ) then
  8096. taicpu(hp2).opcode := A_VMOVDQU;
  8097. taicpu(hp2).opsize := S_YMM;
  8098. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8099. if not (
  8100. ((TargetRef.offset mod 32) = 0) and
  8101. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8102. ) then
  8103. taicpu(hp3).opcode := A_VMOVDQU;
  8104. taicpu(hp3).opsize := S_YMM;
  8105. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8106. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8107. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8108. if (pi_uses_ymm in current_procinfo.flags) then
  8109. RemoveInstruction(hp1)
  8110. else
  8111. begin
  8112. taicpu(hp1).opcode := A_VPXOR;
  8113. taicpu(hp1).opsize := S_YMM;
  8114. taicpu(hp1).loadreg(0, CurrentReg);
  8115. taicpu(hp1).loadreg(1, CurrentReg);
  8116. taicpu(hp1).loadreg(2, CurrentReg);
  8117. taicpu(hp1).ops := 3;
  8118. Asml.Remove(hp1);
  8119. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8120. end;
  8121. RemoveCurrentP(p, hp2);
  8122. Result := True;
  8123. Exit;
  8124. end;
  8125. end;
  8126. end;
  8127. end;
  8128. end;
  8129. end;
  8130. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8131. var
  8132. hp2, hp3, first_assignment: tai;
  8133. IncCount, OperIdx: Integer;
  8134. OrigLabel: TAsmLabel;
  8135. begin
  8136. Count := 0;
  8137. Result := False;
  8138. first_assignment := nil;
  8139. if (LoopCount >= 20) then
  8140. begin
  8141. { Guard against infinite loops }
  8142. Exit;
  8143. end;
  8144. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8145. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8146. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8147. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8148. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8149. Exit;
  8150. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8151. {
  8152. change
  8153. jmp .L1
  8154. ...
  8155. .L1:
  8156. mov ##, ## ( multiple movs possible )
  8157. jmp/ret
  8158. into
  8159. mov ##, ##
  8160. jmp/ret
  8161. }
  8162. if not Assigned(hp1) then
  8163. begin
  8164. hp1 := GetLabelWithSym(OrigLabel);
  8165. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8166. Exit;
  8167. end;
  8168. hp2 := hp1;
  8169. while Assigned(hp2) do
  8170. begin
  8171. if Assigned(hp2) and (hp2.typ = ait_label) then
  8172. SkipLabels(hp2,hp2);
  8173. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8174. Break;
  8175. case taicpu(hp2).opcode of
  8176. A_MOVSD:
  8177. begin
  8178. if taicpu(hp2).ops = 0 then
  8179. { Wrong MOVSD }
  8180. Break;
  8181. Inc(Count);
  8182. if Count >= 5 then
  8183. { Too many to be worthwhile }
  8184. Break;
  8185. GetNextInstruction(hp2, hp2);
  8186. Continue;
  8187. end;
  8188. A_MOV,
  8189. A_MOVD,
  8190. A_MOVQ,
  8191. A_MOVSX,
  8192. {$ifdef x86_64}
  8193. A_MOVSXD,
  8194. {$endif x86_64}
  8195. A_MOVZX,
  8196. A_MOVAPS,
  8197. A_MOVUPS,
  8198. A_MOVSS,
  8199. A_MOVAPD,
  8200. A_MOVUPD,
  8201. A_MOVDQA,
  8202. A_MOVDQU,
  8203. A_VMOVSS,
  8204. A_VMOVAPS,
  8205. A_VMOVUPS,
  8206. A_VMOVSD,
  8207. A_VMOVAPD,
  8208. A_VMOVUPD,
  8209. A_VMOVDQA,
  8210. A_VMOVDQU:
  8211. begin
  8212. Inc(Count);
  8213. if Count >= 5 then
  8214. { Too many to be worthwhile }
  8215. Break;
  8216. GetNextInstruction(hp2, hp2);
  8217. Continue;
  8218. end;
  8219. A_JMP:
  8220. begin
  8221. { Guard against infinite loops }
  8222. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8223. Exit;
  8224. { Analyse this jump first in case it also duplicates assignments }
  8225. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8226. begin
  8227. { Something did change! }
  8228. Result := True;
  8229. Inc(Count, IncCount);
  8230. if Count >= 5 then
  8231. begin
  8232. { Too many to be worthwhile }
  8233. Exit;
  8234. end;
  8235. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8236. Break;
  8237. end;
  8238. Result := True;
  8239. Break;
  8240. end;
  8241. A_RET:
  8242. begin
  8243. Result := True;
  8244. Break;
  8245. end;
  8246. else
  8247. Break;
  8248. end;
  8249. end;
  8250. if Result then
  8251. begin
  8252. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8253. if Count = 0 then
  8254. begin
  8255. Result := False;
  8256. Exit;
  8257. end;
  8258. hp3 := p;
  8259. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8260. while True do
  8261. begin
  8262. if Assigned(hp1) and (hp1.typ = ait_label) then
  8263. SkipLabels(hp1,hp1);
  8264. if (hp1.typ <> ait_instruction) then
  8265. InternalError(2021040720);
  8266. case taicpu(hp1).opcode of
  8267. A_JMP:
  8268. begin
  8269. { Change the original jump to the new destination }
  8270. OrigLabel.decrefs;
  8271. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8272. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8273. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8274. if not Assigned(first_assignment) then
  8275. InternalError(2021040810)
  8276. else
  8277. p := first_assignment;
  8278. Exit;
  8279. end;
  8280. A_RET:
  8281. begin
  8282. { Now change the jump into a RET instruction }
  8283. ConvertJumpToRET(p, hp1);
  8284. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8285. if not Assigned(first_assignment) then
  8286. InternalError(2021040811)
  8287. else
  8288. p := first_assignment;
  8289. Exit;
  8290. end;
  8291. else
  8292. begin
  8293. { Duplicate the MOV instruction }
  8294. hp3:=tai(hp1.getcopy);
  8295. if first_assignment = nil then
  8296. first_assignment := hp3;
  8297. asml.InsertBefore(hp3, p);
  8298. { Make sure the compiler knows about any final registers written here }
  8299. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8300. with taicpu(hp3).oper[OperIdx]^ do
  8301. begin
  8302. case typ of
  8303. top_ref:
  8304. begin
  8305. if (ref^.base <> NR_NO) and
  8306. (getsupreg(ref^.base) <> RS_ESP) and
  8307. (getsupreg(ref^.base) <> RS_EBP)
  8308. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8309. then
  8310. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8311. if (ref^.index <> NR_NO) and
  8312. (getsupreg(ref^.index) <> RS_ESP) and
  8313. (getsupreg(ref^.index) <> RS_EBP)
  8314. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8315. (ref^.index <> ref^.base) then
  8316. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8317. end;
  8318. top_reg:
  8319. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8320. else
  8321. ;
  8322. end;
  8323. end;
  8324. end;
  8325. end;
  8326. if not GetNextInstruction(hp1, hp1) then
  8327. { Should have dropped out earlier }
  8328. InternalError(2021040710);
  8329. end;
  8330. end;
  8331. end;
  8332. const
  8333. WriteOp: array[0..3] of set of TInsChange = (
  8334. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8335. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8336. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8337. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8338. RegWriteFlags: array[0..7] of set of TInsChange = (
  8339. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8340. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8341. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8342. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8343. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8344. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8345. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8346. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8347. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8348. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8349. var
  8350. hp2: tai;
  8351. X: Integer;
  8352. begin
  8353. { If we have something like:
  8354. op ###,###
  8355. mov ###,###
  8356. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8357. interfere in regards to what they write to.
  8358. NOTE: p must be a 2-operand instruction
  8359. }
  8360. Result := False;
  8361. if (hp1.typ <> ait_instruction) or
  8362. taicpu(hp1).is_jmp or
  8363. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8364. Exit;
  8365. { NOP is a pipeline fence, likely marking the beginning of the function
  8366. epilogue, so drop out. Similarly, drop out if POP or RET are
  8367. encountered }
  8368. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8369. Exit;
  8370. if (taicpu(hp1).opcode = A_MOVSD) and
  8371. (taicpu(hp1).ops = 0) then
  8372. { Wrong MOVSD }
  8373. Exit;
  8374. { Check for writes to specific registers first }
  8375. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8376. for X := 0 to 7 do
  8377. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8378. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8379. Exit;
  8380. for X := 0 to taicpu(hp1).ops - 1 do
  8381. begin
  8382. { Check to see if this operand writes to something }
  8383. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8384. { And matches something in the CMP/TEST instruction }
  8385. (
  8386. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8387. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8388. (
  8389. { If it's a register, make sure the register written to doesn't
  8390. appear in the cmp instruction as part of a reference }
  8391. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8392. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8393. )
  8394. ) then
  8395. Exit;
  8396. end;
  8397. { Check p to make sure it doesn't write to something that affects hp1 }
  8398. { Check for writes to specific registers first }
  8399. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8400. for X := 0 to 7 do
  8401. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8402. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8403. Exit;
  8404. for X := 0 to taicpu(p).ops - 1 do
  8405. begin
  8406. { Check to see if this operand writes to something }
  8407. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8408. { And matches something in hp1 }
  8409. (taicpu(p).oper[X]^.typ = top_reg) and
  8410. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8411. Exit;
  8412. end;
  8413. { The instruction can be safely moved }
  8414. asml.Remove(hp1);
  8415. { Try to insert after the last instructions where the FLAGS register is not
  8416. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8417. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8418. asml.InsertBefore(hp1, hp2)
  8419. { Failing that, try to insert after the last instructions where the
  8420. FLAGS register is not yet in use }
  8421. else if GetLastInstruction(p, hp2) and
  8422. (
  8423. (hp2.typ <> ait_instruction) or
  8424. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8425. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8426. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8427. ) then
  8428. asml.InsertAfter(hp1, hp2)
  8429. else
  8430. { Note, if p.Previous is nil (even if it should logically never be the
  8431. case), FindRegAllocBackward immediately exits with False and so we
  8432. safely land here (we can't just pass p because FindRegAllocBackward
  8433. immediately exits on an instruction). [Kit] }
  8434. asml.InsertBefore(hp1, p);
  8435. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8436. { We can't trust UsedRegs because we're looking backwards, although we
  8437. know the registers are allocated after p at the very least, so manually
  8438. create tai_regalloc objects if needed }
  8439. for X := 0 to taicpu(hp1).ops - 1 do
  8440. case taicpu(hp1).oper[X]^.typ of
  8441. top_reg:
  8442. begin
  8443. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8444. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8445. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8446. end;
  8447. top_ref:
  8448. begin
  8449. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8450. begin
  8451. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8452. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8453. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8454. end;
  8455. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8456. begin
  8457. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8458. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8459. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8460. end;
  8461. end;
  8462. else
  8463. ;
  8464. end;
  8465. Result := True;
  8466. end;
  8467. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8468. var
  8469. hp2: tai;
  8470. X: Integer;
  8471. begin
  8472. { If we have something like:
  8473. cmp ###,%reg1
  8474. mov 0,%reg2
  8475. And no modified registers are shared, move the instruction to before
  8476. the comparison as this means it can be optimised without worrying
  8477. about the FLAGS register. (CMP/MOV is generated by
  8478. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8479. As long as the second instruction doesn't use the flags or one of the
  8480. registers used by CMP or TEST (also check any references that use the
  8481. registers), then it can be moved prior to the comparison.
  8482. }
  8483. Result := False;
  8484. if not TrySwapMovOp(p, hp1) then
  8485. Exit;
  8486. if taicpu(hp1).opcode = A_LEA then
  8487. { The flags will be overwritten by the CMP/TEST instruction }
  8488. ConvertLEA(taicpu(hp1));
  8489. Result := True;
  8490. { Can we move it one further back? }
  8491. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8492. { Check to see if CMP/TEST is a comparison against zero }
  8493. (
  8494. (
  8495. (taicpu(p).opcode = A_CMP) and
  8496. MatchOperand(taicpu(p).oper[0]^, 0)
  8497. ) or
  8498. (
  8499. (taicpu(p).opcode = A_TEST) and
  8500. (
  8501. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8502. MatchOperand(taicpu(p).oper[0]^, -1)
  8503. )
  8504. )
  8505. ) and
  8506. { These instructions set the zero flag if the result is zero }
  8507. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8508. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8509. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8510. TrySwapMovOp(hp2, hp1);
  8511. end;
  8512. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8513. var
  8514. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8515. JumpLabel: TAsmLabel;
  8516. TmpBool: Boolean;
  8517. begin
  8518. Result := False;
  8519. { Look for:
  8520. stc/clc
  8521. j(c) .L1
  8522. ...
  8523. .L1:
  8524. set(n)cb %reg
  8525. (flags deallocated)
  8526. j(c) .L2
  8527. Change to:
  8528. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8529. j(c) .L2
  8530. }
  8531. p_last := p;
  8532. while GetNextInstruction(p_last, hp1) and
  8533. (hp1.typ = ait_instruction) and
  8534. IsJumpToLabel(taicpu(hp1)) do
  8535. begin
  8536. if DoJumpOptimizations(hp1, TmpBool) then
  8537. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8538. Continue;
  8539. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8540. if not Assigned(JumpLabel) then
  8541. InternalError(2024012801);
  8542. { Optimise the J(c); stc/clc optimisation first since this will
  8543. get missed if the main optimisation takes place }
  8544. if (taicpu(hp1).opcode = A_JCC) then
  8545. begin
  8546. if GetNextInstruction(hp1, hp2) and
  8547. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8548. TryJccStcClcOpt(hp1, hp2) then
  8549. begin
  8550. Result := True;
  8551. Exit;
  8552. end;
  8553. hp2 := nil; { Suppress compiler warning }
  8554. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8555. { Make sure the flags aren't used again }
  8556. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8557. begin
  8558. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8559. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8560. begin
  8561. if (taicpu(p).opcode = A_STC) then
  8562. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8563. else
  8564. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8565. MakeUnconditional(taicpu(hp1));
  8566. { Move the jump to after the flag deallocations }
  8567. Asml.Remove(hp1);
  8568. Asml.InsertAfter(hp1, hp2);
  8569. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8570. Result := True;
  8571. Exit;
  8572. end
  8573. else
  8574. begin
  8575. if (taicpu(p).opcode = A_STC) then
  8576. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8577. else
  8578. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8579. { In this case, the jump is deterministic in that it will never be taken }
  8580. JumpLabel.DecRefs;
  8581. RemoveInstruction(hp1);
  8582. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8583. Result := True;
  8584. Exit;
  8585. end;
  8586. end;
  8587. end;
  8588. hp2 := nil; { Suppress compiler warning }
  8589. if
  8590. { Make sure the carry flag doesn't appear in the jump conditions }
  8591. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8592. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8593. GetNextInstruction(hp2, p_dist) and
  8594. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8595. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8596. begin
  8597. case taicpu(p_dist).opcode of
  8598. A_Jcc:
  8599. begin
  8600. if DoJumpOptimizations(p_dist, TmpBool) then
  8601. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8602. Continue;
  8603. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8604. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8605. begin
  8606. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8607. JumpLabel.decrefs;
  8608. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8609. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8610. Result := True;
  8611. Exit;
  8612. end
  8613. else if GetNextInstruction(p_dist, hp1_dist) and
  8614. (hp1_dist.typ = ait_label) then
  8615. begin
  8616. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8617. JumpLabel.decrefs;
  8618. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8619. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8620. Result := True;
  8621. Exit;
  8622. end;
  8623. end;
  8624. A_SETcc:
  8625. if { Make sure the flags aren't used again }
  8626. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8627. GetNextInstruction(hp2, hp1_dist) and
  8628. (hp1_dist.typ = ait_instruction) and
  8629. IsJumpToLabel(taicpu(hp1_dist)) and
  8630. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8631. { This works if hp1_dist or both are regular JMP instructions }
  8632. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  8633. begin
  8634. taicpu(p).allocate_oper(2);
  8635. taicpu(p).ops := 2;
  8636. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8637. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8638. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8639. taicpu(p).opcode := A_MOV;
  8640. taicpu(p).opsize := S_B;
  8641. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8642. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8643. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8644. JumpLabel.decrefs;
  8645. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8646. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8647. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8648. (tai_regalloc(hp2).ratype = ra_alloc) then
  8649. begin
  8650. Asml.Remove(hp2);
  8651. Asml.InsertAfter(hp2, p);
  8652. end;
  8653. Result := True;
  8654. Exit;
  8655. end;
  8656. else
  8657. ;
  8658. end;
  8659. end;
  8660. p_last := hp1;
  8661. end;
  8662. end;
  8663. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8664. var
  8665. hp2, hp3: tai;
  8666. TempBool: Boolean;
  8667. begin
  8668. Result := False;
  8669. {
  8670. j(c) .L1
  8671. stc/clc
  8672. .L1:
  8673. jc/jnc .L2
  8674. (Flags deallocated)
  8675. Change to:
  8676. j)c) .L1
  8677. jmp .L2
  8678. .L1:
  8679. jc/jnc .L2
  8680. Then call DoJumpOptimizations to convert to:
  8681. j(nc) .L2
  8682. .L1: (may become a dead label)
  8683. jc/jnc .L2
  8684. }
  8685. if GetNextInstruction(hp1, hp2) and
  8686. (hp2.typ = ait_label) and
  8687. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8688. GetNextInstruction(hp2, hp3) and
  8689. MatchInstruction(hp3, A_Jcc, []) and
  8690. (
  8691. (
  8692. (taicpu(hp3).condition = C_C) and
  8693. (taicpu(hp1).opcode = A_STC)
  8694. ) or (
  8695. (taicpu(hp3).condition = C_NC) and
  8696. (taicpu(hp1).opcode = A_CLC)
  8697. )
  8698. ) and
  8699. { Make sure the flags aren't used again }
  8700. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8701. begin
  8702. taicpu(hp1).allocate_oper(1);
  8703. taicpu(hp1).ops := 1;
  8704. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8705. taicpu(hp1).opcode := A_JMP;
  8706. taicpu(hp1).is_jmp := True;
  8707. TempBool := True; { Prevent compiler warnings }
  8708. if DoJumpOptimizations(p, TempBool) then
  8709. Result := True
  8710. else
  8711. Include(OptsToCheck, aoc_ForceNewIteration);
  8712. end;
  8713. end;
  8714. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8715. function IsXCHGAcceptable: Boolean; inline;
  8716. begin
  8717. { Always accept if optimising for size }
  8718. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8719. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8720. than 3, so it becomes a saving compared to three MOVs with two of
  8721. them able to execute simultaneously. [Kit] }
  8722. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8723. end;
  8724. var
  8725. NewRef: TReference;
  8726. hp1, hp2, hp3, hp4: Tai;
  8727. {$ifndef x86_64}
  8728. OperIdx: Integer;
  8729. {$endif x86_64}
  8730. NewInstr : Taicpu;
  8731. NewAligh : Tai_align;
  8732. DestLabel: TAsmLabel;
  8733. TempTracking: TAllUsedRegs;
  8734. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8735. var
  8736. NextInstr: tai;
  8737. begin
  8738. Result := False;
  8739. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8740. if not GetNextInstruction(InputInstr, NextInstr) or
  8741. (
  8742. { The FLAGS register isn't always tracked properly, so do not
  8743. perform this optimisation if a conditional statement follows }
  8744. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8745. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8746. ) then
  8747. begin
  8748. reference_reset(NewRef, 1, []);
  8749. NewRef.base := taicpu(p).oper[0]^.reg;
  8750. NewRef.scalefactor := 1;
  8751. if taicpu(InputInstr).opcode = A_ADD then
  8752. begin
  8753. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8754. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8755. end
  8756. else
  8757. begin
  8758. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8759. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8760. end;
  8761. taicpu(p).opcode := A_LEA;
  8762. taicpu(p).loadref(0, NewRef);
  8763. RemoveInstruction(InputInstr);
  8764. Result := True;
  8765. end;
  8766. end;
  8767. begin
  8768. Result:=false;
  8769. { This optimisation adds an instruction, so only do it for speed }
  8770. if not (cs_opt_size in current_settings.optimizerswitches) and
  8771. MatchOpType(taicpu(p), top_const, top_reg) and
  8772. (taicpu(p).oper[0]^.val = 0) then
  8773. begin
  8774. { To avoid compiler warning }
  8775. DestLabel := nil;
  8776. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8777. InternalError(2021040750);
  8778. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8779. Exit;
  8780. case hp1.typ of
  8781. ait_label:
  8782. begin
  8783. { Change:
  8784. mov $0,%reg mov $0,%reg
  8785. @Lbl1: @Lbl1:
  8786. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8787. je @Lbl2 jne @Lbl2
  8788. To: To:
  8789. mov $0,%reg mov $0,%reg
  8790. jmp @Lbl2 jmp @Lbl3
  8791. (align) (align)
  8792. @Lbl1: @Lbl1:
  8793. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8794. je @Lbl2 je @Lbl2
  8795. @Lbl3: <-- Only if label exists
  8796. (Not if it's optimised for size)
  8797. }
  8798. if not GetNextInstruction(hp1, hp2) then
  8799. Exit;
  8800. if (hp2.typ = ait_instruction) and
  8801. (
  8802. { Register sizes must exactly match }
  8803. (
  8804. (taicpu(hp2).opcode = A_CMP) and
  8805. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8806. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8807. ) or (
  8808. (taicpu(hp2).opcode = A_TEST) and
  8809. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8810. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8811. )
  8812. ) and GetNextInstruction(hp2, hp3) and
  8813. (hp3.typ = ait_instruction) and
  8814. (taicpu(hp3).opcode = A_JCC) and
  8815. (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
  8816. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8817. begin
  8818. { Check condition of jump }
  8819. { Always true? }
  8820. if condition_in(C_E, taicpu(hp3).condition) then
  8821. begin
  8822. { Copy label symbol and obtain matching label entry for the
  8823. conditional jump, as this will be our destination}
  8824. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8825. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8826. Result := True;
  8827. end
  8828. { Always false? }
  8829. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8830. begin
  8831. { This is only worth it if there's a jump to take }
  8832. case hp2.typ of
  8833. ait_instruction:
  8834. begin
  8835. if taicpu(hp2).opcode = A_JMP then
  8836. begin
  8837. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8838. { An unconditional jump follows the conditional jump which will always be false,
  8839. so use this jump's destination for the new jump }
  8840. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8841. Result := True;
  8842. end
  8843. else if taicpu(hp2).opcode = A_JCC then
  8844. begin
  8845. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8846. if condition_in(C_E, taicpu(hp2).condition) then
  8847. begin
  8848. { A second conditional jump follows the conditional jump which will always be false,
  8849. while the second jump is always True, so use this jump's destination for the new jump }
  8850. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8851. Result := True;
  8852. end;
  8853. { Don't risk it if the jump isn't always true (Result remains False) }
  8854. end;
  8855. end;
  8856. else
  8857. { If anything else don't optimise };
  8858. end;
  8859. end;
  8860. if Result then
  8861. begin
  8862. { Just so we have something to insert as a paremeter}
  8863. reference_reset(NewRef, 1, []);
  8864. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8865. { Now actually load the correct parameter (this also
  8866. increases the reference count) }
  8867. NewInstr.loadsymbol(0, DestLabel, 0);
  8868. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8869. begin
  8870. { Get instruction before original label (may not be p under -O3) }
  8871. if not GetLastInstruction(hp1, hp2) then
  8872. { Shouldn't fail here }
  8873. InternalError(2021040701);
  8874. end
  8875. else
  8876. hp2 := p;
  8877. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8878. AsmL.InsertAfter(NewInstr, hp2);
  8879. { Add new alignment field }
  8880. (* AsmL.InsertAfter(
  8881. cai_align.create_max(
  8882. current_settings.alignment.jumpalign,
  8883. current_settings.alignment.jumpalignskipmax
  8884. ),
  8885. NewInstr
  8886. ); *)
  8887. end;
  8888. Exit;
  8889. end;
  8890. end;
  8891. else
  8892. ;
  8893. end;
  8894. end;
  8895. if not GetNextInstruction(p, hp1) then
  8896. Exit;
  8897. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8898. and DoMovCmpMemOpt(p, hp1) then
  8899. begin
  8900. Result := True;
  8901. Exit;
  8902. end
  8903. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8904. begin
  8905. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8906. further, but we can't just put this jump optimisation in pass 1
  8907. because it tends to perform worse when conditional jumps are
  8908. nearby (e.g. when converting CMOV instructions). [Kit] }
  8909. CopyUsedRegs(TempTracking);
  8910. UpdateUsedRegs(tai(p.Next));
  8911. if OptPass2JMP(hp1) then
  8912. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8913. Result := OptPass1MOV(p);
  8914. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8915. returned True and the instruction is still a MOV, thus checking
  8916. the optimisations below }
  8917. { If OptPass2JMP returned False, no optimisations were done to
  8918. the jump and there are no further optimisations that can be done
  8919. to the MOV instruction on this pass }
  8920. { Restore register state }
  8921. RestoreUsedRegs(TempTracking);
  8922. ReleaseUsedRegs(TempTracking);
  8923. end
  8924. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8925. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8926. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8927. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8928. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8929. begin
  8930. { Change:
  8931. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8932. addl/q $x,%reg2 subl/q $x,%reg2
  8933. To:
  8934. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8935. }
  8936. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8937. { be lazy, checking separately for sub would be slightly better }
  8938. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8939. begin
  8940. TransferUsedRegs(TmpUsedRegs);
  8941. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8942. if TryMovArith2Lea(hp1) then
  8943. begin
  8944. Result := True;
  8945. Exit;
  8946. end
  8947. end
  8948. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8949. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8950. { Same as above, but also adds or subtracts to %reg2 in between.
  8951. It's still valid as long as the flags aren't in use }
  8952. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8953. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8954. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8955. { be lazy, checking separately for sub would be slightly better }
  8956. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8957. begin
  8958. TransferUsedRegs(TmpUsedRegs);
  8959. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8960. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8961. if TryMovArith2Lea(hp2) then
  8962. begin
  8963. Result := True;
  8964. Exit;
  8965. end;
  8966. end;
  8967. end
  8968. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8969. {$ifdef x86_64}
  8970. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8971. {$else x86_64}
  8972. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8973. {$endif x86_64}
  8974. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8975. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8976. { mov reg1, reg2 mov reg1, reg2
  8977. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8978. begin
  8979. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8980. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8981. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8982. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8983. TransferUsedRegs(TmpUsedRegs);
  8984. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8985. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8986. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8987. then
  8988. begin
  8989. RemoveCurrentP(p, hp1);
  8990. Result:=true;
  8991. end;
  8992. exit;
  8993. end
  8994. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8995. IsXCHGAcceptable and
  8996. { XCHG doesn't support 8-byte registers }
  8997. (taicpu(p).opsize <> S_B) and
  8998. MatchInstruction(hp1, A_MOV, []) and
  8999. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9000. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9001. GetNextInstruction(hp1, hp2) and
  9002. MatchInstruction(hp2, A_MOV, []) and
  9003. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9004. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9005. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9006. begin
  9007. { mov %reg1,%reg2
  9008. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9009. mov %reg2,%reg3
  9010. (%reg2 not used afterwards)
  9011. Note that xchg takes 3 cycles to execute, and generally mov's take
  9012. only one cycle apiece, but the first two mov's can be executed in
  9013. parallel, only taking 2 cycles overall. Older processors should
  9014. therefore only optimise for size. [Kit]
  9015. }
  9016. TransferUsedRegs(TmpUsedRegs);
  9017. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9018. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9019. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9020. begin
  9021. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9022. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9023. taicpu(hp1).opcode := A_XCHG;
  9024. RemoveCurrentP(p, hp1);
  9025. RemoveInstruction(hp2);
  9026. Result := True;
  9027. Exit;
  9028. end;
  9029. end
  9030. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9031. MatchInstruction(hp1, A_SAR, []) then
  9032. begin
  9033. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9034. begin
  9035. { the use of %edx also covers the opsize being S_L }
  9036. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9037. begin
  9038. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9039. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9040. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9041. begin
  9042. { Change:
  9043. movl %eax,%edx
  9044. sarl $31,%edx
  9045. To:
  9046. cltd
  9047. }
  9048. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9049. RemoveInstruction(hp1);
  9050. taicpu(p).opcode := A_CDQ;
  9051. taicpu(p).opsize := S_NO;
  9052. taicpu(p).clearop(1);
  9053. taicpu(p).clearop(0);
  9054. taicpu(p).ops:=0;
  9055. Result := True;
  9056. end
  9057. else if (cs_opt_size in current_settings.optimizerswitches) and
  9058. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9059. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9060. begin
  9061. { Change:
  9062. movl %edx,%eax
  9063. sarl $31,%edx
  9064. To:
  9065. movl %edx,%eax
  9066. cltd
  9067. Note that this creates a dependency between the two instructions,
  9068. so only perform if optimising for size.
  9069. }
  9070. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9071. taicpu(hp1).opcode := A_CDQ;
  9072. taicpu(hp1).opsize := S_NO;
  9073. taicpu(hp1).clearop(1);
  9074. taicpu(hp1).clearop(0);
  9075. taicpu(hp1).ops:=0;
  9076. end;
  9077. {$ifndef x86_64}
  9078. end
  9079. { Don't bother if CMOV is supported, because a more optimal
  9080. sequence would have been generated for the Abs() intrinsic }
  9081. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9082. { the use of %eax also covers the opsize being S_L }
  9083. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9084. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9085. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9086. GetNextInstruction(hp1, hp2) and
  9087. MatchInstruction(hp2, A_XOR, [S_L]) and
  9088. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9089. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9090. GetNextInstruction(hp2, hp3) and
  9091. MatchInstruction(hp3, A_SUB, [S_L]) and
  9092. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9093. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9094. begin
  9095. { Change:
  9096. movl %eax,%edx
  9097. sarl $31,%eax
  9098. xorl %eax,%edx
  9099. subl %eax,%edx
  9100. (Instruction that uses %edx)
  9101. (%eax deallocated)
  9102. (%edx deallocated)
  9103. To:
  9104. cltd
  9105. xorl %edx,%eax <-- Note the registers have swapped
  9106. subl %edx,%eax
  9107. (Instruction that uses %eax) <-- %eax rather than %edx
  9108. }
  9109. TransferUsedRegs(TmpUsedRegs);
  9110. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9112. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9113. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9114. begin
  9115. if GetNextInstruction(hp3, hp4) and
  9116. not RegModifiedByInstruction(NR_EDX, hp4) and
  9117. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9118. begin
  9119. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9120. taicpu(p).opcode := A_CDQ;
  9121. taicpu(p).clearop(1);
  9122. taicpu(p).clearop(0);
  9123. taicpu(p).ops:=0;
  9124. RemoveInstruction(hp1);
  9125. taicpu(hp2).loadreg(0, NR_EDX);
  9126. taicpu(hp2).loadreg(1, NR_EAX);
  9127. taicpu(hp3).loadreg(0, NR_EDX);
  9128. taicpu(hp3).loadreg(1, NR_EAX);
  9129. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9130. { Convert references in the following instruction (hp4) from %edx to %eax }
  9131. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9132. with taicpu(hp4).oper[OperIdx]^ do
  9133. case typ of
  9134. top_reg:
  9135. if getsupreg(reg) = RS_EDX then
  9136. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9137. top_ref:
  9138. begin
  9139. if getsupreg(reg) = RS_EDX then
  9140. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9141. if getsupreg(reg) = RS_EDX then
  9142. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9143. end;
  9144. else
  9145. ;
  9146. end;
  9147. end;
  9148. end;
  9149. {$else x86_64}
  9150. end;
  9151. end
  9152. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9153. { the use of %rdx also covers the opsize being S_Q }
  9154. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9155. begin
  9156. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9157. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9158. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9159. begin
  9160. { Change:
  9161. movq %rax,%rdx
  9162. sarq $63,%rdx
  9163. To:
  9164. cqto
  9165. }
  9166. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9167. RemoveInstruction(hp1);
  9168. taicpu(p).opcode := A_CQO;
  9169. taicpu(p).opsize := S_NO;
  9170. taicpu(p).clearop(1);
  9171. taicpu(p).clearop(0);
  9172. taicpu(p).ops:=0;
  9173. Result := True;
  9174. end
  9175. else if (cs_opt_size in current_settings.optimizerswitches) and
  9176. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9177. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9178. begin
  9179. { Change:
  9180. movq %rdx,%rax
  9181. sarq $63,%rdx
  9182. To:
  9183. movq %rdx,%rax
  9184. cqto
  9185. Note that this creates a dependency between the two instructions,
  9186. so only perform if optimising for size.
  9187. }
  9188. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9189. taicpu(hp1).opcode := A_CQO;
  9190. taicpu(hp1).opsize := S_NO;
  9191. taicpu(hp1).clearop(1);
  9192. taicpu(hp1).clearop(0);
  9193. taicpu(hp1).ops:=0;
  9194. {$endif x86_64}
  9195. end;
  9196. end;
  9197. end
  9198. else if MatchInstruction(hp1, A_MOV, []) and
  9199. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9200. { Though "GetNextInstruction" could be factored out, along with
  9201. the instructions that depend on hp2, it is an expensive call that
  9202. should be delayed for as long as possible, hence we do cheaper
  9203. checks first that are likely to be False. [Kit] }
  9204. begin
  9205. if (
  9206. (
  9207. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9208. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9209. (
  9210. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9211. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9212. )
  9213. ) or
  9214. (
  9215. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9216. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9217. (
  9218. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9219. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9220. )
  9221. )
  9222. ) and
  9223. GetNextInstruction(hp1, hp2) and
  9224. MatchInstruction(hp2, A_SAR, []) and
  9225. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9226. begin
  9227. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9228. begin
  9229. { Change:
  9230. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9231. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9232. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9233. To:
  9234. movl r/m,%eax <- Note the change in register
  9235. cltd
  9236. }
  9237. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9238. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9239. taicpu(p).loadreg(1, NR_EAX);
  9240. taicpu(hp1).opcode := A_CDQ;
  9241. taicpu(hp1).clearop(1);
  9242. taicpu(hp1).clearop(0);
  9243. taicpu(hp1).ops:=0;
  9244. RemoveInstruction(hp2);
  9245. (*
  9246. {$ifdef x86_64}
  9247. end
  9248. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9249. { This code sequence does not get generated - however it might become useful
  9250. if and when 128-bit signed integer types make an appearance, so the code
  9251. is kept here for when it is eventually needed. [Kit] }
  9252. (
  9253. (
  9254. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9255. (
  9256. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9257. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9258. )
  9259. ) or
  9260. (
  9261. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9262. (
  9263. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9264. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9265. )
  9266. )
  9267. ) and
  9268. GetNextInstruction(hp1, hp2) and
  9269. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9270. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9271. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9272. begin
  9273. { Change:
  9274. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9275. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9276. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9277. To:
  9278. movq r/m,%rax <- Note the change in register
  9279. cqto
  9280. }
  9281. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9282. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9283. taicpu(p).loadreg(1, NR_RAX);
  9284. taicpu(hp1).opcode := A_CQO;
  9285. taicpu(hp1).clearop(1);
  9286. taicpu(hp1).clearop(0);
  9287. taicpu(hp1).ops:=0;
  9288. RemoveInstruction(hp2);
  9289. {$endif x86_64}
  9290. *)
  9291. end;
  9292. end;
  9293. {$ifdef x86_64}
  9294. end
  9295. else if (taicpu(p).opsize = S_L) and
  9296. (taicpu(p).oper[1]^.typ = top_reg) and
  9297. (
  9298. MatchInstruction(hp1, A_MOV,[]) and
  9299. (taicpu(hp1).opsize = S_L) and
  9300. (taicpu(hp1).oper[1]^.typ = top_reg)
  9301. ) and (
  9302. GetNextInstruction(hp1, hp2) and
  9303. (tai(hp2).typ=ait_instruction) and
  9304. (taicpu(hp2).opsize = S_Q) and
  9305. (
  9306. (
  9307. MatchInstruction(hp2, A_ADD,[]) and
  9308. (taicpu(hp2).opsize = S_Q) and
  9309. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9310. (
  9311. (
  9312. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9313. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9314. ) or (
  9315. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9316. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9317. )
  9318. )
  9319. ) or (
  9320. MatchInstruction(hp2, A_LEA,[]) and
  9321. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9322. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9323. (
  9324. (
  9325. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9326. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9327. ) or (
  9328. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9329. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9330. )
  9331. ) and (
  9332. (
  9333. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9334. ) or (
  9335. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9336. )
  9337. )
  9338. )
  9339. )
  9340. ) and (
  9341. GetNextInstruction(hp2, hp3) and
  9342. MatchInstruction(hp3, A_SHR,[]) and
  9343. (taicpu(hp3).opsize = S_Q) and
  9344. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9345. (taicpu(hp3).oper[0]^.val = 1) and
  9346. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9347. ) then
  9348. begin
  9349. { Change movl x, reg1d movl x, reg1d
  9350. movl y, reg2d movl y, reg2d
  9351. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9352. shrq $1, reg1q shrq $1, reg1q
  9353. ( reg1d and reg2d can be switched around in the first two instructions )
  9354. To movl x, reg1d
  9355. addl y, reg1d
  9356. rcrl $1, reg1d
  9357. This corresponds to the common expression (x + y) shr 1, where
  9358. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9359. smaller code, but won't account for x + y causing an overflow). [Kit]
  9360. }
  9361. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9362. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9363. { Change first MOV command to have the same register as the final output }
  9364. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9365. else
  9366. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9367. { Change second MOV command to an ADD command. This is easier than
  9368. converting the existing command because it means we don't have to
  9369. touch 'y', which might be a complicated reference, and also the
  9370. fact that the third command might either be ADD or LEA. [Kit] }
  9371. taicpu(hp1).opcode := A_ADD;
  9372. { Delete old ADD/LEA instruction }
  9373. RemoveInstruction(hp2);
  9374. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9375. taicpu(hp3).opcode := A_RCR;
  9376. taicpu(hp3).changeopsize(S_L);
  9377. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9378. {$endif x86_64}
  9379. end;
  9380. if FuncMov2Func(p, hp1) then
  9381. begin
  9382. Result := True;
  9383. Exit;
  9384. end;
  9385. end;
  9386. {$push}
  9387. {$q-}{$r-}
  9388. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9389. var
  9390. ThisReg: TRegister;
  9391. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9392. TargetSubReg: TSubRegister;
  9393. hp1, hp2: tai;
  9394. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9395. { Store list of found instructions so we don't have to call
  9396. GetNextInstructionUsingReg multiple times }
  9397. InstrList: array of taicpu;
  9398. InstrMax, Index: Integer;
  9399. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9400. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9401. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9402. WorkingValue: TCgInt;
  9403. PreMessage: string;
  9404. { Data flow analysis }
  9405. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9406. BitwiseOnly, OrXorUsed,
  9407. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9408. function CheckOverflowConditions: Boolean;
  9409. begin
  9410. Result := True;
  9411. if (TestValSignedMax > SignedUpperLimit) then
  9412. UpperSignedOverflow := True;
  9413. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9414. LowerSignedOverflow := True;
  9415. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9416. LowerUnsignedOverflow := True;
  9417. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9418. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9419. begin
  9420. { Absolute overflow }
  9421. Result := False;
  9422. Exit;
  9423. end;
  9424. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9425. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9426. ShiftDownOverflow := True;
  9427. if (TestValMin < 0) or (TestValMax < 0) then
  9428. begin
  9429. LowerUnsignedOverflow := True;
  9430. UpperUnsignedOverflow := True;
  9431. end;
  9432. end;
  9433. function AdjustInitialLoadAndSize: Boolean;
  9434. begin
  9435. Result := False;
  9436. if not p_removed then
  9437. begin
  9438. if TargetSize = MinSize then
  9439. begin
  9440. { Convert the input MOVZX to a MOV }
  9441. if (taicpu(p).oper[0]^.typ = top_reg) and
  9442. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9443. begin
  9444. { Or remove it completely! }
  9445. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9446. RemoveCurrentP(p);
  9447. p_removed := True;
  9448. end
  9449. else
  9450. begin
  9451. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9452. taicpu(p).opcode := A_MOV;
  9453. taicpu(p).oper[1]^.reg := ThisReg;
  9454. taicpu(p).opsize := TargetSize;
  9455. end;
  9456. Result := True;
  9457. end
  9458. else if TargetSize <> MaxSize then
  9459. begin
  9460. case MaxSize of
  9461. S_L:
  9462. if TargetSize = S_W then
  9463. begin
  9464. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9465. taicpu(p).opsize := S_BW;
  9466. taicpu(p).oper[1]^.reg := ThisReg;
  9467. Result := True;
  9468. end
  9469. else
  9470. InternalError(2020112341);
  9471. S_W:
  9472. if TargetSize = S_L then
  9473. begin
  9474. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9475. taicpu(p).opsize := S_BL;
  9476. taicpu(p).oper[1]^.reg := ThisReg;
  9477. Result := True;
  9478. end
  9479. else
  9480. InternalError(2020112342);
  9481. else
  9482. ;
  9483. end;
  9484. end
  9485. else if not hp1_removed and not RegInUse then
  9486. begin
  9487. { If we have something like:
  9488. movzbl (oper),%regd
  9489. add x, %regd
  9490. movzbl %regb, %regd
  9491. We can reduce the register size to the input of the final
  9492. movzbl instruction. Overflows won't have any effect.
  9493. }
  9494. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9495. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9496. begin
  9497. TargetSize := S_B;
  9498. setsubreg(ThisReg, R_SUBL);
  9499. Result := True;
  9500. end
  9501. else if (taicpu(p).opsize = S_WL) and
  9502. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9503. begin
  9504. TargetSize := S_W;
  9505. setsubreg(ThisReg, R_SUBW);
  9506. Result := True;
  9507. end;
  9508. if Result then
  9509. begin
  9510. { Convert the input MOVZX to a MOV }
  9511. if (taicpu(p).oper[0]^.typ = top_reg) and
  9512. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9513. begin
  9514. { Or remove it completely! }
  9515. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9516. RemoveCurrentP(p);
  9517. p_removed := True;
  9518. end
  9519. else
  9520. begin
  9521. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9522. taicpu(p).opcode := A_MOV;
  9523. taicpu(p).oper[1]^.reg := ThisReg;
  9524. taicpu(p).opsize := TargetSize;
  9525. end;
  9526. end;
  9527. end;
  9528. end;
  9529. end;
  9530. procedure AdjustFinalLoad;
  9531. begin
  9532. if not LowerUnsignedOverflow then
  9533. begin
  9534. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9535. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9536. begin
  9537. { Convert the output MOVZX to a MOV }
  9538. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9539. begin
  9540. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9541. if (MinSize = S_B) or
  9542. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9543. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9544. begin
  9545. { Remove it completely! }
  9546. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9547. { Be careful; if p = hp1 and p was also removed, p
  9548. will become a dangling pointer }
  9549. if p = hp1 then
  9550. begin
  9551. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9552. p_removed := True;
  9553. end
  9554. else
  9555. RemoveInstruction(hp1);
  9556. hp1_removed := True;
  9557. end;
  9558. end
  9559. else
  9560. begin
  9561. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9562. taicpu(hp1).opcode := A_MOV;
  9563. taicpu(hp1).oper[0]^.reg := ThisReg;
  9564. taicpu(hp1).opsize := TargetSize;
  9565. end;
  9566. end
  9567. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9568. begin
  9569. { Need to change the size of the output }
  9570. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9571. taicpu(hp1).oper[0]^.reg := ThisReg;
  9572. taicpu(hp1).opsize := S_BL;
  9573. end;
  9574. end;
  9575. end;
  9576. function CompressInstructions: Boolean;
  9577. var
  9578. LocalIndex: Integer;
  9579. begin
  9580. Result := False;
  9581. { The objective here is to try to find a combination that
  9582. removes one of the MOV/Z instructions. }
  9583. if (
  9584. (taicpu(p).oper[0]^.typ <> top_reg) or
  9585. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9586. ) and
  9587. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9588. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9589. begin
  9590. { Make a preference to remove the second MOVZX instruction }
  9591. case taicpu(hp1).opsize of
  9592. S_BL, S_WL:
  9593. begin
  9594. TargetSize := S_L;
  9595. TargetSubReg := R_SUBD;
  9596. end;
  9597. S_BW:
  9598. begin
  9599. TargetSize := S_W;
  9600. TargetSubReg := R_SUBW;
  9601. end;
  9602. else
  9603. InternalError(2020112302);
  9604. end;
  9605. end
  9606. else
  9607. begin
  9608. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9609. begin
  9610. { Exceeded lower bound but not upper bound }
  9611. TargetSize := MaxSize;
  9612. end
  9613. else if not LowerUnsignedOverflow then
  9614. begin
  9615. { Size didn't exceed lower bound }
  9616. TargetSize := MinSize;
  9617. end
  9618. else
  9619. Exit;
  9620. end;
  9621. case TargetSize of
  9622. S_B:
  9623. TargetSubReg := R_SUBL;
  9624. S_W:
  9625. TargetSubReg := R_SUBW;
  9626. S_L:
  9627. TargetSubReg := R_SUBD;
  9628. else
  9629. InternalError(2020112350);
  9630. end;
  9631. { Update the register to its new size }
  9632. setsubreg(ThisReg, TargetSubReg);
  9633. RegInUse := False;
  9634. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9635. begin
  9636. { Check to see if the active register is used afterwards;
  9637. if not, we can change it and make a saving. }
  9638. TransferUsedRegs(TmpUsedRegs);
  9639. { The target register may be marked as in use to cross
  9640. a jump to a distant label, so exclude it }
  9641. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9642. hp2 := p;
  9643. repeat
  9644. { Explicitly check for the excluded register (don't include the first
  9645. instruction as it may be reading from here }
  9646. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9647. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9648. begin
  9649. RegInUse := True;
  9650. Break;
  9651. end;
  9652. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9653. if not GetNextInstruction(hp2, hp2) then
  9654. InternalError(2020112340);
  9655. until (hp2 = hp1);
  9656. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9657. { We might still be able to get away with this }
  9658. RegInUse := not
  9659. (
  9660. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9661. (hp2.typ = ait_instruction) and
  9662. (
  9663. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9664. instruction that doesn't actually contain ThisReg }
  9665. (cs_opt_level3 in current_settings.optimizerswitches) or
  9666. RegInInstruction(ThisReg, hp2)
  9667. ) and
  9668. RegLoadedWithNewValue(ThisReg, hp2)
  9669. );
  9670. if not RegInUse then
  9671. begin
  9672. { Force the register size to the same as this instruction so it can be removed}
  9673. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9674. begin
  9675. TargetSize := S_L;
  9676. TargetSubReg := R_SUBD;
  9677. end
  9678. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9679. begin
  9680. TargetSize := S_W;
  9681. TargetSubReg := R_SUBW;
  9682. end;
  9683. ThisReg := taicpu(hp1).oper[1]^.reg;
  9684. setsubreg(ThisReg, TargetSubReg);
  9685. RegChanged := True;
  9686. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9687. TransferUsedRegs(TmpUsedRegs);
  9688. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9689. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9690. if p = hp1 then
  9691. begin
  9692. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9693. p_removed := True;
  9694. end
  9695. else
  9696. RemoveInstruction(hp1);
  9697. hp1_removed := True;
  9698. { Instruction will become "mov %reg,%reg" }
  9699. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9700. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9701. begin
  9702. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9703. RemoveCurrentP(p);
  9704. p_removed := True;
  9705. end
  9706. else
  9707. taicpu(p).oper[1]^.reg := ThisReg;
  9708. Result := True;
  9709. end
  9710. else
  9711. begin
  9712. if TargetSize <> MaxSize then
  9713. begin
  9714. { Since the register is in use, we have to force it to
  9715. MaxSize otherwise part of it may become undefined later on }
  9716. TargetSize := MaxSize;
  9717. case TargetSize of
  9718. S_B:
  9719. TargetSubReg := R_SUBL;
  9720. S_W:
  9721. TargetSubReg := R_SUBW;
  9722. S_L:
  9723. TargetSubReg := R_SUBD;
  9724. else
  9725. InternalError(2020112351);
  9726. end;
  9727. setsubreg(ThisReg, TargetSubReg);
  9728. end;
  9729. AdjustFinalLoad;
  9730. end;
  9731. end
  9732. else
  9733. AdjustFinalLoad;
  9734. Result := AdjustInitialLoadAndSize or Result;
  9735. { Now go through every instruction we found and change the
  9736. size. If TargetSize = MaxSize, then almost no changes are
  9737. needed and Result can remain False if it hasn't been set
  9738. yet.
  9739. If RegChanged is True, then the register requires changing
  9740. and so the point about TargetSize = MaxSize doesn't apply. }
  9741. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9742. begin
  9743. for LocalIndex := 0 to InstrMax do
  9744. begin
  9745. { If p_removed is true, then the original MOV/Z was removed
  9746. and removing the AND instruction may not be safe if it
  9747. appears first }
  9748. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9749. InternalError(2020112310);
  9750. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9751. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9752. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9753. InstrList[LocalIndex].opsize := TargetSize;
  9754. end;
  9755. Result := True;
  9756. end;
  9757. end;
  9758. begin
  9759. Result := False;
  9760. p_removed := False;
  9761. hp1_removed := False;
  9762. ThisReg := taicpu(p).oper[1]^.reg;
  9763. { Check for:
  9764. movs/z ###,%ecx (or %cx or %rcx)
  9765. ...
  9766. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9767. (dealloc %ecx)
  9768. Change to:
  9769. mov ###,%cl (if ### = %cl, then remove completely)
  9770. ...
  9771. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9772. }
  9773. if (getsupreg(ThisReg) = RS_ECX) and
  9774. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9775. (hp1.typ = ait_instruction) and
  9776. (
  9777. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9778. instruction that doesn't actually contain ECX }
  9779. (cs_opt_level3 in current_settings.optimizerswitches) or
  9780. RegInInstruction(NR_ECX, hp1) or
  9781. (
  9782. { It's common for the shift/rotate's read/write register to be
  9783. initialised in between, so under -O2 and under, search ahead
  9784. one more instruction
  9785. }
  9786. GetNextInstruction(hp1, hp1) and
  9787. (hp1.typ = ait_instruction) and
  9788. RegInInstruction(NR_ECX, hp1)
  9789. )
  9790. ) and
  9791. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9792. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9793. begin
  9794. TransferUsedRegs(TmpUsedRegs);
  9795. hp2 := p;
  9796. repeat
  9797. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9798. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9799. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9800. begin
  9801. case taicpu(p).opsize of
  9802. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9803. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9804. begin
  9805. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9806. RemoveCurrentP(p);
  9807. end
  9808. else
  9809. begin
  9810. taicpu(p).opcode := A_MOV;
  9811. taicpu(p).opsize := S_B;
  9812. taicpu(p).oper[1]^.reg := NR_CL;
  9813. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9814. end;
  9815. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9816. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9817. begin
  9818. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9819. RemoveCurrentP(p);
  9820. end
  9821. else
  9822. begin
  9823. taicpu(p).opcode := A_MOV;
  9824. taicpu(p).opsize := S_W;
  9825. taicpu(p).oper[1]^.reg := NR_CX;
  9826. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9827. end;
  9828. {$ifdef x86_64}
  9829. S_LQ:
  9830. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9831. begin
  9832. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9833. RemoveCurrentP(p);
  9834. end
  9835. else
  9836. begin
  9837. taicpu(p).opcode := A_MOV;
  9838. taicpu(p).opsize := S_L;
  9839. taicpu(p).oper[1]^.reg := NR_ECX;
  9840. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9841. end;
  9842. {$endif x86_64}
  9843. else
  9844. InternalError(2021120401);
  9845. end;
  9846. Result := True;
  9847. Exit;
  9848. end;
  9849. end;
  9850. { This is anything but quick! }
  9851. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9852. Exit;
  9853. SetLength(InstrList, 0);
  9854. InstrMax := -1;
  9855. case taicpu(p).opsize of
  9856. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9857. begin
  9858. {$if defined(i386) or defined(i8086)}
  9859. { If the target size is 8-bit, make sure we can actually encode it }
  9860. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9861. Exit;
  9862. {$endif i386 or i8086}
  9863. LowerLimit := $FF;
  9864. SignedLowerLimit := $7F;
  9865. SignedLowerLimitBottom := -128;
  9866. MinSize := S_B;
  9867. if taicpu(p).opsize = S_BW then
  9868. begin
  9869. MaxSize := S_W;
  9870. UpperLimit := $FFFF;
  9871. SignedUpperLimit := $7FFF;
  9872. SignedUpperLimitBottom := -32768;
  9873. end
  9874. else
  9875. begin
  9876. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9877. MaxSize := S_L;
  9878. UpperLimit := $FFFFFFFF;
  9879. SignedUpperLimit := $7FFFFFFF;
  9880. SignedUpperLimitBottom := -2147483648;
  9881. end;
  9882. end;
  9883. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9884. begin
  9885. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9886. LowerLimit := $FFFF;
  9887. SignedLowerLimit := $7FFF;
  9888. SignedLowerLimitBottom := -32768;
  9889. UpperLimit := $FFFFFFFF;
  9890. SignedUpperLimit := $7FFFFFFF;
  9891. SignedUpperLimitBottom := -2147483648;
  9892. MinSize := S_W;
  9893. MaxSize := S_L;
  9894. end;
  9895. {$ifdef x86_64}
  9896. S_LQ:
  9897. begin
  9898. { Both the lower and upper limits are set to 32-bit. If a limit
  9899. is breached, then optimisation is impossible }
  9900. LowerLimit := $FFFFFFFF;
  9901. SignedLowerLimit := $7FFFFFFF;
  9902. SignedLowerLimitBottom := -2147483648;
  9903. UpperLimit := $FFFFFFFF;
  9904. SignedUpperLimit := $7FFFFFFF;
  9905. SignedUpperLimitBottom := -2147483648;
  9906. MinSize := S_L;
  9907. MaxSize := S_L;
  9908. end;
  9909. {$endif x86_64}
  9910. else
  9911. InternalError(2020112301);
  9912. end;
  9913. TestValMin := 0;
  9914. TestValMax := LowerLimit;
  9915. TestValSignedMax := SignedLowerLimit;
  9916. TryShiftDownLimit := LowerLimit;
  9917. TryShiftDown := S_NO;
  9918. ShiftDownOverflow := False;
  9919. RegChanged := False;
  9920. BitwiseOnly := True;
  9921. OrXorUsed := False;
  9922. UpperSignedOverflow := False;
  9923. LowerSignedOverflow := False;
  9924. UpperUnsignedOverflow := False;
  9925. LowerUnsignedOverflow := False;
  9926. hp1 := p;
  9927. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9928. (hp1.typ = ait_instruction) and
  9929. (
  9930. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9931. instruction that doesn't actually contain ThisReg }
  9932. (cs_opt_level3 in current_settings.optimizerswitches) or
  9933. { This allows this Movx optimisation to work through the SETcc instructions
  9934. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9935. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9936. skip over these SETcc instructions). }
  9937. (taicpu(hp1).opcode = A_SETcc) or
  9938. RegInInstruction(ThisReg, hp1)
  9939. ) do
  9940. begin
  9941. case taicpu(hp1).opcode of
  9942. A_INC,A_DEC:
  9943. begin
  9944. { Has to be an exact match on the register }
  9945. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9946. Break;
  9947. if taicpu(hp1).opcode = A_INC then
  9948. begin
  9949. Inc(TestValMin);
  9950. Inc(TestValMax);
  9951. Inc(TestValSignedMax);
  9952. end
  9953. else
  9954. begin
  9955. Dec(TestValMin);
  9956. Dec(TestValMax);
  9957. Dec(TestValSignedMax);
  9958. end;
  9959. end;
  9960. A_TEST, A_CMP:
  9961. begin
  9962. if (
  9963. { Too high a risk of non-linear behaviour that breaks DFA
  9964. here, unless it's cmp $0,%reg, which is equivalent to
  9965. test %reg,%reg }
  9966. OrXorUsed and
  9967. (taicpu(hp1).opcode = A_CMP) and
  9968. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9969. ) or
  9970. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9971. { Has to be an exact match on the register }
  9972. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9973. (
  9974. { Permit "test %reg,%reg" }
  9975. (taicpu(hp1).opcode = A_TEST) and
  9976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9977. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9978. ) or
  9979. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9980. { Make sure the comparison value is not smaller than the
  9981. smallest allowed signed value for the minimum size (e.g.
  9982. -128 for 8-bit) }
  9983. not (
  9984. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9985. { Is it in the negative range? }
  9986. (
  9987. (taicpu(hp1).oper[0]^.val < 0) and
  9988. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9989. )
  9990. ) then
  9991. Break;
  9992. { Check to see if the active register is used afterwards }
  9993. TransferUsedRegs(TmpUsedRegs);
  9994. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9995. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9996. begin
  9997. { Make sure the comparison or any previous instructions
  9998. hasn't pushed the test values outside of the range of
  9999. MinSize }
  10000. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10001. begin
  10002. { Exceeded lower bound but not upper bound }
  10003. Exit;
  10004. end
  10005. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10006. begin
  10007. { Size didn't exceed lower bound }
  10008. TargetSize := MinSize;
  10009. end
  10010. else
  10011. Break;
  10012. case TargetSize of
  10013. S_B:
  10014. TargetSubReg := R_SUBL;
  10015. S_W:
  10016. TargetSubReg := R_SUBW;
  10017. S_L:
  10018. TargetSubReg := R_SUBD;
  10019. else
  10020. InternalError(2021051002);
  10021. end;
  10022. if TargetSize <> MaxSize then
  10023. begin
  10024. { Update the register to its new size }
  10025. setsubreg(ThisReg, TargetSubReg);
  10026. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10027. taicpu(hp1).oper[1]^.reg := ThisReg;
  10028. taicpu(hp1).opsize := TargetSize;
  10029. { Convert the input MOVZX to a MOV if necessary }
  10030. AdjustInitialLoadAndSize;
  10031. if (InstrMax >= 0) then
  10032. begin
  10033. for Index := 0 to InstrMax do
  10034. begin
  10035. { If p_removed is true, then the original MOV/Z was removed
  10036. and removing the AND instruction may not be safe if it
  10037. appears first }
  10038. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10039. InternalError(2020112311);
  10040. if InstrList[Index].oper[0]^.typ = top_reg then
  10041. InstrList[Index].oper[0]^.reg := ThisReg;
  10042. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10043. InstrList[Index].opsize := MinSize;
  10044. end;
  10045. end;
  10046. Result := True;
  10047. end;
  10048. Exit;
  10049. end;
  10050. end;
  10051. A_SETcc:
  10052. begin
  10053. { This allows this Movx optimisation to work through the SETcc instructions
  10054. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10055. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10056. skip over these SETcc instructions). }
  10057. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10058. { Of course, break out if the current register is used }
  10059. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10060. Break
  10061. else
  10062. { We must use Continue so the instruction doesn't get added
  10063. to InstrList }
  10064. Continue;
  10065. end;
  10066. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10067. begin
  10068. if
  10069. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10070. { Has to be an exact match on the register }
  10071. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10072. (
  10073. (
  10074. (taicpu(hp1).oper[0]^.typ = top_const) and
  10075. (
  10076. (
  10077. (taicpu(hp1).opcode = A_SHL) and
  10078. (
  10079. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10080. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10081. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10082. )
  10083. ) or (
  10084. (taicpu(hp1).opcode <> A_SHL) and
  10085. (
  10086. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10087. { Is it in the negative range? }
  10088. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10089. )
  10090. )
  10091. )
  10092. ) or (
  10093. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10094. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10095. )
  10096. ) then
  10097. Break;
  10098. { Only process OR and XOR if there are only bitwise operations,
  10099. since otherwise they can too easily fool the data flow
  10100. analysis (they can cause non-linear behaviour) }
  10101. case taicpu(hp1).opcode of
  10102. A_ADD:
  10103. begin
  10104. if OrXorUsed then
  10105. { Too high a risk of non-linear behaviour that breaks DFA here }
  10106. Break
  10107. else
  10108. BitwiseOnly := False;
  10109. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10110. begin
  10111. TestValMin := TestValMin * 2;
  10112. TestValMax := TestValMax * 2;
  10113. TestValSignedMax := TestValSignedMax * 2;
  10114. end
  10115. else
  10116. begin
  10117. WorkingValue := taicpu(hp1).oper[0]^.val;
  10118. TestValMin := TestValMin + WorkingValue;
  10119. TestValMax := TestValMax + WorkingValue;
  10120. TestValSignedMax := TestValSignedMax + WorkingValue;
  10121. end;
  10122. end;
  10123. A_SUB:
  10124. begin
  10125. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10126. begin
  10127. TestValMin := 0;
  10128. TestValMax := 0;
  10129. TestValSignedMax := 0;
  10130. end
  10131. else
  10132. begin
  10133. if OrXorUsed then
  10134. { Too high a risk of non-linear behaviour that breaks DFA here }
  10135. Break
  10136. else
  10137. BitwiseOnly := False;
  10138. WorkingValue := taicpu(hp1).oper[0]^.val;
  10139. TestValMin := TestValMin - WorkingValue;
  10140. TestValMax := TestValMax - WorkingValue;
  10141. TestValSignedMax := TestValSignedMax - WorkingValue;
  10142. end;
  10143. end;
  10144. A_AND:
  10145. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10146. begin
  10147. { we might be able to go smaller if AND appears first }
  10148. if InstrMax = -1 then
  10149. case MinSize of
  10150. S_B:
  10151. ;
  10152. S_W:
  10153. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10154. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10155. begin
  10156. TryShiftDown := S_B;
  10157. TryShiftDownLimit := $FF;
  10158. end;
  10159. S_L:
  10160. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10161. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10162. begin
  10163. TryShiftDown := S_B;
  10164. TryShiftDownLimit := $FF;
  10165. end
  10166. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10167. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10168. begin
  10169. TryShiftDown := S_W;
  10170. TryShiftDownLimit := $FFFF;
  10171. end;
  10172. else
  10173. InternalError(2020112320);
  10174. end;
  10175. WorkingValue := taicpu(hp1).oper[0]^.val;
  10176. TestValMin := TestValMin and WorkingValue;
  10177. TestValMax := TestValMax and WorkingValue;
  10178. TestValSignedMax := TestValSignedMax and WorkingValue;
  10179. end;
  10180. A_OR:
  10181. begin
  10182. if not BitwiseOnly then
  10183. Break;
  10184. OrXorUsed := True;
  10185. WorkingValue := taicpu(hp1).oper[0]^.val;
  10186. TestValMin := TestValMin or WorkingValue;
  10187. TestValMax := TestValMax or WorkingValue;
  10188. TestValSignedMax := TestValSignedMax or WorkingValue;
  10189. end;
  10190. A_XOR:
  10191. begin
  10192. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10193. begin
  10194. TestValMin := 0;
  10195. TestValMax := 0;
  10196. TestValSignedMax := 0;
  10197. end
  10198. else
  10199. begin
  10200. if not BitwiseOnly then
  10201. Break;
  10202. OrXorUsed := True;
  10203. WorkingValue := taicpu(hp1).oper[0]^.val;
  10204. TestValMin := TestValMin xor WorkingValue;
  10205. TestValMax := TestValMax xor WorkingValue;
  10206. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10207. end;
  10208. end;
  10209. A_SHL:
  10210. begin
  10211. BitwiseOnly := False;
  10212. WorkingValue := taicpu(hp1).oper[0]^.val;
  10213. TestValMin := TestValMin shl WorkingValue;
  10214. TestValMax := TestValMax shl WorkingValue;
  10215. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10216. end;
  10217. A_SHR,
  10218. { The first instruction was MOVZX, so the value won't be negative }
  10219. A_SAR:
  10220. begin
  10221. if InstrMax <> -1 then
  10222. BitwiseOnly := False
  10223. else
  10224. { we might be able to go smaller if SHR appears first }
  10225. case MinSize of
  10226. S_B:
  10227. ;
  10228. S_W:
  10229. if (taicpu(hp1).oper[0]^.val >= 8) then
  10230. begin
  10231. TryShiftDown := S_B;
  10232. TryShiftDownLimit := $FF;
  10233. TryShiftDownSignedLimit := $7F;
  10234. TryShiftDownSignedLimitLower := -128;
  10235. end;
  10236. S_L:
  10237. if (taicpu(hp1).oper[0]^.val >= 24) then
  10238. begin
  10239. TryShiftDown := S_B;
  10240. TryShiftDownLimit := $FF;
  10241. TryShiftDownSignedLimit := $7F;
  10242. TryShiftDownSignedLimitLower := -128;
  10243. end
  10244. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10245. begin
  10246. TryShiftDown := S_W;
  10247. TryShiftDownLimit := $FFFF;
  10248. TryShiftDownSignedLimit := $7FFF;
  10249. TryShiftDownSignedLimitLower := -32768;
  10250. end;
  10251. else
  10252. InternalError(2020112321);
  10253. end;
  10254. WorkingValue := taicpu(hp1).oper[0]^.val;
  10255. if taicpu(hp1).opcode = A_SAR then
  10256. begin
  10257. TestValMin := SarInt64(TestValMin, WorkingValue);
  10258. TestValMax := SarInt64(TestValMax, WorkingValue);
  10259. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10260. end
  10261. else
  10262. begin
  10263. TestValMin := TestValMin shr WorkingValue;
  10264. TestValMax := TestValMax shr WorkingValue;
  10265. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10266. end;
  10267. end;
  10268. else
  10269. InternalError(2020112303);
  10270. end;
  10271. end;
  10272. (*
  10273. A_IMUL:
  10274. case taicpu(hp1).ops of
  10275. 2:
  10276. begin
  10277. if not MatchOpType(hp1, top_reg, top_reg) or
  10278. { Has to be an exact match on the register }
  10279. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10280. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10281. Break;
  10282. TestValMin := TestValMin * TestValMin;
  10283. TestValMax := TestValMax * TestValMax;
  10284. TestValSignedMax := TestValSignedMax * TestValMax;
  10285. end;
  10286. 3:
  10287. begin
  10288. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10289. { Has to be an exact match on the register }
  10290. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10291. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10292. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10293. { Is it in the negative range? }
  10294. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10295. Break;
  10296. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10297. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10298. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10299. end;
  10300. else
  10301. Break;
  10302. end;
  10303. A_IDIV:
  10304. case taicpu(hp1).ops of
  10305. 3:
  10306. begin
  10307. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10308. { Has to be an exact match on the register }
  10309. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10310. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10311. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10312. { Is it in the negative range? }
  10313. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10314. Break;
  10315. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10316. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10317. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10318. end;
  10319. else
  10320. Break;
  10321. end;
  10322. *)
  10323. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10324. begin
  10325. { If there are no instructions in between, then we might be able to make a saving }
  10326. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10327. Break;
  10328. { We have something like:
  10329. movzbw %dl,%dx
  10330. ...
  10331. movswl %dx,%edx
  10332. Change the latter to a zero-extension then enter the
  10333. A_MOVZX case branch.
  10334. }
  10335. {$ifdef x86_64}
  10336. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10337. begin
  10338. { this becomes a zero extension from 32-bit to 64-bit, but
  10339. the upper 32 bits are already zero, so just delete the
  10340. instruction }
  10341. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10342. RemoveInstruction(hp1);
  10343. Result := True;
  10344. Exit;
  10345. end
  10346. else
  10347. {$endif x86_64}
  10348. begin
  10349. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10350. taicpu(hp1).opcode := A_MOVZX;
  10351. {$ifdef x86_64}
  10352. case taicpu(hp1).opsize of
  10353. S_BQ:
  10354. begin
  10355. taicpu(hp1).opsize := S_BL;
  10356. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10357. end;
  10358. S_WQ:
  10359. begin
  10360. taicpu(hp1).opsize := S_WL;
  10361. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10362. end;
  10363. S_LQ:
  10364. begin
  10365. taicpu(hp1).opcode := A_MOV;
  10366. taicpu(hp1).opsize := S_L;
  10367. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10368. { In this instance, we need to break out because the
  10369. instruction is no longer MOVZX or MOVSXD }
  10370. Result := True;
  10371. Exit;
  10372. end;
  10373. else
  10374. ;
  10375. end;
  10376. {$endif x86_64}
  10377. Result := CompressInstructions;
  10378. Exit;
  10379. end;
  10380. end;
  10381. A_MOVZX:
  10382. begin
  10383. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10384. Break;
  10385. if (InstrMax = -1) then
  10386. begin
  10387. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10388. begin
  10389. { Optimise around i40003 }
  10390. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10391. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10392. {$ifndef x86_64}
  10393. and (
  10394. (taicpu(p).oper[0]^.typ <> top_reg) or
  10395. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10396. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10397. )
  10398. {$endif not x86_64}
  10399. then
  10400. begin
  10401. if (taicpu(p).oper[0]^.typ = top_reg) then
  10402. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10403. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10404. taicpu(p).opsize := S_BL;
  10405. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10406. RemoveInstruction(hp1);
  10407. Result := True;
  10408. Exit;
  10409. end;
  10410. end
  10411. else
  10412. begin
  10413. { Will return false if the second parameter isn't ThisReg
  10414. (can happen on -O2 and under) }
  10415. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10416. begin
  10417. { The two MOVZX instructions are adjacent, so remove the first one }
  10418. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10419. RemoveCurrentP(p);
  10420. Result := True;
  10421. Exit;
  10422. end;
  10423. Break;
  10424. end;
  10425. end;
  10426. Result := CompressInstructions;
  10427. Exit;
  10428. end;
  10429. else
  10430. { This includes ADC, SBB and IDIV }
  10431. Break;
  10432. end;
  10433. if not CheckOverflowConditions then
  10434. Break;
  10435. { Contains highest index (so instruction count - 1) }
  10436. Inc(InstrMax);
  10437. if InstrMax > High(InstrList) then
  10438. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10439. InstrList[InstrMax] := taicpu(hp1);
  10440. end;
  10441. end;
  10442. {$pop}
  10443. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10444. var
  10445. hp1 : tai;
  10446. begin
  10447. Result:=false;
  10448. if (taicpu(p).ops >= 2) and
  10449. ((taicpu(p).oper[0]^.typ = top_const) or
  10450. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10451. (taicpu(p).oper[1]^.typ = top_reg) and
  10452. ((taicpu(p).ops = 2) or
  10453. ((taicpu(p).oper[2]^.typ = top_reg) and
  10454. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10455. GetLastInstruction(p,hp1) and
  10456. MatchInstruction(hp1,A_MOV,[]) and
  10457. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10458. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10459. begin
  10460. TransferUsedRegs(TmpUsedRegs);
  10461. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10462. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10463. { change
  10464. mov reg1,reg2
  10465. imul y,reg2 to imul y,reg1,reg2 }
  10466. begin
  10467. taicpu(p).ops := 3;
  10468. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10469. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10470. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10471. RemoveInstruction(hp1);
  10472. result:=true;
  10473. end;
  10474. end;
  10475. end;
  10476. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10477. var
  10478. ThisLabel: TAsmLabel;
  10479. begin
  10480. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10481. ThisLabel.decrefs;
  10482. taicpu(p).condition := C_None;
  10483. taicpu(p).opcode := A_RET;
  10484. taicpu(p).is_jmp := false;
  10485. taicpu(p).ops := taicpu(ret_p).ops;
  10486. case taicpu(ret_p).ops of
  10487. 0:
  10488. taicpu(p).clearop(0);
  10489. 1:
  10490. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10491. else
  10492. internalerror(2016041301);
  10493. end;
  10494. { If the original label is now dead, it might turn out that the label
  10495. immediately follows p. As a result, everything beyond it, which will
  10496. be just some final register configuration and a RET instruction, is
  10497. now dead code. [Kit] }
  10498. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10499. running RemoveDeadCodeAfterJump for each RET instruction, because
  10500. this optimisation rarely happens and most RETs appear at the end of
  10501. routines where there is nothing that can be stripped. [Kit] }
  10502. if not ThisLabel.is_used then
  10503. RemoveDeadCodeAfterJump(p);
  10504. end;
  10505. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10506. var
  10507. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10508. Unconditional, PotentialModified: Boolean;
  10509. OperPtr: POper;
  10510. NewRef: TReference;
  10511. InstrList: array of taicpu;
  10512. InstrMax, Index: Integer;
  10513. const
  10514. {$ifdef DEBUG_AOPTCPU}
  10515. SNoFlags: shortstring = ' so the flags aren''t modified';
  10516. {$else DEBUG_AOPTCPU}
  10517. SNoFlags = '';
  10518. {$endif DEBUG_AOPTCPU}
  10519. begin
  10520. Result:=false;
  10521. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10522. begin
  10523. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10524. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10525. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10526. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10527. GetNextInstruction(hp1, hp2) and
  10528. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10529. { Change from: To:
  10530. set(C) %reg j(~C) label
  10531. test %reg,%reg/cmp $0,%reg
  10532. je label
  10533. set(C) %reg j(C) label
  10534. test %reg,%reg/cmp $0,%reg
  10535. jne label
  10536. (Also do something similar with sete/setne instead of je/jne)
  10537. }
  10538. begin
  10539. { Before we do anything else, we need to check the instructions
  10540. in between SETcc and TEST to make sure they don't modify the
  10541. FLAGS register - if -O2 or under, there won't be any
  10542. instructions between SET and TEST }
  10543. TransferUsedRegs(TmpUsedRegs);
  10544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10545. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10546. begin
  10547. next := p;
  10548. SetLength(InstrList, 0);
  10549. InstrMax := -1;
  10550. PotentialModified := False;
  10551. { Make a note of every instruction that modifies the FLAGS
  10552. register }
  10553. while GetNextInstruction(next, next) and (next <> hp1) do
  10554. begin
  10555. if next.typ <> ait_instruction then
  10556. { GetNextInstructionUsingReg should have returned False }
  10557. InternalError(2021051701);
  10558. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10559. begin
  10560. case taicpu(next).opcode of
  10561. A_SETcc,
  10562. A_CMOVcc,
  10563. A_Jcc:
  10564. begin
  10565. if PotentialModified then
  10566. { Not safe because the flags were modified earlier }
  10567. Exit
  10568. else
  10569. { Condition is the same as the initial SETcc, so this is safe
  10570. (don't add to instruction list though) }
  10571. Continue;
  10572. end;
  10573. A_ADD:
  10574. begin
  10575. if (taicpu(next).opsize = S_B) or
  10576. { LEA doesn't support 8-bit operands }
  10577. (taicpu(next).oper[1]^.typ <> top_reg) or
  10578. { Must write to a register }
  10579. (taicpu(next).oper[0]^.typ = top_ref) then
  10580. { Require a constant or a register }
  10581. Exit;
  10582. PotentialModified := True;
  10583. end;
  10584. A_SUB:
  10585. begin
  10586. if (taicpu(next).opsize = S_B) or
  10587. { LEA doesn't support 8-bit operands }
  10588. (taicpu(next).oper[1]^.typ <> top_reg) or
  10589. { Must write to a register }
  10590. (taicpu(next).oper[0]^.typ <> top_const) or
  10591. (taicpu(next).oper[0]^.val = $80000000) then
  10592. { Can't subtract a register with LEA - also
  10593. check that the value isn't -2^31, as this
  10594. can't be negated }
  10595. Exit;
  10596. PotentialModified := True;
  10597. end;
  10598. A_SAL,
  10599. A_SHL:
  10600. begin
  10601. if (taicpu(next).opsize = S_B) or
  10602. { LEA doesn't support 8-bit operands }
  10603. (taicpu(next).oper[1]^.typ <> top_reg) or
  10604. { Must write to a register }
  10605. (taicpu(next).oper[0]^.typ <> top_const) or
  10606. (taicpu(next).oper[0]^.val < 0) or
  10607. (taicpu(next).oper[0]^.val > 3) then
  10608. Exit;
  10609. PotentialModified := True;
  10610. end;
  10611. A_IMUL:
  10612. begin
  10613. if (taicpu(next).ops <> 3) or
  10614. (taicpu(next).oper[1]^.typ <> top_reg) or
  10615. { Must write to a register }
  10616. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10617. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10618. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10619. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10620. Exit
  10621. else
  10622. PotentialModified := True;
  10623. end;
  10624. else
  10625. { Don't know how to change this, so abort }
  10626. Exit;
  10627. end;
  10628. { Contains highest index (so instruction count - 1) }
  10629. Inc(InstrMax);
  10630. if InstrMax > High(InstrList) then
  10631. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10632. InstrList[InstrMax] := taicpu(next);
  10633. end;
  10634. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10635. end;
  10636. if not Assigned(next) or (next <> hp1) then
  10637. { It should be equal to hp1 }
  10638. InternalError(2021051702);
  10639. { Cycle through each instruction and check to see if we can
  10640. change them to versions that don't modify the flags }
  10641. if (InstrMax >= 0) then
  10642. begin
  10643. for Index := 0 to InstrMax do
  10644. case InstrList[Index].opcode of
  10645. A_ADD:
  10646. begin
  10647. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10648. InstrList[Index].opcode := A_LEA;
  10649. reference_reset(NewRef, 1, []);
  10650. NewRef.base := InstrList[Index].oper[1]^.reg;
  10651. if InstrList[Index].oper[0]^.typ = top_reg then
  10652. begin
  10653. NewRef.index := InstrList[Index].oper[0]^.reg;
  10654. NewRef.scalefactor := 1;
  10655. end
  10656. else
  10657. NewRef.offset := InstrList[Index].oper[0]^.val;
  10658. InstrList[Index].loadref(0, NewRef);
  10659. end;
  10660. A_SUB:
  10661. begin
  10662. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10663. InstrList[Index].opcode := A_LEA;
  10664. reference_reset(NewRef, 1, []);
  10665. NewRef.base := InstrList[Index].oper[1]^.reg;
  10666. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10667. InstrList[Index].loadref(0, NewRef);
  10668. end;
  10669. A_SHL,
  10670. A_SAL:
  10671. begin
  10672. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10673. InstrList[Index].opcode := A_LEA;
  10674. reference_reset(NewRef, 1, []);
  10675. NewRef.index := InstrList[Index].oper[1]^.reg;
  10676. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10677. InstrList[Index].loadref(0, NewRef);
  10678. end;
  10679. A_IMUL:
  10680. begin
  10681. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10682. InstrList[Index].opcode := A_LEA;
  10683. reference_reset(NewRef, 1, []);
  10684. NewRef.index := InstrList[Index].oper[1]^.reg;
  10685. case InstrList[Index].oper[0]^.val of
  10686. 2, 4, 8:
  10687. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10688. else {3, 5 and 9}
  10689. begin
  10690. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10691. NewRef.base := InstrList[Index].oper[1]^.reg;
  10692. end;
  10693. end;
  10694. InstrList[Index].loadref(0, NewRef);
  10695. end;
  10696. else
  10697. InternalError(2021051710);
  10698. end;
  10699. end;
  10700. { Mark the FLAGS register as used across this whole block }
  10701. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10702. end;
  10703. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10704. JumpC := taicpu(hp2).condition;
  10705. Unconditional := False;
  10706. if conditions_equal(JumpC, C_E) then
  10707. SetC := inverse_cond(taicpu(p).condition)
  10708. else if conditions_equal(JumpC, C_NE) then
  10709. SetC := taicpu(p).condition
  10710. else
  10711. { We've got something weird here (and inefficent) }
  10712. begin
  10713. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10714. SetC := C_NONE;
  10715. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10716. if condition_in(C_AE, JumpC) then
  10717. Unconditional := True
  10718. else
  10719. { Not sure what to do with this jump - drop out }
  10720. Exit;
  10721. end;
  10722. RemoveInstruction(hp1);
  10723. if Unconditional then
  10724. MakeUnconditional(taicpu(hp2))
  10725. else
  10726. begin
  10727. if SetC = C_NONE then
  10728. InternalError(2018061402);
  10729. taicpu(hp2).SetCondition(SetC);
  10730. end;
  10731. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10732. TmpUsedRegs }
  10733. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10734. begin
  10735. RemoveCurrentp(p, hp2);
  10736. if taicpu(hp2).opcode = A_SETcc then
  10737. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10738. else
  10739. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10740. end
  10741. else
  10742. if taicpu(hp2).opcode = A_SETcc then
  10743. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10744. else
  10745. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10746. Result := True;
  10747. end
  10748. else if
  10749. { Make sure the instructions are adjacent }
  10750. (
  10751. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10752. GetNextInstruction(p, hp1)
  10753. ) and
  10754. MatchInstruction(hp1, A_MOV, [S_B]) and
  10755. { Writing to memory is allowed }
  10756. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10757. begin
  10758. {
  10759. Watch out for sequences such as:
  10760. set(c)b %regb
  10761. movb %regb,(ref)
  10762. movb $0,1(ref)
  10763. movb $0,2(ref)
  10764. movb $0,3(ref)
  10765. Much more efficient to turn it into:
  10766. movl $0,%regl
  10767. set(c)b %regb
  10768. movl %regl,(ref)
  10769. Or:
  10770. set(c)b %regb
  10771. movzbl %regb,%regl
  10772. movl %regl,(ref)
  10773. }
  10774. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10775. GetNextInstruction(hp1, hp2) and
  10776. MatchInstruction(hp2, A_MOV, [S_B]) and
  10777. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10778. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10779. begin
  10780. { Don't do anything else except set Result to True }
  10781. end
  10782. else
  10783. begin
  10784. if taicpu(p).oper[0]^.typ = top_reg then
  10785. begin
  10786. TransferUsedRegs(TmpUsedRegs);
  10787. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10788. end;
  10789. { If it's not a register, it's a memory address }
  10790. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10791. begin
  10792. { Even if the register is still in use, we can minimise the
  10793. pipeline stall by changing the MOV into another SETcc. }
  10794. taicpu(hp1).opcode := A_SETcc;
  10795. taicpu(hp1).condition := taicpu(p).condition;
  10796. if taicpu(hp1).oper[1]^.typ = top_ref then
  10797. begin
  10798. { Swapping the operand pointers like this is probably a
  10799. bit naughty, but it is far faster than using loadoper
  10800. to transfer the reference from oper[1] to oper[0] if
  10801. you take into account the extra procedure calls and
  10802. the memory allocation and deallocation required }
  10803. OperPtr := taicpu(hp1).oper[1];
  10804. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10805. taicpu(hp1).oper[0] := OperPtr;
  10806. end
  10807. else
  10808. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10809. taicpu(hp1).clearop(1);
  10810. taicpu(hp1).ops := 1;
  10811. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10812. end
  10813. else
  10814. begin
  10815. if taicpu(hp1).oper[1]^.typ = top_reg then
  10816. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10817. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10818. RemoveInstruction(hp1);
  10819. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10820. end
  10821. end;
  10822. Result := True;
  10823. end;
  10824. end;
  10825. end;
  10826. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10827. var
  10828. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  10829. TargetReg: TRegister;
  10830. condition, inverted_condition: TAsmCond;
  10831. FoundMOV: Boolean;
  10832. begin
  10833. Result := False;
  10834. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10835. create the most optimial instructions possible due to limited
  10836. register availability, and there are situations where two
  10837. complementary "simple" CMOV blocks are created which, after the fact
  10838. can be merged into a "double" block. For example:
  10839. movw $257,%ax
  10840. movw $2,%r8w
  10841. xorl r9d,%r9d
  10842. testw $16,18(%rcx)
  10843. cmovew %ax,%dx
  10844. cmovew %r8w,%bx
  10845. cmovel %r9d,%r14d
  10846. movw $1283,%ax
  10847. movw $4,%r8w
  10848. movl $9,%r9d
  10849. cmovnew %ax,%dx
  10850. cmovnew %r8w,%bx
  10851. cmovnel %r9d,%r14d
  10852. The CMOVNE instructions at the end can be removed, and the
  10853. destination registers copied into the MOV instructions directly
  10854. above them, before finally being moved to before the first CMOVE
  10855. instructions, to produce:
  10856. movw $257,%ax
  10857. movw $2,%r8w
  10858. xorl r9d,%r9d
  10859. testw $16,18(%rcx)
  10860. movw $1283,%dx
  10861. movw $4,%bx
  10862. movl $9,%r14d
  10863. cmovew %ax,%dx
  10864. cmovew %r8w,%bx
  10865. cmovel %r9d,%r14d
  10866. Which can then be later optimised to:
  10867. movw $257,%ax
  10868. movw $2,%r8w
  10869. xorl r9d,%r9d
  10870. movw $1283,%dx
  10871. movw $4,%bx
  10872. movl $9,%r14d
  10873. testw $16,18(%rcx)
  10874. cmovew %ax,%dx
  10875. cmovew %r8w,%bx
  10876. cmovel %r9d,%r14d
  10877. }
  10878. TargetReg := taicpu(hp1).oper[1]^.reg;
  10879. condition := taicpu(hp1).condition;
  10880. inverted_condition := inverse_cond(condition);
  10881. pFirstMov := nil;
  10882. pLastMov := nil;
  10883. pCMOV := nil;
  10884. if (p.typ = ait_instruction) then
  10885. pCond := p
  10886. else if not GetNextInstruction(p, pCond) then
  10887. InternalError(2024012501);
  10888. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  10889. { We should get the CMP or TEST instructeion }
  10890. InternalError(2024012502);
  10891. if (
  10892. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10893. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10894. ) then
  10895. begin
  10896. { We have to tread carefully here, hence why we're not using
  10897. GetNextInstructionUsingReg... we can only accept MOV and other
  10898. CMOV instructions. Anything else and we must drop out}
  10899. hp2 := hp1;
  10900. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  10901. begin
  10902. if (hp2.typ <> ait_instruction) then
  10903. Exit;
  10904. case taicpu(hp2).opcode of
  10905. A_MOV:
  10906. begin
  10907. if not Assigned(pFirstMov) then
  10908. pFirstMov := hp2;
  10909. pLastMOV := hp2;
  10910. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10911. { Something different - drop out }
  10912. Exit;
  10913. { Otherwise, leave it for now }
  10914. end;
  10915. A_CMOVcc:
  10916. begin
  10917. if taicpu(hp2).condition = inverted_condition then
  10918. begin
  10919. { We found what we're looking for }
  10920. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10921. begin
  10922. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10923. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10924. begin
  10925. pCMOV := hp2;
  10926. Break;
  10927. end
  10928. else
  10929. { Unsafe reference - drop out }
  10930. Exit;
  10931. end;
  10932. end
  10933. else if taicpu(hp2).condition <> condition then
  10934. { Something weird - drop out }
  10935. Exit;
  10936. end;
  10937. else
  10938. { Invalid }
  10939. Exit;
  10940. end;
  10941. end;
  10942. if not Assigned(pCMOV) then
  10943. { No complementary CMOV found }
  10944. Exit;
  10945. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10946. begin
  10947. { Don't need to do anything special or search for a matching MOV }
  10948. Asml.Remove(pCMOV);
  10949. if RegInInstruction(TargetReg, pCond) then
  10950. { Make sure we don't overwrite the register if it's being used in the condition }
  10951. Asml.InsertAfter(pCMOV, pCond)
  10952. else
  10953. Asml.InsertBefore(pCMOV, pCond);
  10954. taicpu(pCMOV).opcode := A_MOV;
  10955. taicpu(pCMOV).condition := C_None;
  10956. { Don't need to worry about allocating new registers in these cases }
  10957. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  10958. Result := True;
  10959. Exit;
  10960. end
  10961. else
  10962. begin
  10963. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  10964. FoundMOV := False;
  10965. { Search for the MOV that sets the target register }
  10966. hp2 := pFirstMov;
  10967. repeat
  10968. if (taicpu(hp2).opcode = A_MOV) and
  10969. (taicpu(hp2).oper[1]^.typ = top_reg) and
  10970. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  10971. begin
  10972. { Change the destination }
  10973. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  10974. if not FoundMOV then
  10975. begin
  10976. FoundMOV := True;
  10977. { Make sure the register is allocated }
  10978. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  10979. end;
  10980. hp1 := tai(hp2.Previous);
  10981. Asml.Remove(hp2);
  10982. if RegInInstruction(TargetReg, pCond) then
  10983. { Make sure we don't overwrite the register if it's being used in the condition }
  10984. Asml.InsertAfter(hp2, pCond)
  10985. else
  10986. Asml.InsertBefore(hp2, pCond);
  10987. if (hp2 = pLastMov) then
  10988. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  10989. Break;
  10990. hp2 := hp1;
  10991. end;
  10992. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  10993. if FoundMOV then
  10994. { Delete the CMOV }
  10995. RemoveInstruction(pCMOV)
  10996. else
  10997. begin
  10998. { If no MOV was found, we have to actually move and transmute the CMOV }
  10999. Asml.Remove(pCMOV);
  11000. if RegInInstruction(TargetReg, pCond) then
  11001. { Make sure we don't overwrite the register if it's being used in the condition }
  11002. Asml.InsertAfter(pCMOV, pCond)
  11003. else
  11004. Asml.InsertBefore(pCMOV, pCond);
  11005. taicpu(pCMOV).opcode := A_MOV;
  11006. taicpu(pCMOV).condition := C_None;
  11007. end;
  11008. Result := True;
  11009. Exit;
  11010. end;
  11011. end;
  11012. end;
  11013. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11014. var
  11015. hp1, hp2, pCond: tai;
  11016. begin
  11017. Result := False;
  11018. { Search ahead for CMOV instructions }
  11019. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11020. begin
  11021. hp1 := p;
  11022. hp2 := p;
  11023. pCond := nil; { To prevent compiler warnings }
  11024. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11025. DEFAULTFLAGS }
  11026. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11027. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11028. pCond := p;
  11029. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11030. begin
  11031. if (hp1.typ <> ait_instruction) then
  11032. { Break out on markers and labels etc. }
  11033. Break;
  11034. case taicpu(hp1).opcode of
  11035. A_MOV:
  11036. { Ignore regular MOVs unless they are obviously not related
  11037. to a CMOV block }
  11038. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11039. Break;
  11040. A_CMOVcc:
  11041. if TryCmpCMovOpts(pCond, hp1) then
  11042. begin
  11043. hp1 := hp2;
  11044. { p itself isn't changed, and we're still inside a
  11045. while loop to catch subsequent CMOVs, so just flag
  11046. a new iteration }
  11047. Include(OptsToCheck, aoc_ForceNewIteration);
  11048. Continue;
  11049. end;
  11050. else
  11051. { Drop out if we find anything else }
  11052. Break;
  11053. end;
  11054. hp2 := hp1;
  11055. end;
  11056. end;
  11057. end;
  11058. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11059. var
  11060. hp1, hp2, pCond: tai;
  11061. begin
  11062. Result := False;
  11063. { Search ahead for CMOV instructions }
  11064. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11065. begin
  11066. hp1 := p;
  11067. hp2 := p;
  11068. pCond := nil; { To prevent compiler warnings }
  11069. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11070. DEFAULTFLAGS }
  11071. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11072. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11073. pCond := p;
  11074. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11075. begin
  11076. if (hp1.typ <> ait_instruction) then
  11077. { Break out on markers and labels etc. }
  11078. Break;
  11079. case taicpu(hp1).opcode of
  11080. A_MOV:
  11081. { Ignore regular MOVs unless they are obviously not related
  11082. to a CMOV block }
  11083. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11084. Break;
  11085. A_CMOVcc:
  11086. if TryCmpCMovOpts(pCond, hp1) then
  11087. begin
  11088. hp1 := hp2;
  11089. { p itself isn't changed, and we're still inside a
  11090. while loop to catch subsequent CMOVs, so just flag
  11091. a new iteration }
  11092. Include(OptsToCheck, aoc_ForceNewIteration);
  11093. Continue;
  11094. end;
  11095. else
  11096. { Drop out if we find anything else }
  11097. Break;
  11098. end;
  11099. hp2 := hp1;
  11100. end;
  11101. end;
  11102. end;
  11103. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11104. var
  11105. hp1: tai;
  11106. Count: Integer;
  11107. OrigLabel: TAsmLabel;
  11108. begin
  11109. result := False;
  11110. { Sometimes, the optimisations below can permit this }
  11111. RemoveDeadCodeAfterJump(p);
  11112. 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
  11113. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11114. begin
  11115. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11116. { Also a side-effect of optimisations }
  11117. if CollapseZeroDistJump(p, OrigLabel) then
  11118. begin
  11119. Result := True;
  11120. Exit;
  11121. end;
  11122. hp1 := GetLabelWithSym(OrigLabel);
  11123. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11124. begin
  11125. if taicpu(hp1).opcode = A_RET then
  11126. begin
  11127. {
  11128. change
  11129. jmp .L1
  11130. ...
  11131. .L1:
  11132. ret
  11133. into
  11134. ret
  11135. }
  11136. begin
  11137. ConvertJumpToRET(p, hp1);
  11138. result:=true;
  11139. end;
  11140. end
  11141. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11142. not (cs_opt_size in current_settings.optimizerswitches) and
  11143. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11144. begin
  11145. Result := True;
  11146. Exit;
  11147. end;
  11148. end;
  11149. end;
  11150. end;
  11151. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11152. begin
  11153. Result := assigned(p) and
  11154. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11155. (taicpu(p).oper[1]^.typ = top_reg) and
  11156. (
  11157. (taicpu(p).oper[0]^.typ = top_reg) or
  11158. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11159. it is not expected that this can cause a seg. violation }
  11160. (
  11161. (taicpu(p).oper[0]^.typ = top_ref) and
  11162. { TODO: Can we detect which references become constants at this
  11163. stage so we don't have to do a blanket ban? }
  11164. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11165. (
  11166. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11167. (
  11168. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11169. not RefModified and
  11170. { If the reference also appears in the condition, then we know it's safe, otherwise
  11171. any kind of access violation would have occurred already }
  11172. Assigned(cond_p) and
  11173. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11174. (cond_p.typ = ait_instruction) and
  11175. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11176. { Just consider 2-operand comparison instructions for now to be safe }
  11177. (taicpu(cond_p).ops = 2) and
  11178. (
  11179. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11180. (
  11181. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11182. { Don't risk identical registers but different offsets, as we may have constructs
  11183. such as buffer streams with things like length fields that indicate whether
  11184. any more data follows. And there are probably some contrived examples where
  11185. writing to offsets behind the one being read also lead to access violations }
  11186. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11187. (
  11188. { Check that we're not modifying a register that appears in the reference }
  11189. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11190. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11191. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11192. )
  11193. )
  11194. )
  11195. )
  11196. )
  11197. )
  11198. );
  11199. end;
  11200. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11201. begin
  11202. { Update integer registers, ignoring deallocations }
  11203. repeat
  11204. while assigned(p) and
  11205. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11206. (p.typ = ait_label) or
  11207. ((p.typ = ait_marker) and
  11208. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11209. p := tai(p.next);
  11210. while assigned(p) and
  11211. (p.typ=ait_RegAlloc) Do
  11212. begin
  11213. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11214. begin
  11215. case tai_regalloc(p).ratype of
  11216. ra_alloc :
  11217. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11218. else
  11219. ;
  11220. end;
  11221. end;
  11222. p := tai(p.next);
  11223. end;
  11224. until not(assigned(p)) or
  11225. (not(p.typ in SkipInstr) and
  11226. not((p.typ = ait_label) and
  11227. labelCanBeSkipped(tai_label(p))));
  11228. end;
  11229. {$ifndef 8086}
  11230. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11231. begin
  11232. Result := False;
  11233. EndJump := nil;
  11234. BlockStop := nil;
  11235. while (BlockStart <> fOptimizer.BlockEnd) and
  11236. { stop on labels }
  11237. (BlockStart.typ <> ait_label) do
  11238. begin
  11239. { Keep track of all integer registers that are used }
  11240. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11241. if BlockStart.typ = ait_instruction then
  11242. begin
  11243. if (taicpu(BlockStart).opcode = A_JMP) then
  11244. begin
  11245. if not IsJumpToLabel(taicpu(BlockStart)) or
  11246. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11247. Exit;
  11248. EndJump := BlockStart;
  11249. Break;
  11250. end
  11251. { Check to see if we have a valid MOV instruction instead }
  11252. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11253. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11254. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11255. begin
  11256. Exit;
  11257. end
  11258. else
  11259. { This will be a valid MOV }
  11260. fAllocationRange := BlockStart;
  11261. end;
  11262. OneBeforeBlock := BlockStart;
  11263. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11264. end;
  11265. if (BlockStart = fOptimizer.BlockEnd) then
  11266. Exit;
  11267. BlockStop := BlockStart;
  11268. Result := True;
  11269. end;
  11270. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11271. var
  11272. hp1: tai;
  11273. RefModified: Boolean;
  11274. begin
  11275. Result := 0;
  11276. hp1 := BlockStart;
  11277. RefModified := False; { As long as the condition is inverted, this can be reset }
  11278. while assigned(hp1) and
  11279. (hp1 <> BlockStop) do
  11280. begin
  11281. case hp1.typ of
  11282. ait_instruction:
  11283. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11284. begin
  11285. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11286. begin
  11287. Inc(Result);
  11288. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11289. Assigned(fCondition) and
  11290. { Will have 2 operands }
  11291. (
  11292. (
  11293. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11294. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11295. ) or
  11296. (
  11297. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11298. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11299. )
  11300. ) then
  11301. { It is no longer safe to use the reference in the condition.
  11302. this prevents problems such as:
  11303. mov (%reg),%reg
  11304. mov (%reg),...
  11305. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11306. (fixes #40165)
  11307. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11308. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11309. }
  11310. RefModified := True;
  11311. end
  11312. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11313. { CMOV with constants grows the code size }
  11314. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11315. begin
  11316. { Register was reserved by TryCMOVConst and
  11317. stored on ConstRegs }
  11318. end
  11319. else
  11320. begin
  11321. Result := -1;
  11322. Exit;
  11323. end;
  11324. end
  11325. else
  11326. begin
  11327. Result := -1;
  11328. Exit;
  11329. end;
  11330. else
  11331. { Most likely an align };
  11332. end;
  11333. fOptimizer.GetNextInstruction(hp1, hp1);
  11334. end;
  11335. end;
  11336. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11337. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11338. (this is done as a separate stage because the double types are extensions of the branching type,
  11339. but we can't discount the conditional jump until the last step) }
  11340. procedure EvaluateBranchingType;
  11341. begin
  11342. Inc(CMOVScore);
  11343. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11344. { Too many instructions to be worthwhile }
  11345. fState := tsInvalid;
  11346. end;
  11347. var
  11348. hp1: tai;
  11349. Count: Integer;
  11350. begin
  11351. { Table of valid CMOV block types
  11352. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11353. ---------- --------- --------- --------- --------- ---------
  11354. tsSimple X Yes X X X
  11355. tsDetour = 1st X X X X
  11356. tsBranching <> Mid Yes X X X
  11357. tsDouble End-label Yes * Yes X Yes
  11358. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11359. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11360. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11361. * Only one reference allowed
  11362. }
  11363. hp1 := nil; { To prevent compiler warnings }
  11364. Optimizer.CopyUsedRegs(RegisterTracking);
  11365. fOptimizer := Optimizer;
  11366. fLabel := AFirstLabel;
  11367. CMOVScore := 0;
  11368. ConstCount := 0;
  11369. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11370. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11371. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11372. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11373. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11374. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11375. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11376. fInsertionPoint := p_initialjump;
  11377. fCondition := nil;
  11378. fInitialJump := p_initialjump;
  11379. fFirstMovBlock := p_initialmov;
  11380. fFirstMovBlockStop := nil;
  11381. fSecondJump := nil;
  11382. fSecondMovBlock := nil;
  11383. fSecondMovBlockStop := nil;
  11384. fMidLabel := nil;
  11385. fSecondJump := nil;
  11386. fSecondMovBlock := nil;
  11387. fEndLabel := nil;
  11388. fAllocationRange := nil;
  11389. { Assume it all goes horribly wrong! }
  11390. fState := tsInvalid;
  11391. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11392. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11393. 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
  11394. begin
  11395. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11396. for Count := 0 to 1 do
  11397. with taicpu(fCondition).oper[Count]^ do
  11398. case typ of
  11399. top_reg:
  11400. if getregtype(reg) = R_INTREGISTER then
  11401. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11402. top_ref:
  11403. begin
  11404. if
  11405. {$ifdef x86_64}
  11406. (ref^.base <> NR_RIP) and
  11407. {$endif x86_64}
  11408. (ref^.base <> NR_NO) then
  11409. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11410. if (ref^.index <> NR_NO) then
  11411. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11412. end
  11413. else
  11414. ;
  11415. end;
  11416. { When inserting instructions before hp_prev, try to insert them
  11417. before the allocation of the FLAGS register }
  11418. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11419. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11420. { If not found, set it equal to the condition so it's something sensible }
  11421. fInsertionPoint := fCondition;
  11422. { When dealing with a comparison against zero, take note of the
  11423. instruction before it to see if we can move instructions further
  11424. back in order to benefit PostPeepholeOptTestOr.
  11425. }
  11426. if (
  11427. (
  11428. (taicpu(fCondition).opcode = A_CMP) and
  11429. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11430. ) or
  11431. (
  11432. (taicpu(fCondition).opcode = A_TEST) and
  11433. (
  11434. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11435. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11436. )
  11437. )
  11438. ) and
  11439. Optimizer.GetLastInstruction(fCondition, hp1) then
  11440. begin
  11441. { These instructions set the zero flag if the result is zero }
  11442. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11443. begin
  11444. fInsertionPoint := hp1;
  11445. { Also mark all the registers in this previous instruction
  11446. as 'in use', even if they've just been deallocated }
  11447. for Count := 0 to 1 do
  11448. with taicpu(hp1).oper[Count]^ do
  11449. case typ of
  11450. top_reg:
  11451. if getregtype(reg) = R_INTREGISTER then
  11452. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11453. top_ref:
  11454. begin
  11455. if
  11456. {$ifdef x86_64}
  11457. (ref^.base <> NR_RIP) and
  11458. {$endif x86_64}
  11459. (ref^.base <> NR_NO) then
  11460. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11461. if (ref^.index <> NR_NO) then
  11462. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11463. end
  11464. else
  11465. ;
  11466. end;
  11467. end;
  11468. end;
  11469. end
  11470. else
  11471. fCondition := nil;
  11472. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11473. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11474. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11475. { If not found, set it equal to p so it's something sensible }
  11476. fInsertionPoint := hp1;
  11477. hp1 := p_initialmov;
  11478. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11479. Exit;
  11480. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11481. if (hp1.typ <> ait_label) then { should be on a jump }
  11482. begin
  11483. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11484. { Need a label afterwards }
  11485. Exit;
  11486. end
  11487. else
  11488. fMidLabel := hp1;
  11489. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11490. { Not the correct label }
  11491. fMidLabel := nil;
  11492. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11493. { If there's neither a 2nd jump nor correct label, then it's invalid
  11494. (see above table) }
  11495. Exit;
  11496. { Analyse the first block of MOVs more closely }
  11497. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11498. if Assigned(fSecondJump) then
  11499. begin
  11500. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11501. begin
  11502. fState := tsDetour
  11503. end
  11504. else
  11505. begin
  11506. { Need the correct mid-label for this one }
  11507. if not Assigned(fMidLabel) then
  11508. Exit;
  11509. fState := tsBranching;
  11510. end;
  11511. end
  11512. else
  11513. { No jump. but mid-label is present }
  11514. fState := tsSimple;
  11515. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11516. begin
  11517. { Invalid or too many instructions to be worthwhile }
  11518. fState := tsInvalid;
  11519. Exit;
  11520. end;
  11521. { check further for
  11522. jCC xxx
  11523. <several movs 1>
  11524. jmp yyy
  11525. xxx:
  11526. <several movs 2>
  11527. yyy:
  11528. etc.
  11529. }
  11530. if (fState = tsBranching) and
  11531. { Estimate for required savings for extra jump }
  11532. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11533. { Only one reference is allowed for double blocks }
  11534. (AFirstLabel.getrefs = 1) then
  11535. begin
  11536. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11537. fSecondMovBlock := hp1;
  11538. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11539. begin
  11540. EvaluateBranchingType;
  11541. Exit;
  11542. end;
  11543. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11544. if (hp1.typ <> ait_label) then { should be on a jump }
  11545. begin
  11546. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11547. begin
  11548. { Need a label afterwards }
  11549. EvaluateBranchingType;
  11550. Exit;
  11551. end;
  11552. end
  11553. else
  11554. fEndLabel := hp1;
  11555. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11556. { Second jump doesn't go to the end }
  11557. fEndLabel := nil;
  11558. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11559. begin
  11560. { If there's neither a 3rd jump nor correct end label, then it's
  11561. not a invalid double block, but is a valid single branching
  11562. block (see above table) }
  11563. EvaluateBranchingType;
  11564. Exit;
  11565. end;
  11566. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11567. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11568. { Invalid or too many instructions to be worthwhile }
  11569. Exit;
  11570. Inc(CMOVScore, Count);
  11571. if Assigned(fThirdJump) then
  11572. begin
  11573. if not Assigned(fSecondJump) then
  11574. fState := tsDoubleSecondBranching
  11575. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11576. fState := tsDoubleBranchSame
  11577. else
  11578. fState := tsDoubleBranchDifferent;
  11579. end
  11580. else
  11581. fState := tsDouble;
  11582. end;
  11583. if fState = tsBranching then
  11584. EvaluateBranchingType;
  11585. end;
  11586. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11587. new register to store the constant }
  11588. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11589. var
  11590. RegSize: TSubRegister;
  11591. CurrentVal: TCGInt;
  11592. ANewReg: TRegister;
  11593. X: ShortInt;
  11594. begin
  11595. Result := False;
  11596. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11597. Exit;
  11598. if ConstCount >= MAX_CMOV_REGISTERS then
  11599. { Arrays are full }
  11600. Exit;
  11601. { Remember that CMOV can't encode 8-bit registers }
  11602. case taicpu(p).opsize of
  11603. S_W:
  11604. RegSize := R_SUBW;
  11605. S_L:
  11606. RegSize := R_SUBD;
  11607. {$ifdef x86_64}
  11608. S_Q:
  11609. RegSize := R_SUBQ;
  11610. {$endif x86_64}
  11611. else
  11612. InternalError(2021100401);
  11613. end;
  11614. { See if the value has already been reserved for another CMOV instruction }
  11615. CurrentVal := taicpu(p).oper[0]^.val;
  11616. for X := 0 to ConstCount - 1 do
  11617. if ConstVals[X] = CurrentVal then
  11618. begin
  11619. ConstRegs[ConstCount] := ConstRegs[X];
  11620. ConstSizes[ConstCount] := RegSize;
  11621. ConstVals[ConstCount] := CurrentVal;
  11622. Inc(ConstCount);
  11623. Inc(Count);
  11624. Result := True;
  11625. Exit;
  11626. end;
  11627. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11628. if ANewReg = NR_NO then
  11629. { No free registers }
  11630. Exit;
  11631. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11632. up vying for the same register }
  11633. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11634. ConstRegs[ConstCount] := ANewReg;
  11635. ConstSizes[ConstCount] := RegSize;
  11636. ConstVals[ConstCount] := CurrentVal;
  11637. Inc(ConstCount);
  11638. Inc(Count);
  11639. Result := True;
  11640. end;
  11641. destructor TCMOVTracking.Done;
  11642. begin
  11643. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11644. end;
  11645. procedure TCMOVTracking.Process(out new_p: tai);
  11646. var
  11647. Count, Writes: LongInt;
  11648. RegMatch: Boolean;
  11649. hp1, hp_new: tai;
  11650. inverted_condition, condition: TAsmCond;
  11651. begin
  11652. if (fState in [tsInvalid, tsProcessed]) then
  11653. InternalError(2023110701);
  11654. { Repurpose RegisterTracking to mark registers that we've defined }
  11655. RegisterTracking[R_INTREGISTER].Clear;
  11656. Count := 0;
  11657. Writes := 0;
  11658. condition := taicpu(fInitialJump).condition;
  11659. inverted_condition := inverse_cond(condition);
  11660. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11661. doesn't get CMOVs in this case }
  11662. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11663. begin
  11664. { Include the jump in the flag tracking }
  11665. if Assigned(fThirdJump) then
  11666. begin
  11667. if (fState = tsDoubleBranchSame) then
  11668. begin
  11669. { Will be an unconditional jump, so track to the instruction before it }
  11670. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11671. InternalError(2023110710);
  11672. end
  11673. else
  11674. hp1 := fThirdJump;
  11675. end
  11676. else
  11677. hp1 := fSecondMovBlockStop;
  11678. end
  11679. else
  11680. begin
  11681. { Include a conditional jump in the flag tracking }
  11682. if Assigned(fSecondJump) then
  11683. begin
  11684. if (fState = tsDetour) then
  11685. begin
  11686. { Will be an unconditional jump, so track to the instruction before it }
  11687. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11688. InternalError(2023110711);
  11689. end
  11690. else
  11691. hp1 := fSecondJump;
  11692. end
  11693. else
  11694. hp1 := fFirstMovBlockStop;
  11695. end;
  11696. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11697. { Process the second set of MOVs first, because if a destination
  11698. register is shared between the first and second MOV sets, it is more
  11699. efficient to turn the first one into a MOV instruction and place it
  11700. before the CMP if possible, but we won't know which registers are
  11701. shared until we've processed at least one list, so we might as well
  11702. make it the second one since that won't be modified again. }
  11703. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11704. begin
  11705. hp1 := fSecondMovBlock;
  11706. repeat
  11707. if not Assigned(hp1) then
  11708. InternalError(2018062902);
  11709. if (hp1.typ = ait_instruction) then
  11710. begin
  11711. { Extra safeguard }
  11712. if (taicpu(hp1).opcode <> A_MOV) then
  11713. InternalError(2018062903);
  11714. { Note: tsDoubleBranchDifferent is essentially identical to
  11715. tsBranching and the 2nd block is best left largely
  11716. untouched, but we need to evaluate which registers the MOVs
  11717. write to in order to track what would be complementary CMOV
  11718. pairs that can be further optimised. [Kit] }
  11719. if fState <> tsDoubleBranchDifferent then
  11720. begin
  11721. if taicpu(hp1).oper[0]^.typ = top_const then
  11722. begin
  11723. RegMatch := False;
  11724. for Count := 0 to ConstCount - 1 do
  11725. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11726. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11727. begin
  11728. RegMatch := True;
  11729. { If it's in RegisterTracking, then this register
  11730. is being used more than once and hence has
  11731. already had its value defined (it gets added to
  11732. UsedRegs through AllocRegBetween below) }
  11733. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11734. begin
  11735. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11736. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11737. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11738. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11739. ConstMovs[Count] := hp_new;
  11740. end
  11741. else
  11742. { We just need an instruction between hp_prev and hp1
  11743. where we know the register is marked as in use }
  11744. hp_new := fSecondMovBlock;
  11745. { Keep track of largest write for this register so it can be optimised later }
  11746. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11747. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11748. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11749. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11750. Break;
  11751. end;
  11752. if not RegMatch then
  11753. InternalError(2021100411);
  11754. end;
  11755. taicpu(hp1).opcode := A_CMOVcc;
  11756. taicpu(hp1).condition := condition;
  11757. end;
  11758. { Store these writes to search for duplicates later on }
  11759. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11760. Inc(Writes);
  11761. end;
  11762. fOptimizer.GetNextInstruction(hp1, hp1);
  11763. until (hp1 = fSecondMovBlockStop);
  11764. end;
  11765. { Now do the first set of MOVs }
  11766. hp1 := fFirstMovBlock;
  11767. repeat
  11768. if not Assigned(hp1) then
  11769. InternalError(2018062904);
  11770. if (hp1.typ = ait_instruction) then
  11771. begin
  11772. RegMatch := False;
  11773. { Extra safeguard }
  11774. if (taicpu(hp1).opcode <> A_MOV) then
  11775. InternalError(2018062905);
  11776. { Search through the RegWrites list to see if there are any
  11777. opposing CMOV pairs that write to the same register }
  11778. for Count := 0 to Writes - 1 do
  11779. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11780. begin
  11781. { We have a match. Keep this as a MOV }
  11782. { Move ahead in preparation }
  11783. fOptimizer.GetNextInstruction(hp1, hp1);
  11784. RegMatch := True;
  11785. Break;
  11786. end;
  11787. if RegMatch then
  11788. Continue;
  11789. if taicpu(hp1).oper[0]^.typ = top_const then
  11790. begin
  11791. for Count := 0 to ConstCount - 1 do
  11792. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11793. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11794. begin
  11795. RegMatch := True;
  11796. { If it's in RegisterTracking, then this register is
  11797. being used more than once and hence has already had
  11798. its value defined (it gets added to UsedRegs through
  11799. AllocRegBetween below) }
  11800. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11801. begin
  11802. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11803. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11804. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11805. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11806. ConstMovs[Count] := hp_new;
  11807. end
  11808. else
  11809. { We just need an instruction between hp_prev and hp1
  11810. where we know the register is marked as in use }
  11811. hp_new := fFirstMovBlock;
  11812. { Keep track of largest write for this register so it can be optimised later }
  11813. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11814. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11815. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11816. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11817. Break;
  11818. end;
  11819. if not RegMatch then
  11820. InternalError(2021100412);
  11821. end;
  11822. taicpu(hp1).opcode := A_CMOVcc;
  11823. taicpu(hp1).condition := inverted_condition;
  11824. if (fState = tsDoubleBranchDifferent) then
  11825. begin
  11826. { Store these writes to search for duplicates later on }
  11827. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11828. Inc(Writes);
  11829. end;
  11830. end;
  11831. fOptimizer.GetNextInstruction(hp1, hp1);
  11832. until (hp1 = fFirstMovBlockStop);
  11833. { Update initialisation MOVs to the smallest possible size }
  11834. for Count := 0 to ConstCount - 1 do
  11835. if Assigned(ConstMovs[Count]) then
  11836. begin
  11837. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11838. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11839. end;
  11840. case fState of
  11841. tsSimple:
  11842. begin
  11843. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11844. { No branch to delete }
  11845. end;
  11846. tsDetour:
  11847. begin
  11848. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11849. { Preserve jump }
  11850. end;
  11851. tsBranching, tsDoubleBranchDifferent:
  11852. begin
  11853. if (fState = tsBranching) then
  11854. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11855. else
  11856. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11857. taicpu(fSecondJump).opcode := A_JCC;
  11858. taicpu(fSecondJump).condition := inverted_condition;
  11859. end;
  11860. tsDouble, tsDoubleBranchSame:
  11861. begin
  11862. if (fState = tsDouble) then
  11863. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11864. else
  11865. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11866. { Delete second jump }
  11867. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11868. fOptimizer.RemoveInstruction(fSecondJump);
  11869. end;
  11870. tsDoubleSecondBranching:
  11871. begin
  11872. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11873. { Delete second jump, preserve third jump as conditional }
  11874. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11875. fOptimizer.RemoveInstruction(fSecondJump);
  11876. taicpu(fThirdJump).opcode := A_JCC;
  11877. taicpu(fThirdJump).condition := condition;
  11878. end;
  11879. else
  11880. InternalError(2023110720);
  11881. end;
  11882. { Now we can safely decrement the reference count }
  11883. tasmlabel(fLabel).decrefs;
  11884. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11885. { Remove the original jump }
  11886. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11887. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11888. fState := tsProcessed;
  11889. end;
  11890. {$endif 8086}
  11891. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11892. var
  11893. hp1,hp2: tai;
  11894. carryadd_opcode : TAsmOp;
  11895. symbol: TAsmSymbol;
  11896. increg, tmpreg: TRegister;
  11897. {$ifndef i8086}
  11898. CMOVTracking: PCMOVTracking;
  11899. hp3,hp4,hp5: tai;
  11900. {$endif i8086}
  11901. begin
  11902. result:=false;
  11903. if GetNextInstruction(p,hp1) then
  11904. begin
  11905. if (hp1.typ=ait_label) then
  11906. begin
  11907. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11908. Exit;
  11909. end
  11910. else if (hp1.typ<>ait_instruction) then
  11911. Exit;
  11912. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11913. if (
  11914. (
  11915. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11916. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11917. (Taicpu(hp1).oper[0]^.val=1)
  11918. ) or
  11919. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11920. ) and
  11921. GetNextInstruction(hp1,hp2) and
  11922. (hp2.typ = ait_label) and
  11923. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11924. { jb @@1 cmc
  11925. inc/dec operand --> adc/sbb operand,0
  11926. @@1:
  11927. ... and ...
  11928. jnb @@1
  11929. inc/dec operand --> adc/sbb operand,0
  11930. @@1: }
  11931. begin
  11932. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11933. begin
  11934. case taicpu(hp1).opcode of
  11935. A_INC,
  11936. A_ADD:
  11937. carryadd_opcode:=A_ADC;
  11938. A_DEC,
  11939. A_SUB:
  11940. carryadd_opcode:=A_SBB;
  11941. else
  11942. InternalError(2021011001);
  11943. end;
  11944. Taicpu(p).clearop(0);
  11945. Taicpu(p).ops:=0;
  11946. Taicpu(p).is_jmp:=false;
  11947. Taicpu(p).opcode:=A_CMC;
  11948. Taicpu(p).condition:=C_NONE;
  11949. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11950. Taicpu(hp1).ops:=2;
  11951. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11952. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11953. else
  11954. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11955. Taicpu(hp1).loadconst(0,0);
  11956. Taicpu(hp1).opcode:=carryadd_opcode;
  11957. result:=true;
  11958. exit;
  11959. end
  11960. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  11961. begin
  11962. case taicpu(hp1).opcode of
  11963. A_INC,
  11964. A_ADD:
  11965. carryadd_opcode:=A_ADC;
  11966. A_DEC,
  11967. A_SUB:
  11968. carryadd_opcode:=A_SBB;
  11969. else
  11970. InternalError(2021011002);
  11971. end;
  11972. Taicpu(hp1).ops:=2;
  11973. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  11974. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11975. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11976. else
  11977. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11978. Taicpu(hp1).loadconst(0,0);
  11979. Taicpu(hp1).opcode:=carryadd_opcode;
  11980. RemoveCurrentP(p, hp1);
  11981. result:=true;
  11982. exit;
  11983. end
  11984. {
  11985. jcc @@1 setcc tmpreg
  11986. inc/dec/add/sub operand -> (movzx tmpreg)
  11987. @@1: add/sub tmpreg,operand
  11988. While this increases code size slightly, it makes the code much faster if the
  11989. jump is unpredictable
  11990. }
  11991. else if not(cs_opt_size in current_settings.optimizerswitches) then
  11992. begin
  11993. { search for an available register which is volatile }
  11994. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  11995. if increg <> NR_NO then
  11996. begin
  11997. { We don't need to check if tmpreg is in hp1 or not, because
  11998. it will be marked as in use at p (if not, this is
  11999. indictive of a compiler bug). }
  12000. TAsmLabel(symbol).decrefs;
  12001. Taicpu(p).clearop(0);
  12002. Taicpu(p).ops:=1;
  12003. Taicpu(p).is_jmp:=false;
  12004. Taicpu(p).opcode:=A_SETcc;
  12005. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12006. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12007. Taicpu(p).loadreg(0,increg);
  12008. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12009. begin
  12010. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12011. R_SUBW:
  12012. begin
  12013. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12014. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12015. end;
  12016. R_SUBD:
  12017. begin
  12018. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12019. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12020. end;
  12021. {$ifdef x86_64}
  12022. R_SUBQ:
  12023. begin
  12024. { MOVZX doesn't have a 64-bit variant, because
  12025. the 32-bit version implicitly zeroes the
  12026. upper 32-bits of the destination register }
  12027. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12028. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12029. setsubreg(tmpreg, R_SUBQ);
  12030. end;
  12031. {$endif x86_64}
  12032. else
  12033. Internalerror(2020030601);
  12034. end;
  12035. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12036. asml.InsertAfter(hp2,p);
  12037. end
  12038. else
  12039. tmpreg := increg;
  12040. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12041. begin
  12042. Taicpu(hp1).ops:=2;
  12043. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12044. end;
  12045. Taicpu(hp1).loadreg(0,tmpreg);
  12046. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12047. Result := True;
  12048. { p is no longer a Jcc instruction, so exit }
  12049. Exit;
  12050. end;
  12051. end;
  12052. end;
  12053. { Detect the following:
  12054. jmp<cond> @Lbl1
  12055. jmp @Lbl2
  12056. ...
  12057. @Lbl1:
  12058. ret
  12059. Change to:
  12060. jmp<inv_cond> @Lbl2
  12061. ret
  12062. }
  12063. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12064. begin
  12065. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12066. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12067. MatchInstruction(hp2,A_RET,[S_NO]) then
  12068. begin
  12069. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12070. { Change label address to that of the unconditional jump }
  12071. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12072. TAsmLabel(symbol).DecRefs;
  12073. taicpu(hp1).opcode := A_RET;
  12074. taicpu(hp1).is_jmp := false;
  12075. taicpu(hp1).ops := taicpu(hp2).ops;
  12076. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12077. case taicpu(hp2).ops of
  12078. 0:
  12079. taicpu(hp1).clearop(0);
  12080. 1:
  12081. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12082. else
  12083. internalerror(2016041302);
  12084. end;
  12085. end;
  12086. {$ifndef i8086}
  12087. end
  12088. {
  12089. convert
  12090. j<c> .L1
  12091. mov 1,reg
  12092. jmp .L2
  12093. .L1
  12094. mov 0,reg
  12095. .L2
  12096. into
  12097. mov 0,reg
  12098. set<not(c)> reg
  12099. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12100. would destroy the flag contents
  12101. }
  12102. else if MatchInstruction(hp1,A_MOV,[]) and
  12103. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12104. {$ifdef i386}
  12105. (
  12106. { Under i386, ESI, EDI, EBP and ESP
  12107. don't have an 8-bit representation }
  12108. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12109. ) and
  12110. {$endif i386}
  12111. (taicpu(hp1).oper[0]^.val=1) and
  12112. GetNextInstruction(hp1,hp2) and
  12113. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12114. GetNextInstruction(hp2,hp3) and
  12115. (hp3.typ=ait_label) and
  12116. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12117. (tai_label(hp3).labsym.getrefs=1) and
  12118. GetNextInstruction(hp3,hp4) and
  12119. MatchInstruction(hp4,A_MOV,[]) and
  12120. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12121. (taicpu(hp4).oper[0]^.val=0) and
  12122. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12123. GetNextInstruction(hp4,hp5) and
  12124. (hp5.typ=ait_label) and
  12125. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12126. (tai_label(hp5).labsym.getrefs=1) then
  12127. begin
  12128. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12129. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12130. { remove last label }
  12131. RemoveInstruction(hp5);
  12132. { remove second label }
  12133. RemoveInstruction(hp3);
  12134. { remove jmp }
  12135. RemoveInstruction(hp2);
  12136. if taicpu(hp1).opsize=S_B then
  12137. RemoveInstruction(hp1)
  12138. else
  12139. taicpu(hp1).loadconst(0,0);
  12140. taicpu(hp4).opcode:=A_SETcc;
  12141. taicpu(hp4).opsize:=S_B;
  12142. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12143. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12144. taicpu(hp4).opercnt:=1;
  12145. taicpu(hp4).ops:=1;
  12146. taicpu(hp4).freeop(1);
  12147. RemoveCurrentP(p);
  12148. Result:=true;
  12149. exit;
  12150. end
  12151. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12152. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12153. begin
  12154. { check for
  12155. jCC xxx
  12156. <several movs>
  12157. xxx:
  12158. Also spot:
  12159. Jcc xxx
  12160. <several movs>
  12161. jmp xxx
  12162. Change to:
  12163. <several cmovs with inverted condition>
  12164. jmp xxx (only for the 2nd case)
  12165. }
  12166. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12167. if CMOVTracking^.State <> tsInvalid then
  12168. begin
  12169. CMovTracking^.Process(p);
  12170. Result := True;
  12171. end;
  12172. CMOVTracking^.Done;
  12173. {$endif i8086}
  12174. end;
  12175. end;
  12176. end;
  12177. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12178. var
  12179. hp1,hp2,hp3: tai;
  12180. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12181. NewSize: TOpSize;
  12182. NewRegSize: TSubRegister;
  12183. Limit: TCgInt;
  12184. SwapOper: POper;
  12185. begin
  12186. result:=false;
  12187. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12188. GetNextInstruction(p,hp1) and
  12189. (hp1.typ = ait_instruction);
  12190. if reg_and_hp1_is_instr and
  12191. (
  12192. (taicpu(hp1).opcode <> A_LEA) or
  12193. { If the LEA instruction can be converted into an arithmetic instruction,
  12194. it may be possible to then fold it. }
  12195. (
  12196. { If the flags register is in use, don't change the instruction
  12197. to an ADD otherwise this will scramble the flags. [Kit] }
  12198. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12199. ConvertLEA(taicpu(hp1))
  12200. )
  12201. ) and
  12202. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12203. GetNextInstruction(hp1,hp2) and
  12204. MatchInstruction(hp2,A_MOV,[]) and
  12205. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12206. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12207. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12208. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12209. {$ifdef i386}
  12210. { not all registers have byte size sub registers on i386 }
  12211. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12212. {$endif i386}
  12213. (((taicpu(hp1).ops=2) and
  12214. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12215. ((taicpu(hp1).ops=1) and
  12216. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12217. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12218. begin
  12219. { change movsX/movzX reg/ref, reg2
  12220. add/sub/or/... reg3/$const, reg2
  12221. mov reg2 reg/ref
  12222. to add/sub/or/... reg3/$const, reg/ref }
  12223. { by example:
  12224. movswl %si,%eax movswl %si,%eax p
  12225. decl %eax addl %edx,%eax hp1
  12226. movw %ax,%si movw %ax,%si hp2
  12227. ->
  12228. movswl %si,%eax movswl %si,%eax p
  12229. decw %eax addw %edx,%eax hp1
  12230. movw %ax,%si movw %ax,%si hp2
  12231. }
  12232. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12233. {
  12234. ->
  12235. movswl %si,%eax movswl %si,%eax p
  12236. decw %si addw %dx,%si hp1
  12237. movw %ax,%si movw %ax,%si hp2
  12238. }
  12239. case taicpu(hp1).ops of
  12240. 1:
  12241. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12242. 2:
  12243. begin
  12244. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12245. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12246. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12247. end;
  12248. else
  12249. internalerror(2008042702);
  12250. end;
  12251. {
  12252. ->
  12253. decw %si addw %dx,%si p
  12254. }
  12255. DebugMsg(SPeepholeOptimization + 'var3',p);
  12256. RemoveCurrentP(p, hp1);
  12257. RemoveInstruction(hp2);
  12258. Result := True;
  12259. Exit;
  12260. end;
  12261. if reg_and_hp1_is_instr and
  12262. (taicpu(hp1).opcode = A_MOV) and
  12263. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12264. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12265. {$ifdef x86_64}
  12266. { check for implicit extension to 64 bit }
  12267. or
  12268. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12269. (taicpu(hp1).opsize=S_Q) and
  12270. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12271. )
  12272. {$endif x86_64}
  12273. )
  12274. then
  12275. begin
  12276. { change
  12277. movx %reg1,%reg2
  12278. mov %reg2,%reg3
  12279. dealloc %reg2
  12280. into
  12281. movx %reg,%reg3
  12282. }
  12283. TransferUsedRegs(TmpUsedRegs);
  12284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12285. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12286. begin
  12287. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12288. {$ifdef x86_64}
  12289. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12290. (taicpu(hp1).opsize=S_Q) then
  12291. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12292. else
  12293. {$endif x86_64}
  12294. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12295. RemoveInstruction(hp1);
  12296. Result := True;
  12297. Exit;
  12298. end;
  12299. end;
  12300. if reg_and_hp1_is_instr and
  12301. ((taicpu(hp1).opcode=A_MOV) or
  12302. (taicpu(hp1).opcode=A_ADD) or
  12303. (taicpu(hp1).opcode=A_SUB) or
  12304. (taicpu(hp1).opcode=A_CMP) or
  12305. (taicpu(hp1).opcode=A_OR) or
  12306. (taicpu(hp1).opcode=A_XOR) or
  12307. (taicpu(hp1).opcode=A_AND)
  12308. ) and
  12309. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12310. begin
  12311. AndTest := (taicpu(hp1).opcode=A_AND) and
  12312. GetNextInstruction(hp1, hp2) and
  12313. (hp2.typ = ait_instruction) and
  12314. (
  12315. (
  12316. (taicpu(hp2).opcode=A_TEST) and
  12317. (
  12318. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12319. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12320. (
  12321. { If the AND and TEST instructions share a constant, this is also valid }
  12322. (taicpu(hp1).oper[0]^.typ = top_const) and
  12323. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12324. )
  12325. ) and
  12326. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12327. ) or
  12328. (
  12329. (taicpu(hp2).opcode=A_CMP) and
  12330. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12331. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12332. )
  12333. );
  12334. { change
  12335. movx (oper),%reg2
  12336. and $x,%reg2
  12337. test %reg2,%reg2
  12338. dealloc %reg2
  12339. into
  12340. op %reg1,%reg3
  12341. if the second op accesses only the bits stored in reg1
  12342. }
  12343. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12344. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12345. (taicpu(hp1).oper[0]^.typ = top_const) and
  12346. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12347. AndTest then
  12348. begin
  12349. { Check if the AND constant is in range }
  12350. case taicpu(p).opsize of
  12351. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12352. begin
  12353. NewSize := S_B;
  12354. Limit := $FF;
  12355. end;
  12356. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12357. begin
  12358. NewSize := S_W;
  12359. Limit := $FFFF;
  12360. end;
  12361. {$ifdef x86_64}
  12362. S_LQ:
  12363. begin
  12364. NewSize := S_L;
  12365. Limit := $FFFFFFFF;
  12366. end;
  12367. {$endif x86_64}
  12368. else
  12369. InternalError(2021120303);
  12370. end;
  12371. if (
  12372. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12373. { Check for negative operands }
  12374. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12375. ) and
  12376. GetNextInstruction(hp2,hp3) and
  12377. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12378. (taicpu(hp3).condition in [C_E,C_NE]) then
  12379. begin
  12380. TransferUsedRegs(TmpUsedRegs);
  12381. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12382. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12383. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12384. begin
  12385. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12386. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12387. taicpu(hp1).opcode := A_TEST;
  12388. taicpu(hp1).opsize := NewSize;
  12389. RemoveInstruction(hp2);
  12390. RemoveCurrentP(p, hp1);
  12391. Result:=true;
  12392. exit;
  12393. end;
  12394. end;
  12395. end;
  12396. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12397. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12398. (taicpu(hp1).opsize=S_B)) or
  12399. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12400. (taicpu(hp1).opsize=S_W))
  12401. {$ifdef x86_64}
  12402. or ((taicpu(p).opsize=S_LQ) and
  12403. (taicpu(hp1).opsize=S_L))
  12404. {$endif x86_64}
  12405. ) and
  12406. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12407. begin
  12408. { change
  12409. movx %reg1,%reg2
  12410. op %reg2,%reg3
  12411. dealloc %reg2
  12412. into
  12413. op %reg1,%reg3
  12414. if the second op accesses only the bits stored in reg1
  12415. }
  12416. TransferUsedRegs(TmpUsedRegs);
  12417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12418. if AndTest then
  12419. begin
  12420. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12421. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12422. end
  12423. else
  12424. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12425. if not RegUsed then
  12426. begin
  12427. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12428. if taicpu(p).oper[0]^.typ=top_reg then
  12429. begin
  12430. case taicpu(hp1).opsize of
  12431. S_B:
  12432. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12433. S_W:
  12434. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12435. S_L:
  12436. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12437. else
  12438. Internalerror(2020102301);
  12439. end;
  12440. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12441. end
  12442. else
  12443. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12444. RemoveCurrentP(p);
  12445. if AndTest then
  12446. RemoveInstruction(hp2);
  12447. result:=true;
  12448. exit;
  12449. end;
  12450. end
  12451. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12452. (
  12453. { Bitwise operations only }
  12454. (taicpu(hp1).opcode=A_AND) or
  12455. (taicpu(hp1).opcode=A_TEST) or
  12456. (
  12457. (taicpu(hp1).oper[0]^.typ = top_const) and
  12458. (
  12459. (taicpu(hp1).opcode=A_OR) or
  12460. (taicpu(hp1).opcode=A_XOR)
  12461. )
  12462. )
  12463. ) and
  12464. (
  12465. (taicpu(hp1).oper[0]^.typ = top_const) or
  12466. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12467. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12468. ) then
  12469. begin
  12470. { change
  12471. movx %reg2,%reg2
  12472. op const,%reg2
  12473. into
  12474. op const,%reg2 (smaller version)
  12475. movx %reg2,%reg2
  12476. also change
  12477. movx %reg1,%reg2
  12478. and/test (oper),%reg2
  12479. dealloc %reg2
  12480. into
  12481. and/test (oper),%reg1
  12482. }
  12483. case taicpu(p).opsize of
  12484. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12485. begin
  12486. NewSize := S_B;
  12487. NewRegSize := R_SUBL;
  12488. Limit := $FF;
  12489. end;
  12490. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12491. begin
  12492. NewSize := S_W;
  12493. NewRegSize := R_SUBW;
  12494. Limit := $FFFF;
  12495. end;
  12496. {$ifdef x86_64}
  12497. S_LQ:
  12498. begin
  12499. NewSize := S_L;
  12500. NewRegSize := R_SUBD;
  12501. Limit := $FFFFFFFF;
  12502. end;
  12503. {$endif x86_64}
  12504. else
  12505. Internalerror(2021120302);
  12506. end;
  12507. TransferUsedRegs(TmpUsedRegs);
  12508. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12509. if AndTest then
  12510. begin
  12511. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12512. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12513. end
  12514. else
  12515. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12516. if
  12517. (
  12518. (taicpu(p).opcode = A_MOVZX) and
  12519. (
  12520. (taicpu(hp1).opcode=A_AND) or
  12521. (taicpu(hp1).opcode=A_TEST)
  12522. ) and
  12523. not (
  12524. { If both are references, then the final instruction will have
  12525. both operands as references, which is not allowed }
  12526. (taicpu(p).oper[0]^.typ = top_ref) and
  12527. (taicpu(hp1).oper[0]^.typ = top_ref)
  12528. ) and
  12529. not RegUsed
  12530. ) or
  12531. (
  12532. (
  12533. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12534. not RegUsed
  12535. ) and
  12536. (taicpu(p).oper[0]^.typ = top_reg) and
  12537. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12538. (taicpu(hp1).oper[0]^.typ = top_const) and
  12539. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12540. ) then
  12541. begin
  12542. {$if defined(i386) or defined(i8086)}
  12543. { If the target size is 8-bit, make sure we can actually encode it }
  12544. 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
  12545. Exit;
  12546. {$endif i386 or i8086}
  12547. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12548. taicpu(hp1).opsize := NewSize;
  12549. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12550. if AndTest then
  12551. begin
  12552. RemoveInstruction(hp2);
  12553. if not RegUsed then
  12554. begin
  12555. taicpu(hp1).opcode := A_TEST;
  12556. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12557. begin
  12558. { Make sure the reference is the second operand }
  12559. SwapOper := taicpu(hp1).oper[0];
  12560. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12561. taicpu(hp1).oper[1] := SwapOper;
  12562. end;
  12563. end;
  12564. end;
  12565. case taicpu(hp1).oper[0]^.typ of
  12566. top_reg:
  12567. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12568. top_const:
  12569. { For the AND/TEST case }
  12570. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12571. else
  12572. ;
  12573. end;
  12574. if RegUsed then
  12575. begin
  12576. AsmL.Remove(p);
  12577. AsmL.InsertAfter(p, hp1);
  12578. p := hp1;
  12579. end
  12580. else
  12581. RemoveCurrentP(p, hp1);
  12582. result:=true;
  12583. exit;
  12584. end;
  12585. end;
  12586. end;
  12587. if reg_and_hp1_is_instr and
  12588. (taicpu(p).oper[0]^.typ = top_reg) and
  12589. (
  12590. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12591. ) and
  12592. (taicpu(hp1).oper[0]^.typ = top_const) and
  12593. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12594. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12595. { Minimum shift value allowed is the bit difference between the sizes }
  12596. (taicpu(hp1).oper[0]^.val >=
  12597. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12598. 8 * (
  12599. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12600. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12601. )
  12602. ) then
  12603. begin
  12604. { For:
  12605. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12606. shl/sal ##, %reg1
  12607. Remove the movsx/movzx instruction if the shift overwrites the
  12608. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12609. }
  12610. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12611. RemoveCurrentP(p, hp1);
  12612. Result := True;
  12613. Exit;
  12614. end
  12615. else if reg_and_hp1_is_instr and
  12616. (taicpu(p).oper[0]^.typ = top_reg) and
  12617. (
  12618. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12619. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12620. ) and
  12621. (taicpu(hp1).oper[0]^.typ = top_const) and
  12622. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12623. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12624. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12625. (taicpu(hp1).oper[0]^.val <
  12626. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12627. 8 * (
  12628. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12629. )
  12630. ) then
  12631. begin
  12632. { For:
  12633. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12634. sar ##, %reg1 shr ##, %reg1
  12635. Move the shift to before the movx instruction if the shift value
  12636. is not too large.
  12637. }
  12638. asml.Remove(hp1);
  12639. asml.InsertBefore(hp1, p);
  12640. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12641. case taicpu(p).opsize of
  12642. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12643. taicpu(hp1).opsize := S_B;
  12644. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12645. taicpu(hp1).opsize := S_W;
  12646. {$ifdef x86_64}
  12647. S_LQ:
  12648. taicpu(hp1).opsize := S_L;
  12649. {$endif}
  12650. else
  12651. InternalError(2020112401);
  12652. end;
  12653. if (taicpu(hp1).opcode = A_SHR) then
  12654. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12655. else
  12656. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12657. Result := True;
  12658. end;
  12659. if reg_and_hp1_is_instr and
  12660. (taicpu(p).oper[0]^.typ = top_reg) and
  12661. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12662. (
  12663. (taicpu(hp1).opcode = taicpu(p).opcode)
  12664. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12665. {$ifdef x86_64}
  12666. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12667. {$endif x86_64}
  12668. ) then
  12669. begin
  12670. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12671. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12672. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12673. begin
  12674. {
  12675. For example:
  12676. movzbw %al,%ax
  12677. movzwl %ax,%eax
  12678. Compress into:
  12679. movzbl %al,%eax
  12680. }
  12681. RegUsed := False;
  12682. case taicpu(p).opsize of
  12683. S_BW:
  12684. case taicpu(hp1).opsize of
  12685. S_WL:
  12686. begin
  12687. taicpu(p).opsize := S_BL;
  12688. RegUsed := True;
  12689. end;
  12690. {$ifdef x86_64}
  12691. S_WQ:
  12692. begin
  12693. if taicpu(p).opcode = A_MOVZX then
  12694. begin
  12695. taicpu(p).opsize := S_BL;
  12696. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12697. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12698. end
  12699. else
  12700. taicpu(p).opsize := S_BQ;
  12701. RegUsed := True;
  12702. end;
  12703. {$endif x86_64}
  12704. else
  12705. ;
  12706. end;
  12707. {$ifdef x86_64}
  12708. S_BL:
  12709. case taicpu(hp1).opsize of
  12710. S_LQ:
  12711. begin
  12712. if taicpu(p).opcode = A_MOVZX then
  12713. begin
  12714. taicpu(p).opsize := S_BL;
  12715. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12716. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12717. end
  12718. else
  12719. taicpu(p).opsize := S_BQ;
  12720. RegUsed := True;
  12721. end;
  12722. else
  12723. ;
  12724. end;
  12725. S_WL:
  12726. case taicpu(hp1).opsize of
  12727. S_LQ:
  12728. begin
  12729. if taicpu(p).opcode = A_MOVZX then
  12730. begin
  12731. taicpu(p).opsize := S_WL;
  12732. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12733. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12734. end
  12735. else
  12736. taicpu(p).opsize := S_WQ;
  12737. RegUsed := True;
  12738. end;
  12739. else
  12740. ;
  12741. end;
  12742. {$endif x86_64}
  12743. else
  12744. ;
  12745. end;
  12746. if RegUsed then
  12747. begin
  12748. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12749. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12750. RemoveInstruction(hp1);
  12751. Result := True;
  12752. Exit;
  12753. end;
  12754. end;
  12755. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12756. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12757. GetNextInstruction(hp1, hp2) and
  12758. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12759. (
  12760. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12761. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12762. {$ifdef x86_64}
  12763. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12764. {$endif x86_64}
  12765. ) and
  12766. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12767. (
  12768. (
  12769. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12770. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12771. ) or
  12772. (
  12773. { Only allow the operands in reverse order for TEST instructions }
  12774. (taicpu(hp2).opcode = A_TEST) and
  12775. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12776. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12777. )
  12778. ) then
  12779. begin
  12780. {
  12781. For example:
  12782. movzbl %al,%eax
  12783. movzbl (ref),%edx
  12784. andl %edx,%eax
  12785. (%edx deallocated)
  12786. Change to:
  12787. andb (ref),%al
  12788. movzbl %al,%eax
  12789. Rules are:
  12790. - First two instructions have the same opcode and opsize
  12791. - First instruction's operands are the same super-register
  12792. - Second instruction operates on a different register
  12793. - Third instruction is AND, OR, XOR or TEST
  12794. - Third instruction's operands are the destination registers of the first two instructions
  12795. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12796. - Second instruction's destination register is deallocated afterwards
  12797. }
  12798. TransferUsedRegs(TmpUsedRegs);
  12799. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12800. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12801. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12802. begin
  12803. case taicpu(p).opsize of
  12804. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12805. NewSize := S_B;
  12806. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12807. NewSize := S_W;
  12808. {$ifdef x86_64}
  12809. S_LQ:
  12810. NewSize := S_L;
  12811. {$endif x86_64}
  12812. else
  12813. InternalError(2021120301);
  12814. end;
  12815. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12816. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12817. taicpu(hp2).opsize := NewSize;
  12818. RemoveInstruction(hp1);
  12819. { With TEST, it's best to keep the MOVX instruction at the top }
  12820. if (taicpu(hp2).opcode <> A_TEST) then
  12821. begin
  12822. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12823. asml.Remove(p);
  12824. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12825. asml.InsertAfter(p, hp2);
  12826. p := hp2;
  12827. end
  12828. else
  12829. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12830. Result := True;
  12831. Exit;
  12832. end;
  12833. end;
  12834. end;
  12835. if taicpu(p).opcode=A_MOVZX then
  12836. begin
  12837. { removes superfluous And's after movzx's }
  12838. if reg_and_hp1_is_instr and
  12839. (taicpu(hp1).opcode = A_AND) and
  12840. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12841. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12842. {$ifdef x86_64}
  12843. { check for implicit extension to 64 bit }
  12844. or
  12845. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12846. (taicpu(hp1).opsize=S_Q) and
  12847. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12848. )
  12849. {$endif x86_64}
  12850. )
  12851. then
  12852. begin
  12853. case taicpu(p).opsize Of
  12854. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12855. if (taicpu(hp1).oper[0]^.val = $ff) then
  12856. begin
  12857. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12858. RemoveInstruction(hp1);
  12859. Result:=true;
  12860. exit;
  12861. end;
  12862. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12863. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12864. begin
  12865. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12866. RemoveInstruction(hp1);
  12867. Result:=true;
  12868. exit;
  12869. end;
  12870. {$ifdef x86_64}
  12871. S_LQ:
  12872. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12873. begin
  12874. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12875. RemoveInstruction(hp1);
  12876. Result:=true;
  12877. exit;
  12878. end;
  12879. {$endif x86_64}
  12880. else
  12881. ;
  12882. end;
  12883. { we cannot get rid of the and, but can we get rid of the movz ?}
  12884. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12885. begin
  12886. case taicpu(p).opsize Of
  12887. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12888. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12889. begin
  12890. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12891. RemoveCurrentP(p,hp1);
  12892. Result:=true;
  12893. exit;
  12894. end;
  12895. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12896. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12897. begin
  12898. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12899. RemoveCurrentP(p,hp1);
  12900. Result:=true;
  12901. exit;
  12902. end;
  12903. {$ifdef x86_64}
  12904. S_LQ:
  12905. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12906. begin
  12907. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12908. RemoveCurrentP(p,hp1);
  12909. Result:=true;
  12910. exit;
  12911. end;
  12912. {$endif x86_64}
  12913. else
  12914. ;
  12915. end;
  12916. end;
  12917. end;
  12918. { changes some movzx constructs to faster synonyms (all examples
  12919. are given with eax/ax, but are also valid for other registers)}
  12920. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12921. begin
  12922. case taicpu(p).opsize of
  12923. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12924. (the machine code is equivalent to movzbl %al,%eax), but the
  12925. code generator still generates that assembler instruction and
  12926. it is silently converted. This should probably be checked.
  12927. [Kit] }
  12928. S_BW:
  12929. begin
  12930. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12931. (
  12932. not IsMOVZXAcceptable
  12933. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12934. or (
  12935. (cs_opt_size in current_settings.optimizerswitches) and
  12936. (taicpu(p).oper[1]^.reg = NR_AX)
  12937. )
  12938. ) then
  12939. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12940. begin
  12941. DebugMsg(SPeepholeOptimization + 'var7',p);
  12942. taicpu(p).opcode := A_AND;
  12943. taicpu(p).changeopsize(S_W);
  12944. taicpu(p).loadConst(0,$ff);
  12945. Result := True;
  12946. end
  12947. else if not IsMOVZXAcceptable and
  12948. GetNextInstruction(p, hp1) and
  12949. (tai(hp1).typ = ait_instruction) and
  12950. (taicpu(hp1).opcode = A_AND) and
  12951. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12952. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12953. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12954. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12955. begin
  12956. DebugMsg(SPeepholeOptimization + 'var8',p);
  12957. taicpu(p).opcode := A_MOV;
  12958. taicpu(p).changeopsize(S_W);
  12959. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12960. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12961. Result := True;
  12962. end;
  12963. end;
  12964. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12965. S_BL:
  12966. if not IsMOVZXAcceptable then
  12967. begin
  12968. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12969. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12970. begin
  12971. DebugMsg(SPeepholeOptimization + 'var9',p);
  12972. taicpu(p).opcode := A_AND;
  12973. taicpu(p).changeopsize(S_L);
  12974. taicpu(p).loadConst(0,$ff);
  12975. Result := True;
  12976. end
  12977. else if GetNextInstruction(p, hp1) and
  12978. (tai(hp1).typ = ait_instruction) and
  12979. (taicpu(hp1).opcode = A_AND) and
  12980. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12981. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12982. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12983. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12984. begin
  12985. DebugMsg(SPeepholeOptimization + 'var10',p);
  12986. taicpu(p).opcode := A_MOV;
  12987. taicpu(p).changeopsize(S_L);
  12988. { do not use R_SUBWHOLE
  12989. as movl %rdx,%eax
  12990. is invalid in assembler PM }
  12991. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12992. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12993. Result := True;
  12994. end;
  12995. end;
  12996. {$endif i8086}
  12997. S_WL:
  12998. if not IsMOVZXAcceptable then
  12999. begin
  13000. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13001. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13002. begin
  13003. DebugMsg(SPeepholeOptimization + 'var11',p);
  13004. taicpu(p).opcode := A_AND;
  13005. taicpu(p).changeopsize(S_L);
  13006. taicpu(p).loadConst(0,$ffff);
  13007. Result := True;
  13008. end
  13009. else if GetNextInstruction(p, hp1) and
  13010. (tai(hp1).typ = ait_instruction) and
  13011. (taicpu(hp1).opcode = A_AND) and
  13012. (taicpu(hp1).oper[0]^.typ = top_const) and
  13013. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13014. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13015. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13016. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13017. begin
  13018. DebugMsg(SPeepholeOptimization + 'var12',p);
  13019. taicpu(p).opcode := A_MOV;
  13020. taicpu(p).changeopsize(S_L);
  13021. { do not use R_SUBWHOLE
  13022. as movl %rdx,%eax
  13023. is invalid in assembler PM }
  13024. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13025. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13026. Result := True;
  13027. end;
  13028. end;
  13029. else
  13030. InternalError(2017050705);
  13031. end;
  13032. end
  13033. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13034. begin
  13035. if GetNextInstruction(p, hp1) and
  13036. (tai(hp1).typ = ait_instruction) and
  13037. (taicpu(hp1).opcode = A_AND) and
  13038. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13039. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13040. begin
  13041. //taicpu(p).opcode := A_MOV;
  13042. case taicpu(p).opsize Of
  13043. S_BL:
  13044. begin
  13045. DebugMsg(SPeepholeOptimization + 'var13',p);
  13046. taicpu(hp1).changeopsize(S_L);
  13047. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13048. end;
  13049. S_WL:
  13050. begin
  13051. DebugMsg(SPeepholeOptimization + 'var14',p);
  13052. taicpu(hp1).changeopsize(S_L);
  13053. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13054. end;
  13055. S_BW:
  13056. begin
  13057. DebugMsg(SPeepholeOptimization + 'var15',p);
  13058. taicpu(hp1).changeopsize(S_W);
  13059. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13060. end;
  13061. else
  13062. Internalerror(2017050704)
  13063. end;
  13064. Result := True;
  13065. end;
  13066. end;
  13067. end;
  13068. end;
  13069. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13070. var
  13071. hp1, hp2 : tai;
  13072. MaskLength : Cardinal;
  13073. MaskedBits : TCgInt;
  13074. ActiveReg : TRegister;
  13075. begin
  13076. Result:=false;
  13077. { There are no optimisations for reference targets }
  13078. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13079. Exit;
  13080. while GetNextInstruction(p, hp1) and
  13081. (hp1.typ = ait_instruction) do
  13082. begin
  13083. if (taicpu(p).oper[0]^.typ = top_const) then
  13084. begin
  13085. case taicpu(hp1).opcode of
  13086. A_AND:
  13087. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13088. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13089. { the second register must contain the first one, so compare their subreg types }
  13090. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13091. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13092. { change
  13093. and const1, reg
  13094. and const2, reg
  13095. to
  13096. and (const1 and const2), reg
  13097. }
  13098. begin
  13099. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13100. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13101. RemoveCurrentP(p, hp1);
  13102. Result:=true;
  13103. exit;
  13104. end;
  13105. A_CMP:
  13106. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13107. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13108. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13109. { Just check that the condition on the next instruction is compatible }
  13110. GetNextInstruction(hp1, hp2) and
  13111. (hp2.typ = ait_instruction) and
  13112. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13113. then
  13114. { change
  13115. and 2^n, reg
  13116. cmp 2^n, reg
  13117. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13118. to
  13119. and 2^n, reg
  13120. test reg, reg
  13121. j(~c) / set(~c) / cmov(~c)
  13122. }
  13123. begin
  13124. { Keep TEST instruction in, rather than remove it, because
  13125. it may trigger other optimisations such as MovAndTest2Test }
  13126. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13127. taicpu(hp1).opcode := A_TEST;
  13128. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13129. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13130. Result := True;
  13131. Exit;
  13132. end
  13133. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13134. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13135. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13136. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13137. { change
  13138. and $ff/$ff/$ffff, reg
  13139. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13140. dealloc reg
  13141. to
  13142. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13143. }
  13144. begin
  13145. TransferUsedRegs(TmpUsedRegs);
  13146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13147. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13148. begin
  13149. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13150. case taicpu(p).oper[0]^.val of
  13151. $ff:
  13152. begin
  13153. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13154. taicpu(hp1).opsize:=S_B;
  13155. end;
  13156. $ffff:
  13157. begin
  13158. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13159. taicpu(hp1).opsize:=S_W;
  13160. end;
  13161. $ffffffff:
  13162. begin
  13163. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13164. taicpu(hp1).opsize:=S_L;
  13165. end;
  13166. else
  13167. Internalerror(2023030401);
  13168. end;
  13169. RemoveCurrentP(p);
  13170. Result := True;
  13171. Exit;
  13172. end;
  13173. end;
  13174. A_MOVZX:
  13175. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13176. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13177. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13178. (
  13179. (
  13180. (taicpu(p).opsize=S_W) and
  13181. (taicpu(hp1).opsize=S_BW)
  13182. ) or
  13183. (
  13184. (taicpu(p).opsize=S_L) and
  13185. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13186. )
  13187. {$ifdef x86_64}
  13188. or
  13189. (
  13190. (taicpu(p).opsize=S_Q) and
  13191. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13192. )
  13193. {$endif x86_64}
  13194. ) then
  13195. begin
  13196. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13197. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13198. ) or
  13199. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13200. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13201. then
  13202. begin
  13203. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13204. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13205. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13206. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13207. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13208. }
  13209. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13210. RemoveInstruction(hp1);
  13211. { See if there are other optimisations possible }
  13212. Continue;
  13213. end;
  13214. end;
  13215. A_SHL:
  13216. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13217. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13218. begin
  13219. {$ifopt R+}
  13220. {$define RANGE_WAS_ON}
  13221. {$R-}
  13222. {$endif}
  13223. { get length of potential and mask }
  13224. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13225. { really a mask? }
  13226. {$ifdef RANGE_WAS_ON}
  13227. {$R+}
  13228. {$endif}
  13229. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13230. { unmasked part shifted out? }
  13231. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13232. begin
  13233. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13234. RemoveCurrentP(p, hp1);
  13235. Result:=true;
  13236. exit;
  13237. end;
  13238. end;
  13239. A_SHR:
  13240. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13241. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13242. (taicpu(hp1).oper[0]^.val <= 63) then
  13243. begin
  13244. { Does SHR combined with the AND cover all the bits?
  13245. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13246. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13247. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13248. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13249. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13250. begin
  13251. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13252. RemoveCurrentP(p, hp1);
  13253. Result := True;
  13254. Exit;
  13255. end;
  13256. end;
  13257. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13258. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13259. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13260. begin
  13261. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13262. (
  13263. (
  13264. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13265. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13266. ) or (
  13267. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13268. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13269. {$ifdef x86_64}
  13270. ) or (
  13271. (taicpu(hp1).opsize = S_LQ) and
  13272. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13273. {$endif x86_64}
  13274. )
  13275. ) then
  13276. begin
  13277. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13278. begin
  13279. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13280. RemoveInstruction(hp1);
  13281. { See if there are other optimisations possible }
  13282. Continue;
  13283. end;
  13284. { The super-registers are the same though.
  13285. Note that this change by itself doesn't improve
  13286. code speed, but it opens up other optimisations. }
  13287. {$ifdef x86_64}
  13288. { Convert 64-bit register to 32-bit }
  13289. case taicpu(hp1).opsize of
  13290. S_BQ:
  13291. begin
  13292. taicpu(hp1).opsize := S_BL;
  13293. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13294. end;
  13295. S_WQ:
  13296. begin
  13297. taicpu(hp1).opsize := S_WL;
  13298. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13299. end
  13300. else
  13301. ;
  13302. end;
  13303. {$endif x86_64}
  13304. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13305. taicpu(hp1).opcode := A_MOVZX;
  13306. { See if there are other optimisations possible }
  13307. Continue;
  13308. end;
  13309. end;
  13310. else
  13311. ;
  13312. end;
  13313. end
  13314. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13315. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13316. begin
  13317. {$ifdef x86_64}
  13318. if (taicpu(p).opsize = S_Q) then
  13319. begin
  13320. { Never necessary }
  13321. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13322. RemoveCurrentP(p, hp1);
  13323. Result := True;
  13324. Exit;
  13325. end;
  13326. {$endif x86_64}
  13327. { Forward check to determine necessity of and %reg,%reg }
  13328. TransferUsedRegs(TmpUsedRegs);
  13329. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13330. { Saves on a bunch of dereferences }
  13331. ActiveReg := taicpu(p).oper[1]^.reg;
  13332. case taicpu(hp1).opcode of
  13333. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13334. if (
  13335. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13336. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13337. ) and
  13338. (
  13339. (taicpu(hp1).opcode <> A_MOV) or
  13340. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13341. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13342. ) and
  13343. not (
  13344. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13345. (taicpu(hp1).opcode = A_MOV) and
  13346. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13347. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13348. ) and
  13349. (
  13350. (
  13351. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13352. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13353. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13354. ) or
  13355. (
  13356. {$ifdef x86_64}
  13357. (
  13358. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13359. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13360. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13361. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13362. ) and
  13363. {$endif x86_64}
  13364. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13365. )
  13366. ) then
  13367. begin
  13368. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13369. RemoveCurrentP(p, hp1);
  13370. Result := True;
  13371. Exit;
  13372. end;
  13373. A_ADD,
  13374. A_AND,
  13375. A_BSF,
  13376. A_BSR,
  13377. A_BTC,
  13378. A_BTR,
  13379. A_BTS,
  13380. A_OR,
  13381. A_SUB,
  13382. A_XOR:
  13383. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13384. if (
  13385. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13386. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13387. ) and
  13388. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13389. begin
  13390. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13391. RemoveCurrentP(p, hp1);
  13392. Result := True;
  13393. Exit;
  13394. end;
  13395. A_CMP,
  13396. A_TEST:
  13397. if (
  13398. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13399. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13400. ) and
  13401. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13402. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13403. begin
  13404. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13405. RemoveCurrentP(p, hp1);
  13406. Result := True;
  13407. Exit;
  13408. end;
  13409. A_BSWAP,
  13410. A_NEG,
  13411. A_NOT:
  13412. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13413. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13414. begin
  13415. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13416. RemoveCurrentP(p, hp1);
  13417. Result := True;
  13418. Exit;
  13419. end;
  13420. else
  13421. ;
  13422. end;
  13423. end;
  13424. if (taicpu(hp1).is_jmp) and
  13425. (taicpu(hp1).opcode<>A_JMP) and
  13426. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13427. begin
  13428. { change
  13429. and x, reg
  13430. jxx
  13431. to
  13432. test x, reg
  13433. jxx
  13434. if reg is deallocated before the
  13435. jump, but only if it's a conditional jump (PFV)
  13436. }
  13437. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13438. taicpu(p).opcode := A_TEST;
  13439. Exit;
  13440. end;
  13441. Break;
  13442. end;
  13443. { Lone AND tests }
  13444. if (taicpu(p).oper[0]^.typ = top_const) then
  13445. begin
  13446. {
  13447. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13448. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13449. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13450. }
  13451. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13452. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13453. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13454. begin
  13455. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13456. if taicpu(p).opsize = S_L then
  13457. begin
  13458. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13459. Result := True;
  13460. end;
  13461. end;
  13462. end;
  13463. { Backward check to determine necessity of and %reg,%reg }
  13464. if (taicpu(p).oper[0]^.typ = top_reg) and
  13465. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13466. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13467. GetLastInstruction(p, hp2) and
  13468. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13469. { Check size of adjacent instruction to determine if the AND is
  13470. effectively a null operation }
  13471. (
  13472. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13473. { Note: Don't include S_Q }
  13474. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13475. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13476. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13477. ) then
  13478. begin
  13479. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13480. { If GetNextInstruction returned False, hp1 will be nil }
  13481. RemoveCurrentP(p, hp1);
  13482. Result := True;
  13483. Exit;
  13484. end;
  13485. end;
  13486. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13487. var
  13488. hp1, hp2: tai;
  13489. NewRef: TReference;
  13490. Distance: Cardinal;
  13491. TempTracking: TAllUsedRegs;
  13492. { This entire nested function is used in an if-statement below, but we
  13493. want to avoid all the used reg transfers and GetNextInstruction calls
  13494. until we really have to check }
  13495. function MemRegisterNotUsedLater: Boolean; inline;
  13496. var
  13497. hp2: tai;
  13498. begin
  13499. TransferUsedRegs(TmpUsedRegs);
  13500. hp2 := p;
  13501. repeat
  13502. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13503. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13504. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13505. end;
  13506. begin
  13507. Result := False;
  13508. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13509. (taicpu(p).oper[1]^.typ = top_reg) then
  13510. begin
  13511. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13512. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13513. (hp1.typ <> ait_instruction) or
  13514. not
  13515. (
  13516. (cs_opt_level3 in current_settings.optimizerswitches) or
  13517. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13518. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13519. ) then
  13520. Exit;
  13521. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13522. addq $x, %rax
  13523. movq %rax, %rdx
  13524. sarq $63, %rdx
  13525. (%rax still in use)
  13526. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13527. leaq $x(%rax),%rdx
  13528. addq $x, %rax
  13529. sarq $63, %rdx
  13530. ...which is okay since it breaks the dependency chain between
  13531. addq and movq, but if OptPass2MOV is called first:
  13532. addq $x, %rax
  13533. cqto
  13534. ...which is better in all ways, taking only 2 cycles to execute
  13535. and much smaller in code size.
  13536. }
  13537. { The extra register tracking is quite strenuous }
  13538. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13539. MatchInstruction(hp1, A_MOV, []) then
  13540. begin
  13541. { Update the register tracking to the MOV instruction }
  13542. CopyUsedRegs(TempTracking);
  13543. hp2 := p;
  13544. repeat
  13545. UpdateUsedRegs(tai(hp2.Next));
  13546. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13547. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13548. OptPass2ADD get called again }
  13549. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13550. begin
  13551. { Reset the tracking to the current instruction }
  13552. RestoreUsedRegs(TempTracking);
  13553. ReleaseUsedRegs(TempTracking);
  13554. Result := True;
  13555. Exit;
  13556. end;
  13557. { Reset the tracking to the current instruction }
  13558. RestoreUsedRegs(TempTracking);
  13559. ReleaseUsedRegs(TempTracking);
  13560. { If OptPass2MOV returned True, we don't need to set Result to
  13561. True if hp1 didn't change because the ADD instruction didn't
  13562. get modified and we'll be evaluating hp1 again when the
  13563. peephole optimizer reaches it }
  13564. end;
  13565. { Change:
  13566. add %reg2,%reg1
  13567. (%reg2 not modified in between)
  13568. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13569. To:
  13570. mov/s/z #(%reg1,%reg2),%reg1
  13571. }
  13572. if (taicpu(p).oper[0]^.typ = top_reg) and
  13573. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13574. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13575. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13576. (
  13577. (
  13578. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13579. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13580. { r/esp cannot be an index }
  13581. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13582. ) or (
  13583. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13584. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13585. )
  13586. ) and (
  13587. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13588. (
  13589. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13590. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13591. MemRegisterNotUsedLater
  13592. )
  13593. ) then
  13594. begin
  13595. if (
  13596. { Instructions are guaranteed to be adjacent on -O2 and under }
  13597. (cs_opt_level3 in current_settings.optimizerswitches) and
  13598. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13599. ) then
  13600. begin
  13601. { If the other register is used in between, move the MOV
  13602. instruction to right after the ADD instruction so a
  13603. saving can still be made }
  13604. Asml.Remove(hp1);
  13605. Asml.InsertAfter(hp1, p);
  13606. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13607. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13608. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13609. RemoveCurrentp(p, hp1);
  13610. end
  13611. else
  13612. begin
  13613. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13614. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13615. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13616. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13617. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13618. { hp1 may not be the immediate next instruction under -O3 }
  13619. RemoveCurrentp(p)
  13620. else
  13621. RemoveCurrentp(p, hp1);
  13622. end;
  13623. Result := True;
  13624. Exit;
  13625. end;
  13626. { Change:
  13627. addl/q $x,%reg1
  13628. movl/q %reg1,%reg2
  13629. To:
  13630. leal/q $x(%reg1),%reg2
  13631. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13632. Breaks the dependency chain.
  13633. }
  13634. if (taicpu(p).oper[0]^.typ = top_const) and
  13635. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13636. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13637. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13638. (
  13639. { Instructions are guaranteed to be adjacent on -O2 and under }
  13640. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13641. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13642. ) then
  13643. begin
  13644. TransferUsedRegs(TmpUsedRegs);
  13645. hp2 := p;
  13646. repeat
  13647. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13648. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13649. if (
  13650. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13651. not (cs_opt_size in current_settings.optimizerswitches) or
  13652. (
  13653. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13654. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13655. )
  13656. ) then
  13657. begin
  13658. { Change the MOV instruction to a LEA instruction, and update the
  13659. first operand }
  13660. reference_reset(NewRef, 1, []);
  13661. NewRef.base := taicpu(p).oper[1]^.reg;
  13662. NewRef.scalefactor := 1;
  13663. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13664. taicpu(hp1).opcode := A_LEA;
  13665. taicpu(hp1).loadref(0, NewRef);
  13666. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13667. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13668. begin
  13669. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13670. { Move what is now the LEA instruction to before the ADD instruction }
  13671. Asml.Remove(hp1);
  13672. Asml.InsertBefore(hp1, p);
  13673. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13674. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13675. p := hp1;
  13676. end
  13677. else
  13678. begin
  13679. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13680. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13681. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13682. { hp1 may not be the immediate next instruction under -O3 }
  13683. RemoveCurrentp(p)
  13684. else
  13685. RemoveCurrentp(p, hp1);
  13686. end;
  13687. Result := True;
  13688. end;
  13689. end;
  13690. end;
  13691. end;
  13692. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13693. var
  13694. SubReg: TSubRegister;
  13695. begin
  13696. Result:=false;
  13697. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13698. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13699. with taicpu(p).oper[0]^.ref^ do
  13700. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13701. begin
  13702. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13703. begin
  13704. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13705. taicpu(p).opcode := A_ADD;
  13706. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13707. Result := True;
  13708. end
  13709. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13710. begin
  13711. if (base <> NR_NO) then
  13712. begin
  13713. if (scalefactor <= 1) then
  13714. begin
  13715. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13716. taicpu(p).opcode := A_ADD;
  13717. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13718. Result := True;
  13719. end;
  13720. end
  13721. else
  13722. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13723. if (scalefactor in [2, 4, 8]) then
  13724. begin
  13725. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13726. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13727. taicpu(p).opcode := A_SHL;
  13728. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13729. Result := True;
  13730. end;
  13731. end;
  13732. end;
  13733. end;
  13734. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13735. var
  13736. hp1, hp2: tai;
  13737. NewRef: TReference;
  13738. Distance: Cardinal;
  13739. TempTracking: TAllUsedRegs;
  13740. begin
  13741. Result := False;
  13742. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13743. MatchOpType(taicpu(p),top_const,top_reg) then
  13744. begin
  13745. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13746. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13747. (hp1.typ <> ait_instruction) or
  13748. not
  13749. (
  13750. (cs_opt_level3 in current_settings.optimizerswitches) or
  13751. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13752. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13753. ) then
  13754. Exit;
  13755. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13756. subq $x, %rax
  13757. movq %rax, %rdx
  13758. sarq $63, %rdx
  13759. (%rax still in use)
  13760. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13761. leaq $-x(%rax),%rdx
  13762. movq $x, %rax
  13763. sarq $63, %rdx
  13764. ...which is okay since it breaks the dependency chain between
  13765. subq and movq, but if OptPass2MOV is called first:
  13766. subq $x, %rax
  13767. cqto
  13768. ...which is better in all ways, taking only 2 cycles to execute
  13769. and much smaller in code size.
  13770. }
  13771. { The extra register tracking is quite strenuous }
  13772. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13773. MatchInstruction(hp1, A_MOV, []) then
  13774. begin
  13775. { Update the register tracking to the MOV instruction }
  13776. CopyUsedRegs(TempTracking);
  13777. hp2 := p;
  13778. repeat
  13779. UpdateUsedRegs(tai(hp2.Next));
  13780. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13781. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13782. OptPass2SUB get called again }
  13783. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13784. begin
  13785. { Reset the tracking to the current instruction }
  13786. RestoreUsedRegs(TempTracking);
  13787. ReleaseUsedRegs(TempTracking);
  13788. Result := True;
  13789. Exit;
  13790. end;
  13791. { Reset the tracking to the current instruction }
  13792. RestoreUsedRegs(TempTracking);
  13793. ReleaseUsedRegs(TempTracking);
  13794. { If OptPass2MOV returned True, we don't need to set Result to
  13795. True if hp1 didn't change because the SUB instruction didn't
  13796. get modified and we'll be evaluating hp1 again when the
  13797. peephole optimizer reaches it }
  13798. end;
  13799. { Change:
  13800. subl/q $x,%reg1
  13801. movl/q %reg1,%reg2
  13802. To:
  13803. leal/q $-x(%reg1),%reg2
  13804. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13805. Breaks the dependency chain and potentially permits the removal of
  13806. a CMP instruction if one follows.
  13807. }
  13808. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13809. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13810. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13811. (
  13812. { Instructions are guaranteed to be adjacent on -O2 and under }
  13813. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13814. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13815. ) then
  13816. begin
  13817. TransferUsedRegs(TmpUsedRegs);
  13818. hp2 := p;
  13819. repeat
  13820. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13821. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13822. if (
  13823. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13824. not (cs_opt_size in current_settings.optimizerswitches) or
  13825. (
  13826. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13827. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13828. )
  13829. ) then
  13830. begin
  13831. { Change the MOV instruction to a LEA instruction, and update the
  13832. first operand }
  13833. reference_reset(NewRef, 1, []);
  13834. NewRef.base := taicpu(p).oper[1]^.reg;
  13835. NewRef.scalefactor := 1;
  13836. NewRef.offset := -taicpu(p).oper[0]^.val;
  13837. taicpu(hp1).opcode := A_LEA;
  13838. taicpu(hp1).loadref(0, NewRef);
  13839. TransferUsedRegs(TmpUsedRegs);
  13840. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13841. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13842. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13843. begin
  13844. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13845. { Move what is now the LEA instruction to before the SUB instruction }
  13846. Asml.Remove(hp1);
  13847. Asml.InsertBefore(hp1, p);
  13848. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13849. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13850. p := hp1;
  13851. end
  13852. else
  13853. begin
  13854. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13855. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13856. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13857. { hp1 may not be the immediate next instruction under -O3 }
  13858. RemoveCurrentp(p)
  13859. else
  13860. RemoveCurrentp(p, hp1);
  13861. end;
  13862. Result := True;
  13863. end;
  13864. end;
  13865. end;
  13866. end;
  13867. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13868. begin
  13869. { we can skip all instructions not messing with the stack pointer }
  13870. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13871. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13872. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13873. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13874. ({(taicpu(hp1).ops=0) or }
  13875. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13876. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13877. ) and }
  13878. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13879. )
  13880. ) do
  13881. GetNextInstruction(hp1,hp1);
  13882. Result:=assigned(hp1);
  13883. end;
  13884. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13885. var
  13886. hp1, hp2, hp3, hp4, hp5: tai;
  13887. begin
  13888. Result:=false;
  13889. hp5:=nil;
  13890. { replace
  13891. leal(q) x(<stackpointer>),<stackpointer>
  13892. call procname
  13893. leal(q) -x(<stackpointer>),<stackpointer>
  13894. ret
  13895. by
  13896. jmp procname
  13897. but do it only on level 4 because it destroys stack back traces
  13898. }
  13899. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13900. MatchOpType(taicpu(p),top_ref,top_reg) and
  13901. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13902. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13903. { the -8 or -24 are not required, but bail out early if possible,
  13904. higher values are unlikely }
  13905. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13906. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13907. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13908. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13909. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13910. GetNextInstruction(p, hp1) and
  13911. { Take a copy of hp1 }
  13912. SetAndTest(hp1, hp4) and
  13913. { trick to skip label }
  13914. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13915. SkipSimpleInstructions(hp1) and
  13916. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13917. GetNextInstruction(hp1, hp2) and
  13918. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13919. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13920. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13921. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13922. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13923. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13924. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13925. { Segment register will be NR_NO }
  13926. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13927. GetNextInstruction(hp2, hp3) and
  13928. { trick to skip label }
  13929. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13930. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13931. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13932. SetAndTest(hp3,hp5) and
  13933. GetNextInstruction(hp3,hp3) and
  13934. MatchInstruction(hp3,A_RET,[S_NO])
  13935. )
  13936. ) and
  13937. (taicpu(hp3).ops=0) then
  13938. begin
  13939. taicpu(hp1).opcode := A_JMP;
  13940. taicpu(hp1).is_jmp := true;
  13941. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13942. RemoveCurrentP(p, hp4);
  13943. RemoveInstruction(hp2);
  13944. RemoveInstruction(hp3);
  13945. if Assigned(hp5) then
  13946. begin
  13947. AsmL.Remove(hp5);
  13948. ASmL.InsertBefore(hp5,hp1)
  13949. end;
  13950. Result:=true;
  13951. end;
  13952. end;
  13953. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13954. {$ifdef x86_64}
  13955. var
  13956. hp1, hp2, hp3, hp4, hp5: tai;
  13957. {$endif x86_64}
  13958. begin
  13959. Result:=false;
  13960. {$ifdef x86_64}
  13961. hp5:=nil;
  13962. { replace
  13963. push %rax
  13964. call procname
  13965. pop %rcx
  13966. ret
  13967. by
  13968. jmp procname
  13969. but do it only on level 4 because it destroys stack back traces
  13970. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13971. for all supported calling conventions
  13972. }
  13973. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13974. MatchOpType(taicpu(p),top_reg) and
  13975. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13976. GetNextInstruction(p, hp1) and
  13977. { Take a copy of hp1 }
  13978. SetAndTest(hp1, hp4) and
  13979. { trick to skip label }
  13980. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13981. SkipSimpleInstructions(hp1) and
  13982. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13983. GetNextInstruction(hp1, hp2) and
  13984. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13985. MatchOpType(taicpu(hp2),top_reg) and
  13986. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13987. GetNextInstruction(hp2, hp3) and
  13988. { trick to skip label }
  13989. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13990. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13991. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13992. SetAndTest(hp3,hp5) and
  13993. GetNextInstruction(hp3,hp3) and
  13994. MatchInstruction(hp3,A_RET,[S_NO])
  13995. )
  13996. ) and
  13997. (taicpu(hp3).ops=0) then
  13998. begin
  13999. taicpu(hp1).opcode := A_JMP;
  14000. taicpu(hp1).is_jmp := true;
  14001. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14002. RemoveCurrentP(p, hp4);
  14003. RemoveInstruction(hp2);
  14004. RemoveInstruction(hp3);
  14005. if Assigned(hp5) then
  14006. begin
  14007. AsmL.Remove(hp5);
  14008. ASmL.InsertBefore(hp5,hp1)
  14009. end;
  14010. Result:=true;
  14011. end;
  14012. {$endif x86_64}
  14013. end;
  14014. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14015. var
  14016. Value, RegName: string;
  14017. hp1: tai;
  14018. begin
  14019. Result:=false;
  14020. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14021. begin
  14022. case taicpu(p).oper[0]^.val of
  14023. 0:
  14024. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14025. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14026. (
  14027. { See if we can still convert the instruction }
  14028. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14029. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14030. ) then
  14031. begin
  14032. { change "mov $0,%reg" into "xor %reg,%reg" }
  14033. taicpu(p).opcode := A_XOR;
  14034. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14035. Result := True;
  14036. {$ifdef x86_64}
  14037. end
  14038. else if (taicpu(p).opsize = S_Q) then
  14039. begin
  14040. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14041. { The actual optimization }
  14042. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14043. taicpu(p).changeopsize(S_L);
  14044. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14045. Result := True;
  14046. end;
  14047. $1..$FFFFFFFF:
  14048. begin
  14049. { Code size reduction by J. Gareth "Kit" Moreton }
  14050. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14051. case taicpu(p).opsize of
  14052. S_Q:
  14053. begin
  14054. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14055. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14056. { The actual optimization }
  14057. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14058. taicpu(p).changeopsize(S_L);
  14059. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14060. Result := True;
  14061. end;
  14062. else
  14063. { Do nothing };
  14064. end;
  14065. {$endif x86_64}
  14066. end;
  14067. -1:
  14068. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14069. if (cs_opt_size in current_settings.optimizerswitches) and
  14070. (taicpu(p).opsize <> S_B) and
  14071. (
  14072. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14073. (
  14074. { See if we can still convert the instruction }
  14075. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14076. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14077. )
  14078. ) then
  14079. begin
  14080. { change "mov $-1,%reg" into "or $-1,%reg" }
  14081. { NOTES:
  14082. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14083. - This operation creates a false dependency on the register, so only do it when optimising for size
  14084. - 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
  14085. }
  14086. taicpu(p).opcode := A_OR;
  14087. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14088. Result := True;
  14089. end;
  14090. else
  14091. { Do nothing };
  14092. end;
  14093. end;
  14094. end;
  14095. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14096. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14097. begin
  14098. Result := False;
  14099. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14100. Exit;
  14101. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14102. so don't bother optimising }
  14103. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14104. Exit;
  14105. if (taicpu(p).oper[0]^.typ <> top_const) or
  14106. { If the value can fit into an 8-bit signed integer, a smaller
  14107. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14108. falls within this range }
  14109. (
  14110. (taicpu(p).oper[0]^.val > -128) and
  14111. (taicpu(p).oper[0]^.val <= 127)
  14112. ) then
  14113. Exit;
  14114. { If we're optimising for size, this is acceptable }
  14115. if (cs_opt_size in current_settings.optimizerswitches) then
  14116. Exit(True);
  14117. if (taicpu(p).oper[1]^.typ = top_reg) and
  14118. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14119. Exit(True);
  14120. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14121. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14122. Exit(True);
  14123. end;
  14124. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14125. var
  14126. hp1: tai;
  14127. Value: TCGInt;
  14128. begin
  14129. Result := False;
  14130. if MatchOpType(taicpu(p), top_const, top_reg) then
  14131. begin
  14132. { Detect:
  14133. andw x, %ax (0 <= x < $8000)
  14134. ...
  14135. movzwl %ax,%eax
  14136. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14137. }
  14138. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14139. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14140. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14141. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14142. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14143. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14144. begin
  14145. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14146. taicpu(hp1).opcode := A_CWDE;
  14147. taicpu(hp1).clearop(0);
  14148. taicpu(hp1).clearop(1);
  14149. taicpu(hp1).ops := 0;
  14150. { A change was made, but not with p, so don't set Result, but
  14151. notify the compiler that a change was made }
  14152. Include(OptsToCheck, aoc_ForceNewIteration);
  14153. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14154. end;
  14155. end;
  14156. { If "not x" is a power of 2 (popcnt = 1), change:
  14157. and $x, %reg/ref
  14158. To:
  14159. btr lb(x), %reg/ref
  14160. }
  14161. if IsBTXAcceptable(p) and
  14162. (
  14163. { Make sure a TEST doesn't follow that plays with the register }
  14164. not GetNextInstruction(p, hp1) or
  14165. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14166. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14167. ) then
  14168. begin
  14169. {$push}{$R-}{$Q-}
  14170. { Value is a sign-extended 32-bit integer - just correct it
  14171. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14172. checks to see if this operand is an immediate. }
  14173. Value := not taicpu(p).oper[0]^.val;
  14174. {$pop}
  14175. {$ifdef x86_64}
  14176. if taicpu(p).opsize = S_L then
  14177. {$endif x86_64}
  14178. Value := Value and $FFFFFFFF;
  14179. if (PopCnt(QWord(Value)) = 1) then
  14180. begin
  14181. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14182. taicpu(p).opcode := A_BTR;
  14183. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14184. Result := True;
  14185. Exit;
  14186. end;
  14187. end;
  14188. end;
  14189. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14190. begin
  14191. Result := False;
  14192. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14193. Exit;
  14194. { Convert:
  14195. movswl %ax,%eax -> cwtl
  14196. movslq %eax,%rax -> cdqe
  14197. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14198. refer to the same opcode and depends only on the assembler's
  14199. current operand-size attribute. [Kit]
  14200. }
  14201. with taicpu(p) do
  14202. case opsize of
  14203. S_WL:
  14204. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14205. begin
  14206. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14207. opcode := A_CWDE;
  14208. clearop(0);
  14209. clearop(1);
  14210. ops := 0;
  14211. Result := True;
  14212. end;
  14213. {$ifdef x86_64}
  14214. S_LQ:
  14215. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14216. begin
  14217. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14218. opcode := A_CDQE;
  14219. clearop(0);
  14220. clearop(1);
  14221. ops := 0;
  14222. Result := True;
  14223. end;
  14224. {$endif x86_64}
  14225. else
  14226. ;
  14227. end;
  14228. end;
  14229. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14230. var
  14231. hp1, hp2: tai;
  14232. IdentityMask, Shift: TCGInt;
  14233. LimitSize: Topsize;
  14234. DoNotMerge: Boolean;
  14235. begin
  14236. Result := False;
  14237. { All these optimisations work on "shr const,%reg" }
  14238. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14239. Exit;
  14240. DoNotMerge := False;
  14241. Shift := taicpu(p).oper[0]^.val;
  14242. LimitSize := taicpu(p).opsize;
  14243. hp1 := p;
  14244. repeat
  14245. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14246. Break;
  14247. { Detect:
  14248. shr x, %reg
  14249. and y, %reg
  14250. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14251. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14252. }
  14253. case taicpu(hp1).opcode of
  14254. A_AND:
  14255. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14256. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14257. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14258. begin
  14259. { Make sure the FLAGS register isn't in use }
  14260. TransferUsedRegs(TmpUsedRegs);
  14261. hp2 := p;
  14262. repeat
  14263. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14264. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14265. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14266. begin
  14267. { Generate the identity mask }
  14268. case taicpu(p).opsize of
  14269. S_B:
  14270. IdentityMask := $FF shr Shift;
  14271. S_W:
  14272. IdentityMask := $FFFF shr Shift;
  14273. S_L:
  14274. IdentityMask := $FFFFFFFF shr Shift;
  14275. {$ifdef x86_64}
  14276. S_Q:
  14277. { We need to force the operands to be unsigned 64-bit
  14278. integers otherwise the wrong value is generated }
  14279. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14280. {$endif x86_64}
  14281. else
  14282. InternalError(2022081501);
  14283. end;
  14284. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14285. begin
  14286. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14287. { All the possible 1 bits are covered, so we can remove the AND }
  14288. hp2 := tai(hp1.Previous);
  14289. RemoveInstruction(hp1);
  14290. { p wasn't actually changed, so don't set Result to True,
  14291. but a change was nonetheless made elsewhere }
  14292. Include(OptsToCheck, aoc_ForceNewIteration);
  14293. { Do another pass in case other AND or MOVZX instructions
  14294. follow }
  14295. hp1 := hp2;
  14296. Continue;
  14297. end;
  14298. end;
  14299. end;
  14300. A_TEST, A_CMP, A_Jcc:
  14301. { Skip over conditional jumps and relevant comparisons }
  14302. Continue;
  14303. A_MOVZX:
  14304. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14305. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14306. begin
  14307. { Since the original register is being read as is, subsequent
  14308. SHRs must not be merged at this point }
  14309. DoNotMerge := True;
  14310. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14311. begin
  14312. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14313. begin
  14314. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14315. { All the possible 1 bits are covered, so we can remove the AND }
  14316. hp2 := tai(hp1.Previous);
  14317. RemoveInstruction(hp1);
  14318. hp1 := hp2;
  14319. end
  14320. else { Different register target }
  14321. begin
  14322. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14323. taicpu(hp1).opcode := A_MOV;
  14324. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14325. case taicpu(hp1).opsize of
  14326. S_BW:
  14327. taicpu(hp1).opsize := S_W;
  14328. S_BL, S_WL:
  14329. taicpu(hp1).opsize := S_L;
  14330. else
  14331. InternalError(2022081503);
  14332. end;
  14333. end;
  14334. end
  14335. else if (Shift > 0) and
  14336. (taicpu(p).opsize = S_W) and
  14337. (taicpu(hp1).opsize = S_WL) and
  14338. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14339. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14340. begin
  14341. { Detect:
  14342. shr x, %ax (x > 0)
  14343. ...
  14344. movzwl %ax,%eax
  14345. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14346. }
  14347. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14348. taicpu(hp1).opcode := A_CWDE;
  14349. taicpu(hp1).clearop(0);
  14350. taicpu(hp1).clearop(1);
  14351. taicpu(hp1).ops := 0;
  14352. end;
  14353. { Move onto the next instruction }
  14354. Continue;
  14355. end;
  14356. A_SHL, A_SAL, A_SHR:
  14357. if (taicpu(hp1).opsize <= LimitSize) and
  14358. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14359. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14360. begin
  14361. { Make sure the sizes don't exceed the register size limit
  14362. (measured by the shift value falling below the limit) }
  14363. if taicpu(hp1).opsize < LimitSize then
  14364. LimitSize := taicpu(hp1).opsize;
  14365. if taicpu(hp1).opcode = A_SHR then
  14366. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14367. else
  14368. begin
  14369. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14370. DoNotMerge := True;
  14371. end;
  14372. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14373. Break;
  14374. { Since we've established that the combined shift is within
  14375. limits, we can actually combine the adjacent SHR
  14376. instructions even if they're different sizes }
  14377. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14378. begin
  14379. hp2 := tai(hp1.Previous);
  14380. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14381. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14382. RemoveInstruction(hp1);
  14383. hp1 := hp2;
  14384. end;
  14385. { Move onto the next instruction }
  14386. Continue;
  14387. end;
  14388. else
  14389. ;
  14390. end;
  14391. Break;
  14392. until False;
  14393. { Detect the following (looking backwards):
  14394. shr %cl,%reg
  14395. shr x, %reg
  14396. Swap the two SHR instructions to minimise a pipeline stall.
  14397. }
  14398. if GetLastInstruction(p, hp1) and
  14399. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14400. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14401. { First operand will be %cl }
  14402. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14403. { Just to be sure }
  14404. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14405. begin
  14406. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14407. { Moving the entries this way ensures the register tracking remains correct }
  14408. Asml.Remove(p);
  14409. Asml.InsertBefore(p, hp1);
  14410. p := hp1;
  14411. { Don't set Result to True because the current instruction is now
  14412. "shr %cl,%reg" and there's nothing more we can do with it }
  14413. end;
  14414. end;
  14415. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14416. var
  14417. hp1, hp2: tai;
  14418. Opposite, SecondOpposite: TAsmOp;
  14419. NewCond: TAsmCond;
  14420. begin
  14421. Result := False;
  14422. { Change:
  14423. add/sub 128,(dest)
  14424. To:
  14425. sub/add -128,(dest)
  14426. This generaally takes fewer bytes to encode because -128 can be stored
  14427. in a signed byte, whereas +128 cannot.
  14428. }
  14429. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14430. begin
  14431. if taicpu(p).opcode = A_ADD then
  14432. Opposite := A_SUB
  14433. else
  14434. Opposite := A_ADD;
  14435. { Be careful if the flags are in use, because the CF flag inverts
  14436. when changing from ADD to SUB and vice versa }
  14437. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14438. GetNextInstruction(p, hp1) then
  14439. begin
  14440. TransferUsedRegs(TmpUsedRegs);
  14441. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14442. hp2 := hp1;
  14443. { Scan ahead to check if everything's safe }
  14444. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14445. begin
  14446. if (hp1.typ <> ait_instruction) then
  14447. { Probably unsafe since the flags are still in use }
  14448. Exit;
  14449. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14450. { Stop searching at an unconditional jump }
  14451. Break;
  14452. if not
  14453. (
  14454. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14455. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14456. ) and
  14457. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14458. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14459. Exit;
  14460. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14461. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14462. { Move to the next instruction }
  14463. GetNextInstruction(hp1, hp1);
  14464. end;
  14465. while Assigned(hp2) and (hp2 <> hp1) do
  14466. begin
  14467. NewCond := C_None;
  14468. case taicpu(hp2).condition of
  14469. C_A, C_NBE:
  14470. NewCond := C_BE;
  14471. C_B, C_C, C_NAE:
  14472. NewCond := C_AE;
  14473. C_AE, C_NB, C_NC:
  14474. NewCond := C_B;
  14475. C_BE, C_NA:
  14476. NewCond := C_A;
  14477. else
  14478. { No change needed };
  14479. end;
  14480. if NewCond <> C_None then
  14481. begin
  14482. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14483. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14484. taicpu(hp2).condition := NewCond;
  14485. end
  14486. else
  14487. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14488. begin
  14489. { Because of the flipping of the carry bit, to ensure
  14490. the operation remains equivalent, ADC becomes SBB
  14491. and vice versa, and the constant is not-inverted.
  14492. If multiple ADCs or SBBs appear in a row, each one
  14493. changed causes the carry bit to invert, so they all
  14494. need to be flipped }
  14495. if taicpu(hp2).opcode = A_ADC then
  14496. SecondOpposite := A_SBB
  14497. else
  14498. SecondOpposite := A_ADC;
  14499. if taicpu(hp2).oper[0]^.typ <> top_const then
  14500. { Should have broken out of this optimisation already }
  14501. InternalError(2021112901);
  14502. 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]^) + ' -> ' +
  14503. 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);
  14504. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14505. taicpu(hp2).opcode := SecondOpposite;
  14506. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14507. end;
  14508. { Move to the next instruction }
  14509. GetNextInstruction(hp2, hp2);
  14510. end;
  14511. if (hp2 <> hp1) then
  14512. InternalError(2021111501);
  14513. end;
  14514. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14515. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14516. taicpu(p).opcode := Opposite;
  14517. taicpu(p).oper[0]^.val := -128;
  14518. { No further optimisations can be made on this instruction, so move
  14519. onto the next one to save time }
  14520. p := tai(p.Next);
  14521. UpdateUsedRegs(p);
  14522. Result := True;
  14523. Exit;
  14524. end;
  14525. { Detect:
  14526. add/sub %reg2,(dest)
  14527. add/sub x, (dest)
  14528. (dest can be a register or a reference)
  14529. Swap the instructions to minimise a pipeline stall. This reverses the
  14530. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14531. optimisations could be made.
  14532. }
  14533. if (taicpu(p).oper[0]^.typ = top_reg) and
  14534. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14535. (
  14536. (
  14537. (taicpu(p).oper[1]^.typ = top_reg) and
  14538. { We can try searching further ahead if we're writing to a register }
  14539. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14540. ) or
  14541. (
  14542. (taicpu(p).oper[1]^.typ = top_ref) and
  14543. GetNextInstruction(p, hp1)
  14544. )
  14545. ) and
  14546. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14547. (taicpu(hp1).oper[0]^.typ = top_const) and
  14548. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14549. begin
  14550. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14551. TransferUsedRegs(TmpUsedRegs);
  14552. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14553. hp2 := p;
  14554. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14555. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14556. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14557. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14558. begin
  14559. asml.remove(hp1);
  14560. asml.InsertBefore(hp1, p);
  14561. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14562. Result := True;
  14563. end;
  14564. end;
  14565. end;
  14566. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14567. var
  14568. hp1: tai;
  14569. begin
  14570. Result:=false;
  14571. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14572. while GetNextInstruction(p, hp1) and
  14573. TrySwapMovCmp(p, hp1) do
  14574. begin
  14575. if MatchInstruction(hp1, A_MOV, []) then
  14576. begin
  14577. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14578. begin
  14579. { A little hacky, but since CMP doesn't read the flags, only
  14580. modify them, it's safe if they get scrambled by MOV -> XOR }
  14581. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14582. Result := PostPeepholeOptMov(hp1);
  14583. {$ifdef x86_64}
  14584. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14585. { Used to shrink instruction size }
  14586. PostPeepholeOptXor(hp1);
  14587. {$endif x86_64}
  14588. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14589. end
  14590. else
  14591. begin
  14592. Result := PostPeepholeOptMov(hp1);
  14593. {$ifdef x86_64}
  14594. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14595. { Used to shrink instruction size }
  14596. PostPeepholeOptXor(hp1);
  14597. {$endif x86_64}
  14598. end;
  14599. end;
  14600. { Enabling this flag is actually a null operation, but it marks
  14601. the code as 'modified' during this pass }
  14602. Include(OptsToCheck, aoc_ForceNewIteration);
  14603. end;
  14604. { change "cmp $0, %reg" to "test %reg, %reg" }
  14605. if MatchOpType(taicpu(p),top_const,top_reg) and
  14606. (taicpu(p).oper[0]^.val = 0) then
  14607. begin
  14608. taicpu(p).opcode := A_TEST;
  14609. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14610. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14611. Result:=true;
  14612. end;
  14613. end;
  14614. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14615. var
  14616. IsTestConstX, IsValid : Boolean;
  14617. hp1,hp2 : tai;
  14618. begin
  14619. Result:=false;
  14620. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14621. if (taicpu(p).opcode = A_TEST) then
  14622. while GetNextInstruction(p, hp1) and
  14623. TrySwapMovCmp(p, hp1) do
  14624. begin
  14625. if MatchInstruction(hp1, A_MOV, []) then
  14626. begin
  14627. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14628. begin
  14629. { A little hacky, but since TEST doesn't read the flags, only
  14630. modify them, it's safe if they get scrambled by MOV -> XOR }
  14631. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14632. Result := PostPeepholeOptMov(hp1);
  14633. {$ifdef x86_64}
  14634. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14635. { Used to shrink instruction size }
  14636. PostPeepholeOptXor(hp1);
  14637. {$endif x86_64}
  14638. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14639. end
  14640. else
  14641. begin
  14642. Result := PostPeepholeOptMov(hp1);
  14643. {$ifdef x86_64}
  14644. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14645. { Used to shrink instruction size }
  14646. PostPeepholeOptXor(hp1);
  14647. {$endif x86_64}
  14648. end;
  14649. end;
  14650. { Enabling this flag is actually a null operation, but it marks
  14651. the code as 'modified' during this pass }
  14652. Include(OptsToCheck, aoc_ForceNewIteration);
  14653. end;
  14654. { If x is a power of 2 (popcnt = 1), change:
  14655. or $x, %reg/ref
  14656. To:
  14657. bts lb(x), %reg/ref
  14658. }
  14659. if (taicpu(p).opcode = A_OR) and
  14660. IsBTXAcceptable(p) and
  14661. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14662. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14663. (
  14664. { Don't optimise if a test instruction follows }
  14665. not GetNextInstruction(p, hp1) or
  14666. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14667. ) then
  14668. begin
  14669. 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);
  14670. taicpu(p).opcode := A_BTS;
  14671. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14672. Result := True;
  14673. Exit;
  14674. end;
  14675. { If x is a power of 2 (popcnt = 1), change:
  14676. test $x, %reg/ref
  14677. je / sete / cmove (or jne / setne)
  14678. To:
  14679. bt lb(x), %reg/ref
  14680. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14681. }
  14682. if (taicpu(p).opcode = A_TEST) and
  14683. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14684. (taicpu(p).oper[0]^.typ = top_const) and
  14685. (
  14686. (cs_opt_size in current_settings.optimizerswitches) or
  14687. (
  14688. (taicpu(p).oper[1]^.typ = top_reg) and
  14689. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14690. ) or
  14691. (
  14692. (taicpu(p).oper[1]^.typ <> top_reg) and
  14693. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14694. )
  14695. ) and
  14696. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14697. { For sizes less than S_L, the byte size is equal or larger with BT,
  14698. so don't bother optimising }
  14699. (taicpu(p).opsize >= S_L) then
  14700. begin
  14701. IsValid := True;
  14702. { Check the next set of instructions, watching the FLAGS register
  14703. and the conditions used }
  14704. TransferUsedRegs(TmpUsedRegs);
  14705. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14706. hp1 := p;
  14707. hp2 := nil;
  14708. while GetNextInstruction(hp1, hp1) do
  14709. begin
  14710. if not Assigned(hp2) then
  14711. { The first instruction after TEST }
  14712. hp2 := hp1;
  14713. if (hp1.typ <> ait_instruction) then
  14714. begin
  14715. { If the flags are no longer in use, everything is fine }
  14716. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14717. IsValid := False;
  14718. Break;
  14719. end;
  14720. case taicpu(hp1).condition of
  14721. C_None:
  14722. begin
  14723. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14724. { Something is not quite normal, so play safe and don't change }
  14725. IsValid := False;
  14726. Break;
  14727. end;
  14728. C_E, C_Z, C_NE, C_NZ:
  14729. { This is fine };
  14730. else
  14731. begin
  14732. { Unsupported condition }
  14733. IsValid := False;
  14734. Break;
  14735. end;
  14736. end;
  14737. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14738. end;
  14739. if IsValid then
  14740. begin
  14741. while hp2 <> hp1 do
  14742. begin
  14743. case taicpu(hp2).condition of
  14744. C_Z, C_E:
  14745. taicpu(hp2).condition := C_NC;
  14746. C_NZ, C_NE:
  14747. taicpu(hp2).condition := C_C;
  14748. else
  14749. { Should not get this by this point }
  14750. InternalError(2022110701);
  14751. end;
  14752. GetNextInstruction(hp2, hp2);
  14753. end;
  14754. 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);
  14755. taicpu(p).opcode := A_BT;
  14756. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14757. Result := True;
  14758. Exit;
  14759. end;
  14760. end;
  14761. { removes the line marked with (x) from the sequence
  14762. and/or/xor/add/sub/... $x, %y
  14763. test/or %y, %y | test $-1, %y (x)
  14764. j(n)z _Label
  14765. as the first instruction already adjusts the ZF
  14766. %y operand may also be a reference }
  14767. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14768. MatchOperand(taicpu(p).oper[0]^,-1);
  14769. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14770. GetLastInstruction(p, hp1) and
  14771. (tai(hp1).typ = ait_instruction) and
  14772. GetNextInstruction(p,hp2) and
  14773. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14774. case taicpu(hp1).opcode Of
  14775. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14776. { These two instructions set the zero flag if the result is zero }
  14777. A_POPCNT, A_LZCNT:
  14778. begin
  14779. if (
  14780. { With POPCNT, an input of zero will set the zero flag
  14781. because the population count of zero is zero }
  14782. (taicpu(hp1).opcode = A_POPCNT) and
  14783. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14784. (
  14785. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14786. { Faster than going through the second half of the 'or'
  14787. condition below }
  14788. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14789. )
  14790. ) or (
  14791. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14792. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14793. { and in case of carry for A(E)/B(E)/C/NC }
  14794. (
  14795. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14796. (
  14797. (taicpu(hp1).opcode <> A_ADD) and
  14798. (taicpu(hp1).opcode <> A_SUB) and
  14799. (taicpu(hp1).opcode <> A_LZCNT)
  14800. )
  14801. )
  14802. ) then
  14803. begin
  14804. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14805. RemoveCurrentP(p, hp2);
  14806. Result:=true;
  14807. Exit;
  14808. end;
  14809. end;
  14810. A_SHL, A_SAL, A_SHR, A_SAR:
  14811. begin
  14812. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14813. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14814. { therefore, it's only safe to do this optimization for }
  14815. { shifts by a (nonzero) constant }
  14816. (taicpu(hp1).oper[0]^.typ = top_const) and
  14817. (taicpu(hp1).oper[0]^.val <> 0) and
  14818. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14819. { and in case of carry for A(E)/B(E)/C/NC }
  14820. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14821. begin
  14822. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14823. RemoveCurrentP(p, hp2);
  14824. Result:=true;
  14825. Exit;
  14826. end;
  14827. end;
  14828. A_DEC, A_INC, A_NEG:
  14829. begin
  14830. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14831. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14832. { and in case of carry for A(E)/B(E)/C/NC }
  14833. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14834. begin
  14835. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14836. RemoveCurrentP(p, hp2);
  14837. Result:=true;
  14838. Exit;
  14839. end;
  14840. end;
  14841. A_ANDN, A_BZHI:
  14842. begin
  14843. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14844. { Only the zero and sign flags are consistent with what the result is }
  14845. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14846. begin
  14847. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14848. RemoveCurrentP(p, hp2);
  14849. Result:=true;
  14850. Exit;
  14851. end;
  14852. end;
  14853. A_BEXTR:
  14854. begin
  14855. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14856. { Only the zero flag is set }
  14857. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14858. begin
  14859. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14860. RemoveCurrentP(p, hp2);
  14861. Result:=true;
  14862. Exit;
  14863. end;
  14864. end;
  14865. else
  14866. ;
  14867. end; { case }
  14868. { change "test $-1,%reg" into "test %reg,%reg" }
  14869. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14870. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14871. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14872. if MatchInstruction(p, A_OR, []) and
  14873. { Can only match if they're both registers }
  14874. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14875. begin
  14876. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14877. taicpu(p).opcode := A_TEST;
  14878. { No need to set Result to True, as we've done all the optimisations we can }
  14879. end;
  14880. end;
  14881. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14882. var
  14883. hp1,hp3 : tai;
  14884. {$ifndef x86_64}
  14885. hp2 : taicpu;
  14886. {$endif x86_64}
  14887. begin
  14888. Result:=false;
  14889. hp3:=nil;
  14890. {$ifndef x86_64}
  14891. { don't do this on modern CPUs, this really hurts them due to
  14892. broken call/ret pairing }
  14893. if (current_settings.optimizecputype < cpu_Pentium2) and
  14894. not(cs_create_pic in current_settings.moduleswitches) and
  14895. GetNextInstruction(p, hp1) and
  14896. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14897. MatchOpType(taicpu(hp1),top_ref) and
  14898. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14899. begin
  14900. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14901. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14902. InsertLLItem(p.previous, p, hp2);
  14903. taicpu(p).opcode := A_JMP;
  14904. taicpu(p).is_jmp := true;
  14905. RemoveInstruction(hp1);
  14906. Result:=true;
  14907. end
  14908. else
  14909. {$endif x86_64}
  14910. { replace
  14911. call procname
  14912. ret
  14913. by
  14914. jmp procname
  14915. but do it only on level 4 because it destroys stack back traces
  14916. else if the subroutine is marked as no return, remove the ret
  14917. }
  14918. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14919. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14920. GetNextInstruction(p, hp1) and
  14921. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14922. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14923. SetAndTest(hp1,hp3) and
  14924. GetNextInstruction(hp1,hp1) and
  14925. MatchInstruction(hp1,A_RET,[S_NO])
  14926. )
  14927. ) and
  14928. (taicpu(hp1).ops=0) then
  14929. begin
  14930. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14931. { we might destroy stack alignment here if we do not do a call }
  14932. (target_info.stackalign<=sizeof(SizeUInt)) then
  14933. begin
  14934. taicpu(p).opcode := A_JMP;
  14935. taicpu(p).is_jmp := true;
  14936. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14937. end
  14938. else
  14939. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14940. RemoveInstruction(hp1);
  14941. if Assigned(hp3) then
  14942. begin
  14943. AsmL.Remove(hp3);
  14944. AsmL.InsertBefore(hp3,p)
  14945. end;
  14946. Result:=true;
  14947. end;
  14948. end;
  14949. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14950. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14951. begin
  14952. case OpSize of
  14953. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14954. Result := (Val <= $FF) and (Val >= -128);
  14955. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14956. Result := (Val <= $FFFF) and (Val >= -32768);
  14957. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14958. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14959. else
  14960. Result := True;
  14961. end;
  14962. end;
  14963. var
  14964. hp1, hp2 : tai;
  14965. SizeChange: Boolean;
  14966. PreMessage: string;
  14967. begin
  14968. Result := False;
  14969. if (taicpu(p).oper[0]^.typ = top_reg) and
  14970. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14971. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14972. begin
  14973. { Change (using movzbl %al,%eax as an example):
  14974. movzbl %al, %eax movzbl %al, %eax
  14975. cmpl x, %eax testl %eax,%eax
  14976. To:
  14977. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14978. movzbl %al, %eax movzbl %al, %eax
  14979. Smaller instruction and minimises pipeline stall as the CPU
  14980. doesn't have to wait for the register to get zero-extended. [Kit]
  14981. Also allow if the smaller of the two registers is being checked,
  14982. as this still removes the false dependency.
  14983. }
  14984. if
  14985. (
  14986. (
  14987. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14988. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14989. ) or (
  14990. { If MatchOperand returns True, they must both be registers }
  14991. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14992. )
  14993. ) and
  14994. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14995. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14996. begin
  14997. 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);
  14998. asml.Remove(hp1);
  14999. asml.InsertBefore(hp1, p);
  15000. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15001. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15002. begin
  15003. taicpu(hp1).opcode := A_TEST;
  15004. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15005. end;
  15006. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15007. case taicpu(p).opsize of
  15008. S_BW, S_BL:
  15009. begin
  15010. SizeChange := taicpu(hp1).opsize <> S_B;
  15011. taicpu(hp1).changeopsize(S_B);
  15012. end;
  15013. S_WL:
  15014. begin
  15015. SizeChange := taicpu(hp1).opsize <> S_W;
  15016. taicpu(hp1).changeopsize(S_W);
  15017. end
  15018. else
  15019. InternalError(2020112701);
  15020. end;
  15021. UpdateUsedRegs(tai(p.Next));
  15022. { Check if the register is used aferwards - if not, we can
  15023. remove the movzx instruction completely }
  15024. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15025. begin
  15026. { Hp1 is a better position than p for debugging purposes }
  15027. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15028. RemoveCurrentp(p, hp1);
  15029. Result := True;
  15030. end;
  15031. if SizeChange then
  15032. DebugMsg(SPeepholeOptimization + PreMessage +
  15033. 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)
  15034. else
  15035. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15036. Exit;
  15037. end;
  15038. { Change (using movzwl %ax,%eax as an example):
  15039. movzwl %ax, %eax
  15040. movb %al, (dest) (Register is smaller than read register in movz)
  15041. To:
  15042. movb %al, (dest) (Move one back to avoid a false dependency)
  15043. movzwl %ax, %eax
  15044. }
  15045. if (taicpu(hp1).opcode = A_MOV) and
  15046. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15047. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15048. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15049. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15050. begin
  15051. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15052. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15053. asml.Remove(hp1);
  15054. asml.InsertBefore(hp1, p);
  15055. if taicpu(hp1).oper[1]^.typ = top_reg then
  15056. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15057. { Check if the register is used aferwards - if not, we can
  15058. remove the movzx instruction completely }
  15059. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15060. begin
  15061. { Hp1 is a better position than p for debugging purposes }
  15062. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15063. RemoveCurrentp(p, hp1);
  15064. Result := True;
  15065. end;
  15066. Exit;
  15067. end;
  15068. end;
  15069. end;
  15070. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15071. var
  15072. hp1: tai;
  15073. {$ifdef x86_64}
  15074. PreMessage, RegName: string;
  15075. {$endif x86_64}
  15076. begin
  15077. Result := False;
  15078. { If x is a power of 2 (popcnt = 1), change:
  15079. xor $x, %reg/ref
  15080. To:
  15081. btc lb(x), %reg/ref
  15082. }
  15083. if IsBTXAcceptable(p) and
  15084. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15085. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15086. (
  15087. { Don't optimise if a test instruction follows }
  15088. not GetNextInstruction(p, hp1) or
  15089. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15090. ) then
  15091. begin
  15092. 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);
  15093. taicpu(p).opcode := A_BTC;
  15094. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15095. Result := True;
  15096. Exit;
  15097. end;
  15098. {$ifdef x86_64}
  15099. { Code size reduction by J. Gareth "Kit" Moreton }
  15100. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15101. as this removes the REX prefix }
  15102. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15103. Exit;
  15104. if taicpu(p).oper[0]^.typ <> top_reg then
  15105. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15106. InternalError(2018011500);
  15107. case taicpu(p).opsize of
  15108. S_Q:
  15109. begin
  15110. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15111. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15112. { The actual optimization }
  15113. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15114. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15115. taicpu(p).changeopsize(S_L);
  15116. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15117. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15118. end;
  15119. else
  15120. ;
  15121. end;
  15122. {$endif x86_64}
  15123. end;
  15124. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15125. var
  15126. XReg: TRegister;
  15127. begin
  15128. Result := False;
  15129. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15130. Smaller encoding and slightly faster on some platforms (also works for
  15131. ZMM-sized registers) }
  15132. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15133. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15134. begin
  15135. XReg := taicpu(p).oper[0]^.reg;
  15136. if (taicpu(p).oper[1]^.reg = XReg) then
  15137. begin
  15138. taicpu(p).changeopsize(S_XMM);
  15139. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15140. if (cs_opt_size in current_settings.optimizerswitches) then
  15141. begin
  15142. { Change input registers to %xmm0 to reduce size. Note that
  15143. there's a risk of a false dependency doing this, so only
  15144. optimise for size here }
  15145. XReg := NR_XMM0;
  15146. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15147. end
  15148. else
  15149. begin
  15150. setsubreg(XReg, R_SUBMMX);
  15151. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15152. end;
  15153. taicpu(p).oper[0]^.reg := XReg;
  15154. taicpu(p).oper[1]^.reg := XReg;
  15155. Result := True;
  15156. end;
  15157. end;
  15158. end;
  15159. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15160. var
  15161. OperIdx: Integer;
  15162. begin
  15163. for OperIdx := 0 to p.ops - 1 do
  15164. if p.oper[OperIdx]^.typ = top_ref then
  15165. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15166. end;
  15167. end.