aoptx86.pas 740 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  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 IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2916. { remove mov reg1,reg1? }
  2917. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2918. then
  2919. begin
  2920. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2921. { take care of the register (de)allocs following p }
  2922. RemoveCurrentP(p, hp1);
  2923. Result:=true;
  2924. exit;
  2925. end;
  2926. { All the next optimisations require a next instruction }
  2927. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2928. Exit;
  2929. { Prevent compiler warnings }
  2930. p_TargetReg := NR_NO;
  2931. if taicpu(p).oper[1]^.typ = top_reg then
  2932. begin
  2933. { Saves on a large number of dereferences }
  2934. p_TargetReg := taicpu(p).oper[1]^.reg;
  2935. { Look for:
  2936. mov %reg1,%reg2
  2937. ??? %reg2,r/m
  2938. Change to:
  2939. mov %reg1,%reg2
  2940. ??? %reg1,r/m
  2941. }
  2942. if taicpu(p).oper[0]^.typ = top_reg then
  2943. begin
  2944. if RegReadByInstruction(p_TargetReg, hp1) and
  2945. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2946. begin
  2947. { A change has occurred, just not in p }
  2948. Result := True;
  2949. TransferUsedRegs(TmpUsedRegs);
  2950. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2951. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2952. { Just in case something didn't get modified (e.g. an
  2953. implicit register) }
  2954. not RegReadByInstruction(p_TargetReg, hp1) then
  2955. begin
  2956. { We can remove the original MOV }
  2957. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2958. RemoveCurrentp(p, hp1);
  2959. { UsedRegs got updated by RemoveCurrentp }
  2960. Result := True;
  2961. Exit;
  2962. end;
  2963. { If we know a MOV instruction has become a null operation, we might as well
  2964. get rid of it now to save time. }
  2965. if (taicpu(hp1).opcode = A_MOV) and
  2966. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2967. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2968. { Just being a register is enough to confirm it's a null operation }
  2969. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2970. begin
  2971. Result := True;
  2972. { Speed-up to reduce a pipeline stall... if we had something like...
  2973. movl %eax,%edx
  2974. movw %dx,%ax
  2975. ... the second instruction would change to movw %ax,%ax, but
  2976. given that it is now %ax that's active rather than %eax,
  2977. penalties might occur due to a partial register write, so instead,
  2978. change it to a MOVZX instruction when optimising for speed.
  2979. }
  2980. if not (cs_opt_size in current_settings.optimizerswitches) and
  2981. IsMOVZXAcceptable and
  2982. (taicpu(hp1).opsize < taicpu(p).opsize)
  2983. {$ifdef x86_64}
  2984. { operations already implicitly set the upper 64 bits to zero }
  2985. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2986. {$endif x86_64}
  2987. then
  2988. begin
  2989. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2990. case taicpu(p).opsize of
  2991. S_W:
  2992. if taicpu(hp1).opsize = S_B then
  2993. taicpu(hp1).opsize := S_BL
  2994. else
  2995. InternalError(2020012911);
  2996. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2997. case taicpu(hp1).opsize of
  2998. S_B:
  2999. taicpu(hp1).opsize := S_BL;
  3000. S_W:
  3001. taicpu(hp1).opsize := S_WL;
  3002. else
  3003. InternalError(2020012912);
  3004. end;
  3005. else
  3006. InternalError(2020012910);
  3007. end;
  3008. taicpu(hp1).opcode := A_MOVZX;
  3009. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3010. end
  3011. else
  3012. begin
  3013. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3014. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3015. RemoveInstruction(hp1);
  3016. { The instruction after what was hp1 is now the immediate next instruction,
  3017. so we can continue to make optimisations if it's present }
  3018. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3019. Exit;
  3020. hp1 := hp2;
  3021. end;
  3022. end;
  3023. end;
  3024. end;
  3025. end;
  3026. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3027. overwrites the original destination register. e.g.
  3028. movl ###,%reg2d
  3029. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3030. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3031. }
  3032. if (taicpu(p).oper[1]^.typ = top_reg) and
  3033. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3034. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3035. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3036. begin
  3037. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3038. begin
  3039. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3040. case taicpu(p).oper[0]^.typ of
  3041. top_const:
  3042. { We have something like:
  3043. movb $x, %regb
  3044. movzbl %regb,%regd
  3045. Change to:
  3046. movl $x, %regd
  3047. }
  3048. begin
  3049. case taicpu(hp1).opsize of
  3050. S_BW:
  3051. begin
  3052. convert_mov_value(A_MOVSX, $FF);
  3053. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3054. taicpu(p).opsize := S_W;
  3055. end;
  3056. S_BL:
  3057. begin
  3058. convert_mov_value(A_MOVSX, $FF);
  3059. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3060. taicpu(p).opsize := S_L;
  3061. end;
  3062. S_WL:
  3063. begin
  3064. convert_mov_value(A_MOVSX, $FFFF);
  3065. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3066. taicpu(p).opsize := S_L;
  3067. end;
  3068. {$ifdef x86_64}
  3069. S_BQ:
  3070. begin
  3071. convert_mov_value(A_MOVSX, $FF);
  3072. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3073. taicpu(p).opsize := S_Q;
  3074. end;
  3075. S_WQ:
  3076. begin
  3077. convert_mov_value(A_MOVSX, $FFFF);
  3078. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3079. taicpu(p).opsize := S_Q;
  3080. end;
  3081. S_LQ:
  3082. begin
  3083. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3084. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3085. taicpu(p).opsize := S_Q;
  3086. end;
  3087. {$endif x86_64}
  3088. else
  3089. { If hp1 was a MOV instruction, it should have been
  3090. optimised already }
  3091. InternalError(2020021001);
  3092. end;
  3093. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3094. RemoveInstruction(hp1);
  3095. Result := True;
  3096. Exit;
  3097. end;
  3098. top_ref:
  3099. begin
  3100. { We have something like:
  3101. movb mem, %regb
  3102. movzbl %regb,%regd
  3103. Change to:
  3104. movzbl mem, %regd
  3105. }
  3106. ThisRef := taicpu(p).oper[0]^.ref^;
  3107. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3108. begin
  3109. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3110. taicpu(hp1).loadref(0, ThisRef);
  3111. { Make sure any registers in the references are properly tracked }
  3112. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  3113. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  3114. if (ThisRef.index <> NR_NO) then
  3115. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  3116. RemoveCurrentP(p, hp1);
  3117. Result := True;
  3118. Exit;
  3119. end;
  3120. end;
  3121. else
  3122. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3123. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3124. Exit;
  3125. end;
  3126. end
  3127. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3128. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3129. optimised }
  3130. else
  3131. begin
  3132. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3133. RemoveCurrentP(p, hp1);
  3134. Result := True;
  3135. Exit;
  3136. end;
  3137. end;
  3138. if (taicpu(hp1).opcode = A_AND) and
  3139. (taicpu(p).oper[1]^.typ = top_reg) and
  3140. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3141. begin
  3142. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3143. begin
  3144. case taicpu(p).opsize of
  3145. S_L:
  3146. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3147. begin
  3148. { Optimize out:
  3149. mov x, %reg
  3150. and ffffffffh, %reg
  3151. }
  3152. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3153. RemoveInstruction(hp1);
  3154. Result:=true;
  3155. exit;
  3156. end;
  3157. S_Q: { TODO: Confirm if this is even possible }
  3158. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3159. begin
  3160. { Optimize out:
  3161. mov x, %reg
  3162. and ffffffffffffffffh, %reg
  3163. }
  3164. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3165. RemoveInstruction(hp1);
  3166. Result:=true;
  3167. exit;
  3168. end;
  3169. else
  3170. ;
  3171. end;
  3172. if (
  3173. (taicpu(p).oper[0]^.typ=top_reg) or
  3174. (
  3175. (taicpu(p).oper[0]^.typ=top_ref) and
  3176. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3177. )
  3178. ) and
  3179. GetNextInstruction(hp1,hp2) and
  3180. MatchInstruction(hp2,A_TEST,[]) and
  3181. (
  3182. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3183. (
  3184. { If the register being tested is smaller than the one
  3185. that received a bitwise AND, permit it if the constant
  3186. fits into the smaller size }
  3187. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3188. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3189. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3190. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3191. (
  3192. (
  3193. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3194. (taicpu(hp1).oper[0]^.val <= $FF)
  3195. ) or
  3196. (
  3197. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3198. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3199. {$ifdef x86_64}
  3200. ) or
  3201. (
  3202. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3203. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3204. {$endif x86_64}
  3205. )
  3206. )
  3207. )
  3208. ) and
  3209. (
  3210. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3211. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3212. ) and
  3213. GetNextInstruction(hp2,hp3) and
  3214. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3215. (taicpu(hp3).condition in [C_E,C_NE]) then
  3216. begin
  3217. TransferUsedRegs(TmpUsedRegs);
  3218. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3219. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3220. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3221. begin
  3222. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3223. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3224. taicpu(hp1).opcode:=A_TEST;
  3225. { Shrink the TEST instruction down to the smallest possible size }
  3226. case taicpu(hp1).oper[0]^.val of
  3227. 0..255:
  3228. if (taicpu(hp1).opsize <> S_B)
  3229. {$ifndef x86_64}
  3230. and (
  3231. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3232. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3233. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3234. )
  3235. {$endif x86_64}
  3236. then
  3237. begin
  3238. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3239. { Only print debug message if the TEST instruction
  3240. is a different size before and after }
  3241. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3242. taicpu(hp1).opsize := S_B;
  3243. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3244. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3245. end;
  3246. 256..65535:
  3247. if (taicpu(hp1).opsize <> S_W) then
  3248. begin
  3249. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3250. { Only print debug message if the TEST instruction
  3251. is a different size before and after }
  3252. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3253. taicpu(hp1).opsize := S_W;
  3254. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3255. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3256. end;
  3257. {$ifdef x86_64}
  3258. 65536..$7FFFFFFF:
  3259. if (taicpu(hp1).opsize <> S_L) then
  3260. begin
  3261. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3262. { Only print debug message if the TEST instruction
  3263. is a different size before and after }
  3264. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3265. taicpu(hp1).opsize := S_L;
  3266. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3267. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3268. end;
  3269. {$endif x86_64}
  3270. else
  3271. ;
  3272. end;
  3273. RemoveInstruction(hp2);
  3274. RemoveCurrentP(p, hp1);
  3275. Result:=true;
  3276. exit;
  3277. end;
  3278. end;
  3279. end
  3280. else if IsMOVZXAcceptable and
  3281. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3282. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3283. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3284. then
  3285. begin
  3286. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3287. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3288. case taicpu(p).opsize of
  3289. S_B:
  3290. if (taicpu(hp1).oper[0]^.val = $ff) then
  3291. begin
  3292. { Convert:
  3293. movb x, %regl movb x, %regl
  3294. andw ffh, %regw andl ffh, %regd
  3295. To:
  3296. movzbw x, %regd movzbl x, %regd
  3297. (Identical registers, just different sizes)
  3298. }
  3299. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3300. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3301. case taicpu(hp1).opsize of
  3302. S_W: NewSize := S_BW;
  3303. S_L: NewSize := S_BL;
  3304. {$ifdef x86_64}
  3305. S_Q: NewSize := S_BQ;
  3306. {$endif x86_64}
  3307. else
  3308. InternalError(2018011510);
  3309. end;
  3310. end
  3311. else
  3312. NewSize := S_NO;
  3313. S_W:
  3314. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3315. begin
  3316. { Convert:
  3317. movw x, %regw
  3318. andl ffffh, %regd
  3319. To:
  3320. movzwl x, %regd
  3321. (Identical registers, just different sizes)
  3322. }
  3323. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3324. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3325. case taicpu(hp1).opsize of
  3326. S_L: NewSize := S_WL;
  3327. {$ifdef x86_64}
  3328. S_Q: NewSize := S_WQ;
  3329. {$endif x86_64}
  3330. else
  3331. InternalError(2018011511);
  3332. end;
  3333. end
  3334. else
  3335. NewSize := S_NO;
  3336. else
  3337. NewSize := S_NO;
  3338. end;
  3339. if NewSize <> S_NO then
  3340. begin
  3341. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3342. { The actual optimization }
  3343. taicpu(p).opcode := A_MOVZX;
  3344. taicpu(p).changeopsize(NewSize);
  3345. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3346. { Safeguard if "and" is followed by a conditional command }
  3347. TransferUsedRegs(TmpUsedRegs);
  3348. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3349. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3350. begin
  3351. { At this point, the "and" command is effectively equivalent to
  3352. "test %reg,%reg". This will be handled separately by the
  3353. Peephole Optimizer. [Kit] }
  3354. DebugMsg(SPeepholeOptimization + PreMessage +
  3355. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3356. end
  3357. else
  3358. begin
  3359. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3360. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3361. RemoveInstruction(hp1);
  3362. end;
  3363. Result := True;
  3364. Exit;
  3365. end;
  3366. end;
  3367. end;
  3368. if (taicpu(hp1).opcode = A_OR) and
  3369. (taicpu(p).oper[1]^.typ = top_reg) and
  3370. MatchOperand(taicpu(p).oper[0]^, 0) and
  3371. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3372. begin
  3373. { mov 0, %reg
  3374. or ###,%reg
  3375. Change to (only if the flags are not used):
  3376. mov ###,%reg
  3377. }
  3378. TransferUsedRegs(TmpUsedRegs);
  3379. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3380. DoOptimisation := True;
  3381. { Even if the flags are used, we might be able to do the optimisation
  3382. if the conditions are predictable }
  3383. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3384. begin
  3385. { Only perform if ### = %reg (the same register) or equal to 0,
  3386. so %reg is guaranteed to still have a value of zero }
  3387. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3388. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3389. begin
  3390. hp2 := hp1;
  3391. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3392. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3393. GetNextInstruction(hp2, hp3) do
  3394. begin
  3395. { Don't continue modifying if the flags state is getting changed }
  3396. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3397. Break;
  3398. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3399. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3400. begin
  3401. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3402. begin
  3403. { Condition is always true }
  3404. case taicpu(hp3).opcode of
  3405. A_Jcc:
  3406. begin
  3407. { Check for jump shortcuts before we destroy the condition }
  3408. hp4 := hp3;
  3409. DoJumpOptimizations(hp3, TempBool);
  3410. { Make sure hp3 hasn't changed }
  3411. if (hp4 = hp3) then
  3412. begin
  3413. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3414. MakeUnconditional(taicpu(hp3));
  3415. end;
  3416. Result := True;
  3417. end;
  3418. A_CMOVcc:
  3419. begin
  3420. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3421. taicpu(hp3).opcode := A_MOV;
  3422. taicpu(hp3).condition := C_None;
  3423. Result := True;
  3424. end;
  3425. A_SETcc:
  3426. begin
  3427. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3428. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3429. taicpu(hp3).opcode := A_MOV;
  3430. taicpu(hp3).ops := 2;
  3431. taicpu(hp3).condition := C_None;
  3432. taicpu(hp3).opsize := S_B;
  3433. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3434. taicpu(hp3).loadconst(0, 1);
  3435. Result := True;
  3436. end;
  3437. else
  3438. InternalError(2021090701);
  3439. end;
  3440. end
  3441. 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
  3442. begin
  3443. { Condition is always false }
  3444. case taicpu(hp3).opcode of
  3445. A_Jcc:
  3446. begin
  3447. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3448. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3449. RemoveInstruction(hp3);
  3450. Result := True;
  3451. { Since hp3 was deleted, hp2 must not be updated }
  3452. Continue;
  3453. end;
  3454. A_CMOVcc:
  3455. begin
  3456. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3457. RemoveInstruction(hp3);
  3458. Result := True;
  3459. { Since hp3 was deleted, hp2 must not be updated }
  3460. Continue;
  3461. end;
  3462. A_SETcc:
  3463. begin
  3464. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3465. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3466. taicpu(hp3).opcode := A_MOV;
  3467. taicpu(hp3).ops := 2;
  3468. taicpu(hp3).condition := C_None;
  3469. taicpu(hp3).opsize := S_B;
  3470. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3471. taicpu(hp3).loadconst(0, 0);
  3472. Result := True;
  3473. end;
  3474. else
  3475. InternalError(2021090702);
  3476. end;
  3477. end
  3478. else
  3479. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3480. DoOptimisation := False;
  3481. end;
  3482. hp2 := hp3;
  3483. end;
  3484. { Flags are still in use - don't optimise }
  3485. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3486. DoOptimisation := False;
  3487. end
  3488. else
  3489. DoOptimisation := False;
  3490. end;
  3491. if DoOptimisation then
  3492. begin
  3493. {$ifdef x86_64}
  3494. { OR only supports 32-bit sign-extended constants for 64-bit
  3495. instructions, so compensate for this if the constant is
  3496. encoded as a value greater than or equal to 2^31 }
  3497. if (taicpu(hp1).opsize = S_Q) and
  3498. (taicpu(hp1).oper[0]^.typ = top_const) and
  3499. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3500. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3501. {$endif x86_64}
  3502. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3503. taicpu(hp1).opcode := A_MOV;
  3504. RemoveCurrentP(p, hp1);
  3505. Result := True;
  3506. Exit;
  3507. end;
  3508. end;
  3509. { Next instruction is also a MOV ? }
  3510. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3511. begin
  3512. if MatchOpType(taicpu(p), top_const, top_ref) and
  3513. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3514. TryConstMerge(p, hp1) then
  3515. begin
  3516. Result := True;
  3517. { In case we have four byte writes in a row, check for 2 more
  3518. right now so we don't have to wait for another iteration of
  3519. pass 1
  3520. }
  3521. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3522. case taicpu(p).opsize of
  3523. S_W:
  3524. begin
  3525. if GetNextInstruction(p, hp1) and
  3526. MatchInstruction(hp1, A_MOV, [S_B]) and
  3527. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3528. GetNextInstruction(hp1, hp2) and
  3529. MatchInstruction(hp2, A_MOV, [S_B]) and
  3530. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3531. { Try to merge the two bytes }
  3532. TryConstMerge(hp1, hp2) then
  3533. { Now try to merge the two words (hp2 will get deleted) }
  3534. TryConstMerge(p, hp1);
  3535. end;
  3536. S_L:
  3537. begin
  3538. { Though this only really benefits x86_64 and not i386, it
  3539. gets a potential optimisation done faster and hence
  3540. reduces the number of times OptPass1MOV is entered }
  3541. if GetNextInstruction(p, hp1) and
  3542. MatchInstruction(hp1, A_MOV, [S_W]) and
  3543. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3544. GetNextInstruction(hp1, hp2) and
  3545. MatchInstruction(hp2, A_MOV, [S_W]) and
  3546. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3547. { Try to merge the two words }
  3548. TryConstMerge(hp1, hp2) then
  3549. { This will always fail on i386, so don't bother
  3550. calling it unless we're doing x86_64 }
  3551. {$ifdef x86_64}
  3552. { Now try to merge the two longwords (hp2 will get deleted) }
  3553. TryConstMerge(p, hp1)
  3554. {$endif x86_64}
  3555. ;
  3556. end;
  3557. else
  3558. ;
  3559. end;
  3560. Exit;
  3561. end;
  3562. if (taicpu(p).oper[1]^.typ = top_reg) and
  3563. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3564. begin
  3565. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3566. TransferUsedRegs(TmpUsedRegs);
  3567. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3568. { we have
  3569. mov x, %treg
  3570. mov %treg, y
  3571. }
  3572. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3573. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3574. { we've got
  3575. mov x, %treg
  3576. mov %treg, y
  3577. with %treg is not used after }
  3578. case taicpu(p).oper[0]^.typ Of
  3579. { top_reg is covered by DeepMOVOpt }
  3580. top_const:
  3581. begin
  3582. { change
  3583. mov const, %treg
  3584. mov %treg, y
  3585. to
  3586. mov const, y
  3587. }
  3588. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3589. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3590. begin
  3591. if taicpu(hp1).oper[1]^.typ=top_reg then
  3592. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3593. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3594. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3595. RemoveInstruction(hp1);
  3596. Result:=true;
  3597. Exit;
  3598. end;
  3599. end;
  3600. top_ref:
  3601. case taicpu(hp1).oper[1]^.typ of
  3602. top_reg:
  3603. begin
  3604. { change
  3605. mov mem, %treg
  3606. mov %treg, %reg
  3607. to
  3608. mov mem, %reg"
  3609. }
  3610. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3611. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3612. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3613. RemoveInstruction(hp1);
  3614. Result:=true;
  3615. Exit;
  3616. end;
  3617. top_ref:
  3618. begin
  3619. {$ifdef x86_64}
  3620. { Look for the following to simplify:
  3621. mov x(mem1), %reg
  3622. mov %reg, y(mem2)
  3623. mov x+8(mem1), %reg
  3624. mov %reg, y+8(mem2)
  3625. Change to:
  3626. movdqu x(mem1), %xmmreg
  3627. movdqu %xmmreg, y(mem2)
  3628. ...but only as long as the memory blocks don't overlap
  3629. }
  3630. SourceRef := taicpu(p).oper[0]^.ref^;
  3631. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3632. if (taicpu(p).opsize = S_Q) and
  3633. GetNextInstruction(hp1, hp2) and
  3634. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3635. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3636. begin
  3637. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3638. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3639. Inc(SourceRef.offset, 8);
  3640. if UseAVX then
  3641. begin
  3642. MovAligned := A_VMOVDQA;
  3643. MovUnaligned := A_VMOVDQU;
  3644. end
  3645. else
  3646. begin
  3647. MovAligned := A_MOVDQA;
  3648. MovUnaligned := A_MOVDQU;
  3649. end;
  3650. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3651. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3652. begin
  3653. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3654. Inc(TargetRef.offset, 8);
  3655. if GetNextInstruction(hp2, hp3) and
  3656. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3657. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3658. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3659. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3660. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3661. begin
  3662. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3663. if NewMMReg <> NR_NO then
  3664. begin
  3665. { Remember that the offsets are 8 ahead }
  3666. if ((SourceRef.offset mod 16) = 8) and
  3667. (
  3668. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3669. (SourceRef.base = current_procinfo.framepointer) or
  3670. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3671. ) then
  3672. taicpu(p).opcode := MovAligned
  3673. else
  3674. taicpu(p).opcode := MovUnaligned;
  3675. taicpu(p).opsize := S_XMM;
  3676. taicpu(p).oper[1]^.reg := NewMMReg;
  3677. if ((TargetRef.offset mod 16) = 8) and
  3678. (
  3679. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3680. (TargetRef.base = current_procinfo.framepointer) or
  3681. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3682. ) then
  3683. taicpu(hp1).opcode := MovAligned
  3684. else
  3685. taicpu(hp1).opcode := MovUnaligned;
  3686. taicpu(hp1).opsize := S_XMM;
  3687. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3688. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3689. RemoveInstruction(hp2);
  3690. RemoveInstruction(hp3);
  3691. Result := True;
  3692. Exit;
  3693. end;
  3694. end;
  3695. end
  3696. else
  3697. begin
  3698. { See if the next references are 8 less rather than 8 greater }
  3699. Dec(SourceRef.offset, 16); { -8 the other way }
  3700. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3701. begin
  3702. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3703. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3704. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3705. GetNextInstruction(hp2, hp3) and
  3706. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3707. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3708. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3709. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3710. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3711. begin
  3712. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3713. if NewMMReg <> NR_NO then
  3714. begin
  3715. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3716. if ((SourceRef.offset mod 16) = 0) and
  3717. (
  3718. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3719. (SourceRef.base = current_procinfo.framepointer) or
  3720. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3721. ) then
  3722. taicpu(hp2).opcode := MovAligned
  3723. else
  3724. taicpu(hp2).opcode := MovUnaligned;
  3725. taicpu(hp2).opsize := S_XMM;
  3726. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3727. if ((TargetRef.offset mod 16) = 0) and
  3728. (
  3729. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3730. (TargetRef.base = current_procinfo.framepointer) or
  3731. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3732. ) then
  3733. taicpu(hp3).opcode := MovAligned
  3734. else
  3735. taicpu(hp3).opcode := MovUnaligned;
  3736. taicpu(hp3).opsize := S_XMM;
  3737. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3738. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3739. RemoveInstruction(hp1);
  3740. RemoveCurrentP(p, hp2);
  3741. Result := True;
  3742. Exit;
  3743. end;
  3744. end;
  3745. end;
  3746. end;
  3747. end;
  3748. {$endif x86_64}
  3749. end;
  3750. else
  3751. { The write target should be a reg or a ref }
  3752. InternalError(2021091601);
  3753. end;
  3754. else
  3755. ;
  3756. end
  3757. else
  3758. { %treg is used afterwards, but all eventualities
  3759. other than the first MOV instruction being a constant
  3760. are covered by DeepMOVOpt, so only check for that }
  3761. if (taicpu(p).oper[0]^.typ = top_const) and
  3762. (
  3763. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3764. not (cs_opt_size in current_settings.optimizerswitches) or
  3765. (taicpu(hp1).opsize = S_B)
  3766. ) and
  3767. (
  3768. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3769. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3770. ) then
  3771. begin
  3772. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3773. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3774. end;
  3775. end;
  3776. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3777. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3778. { mov reg1, mem1 or mov mem1, reg1
  3779. mov mem2, reg2 mov reg2, mem2}
  3780. begin
  3781. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3782. { mov reg1, mem1 or mov mem1, reg1
  3783. mov mem2, reg1 mov reg2, mem1}
  3784. begin
  3785. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3786. { Removes the second statement from
  3787. mov reg1, mem1/reg2
  3788. mov mem1/reg2, reg1 }
  3789. begin
  3790. if taicpu(p).oper[0]^.typ=top_reg then
  3791. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3792. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3793. RemoveInstruction(hp1);
  3794. Result:=true;
  3795. exit;
  3796. end
  3797. else
  3798. begin
  3799. TransferUsedRegs(TmpUsedRegs);
  3800. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3801. if (taicpu(p).oper[1]^.typ = top_ref) and
  3802. { mov reg1, mem1
  3803. mov mem2, reg1 }
  3804. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3805. GetNextInstruction(hp1, hp2) and
  3806. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3807. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3808. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3809. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3810. { change to
  3811. mov reg1, mem1 mov reg1, mem1
  3812. mov mem2, reg1 cmp reg1, mem2
  3813. cmp mem1, reg1
  3814. }
  3815. begin
  3816. RemoveInstruction(hp2);
  3817. taicpu(hp1).opcode := A_CMP;
  3818. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3819. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3821. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3822. end;
  3823. end;
  3824. end
  3825. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3826. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3827. begin
  3828. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3829. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3830. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3831. end
  3832. else
  3833. begin
  3834. TransferUsedRegs(TmpUsedRegs);
  3835. if GetNextInstruction(hp1, hp2) and
  3836. MatchOpType(taicpu(p),top_ref,top_reg) and
  3837. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3838. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3839. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3840. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3841. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3842. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3843. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3844. { mov mem1, %reg1
  3845. mov %reg1, mem2
  3846. mov mem2, reg2
  3847. to:
  3848. mov mem1, reg2
  3849. mov reg2, mem2}
  3850. begin
  3851. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3852. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3853. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3854. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3855. RemoveInstruction(hp2);
  3856. Result := True;
  3857. end
  3858. {$ifdef i386}
  3859. { this is enabled for i386 only, as the rules to create the reg sets below
  3860. are too complicated for x86-64, so this makes this code too error prone
  3861. on x86-64
  3862. }
  3863. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3864. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3865. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3866. { mov mem1, reg1 mov mem1, reg1
  3867. mov reg1, mem2 mov reg1, mem2
  3868. mov mem2, reg2 mov mem2, reg1
  3869. to: to:
  3870. mov mem1, reg1 mov mem1, reg1
  3871. mov mem1, reg2 mov reg1, mem2
  3872. mov reg1, mem2
  3873. or (if mem1 depends on reg1
  3874. and/or if mem2 depends on reg2)
  3875. to:
  3876. mov mem1, reg1
  3877. mov reg1, mem2
  3878. mov reg1, reg2
  3879. }
  3880. begin
  3881. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3882. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3883. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3884. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3885. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3886. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3887. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3888. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3889. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3890. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3891. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3892. end
  3893. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3894. begin
  3895. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3896. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3897. end
  3898. else
  3899. begin
  3900. RemoveInstruction(hp2);
  3901. end
  3902. {$endif i386}
  3903. ;
  3904. end;
  3905. end
  3906. { movl [mem1],reg1
  3907. movl [mem1],reg2
  3908. to
  3909. movl [mem1],reg1
  3910. movl reg1,reg2
  3911. }
  3912. else if not CheckMovMov2MovMov2(p, hp1) and
  3913. { movl const1,[mem1]
  3914. movl [mem1],reg1
  3915. to
  3916. movl const1,reg1
  3917. movl reg1,[mem1]
  3918. }
  3919. MatchOpType(Taicpu(p),top_const,top_ref) and
  3920. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3921. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3922. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3923. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3924. begin
  3925. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3926. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3927. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3928. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3929. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3930. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3931. Result:=true;
  3932. exit;
  3933. end;
  3934. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3935. { Change:
  3936. movl %reg1,%reg2
  3937. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3938. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3939. To:
  3940. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3941. movl x(%reg1),%reg1
  3942. movl %reg1,%regX
  3943. }
  3944. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3945. begin
  3946. p_SourceReg := taicpu(p).oper[0]^.reg;
  3947. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3948. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3949. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3950. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3951. GetNextInstruction(hp1, hp2) and
  3952. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3953. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3954. begin
  3955. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3956. if RegInRef(p_TargetReg, SourceRef) and
  3957. { If %reg1 also appears in the second reference, then it will
  3958. not refer to the same memory block as the first reference }
  3959. not RegInRef(p_SourceReg, SourceRef) then
  3960. begin
  3961. { Check to see if the references match if %reg2 is changed to %reg1 }
  3962. if SourceRef.base = p_TargetReg then
  3963. SourceRef.base := p_SourceReg;
  3964. if SourceRef.index = p_TargetReg then
  3965. SourceRef.index := p_SourceReg;
  3966. { RefsEqual also checks to ensure both references are non-volatile }
  3967. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3968. begin
  3969. taicpu(hp2).loadreg(0, p_SourceReg);
  3970. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3971. Result := True;
  3972. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3973. begin
  3974. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3975. RemoveCurrentP(p, hp1);
  3976. Exit;
  3977. end
  3978. else
  3979. begin
  3980. { Check to see if %reg2 is no longer in use }
  3981. TransferUsedRegs(TmpUsedRegs);
  3982. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3983. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3984. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3985. begin
  3986. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3987. RemoveCurrentP(p, hp1);
  3988. Exit;
  3989. end;
  3990. end;
  3991. { If we reach this point, p and hp1 weren't actually modified,
  3992. so we can do a bit more work on this pass }
  3993. end;
  3994. end;
  3995. end;
  3996. end;
  3997. end;
  3998. {$ifdef x86_64}
  3999. { Change:
  4000. movl %reg1l,%reg2l
  4001. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4002. To:
  4003. movl %reg1l,%reg2l
  4004. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4005. If %reg1 = %reg3, convert to:
  4006. movl %reg1l,%reg2l
  4007. andl %reg1l,%reg1l
  4008. }
  4009. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  4010. MatchOpType(taicpu(p), top_reg, top_reg) and
  4011. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  4012. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  4013. begin
  4014. TransferUsedRegs(TmpUsedRegs);
  4015. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4016. taicpu(hp1).opsize := S_L;
  4017. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  4018. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4019. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  4020. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  4021. begin
  4022. { %reg1 = %reg3 }
  4023. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  4024. taicpu(hp1).opcode := A_AND;
  4025. end
  4026. else
  4027. begin
  4028. { %reg1 <> %reg3 }
  4029. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  4030. end;
  4031. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4032. begin
  4033. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  4034. RemoveCurrentP(p, hp1);
  4035. Result := True;
  4036. Exit;
  4037. end
  4038. else
  4039. begin
  4040. { Initial instruction wasn't actually changed }
  4041. Include(OptsToCheck, aoc_ForceNewIteration);
  4042. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4043. appears below since %reg1 has technically changed }
  4044. if taicpu(hp1).opcode = A_AND then
  4045. Exit;
  4046. end;
  4047. end;
  4048. {$endif x86_64}
  4049. { search further than the next instruction for a mov (as long as it's not a jump) }
  4050. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4051. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4052. (taicpu(p).oper[1]^.typ = top_reg) and
  4053. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4054. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4055. begin
  4056. { we work with hp2 here, so hp1 can be still used later on when
  4057. checking for GetNextInstruction_p }
  4058. hp3 := hp1;
  4059. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4060. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4061. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4062. TransferUsedRegs(TmpUsedRegs);
  4063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4064. if NotFirstIteration then
  4065. JumpTracking := TLinkedList.Create
  4066. else
  4067. JumpTracking := nil;
  4068. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4069. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4070. (hp2.typ=ait_instruction) do
  4071. begin
  4072. case taicpu(hp2).opcode of
  4073. A_POP:
  4074. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4075. begin
  4076. if not CrossJump and
  4077. not RegUsedBetween(p_TargetReg, p, hp2) then
  4078. begin
  4079. { We can remove the original MOV since the register
  4080. wasn't used between it and its popping from the stack }
  4081. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4082. RemoveCurrentp(p, hp1);
  4083. Result := True;
  4084. JumpTracking.Free;
  4085. Exit;
  4086. end;
  4087. { Can't go any further }
  4088. Break;
  4089. end;
  4090. A_MOV:
  4091. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4092. ((taicpu(p).oper[0]^.typ=top_const) or
  4093. ((taicpu(p).oper[0]^.typ=top_reg) and
  4094. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4095. )
  4096. ) then
  4097. begin
  4098. { we have
  4099. mov x, %treg
  4100. mov %treg, y
  4101. }
  4102. { We don't need to call UpdateUsedRegs for every instruction between
  4103. p and hp2 because the register we're concerned about will not
  4104. become deallocated (otherwise GetNextInstructionUsingReg would
  4105. have stopped at an earlier instruction). [Kit] }
  4106. TempRegUsed :=
  4107. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4108. RegReadByInstruction(p_TargetReg, hp3) or
  4109. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4110. case taicpu(p).oper[0]^.typ Of
  4111. top_reg:
  4112. begin
  4113. { change
  4114. mov %reg, %treg
  4115. mov %treg, y
  4116. to
  4117. mov %reg, y
  4118. }
  4119. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4120. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4121. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4122. begin
  4123. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4124. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4125. if TempRegUsed then
  4126. begin
  4127. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4128. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4129. { Set the start of the next GetNextInstructionUsingRegCond search
  4130. to start at the entry right before hp2 (which is about to be removed) }
  4131. hp3 := tai(hp2.Previous);
  4132. RemoveInstruction(hp2);
  4133. Include(OptsToCheck, aoc_ForceNewIteration);
  4134. { See if there's more we can optimise }
  4135. Continue;
  4136. end
  4137. else
  4138. begin
  4139. RemoveInstruction(hp2);
  4140. { We can remove the original MOV too }
  4141. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4142. RemoveCurrentP(p, hp1);
  4143. Result:=true;
  4144. JumpTracking.Free;
  4145. Exit;
  4146. end;
  4147. end
  4148. else
  4149. begin
  4150. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4151. taicpu(hp2).loadReg(0, p_SourceReg);
  4152. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4153. { Check to see if the register also appears in the reference }
  4154. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4155. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4156. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4157. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4158. begin
  4159. { Don't remove the first instruction if the temporary register is in use }
  4160. if not TempRegUsed then
  4161. begin
  4162. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4163. RemoveCurrentP(p, hp1);
  4164. Result:=true;
  4165. JumpTracking.Free;
  4166. Exit;
  4167. end;
  4168. { No need to set Result to True here. If there's another instruction later
  4169. on that can be optimised, it will be detected when the main Pass 1 loop
  4170. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4171. hp3 := hp2;
  4172. Continue;
  4173. end;
  4174. end;
  4175. end;
  4176. top_const:
  4177. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4178. begin
  4179. { change
  4180. mov const, %treg
  4181. mov %treg, y
  4182. to
  4183. mov const, y
  4184. }
  4185. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4186. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4187. begin
  4188. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4189. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4190. if TempRegUsed then
  4191. begin
  4192. { Don't remove the first instruction if the temporary register is in use }
  4193. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4194. { No need to set Result to True. If there's another instruction later on
  4195. that can be optimised, it will be detected when the main Pass 1 loop
  4196. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4197. end
  4198. else
  4199. begin
  4200. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4201. RemoveCurrentP(p, hp1);
  4202. Result:=true;
  4203. Exit;
  4204. end;
  4205. end;
  4206. end;
  4207. else
  4208. Internalerror(2019103001);
  4209. end;
  4210. end
  4211. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4212. begin
  4213. if not CrossJump and
  4214. not RegUsedBetween(p_TargetReg, p, hp2) and
  4215. not RegReadByInstruction(p_TargetReg, hp2) then
  4216. begin
  4217. { Register is not used before it is overwritten }
  4218. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4219. RemoveCurrentp(p, hp1);
  4220. Result := True;
  4221. Exit;
  4222. end;
  4223. if (taicpu(p).oper[0]^.typ = top_const) and
  4224. (taicpu(hp2).oper[0]^.typ = top_const) then
  4225. begin
  4226. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4227. begin
  4228. { Same value - register hasn't changed }
  4229. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4230. RemoveInstruction(hp2);
  4231. Include(OptsToCheck, aoc_ForceNewIteration);
  4232. { See if there's more we can optimise }
  4233. Continue;
  4234. end;
  4235. end;
  4236. {$ifdef x86_64}
  4237. end
  4238. { Change:
  4239. movl %reg1l,%reg2l
  4240. ...
  4241. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4242. To:
  4243. movl %reg1l,%reg2l
  4244. ...
  4245. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4246. If %reg1 = %reg3, convert to:
  4247. movl %reg1l,%reg2l
  4248. ...
  4249. andl %reg1l,%reg1l
  4250. }
  4251. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4252. (taicpu(p).oper[0]^.typ = top_reg) and
  4253. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4254. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4255. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4256. begin
  4257. TempRegUsed :=
  4258. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4259. RegReadByInstruction(p_TargetReg, hp3) or
  4260. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4261. taicpu(hp2).opsize := S_L;
  4262. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4263. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4264. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4265. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4266. begin
  4267. { %reg1 = %reg3 }
  4268. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4269. taicpu(hp2).opcode := A_AND;
  4270. end
  4271. else
  4272. begin
  4273. { %reg1 <> %reg3 }
  4274. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4275. end;
  4276. if not TempRegUsed then
  4277. begin
  4278. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4279. RemoveCurrentP(p, hp1);
  4280. Result := True;
  4281. Exit;
  4282. end
  4283. else
  4284. begin
  4285. { Initial instruction wasn't actually changed }
  4286. Include(OptsToCheck, aoc_ForceNewIteration);
  4287. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4288. appears below since %reg1 has technically changed }
  4289. if taicpu(hp2).opcode = A_AND then
  4290. Break;
  4291. end;
  4292. {$endif x86_64}
  4293. end
  4294. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4295. GetNextInstruction(hp2, hp4) and
  4296. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4297. { Optimise the following first:
  4298. movl [mem1],reg1
  4299. movl [mem1],reg2
  4300. to
  4301. movl [mem1],reg1
  4302. movl reg1,reg2
  4303. If [mem1] contains the target register and reg1 is the
  4304. the source register, this optimisation will get missed
  4305. and produce less efficient code later on.
  4306. }
  4307. if CheckMovMov2MovMov2(hp2, hp4) then
  4308. { Initial instruction wasn't actually changed }
  4309. Include(OptsToCheck, aoc_ForceNewIteration);
  4310. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4311. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4312. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4313. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4314. begin
  4315. {
  4316. Change from:
  4317. mov ###, %reg
  4318. ...
  4319. movs/z %reg,%reg (Same register, just different sizes)
  4320. To:
  4321. movs/z ###, %reg (Longer version)
  4322. ...
  4323. (remove)
  4324. }
  4325. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4326. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4327. { Keep the first instruction as mov if ### is a constant }
  4328. if taicpu(p).oper[0]^.typ = top_const then
  4329. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4330. else
  4331. begin
  4332. taicpu(p).opcode := taicpu(hp2).opcode;
  4333. taicpu(p).opsize := taicpu(hp2).opsize;
  4334. end;
  4335. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4336. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4337. RemoveInstruction(hp2);
  4338. Result := True;
  4339. JumpTracking.Free;
  4340. Exit;
  4341. end;
  4342. else
  4343. { Move down to the if-block below };
  4344. end;
  4345. { Also catches MOV/S/Z instructions that aren't modified }
  4346. if taicpu(p).oper[0]^.typ = top_reg then
  4347. begin
  4348. p_SourceReg := taicpu(p).oper[0]^.reg;
  4349. if
  4350. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4351. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4352. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4353. begin
  4354. Result := True;
  4355. { Just in case something didn't get modified (e.g. an
  4356. implicit register). Also, if it does read from this
  4357. register, then there's no longer an advantage to
  4358. changing the register on subsequent instructions.}
  4359. if not RegReadByInstruction(p_TargetReg, hp2) then
  4360. begin
  4361. { If a conditional jump was crossed, do not delete
  4362. the original MOV no matter what }
  4363. if not CrossJump and
  4364. { RegEndOfLife returns True if the register is
  4365. deallocated before the next instruction or has
  4366. been loaded with a new value }
  4367. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4368. begin
  4369. { We can remove the original MOV }
  4370. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4371. RemoveCurrentp(p, hp1);
  4372. JumpTracking.Free;
  4373. Result := True;
  4374. Exit;
  4375. end;
  4376. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4377. begin
  4378. { See if there's more we can optimise }
  4379. hp3 := hp2;
  4380. Continue;
  4381. end;
  4382. end;
  4383. end;
  4384. end;
  4385. { Break out of the while loop under normal circumstances }
  4386. Break;
  4387. end;
  4388. JumpTracking.Free;
  4389. end;
  4390. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4391. (taicpu(p).oper[1]^.typ = top_reg) and
  4392. (taicpu(p).opsize = S_L) and
  4393. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4394. (hp2.typ = ait_instruction) and
  4395. (taicpu(hp2).opcode = A_AND) and
  4396. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4397. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4398. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4399. ) then
  4400. begin
  4401. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4402. begin
  4403. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4404. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4405. begin
  4406. { Optimize out:
  4407. mov x, %reg
  4408. and ffffffffh, %reg
  4409. }
  4410. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4411. RemoveInstruction(hp2);
  4412. Result:=true;
  4413. exit;
  4414. end;
  4415. end;
  4416. end;
  4417. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4418. x >= RetOffset) as it doesn't do anything (it writes either to a
  4419. parameter or to the temporary storage room for the function
  4420. result)
  4421. }
  4422. if IsExitCode(hp1) and
  4423. (taicpu(p).oper[1]^.typ = top_ref) and
  4424. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4425. (
  4426. (
  4427. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4428. not (
  4429. assigned(current_procinfo.procdef.funcretsym) and
  4430. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4431. )
  4432. ) or
  4433. { Also discard writes to the stack that are below the base pointer,
  4434. as this is temporary storage rather than a function result on the
  4435. stack, say. }
  4436. (
  4437. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4438. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4439. )
  4440. ) then
  4441. begin
  4442. RemoveCurrentp(p, hp1);
  4443. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4444. RemoveLastDeallocForFuncRes(p);
  4445. Result:=true;
  4446. exit;
  4447. end;
  4448. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4449. begin
  4450. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4451. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4452. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4453. begin
  4454. { change
  4455. mov reg1, mem1
  4456. test/cmp x, mem1
  4457. to
  4458. mov reg1, mem1
  4459. test/cmp x, reg1
  4460. }
  4461. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4462. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4463. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4464. Result := True;
  4465. Exit;
  4466. end;
  4467. if DoMovCmpMemOpt(p, hp1) then
  4468. begin
  4469. Result := True;
  4470. Exit;
  4471. end;
  4472. end;
  4473. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4474. { If the flags register is in use, don't change the instruction to an
  4475. ADD otherwise this will scramble the flags. [Kit] }
  4476. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4477. begin
  4478. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4479. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4480. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4481. ) or
  4482. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4483. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4484. )
  4485. ) then
  4486. { mov reg1,ref
  4487. lea reg2,[reg1,reg2]
  4488. to
  4489. add reg2,ref}
  4490. begin
  4491. TransferUsedRegs(TmpUsedRegs);
  4492. { reg1 may not be used afterwards }
  4493. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4494. begin
  4495. Taicpu(hp1).opcode:=A_ADD;
  4496. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4497. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4498. RemoveCurrentp(p, hp1);
  4499. result:=true;
  4500. exit;
  4501. end;
  4502. end;
  4503. { If the LEA instruction can be converted into an arithmetic instruction,
  4504. it may be possible to then fold it in the next optimisation, otherwise
  4505. there's nothing more that can be optimised here. }
  4506. if not ConvertLEA(taicpu(hp1)) then
  4507. Exit;
  4508. end;
  4509. if (taicpu(p).oper[1]^.typ = top_reg) and
  4510. (hp1.typ = ait_instruction) and
  4511. GetNextInstruction(hp1, hp2) and
  4512. MatchInstruction(hp2,A_MOV,[]) and
  4513. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4514. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4515. (
  4516. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4517. {$ifdef x86_64}
  4518. or
  4519. (
  4520. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4521. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4522. )
  4523. {$endif x86_64}
  4524. ) then
  4525. begin
  4526. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4527. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4528. { change movsX/movzX reg/ref, reg2
  4529. add/sub/or/... reg3/$const, reg2
  4530. mov reg2 reg/ref
  4531. dealloc reg2
  4532. to
  4533. add/sub/or/... reg3/$const, reg/ref }
  4534. begin
  4535. TransferUsedRegs(TmpUsedRegs);
  4536. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4537. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4538. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4539. begin
  4540. { by example:
  4541. movswl %si,%eax movswl %si,%eax p
  4542. decl %eax addl %edx,%eax hp1
  4543. movw %ax,%si movw %ax,%si hp2
  4544. ->
  4545. movswl %si,%eax movswl %si,%eax p
  4546. decw %eax addw %edx,%eax hp1
  4547. movw %ax,%si movw %ax,%si hp2
  4548. }
  4549. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4550. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4551. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4552. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4553. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4554. {
  4555. ->
  4556. movswl %si,%eax movswl %si,%eax p
  4557. decw %si addw %dx,%si hp1
  4558. movw %ax,%si movw %ax,%si hp2
  4559. }
  4560. case taicpu(hp1).ops of
  4561. 1:
  4562. begin
  4563. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4564. if taicpu(hp1).oper[0]^.typ=top_reg then
  4565. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4566. end;
  4567. 2:
  4568. begin
  4569. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4570. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4571. (taicpu(hp1).opcode<>A_SHL) and
  4572. (taicpu(hp1).opcode<>A_SHR) and
  4573. (taicpu(hp1).opcode<>A_SAR) then
  4574. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4575. end;
  4576. else
  4577. internalerror(2008042701);
  4578. end;
  4579. {
  4580. ->
  4581. decw %si addw %dx,%si p
  4582. }
  4583. RemoveInstruction(hp2);
  4584. RemoveCurrentP(p, hp1);
  4585. Result:=True;
  4586. Exit;
  4587. end;
  4588. end;
  4589. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4590. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4591. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4592. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4593. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4594. )
  4595. {$ifdef i386}
  4596. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4597. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4598. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4599. {$endif i386}
  4600. then
  4601. { change movsX/movzX reg/ref, reg2
  4602. add/sub/or/... regX/$const, reg2
  4603. mov reg2, reg3
  4604. dealloc reg2
  4605. to
  4606. movsX/movzX reg/ref, reg3
  4607. add/sub/or/... reg3/$const, reg3
  4608. }
  4609. begin
  4610. TransferUsedRegs(TmpUsedRegs);
  4611. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4612. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4613. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4614. begin
  4615. { by example:
  4616. movswl %si,%eax movswl %si,%eax p
  4617. decl %eax addl %edx,%eax hp1
  4618. movw %ax,%si movw %ax,%si hp2
  4619. ->
  4620. movswl %si,%eax movswl %si,%eax p
  4621. decw %eax addw %edx,%eax hp1
  4622. movw %ax,%si movw %ax,%si hp2
  4623. }
  4624. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4625. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4626. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4627. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4628. { limit size of constants as well to avoid assembler errors, but
  4629. check opsize to avoid overflow when left shifting the 1 }
  4630. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4631. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4632. {$ifdef x86_64}
  4633. { Be careful of, for example:
  4634. movl %reg1,%reg2
  4635. addl %reg3,%reg2
  4636. movq %reg2,%reg4
  4637. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4638. }
  4639. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4640. begin
  4641. taicpu(hp2).changeopsize(S_L);
  4642. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4643. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4644. end;
  4645. {$endif x86_64}
  4646. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4647. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4648. if taicpu(p).oper[0]^.typ=top_reg then
  4649. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4650. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4651. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4652. {
  4653. ->
  4654. movswl %si,%eax movswl %si,%eax p
  4655. decw %si addw %dx,%si hp1
  4656. movw %ax,%si movw %ax,%si hp2
  4657. }
  4658. case taicpu(hp1).ops of
  4659. 1:
  4660. begin
  4661. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4662. if taicpu(hp1).oper[0]^.typ=top_reg then
  4663. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4664. end;
  4665. 2:
  4666. begin
  4667. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4668. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4669. (taicpu(hp1).opcode<>A_SHL) and
  4670. (taicpu(hp1).opcode<>A_SHR) and
  4671. (taicpu(hp1).opcode<>A_SAR) then
  4672. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4673. end;
  4674. else
  4675. internalerror(2018111801);
  4676. end;
  4677. {
  4678. ->
  4679. decw %si addw %dx,%si p
  4680. }
  4681. RemoveInstruction(hp2);
  4682. end;
  4683. end;
  4684. end;
  4685. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4686. GetNextInstruction(hp1, hp2) and
  4687. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4688. MatchOperand(Taicpu(p).oper[0]^,0) and
  4689. (Taicpu(p).oper[1]^.typ = top_reg) and
  4690. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4691. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4692. { mov reg1,0
  4693. bts reg1,operand1 --> mov reg1,operand2
  4694. or reg1,operand2 bts reg1,operand1}
  4695. begin
  4696. Taicpu(hp2).opcode:=A_MOV;
  4697. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4698. asml.remove(hp1);
  4699. insertllitem(hp2,hp2.next,hp1);
  4700. RemoveCurrentp(p, hp1);
  4701. Result:=true;
  4702. exit;
  4703. end;
  4704. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4705. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4706. GetNextInstruction(hp1, hp2) and
  4707. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4708. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4709. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4710. { change
  4711. mov reg1,reg2
  4712. sub reg3,reg2
  4713. cmp reg3,reg1
  4714. into
  4715. mov reg1,reg2
  4716. sub reg3,reg2
  4717. }
  4718. begin
  4719. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4720. RemoveInstruction(hp2);
  4721. Result:=true;
  4722. exit;
  4723. end;
  4724. {
  4725. mov ref,reg0
  4726. <op> reg0,reg1
  4727. dealloc reg0
  4728. to
  4729. <op> ref,reg1
  4730. }
  4731. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4732. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4733. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4734. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4735. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4736. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4737. begin
  4738. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4739. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4740. RemoveCurrentp(p, hp1);
  4741. Result:=true;
  4742. exit;
  4743. end;
  4744. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4745. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4746. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4747. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4748. begin
  4749. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4750. {$ifdef x86_64}
  4751. { Convert:
  4752. movq x(ref),%reg64
  4753. shrq y,%reg64
  4754. To:
  4755. movl x+4(ref),%reg32
  4756. shrl y-32,%reg32 (Remove if y = 32)
  4757. }
  4758. if (taicpu(p).opsize = S_Q) and
  4759. (taicpu(hp1).opcode = A_SHR) and
  4760. (taicpu(hp1).oper[0]^.val >= 32) then
  4761. begin
  4762. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4763. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4764. { Convert to 32-bit }
  4765. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4766. taicpu(p).opsize := S_L;
  4767. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4768. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4769. if (taicpu(hp1).oper[0]^.val = 32) then
  4770. begin
  4771. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4772. RemoveInstruction(hp1);
  4773. end
  4774. else
  4775. begin
  4776. { This will potentially open up more arithmetic operations since
  4777. the peephole optimizer now has a big hint that only the lower
  4778. 32 bits are currently in use (and opcodes are smaller in size) }
  4779. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4780. taicpu(hp1).opsize := S_L;
  4781. Dec(taicpu(hp1).oper[0]^.val, 32);
  4782. DebugMsg(SPeepholeOptimization + PreMessage +
  4783. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4784. end;
  4785. Result := True;
  4786. Exit;
  4787. end;
  4788. {$endif x86_64}
  4789. { Convert:
  4790. movl x(ref),%reg
  4791. shrl $24,%reg
  4792. To:
  4793. movzbl x+3(ref),%reg
  4794. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4795. Also accept sar instead of shr, but convert to movsx instead of movzx
  4796. }
  4797. if taicpu(hp1).opcode = A_SHR then
  4798. MovUnaligned := A_MOVZX
  4799. else
  4800. MovUnaligned := A_MOVSX;
  4801. NewSize := S_NO;
  4802. NewOffset := 0;
  4803. case taicpu(p).opsize of
  4804. S_B:
  4805. { No valid combinations };
  4806. S_W:
  4807. if (taicpu(hp1).oper[0]^.val = 8) then
  4808. begin
  4809. NewSize := S_BW;
  4810. NewOffset := 1;
  4811. end;
  4812. S_L:
  4813. case taicpu(hp1).oper[0]^.val of
  4814. 16:
  4815. begin
  4816. NewSize := S_WL;
  4817. NewOffset := 2;
  4818. end;
  4819. 24:
  4820. begin
  4821. NewSize := S_BL;
  4822. NewOffset := 3;
  4823. end;
  4824. else
  4825. ;
  4826. end;
  4827. {$ifdef x86_64}
  4828. S_Q:
  4829. case taicpu(hp1).oper[0]^.val of
  4830. 32:
  4831. begin
  4832. if taicpu(hp1).opcode = A_SAR then
  4833. begin
  4834. { 32-bit to 64-bit is a distinct instruction }
  4835. MovUnaligned := A_MOVSXD;
  4836. NewSize := S_LQ;
  4837. NewOffset := 4;
  4838. end
  4839. else
  4840. { Should have been handled by MovShr2Mov above }
  4841. InternalError(2022081811);
  4842. end;
  4843. 48:
  4844. begin
  4845. NewSize := S_WQ;
  4846. NewOffset := 6;
  4847. end;
  4848. 56:
  4849. begin
  4850. NewSize := S_BQ;
  4851. NewOffset := 7;
  4852. end;
  4853. else
  4854. ;
  4855. end;
  4856. {$endif x86_64}
  4857. else
  4858. InternalError(2022081810);
  4859. end;
  4860. if (NewSize <> S_NO) and
  4861. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4862. begin
  4863. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4864. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4865. debug_op2str(MovUnaligned);
  4866. {$ifdef x86_64}
  4867. if MovUnaligned <> A_MOVSXD then
  4868. { Don't add size suffix for MOVSXD }
  4869. {$endif x86_64}
  4870. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4871. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4872. taicpu(p).opcode := MovUnaligned;
  4873. taicpu(p).opsize := NewSize;
  4874. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4875. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4876. RemoveInstruction(hp1);
  4877. Result := True;
  4878. Exit;
  4879. end;
  4880. end;
  4881. { Backward optimisation shared with OptPass2MOV }
  4882. if FuncMov2Func(p, hp1) then
  4883. begin
  4884. Result := True;
  4885. Exit;
  4886. end;
  4887. end;
  4888. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4889. var
  4890. hp1 : tai;
  4891. begin
  4892. Result:=false;
  4893. if taicpu(p).ops <> 2 then
  4894. exit;
  4895. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4896. GetNextInstruction(p,hp1) then
  4897. begin
  4898. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4899. (taicpu(hp1).ops = 2) then
  4900. begin
  4901. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4902. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4903. { movXX reg1, mem1 or movXX mem1, reg1
  4904. movXX mem2, reg2 movXX reg2, mem2}
  4905. begin
  4906. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4907. { movXX reg1, mem1 or movXX mem1, reg1
  4908. movXX mem2, reg1 movXX reg2, mem1}
  4909. begin
  4910. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4911. begin
  4912. { Removes the second statement from
  4913. movXX reg1, mem1/reg2
  4914. movXX mem1/reg2, reg1
  4915. }
  4916. if taicpu(p).oper[0]^.typ=top_reg then
  4917. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4918. { Removes the second statement from
  4919. movXX mem1/reg1, reg2
  4920. movXX reg2, mem1/reg1
  4921. }
  4922. if (taicpu(p).oper[1]^.typ=top_reg) and
  4923. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4924. begin
  4925. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4926. RemoveInstruction(hp1);
  4927. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4928. Result:=true;
  4929. exit;
  4930. end
  4931. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4932. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4933. begin
  4934. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4935. RemoveInstruction(hp1);
  4936. Result:=true;
  4937. exit;
  4938. end;
  4939. end
  4940. end;
  4941. end;
  4942. end;
  4943. end;
  4944. end;
  4945. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4946. var
  4947. hp1 : tai;
  4948. begin
  4949. result:=false;
  4950. { replace
  4951. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4952. MovX %mreg2,%mreg1
  4953. dealloc %mreg2
  4954. by
  4955. <Op>X %mreg2,%mreg1
  4956. ?
  4957. }
  4958. if GetNextInstruction(p,hp1) and
  4959. { we mix single and double opperations here because we assume that the compiler
  4960. generates vmovapd only after double operations and vmovaps only after single operations }
  4961. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4962. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4963. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4964. (taicpu(p).oper[0]^.typ=top_reg) then
  4965. begin
  4966. TransferUsedRegs(TmpUsedRegs);
  4967. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4968. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4969. begin
  4970. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4971. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4972. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4973. RemoveInstruction(hp1);
  4974. result:=true;
  4975. end;
  4976. end;
  4977. end;
  4978. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4979. var
  4980. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4981. JumpLabel, JumpLabel_dist: TAsmLabel;
  4982. FirstValue, SecondValue: TCGInt;
  4983. function OptimizeJump(var InputP: tai): Boolean;
  4984. var
  4985. TempBool: Boolean;
  4986. begin
  4987. Result := False;
  4988. TempBool := True;
  4989. if DoJumpOptimizations(InputP, TempBool) or
  4990. not TempBool then
  4991. begin
  4992. Result := True;
  4993. if Assigned(InputP) then
  4994. begin
  4995. { CollapseZeroDistJump will be set to the label or an align
  4996. before it after the jump if it optimises, whether or not
  4997. the label is live or dead }
  4998. if (InputP.typ = ait_align) or
  4999. (
  5000. (InputP.typ = ait_label) and
  5001. not (tai_label(InputP).labsym.is_used)
  5002. ) then
  5003. GetNextInstruction(InputP, InputP);
  5004. end;
  5005. Exit;
  5006. end;
  5007. end;
  5008. begin
  5009. Result := False;
  5010. if (taicpu(p).oper[0]^.typ = top_const) and
  5011. (taicpu(p).oper[0]^.val <> -1) then
  5012. begin
  5013. { Convert unsigned maximum constants to -1 to aid optimisation }
  5014. case taicpu(p).opsize of
  5015. S_B:
  5016. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5017. begin
  5018. taicpu(p).oper[0]^.val := -1;
  5019. Result := True;
  5020. Exit;
  5021. end;
  5022. S_W:
  5023. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5024. begin
  5025. taicpu(p).oper[0]^.val := -1;
  5026. Result := True;
  5027. Exit;
  5028. end;
  5029. S_L:
  5030. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5031. begin
  5032. taicpu(p).oper[0]^.val := -1;
  5033. Result := True;
  5034. Exit;
  5035. end;
  5036. {$ifdef x86_64}
  5037. S_Q:
  5038. { Storing anything greater than $7FFFFFFF is not possible so do
  5039. nothing };
  5040. {$endif x86_64}
  5041. else
  5042. InternalError(2021121001);
  5043. end;
  5044. end;
  5045. if GetNextInstruction(p, hp1) and
  5046. TrySwapMovCmp(p, hp1) then
  5047. begin
  5048. Result := True;
  5049. Exit;
  5050. end;
  5051. p_label := nil;
  5052. JumpLabel := nil;
  5053. if MatchInstruction(hp1, A_Jcc, []) then
  5054. begin
  5055. if OptimizeJump(hp1) then
  5056. begin
  5057. Result := True;
  5058. if Assigned(hp1) then
  5059. begin
  5060. { CollapseZeroDistJump will be set to the label or an align
  5061. before it after the jump if it optimises, whether or not
  5062. the label is live or dead }
  5063. if (hp1.typ = ait_align) or
  5064. (
  5065. (hp1.typ = ait_label) and
  5066. not (tai_label(hp1).labsym.is_used)
  5067. ) then
  5068. GetNextInstruction(hp1, hp1);
  5069. end;
  5070. TransferUsedRegs(TmpUsedRegs);
  5071. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5072. if not Assigned(hp1) or
  5073. (
  5074. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5075. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5076. ) then
  5077. begin
  5078. { No more conditional jumps; conditional statement is no longer required }
  5079. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5080. RemoveCurrentP(p);
  5081. end;
  5082. Exit;
  5083. end;
  5084. if IsJumpToLabel(taicpu(hp1)) then
  5085. begin
  5086. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5087. if Assigned(JumpLabel) then
  5088. p_label := getlabelwithsym(JumpLabel);
  5089. end;
  5090. end;
  5091. { Search for:
  5092. test $x,(reg/ref)
  5093. jne @lbl1
  5094. test $y,(reg/ref) (same register or reference)
  5095. jne @lbl1
  5096. Change to:
  5097. test $(x or y),(reg/ref)
  5098. jne @lbl1
  5099. (Note, this doesn't work with je instead of jne)
  5100. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5101. Also search for:
  5102. test $x,(reg/ref)
  5103. je @lbl1
  5104. ...
  5105. test $y,(reg/ref)
  5106. je/jne @lbl2
  5107. If (x or y) = x, then the second jump is deterministic
  5108. }
  5109. if (
  5110. (
  5111. (taicpu(p).oper[0]^.typ = top_const) or
  5112. (
  5113. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5114. (taicpu(p).oper[0]^.typ = top_reg) and
  5115. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5116. )
  5117. ) and
  5118. MatchInstruction(hp1, A_JCC, [])
  5119. ) then
  5120. begin
  5121. if (taicpu(p).oper[0]^.typ = top_reg) and
  5122. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5123. FirstValue := -1
  5124. else
  5125. FirstValue := taicpu(p).oper[0]^.val;
  5126. { If we have several test/jne's in a row, it might be the case that
  5127. the second label doesn't go to the same location, but the one
  5128. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5129. so accommodate for this with a while loop.
  5130. }
  5131. hp1_last := hp1;
  5132. while (
  5133. (
  5134. (taicpu(p).oper[1]^.typ = top_reg) and
  5135. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5136. ) or GetNextInstruction(hp1_last, p_dist)
  5137. ) and (p_dist.typ = ait_instruction) do
  5138. begin
  5139. if (
  5140. (
  5141. (taicpu(p_dist).opcode = A_TEST) and
  5142. (
  5143. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5144. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5145. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5146. )
  5147. ) or
  5148. (
  5149. { cmp 0,%reg = test %reg,%reg }
  5150. (taicpu(p_dist).opcode = A_CMP) and
  5151. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5152. )
  5153. ) and
  5154. { Make sure the destination operands are actually the same }
  5155. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5156. GetNextInstruction(p_dist, hp1_dist) and
  5157. MatchInstruction(hp1_dist, A_JCC, []) then
  5158. begin
  5159. if OptimizeJump(hp1_dist) then
  5160. begin
  5161. Result := True;
  5162. Exit;
  5163. end;
  5164. if
  5165. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5166. (
  5167. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5168. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5169. ) then
  5170. SecondValue := -1
  5171. else
  5172. SecondValue := taicpu(p_dist).oper[0]^.val;
  5173. { If both of the TEST constants are identical, delete the
  5174. second TEST that is unnecessary (be careful though, just
  5175. in case the flags are modified in between) }
  5176. if (FirstValue = SecondValue) then
  5177. begin
  5178. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5179. begin
  5180. { Since the second jump's condition is a subset of the first, we
  5181. know it will never branch because the first jump dominates it.
  5182. Get it out of the way now rather than wait for the jump
  5183. optimisations for a speed boost. }
  5184. if IsJumpToLabel(taicpu(hp1_dist)) then
  5185. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5186. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5187. RemoveInstruction(hp1_dist);
  5188. Result := True;
  5189. end
  5190. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5191. begin
  5192. { If the inverse of the first condition is a subset of the second,
  5193. the second one will definitely branch if the first one doesn't }
  5194. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5195. { We can remove the TEST instruction too }
  5196. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5197. RemoveInstruction(p_dist);
  5198. MakeUnconditional(taicpu(hp1_dist));
  5199. RemoveDeadCodeAfterJump(hp1_dist);
  5200. { Since the jump is now unconditional, we can't
  5201. continue any further with this particular
  5202. optimisation. The original TEST is still intact
  5203. though, so there might be something else we can
  5204. do }
  5205. Include(OptsToCheck, aoc_ForceNewIteration);
  5206. Break;
  5207. end;
  5208. if Result or
  5209. { If a jump wasn't removed or made unconditional, only
  5210. remove the identical TEST instruction if the flags
  5211. weren't modified }
  5212. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5213. begin
  5214. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5215. RemoveInstruction(p_dist);
  5216. { If the jump was removed or made unconditional, we
  5217. don't need to allocate NR_DEFAULTFLAGS over the
  5218. entire range }
  5219. if not Result then
  5220. begin
  5221. { Mark the flags as 'in use' over the entire range }
  5222. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5223. { Speed gain - continue search from the Jcc instruction }
  5224. hp1_last := hp1_dist;
  5225. { Only the TEST instruction was removed, and the
  5226. original was unchanged, so we can safely do
  5227. another iteration of the while loop }
  5228. Include(OptsToCheck, aoc_ForceNewIteration);
  5229. Continue;
  5230. end;
  5231. Exit;
  5232. end;
  5233. end;
  5234. hp1_last := nil;
  5235. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5236. (
  5237. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5238. { Always adjacent under -O2 and under }
  5239. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5240. (
  5241. GetNextInstruction(hp1, hp1_last) and
  5242. (hp1_last = p_dist)
  5243. )
  5244. ) and
  5245. (
  5246. (
  5247. { Test the following variant:
  5248. test $x,(reg/ref)
  5249. jne @lbl1
  5250. test $y,(reg/ref)
  5251. je @lbl2
  5252. @lbl1:
  5253. Becomes:
  5254. test $(x or y),(reg/ref)
  5255. je @lbl2
  5256. @lbl1: (may become a dead label)
  5257. }
  5258. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5259. GetNextInstruction(hp1_dist, hp1_last) and
  5260. (hp1_last = p_label)
  5261. ) or
  5262. (
  5263. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5264. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5265. then the second jump will never branch, so it can also be
  5266. removed regardless of where it goes }
  5267. (
  5268. (FirstValue = -1) or
  5269. (SecondValue = -1) or
  5270. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5271. )
  5272. )
  5273. ) then
  5274. begin
  5275. { Same jump location... can be a register since nothing's changed }
  5276. { If any of the entries are equivalent to test %reg,%reg, then the
  5277. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5278. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5279. if (hp1_last = p_label) then
  5280. begin
  5281. { Variant }
  5282. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5283. RemoveInstruction(p_dist);
  5284. if Assigned(JumpLabel) then
  5285. JumpLabel.decrefs;
  5286. RemoveInstruction(hp1);
  5287. end
  5288. else
  5289. begin
  5290. { Only remove the second test if no jumps or other conditional instructions follow }
  5291. TransferUsedRegs(TmpUsedRegs);
  5292. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5293. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5294. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5295. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5296. begin
  5297. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5298. RemoveInstruction(p_dist);
  5299. { Remove the first jump, not the second, to keep
  5300. any register deallocations between the second
  5301. TEST/JNE pair in the same place. Aids future
  5302. optimisation. }
  5303. if Assigned(JumpLabel) then
  5304. JumpLabel.decrefs;
  5305. RemoveInstruction(hp1);
  5306. end
  5307. else
  5308. begin
  5309. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5310. if IsJumpToLabel(taicpu(hp1_dist)) then
  5311. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5312. { Remove second jump in this instance }
  5313. RemoveInstruction(hp1_dist);
  5314. end;
  5315. end;
  5316. Result := True;
  5317. Exit;
  5318. end;
  5319. end;
  5320. if { If -O2 and under, it may stop on any old instruction }
  5321. (cs_opt_level3 in current_settings.optimizerswitches) and
  5322. (taicpu(p).oper[1]^.typ = top_reg) and
  5323. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5324. begin
  5325. hp1_last := p_dist;
  5326. Continue;
  5327. end;
  5328. Break;
  5329. end;
  5330. end;
  5331. { Search for:
  5332. test %reg,%reg
  5333. j(c1) @lbl1
  5334. ...
  5335. @lbl:
  5336. test %reg,%reg (same register)
  5337. j(c2) @lbl2
  5338. If c2 is a subset of c1, change to:
  5339. test %reg,%reg
  5340. j(c1) @lbl2
  5341. (@lbl1 may become a dead label as a result)
  5342. }
  5343. if (taicpu(p).oper[1]^.typ = top_reg) and
  5344. (taicpu(p).oper[0]^.typ = top_reg) and
  5345. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5346. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5347. Assigned(p_label) and
  5348. GetNextInstruction(p_label, p_dist) and
  5349. MatchInstruction(p_dist, A_TEST, []) and
  5350. { It's fine if the second test uses smaller sub-registers }
  5351. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5352. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5353. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5354. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5355. GetNextInstruction(p_dist, hp1_dist) and
  5356. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5357. begin
  5358. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5359. if JumpLabel = JumpLabel_dist then
  5360. { This is an infinite loop }
  5361. Exit;
  5362. { Best optimisation when the first condition is a subset (or equal) of the second }
  5363. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5364. begin
  5365. { Any registers used here will already be allocated }
  5366. if Assigned(JumpLabel) then
  5367. JumpLabel.DecRefs;
  5368. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5369. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5370. Result := True;
  5371. Exit;
  5372. end;
  5373. end;
  5374. end;
  5375. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5376. var
  5377. hp1, hp2: tai;
  5378. ActiveReg: TRegister;
  5379. OldOffset: asizeint;
  5380. ThisConst: TCGInt;
  5381. function RegDeallocated: Boolean;
  5382. begin
  5383. TransferUsedRegs(TmpUsedRegs);
  5384. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5385. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5386. end;
  5387. begin
  5388. result:=false;
  5389. hp1 := nil;
  5390. { replace
  5391. addX const,%reg1
  5392. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5393. dealloc %reg1
  5394. by
  5395. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5396. }
  5397. if MatchOpType(taicpu(p),top_const,top_reg) then
  5398. begin
  5399. ActiveReg := taicpu(p).oper[1]^.reg;
  5400. { Ensures the entire register was updated }
  5401. if (taicpu(p).opsize >= S_L) and
  5402. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5403. MatchInstruction(hp1,A_LEA,[]) and
  5404. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5405. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5406. (
  5407. { Cover the case where the register in the reference is also the destination register }
  5408. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5409. (
  5410. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5411. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5412. RegDeallocated
  5413. )
  5414. ) then
  5415. begin
  5416. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5417. {$push}
  5418. {$R-}{$Q-}
  5419. { Explicitly disable overflow checking for these offset calculation
  5420. as those do not matter for the final result }
  5421. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5422. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5423. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5424. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5425. {$pop}
  5426. {$ifdef x86_64}
  5427. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5428. begin
  5429. { Overflow; abort }
  5430. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5431. end
  5432. else
  5433. {$endif x86_64}
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5436. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5437. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5438. RemoveCurrentP(p, hp1)
  5439. else
  5440. RemoveCurrentP(p);
  5441. result:=true;
  5442. Exit;
  5443. end;
  5444. end;
  5445. if (
  5446. { Save calling GetNextInstructionUsingReg again }
  5447. Assigned(hp1) or
  5448. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5449. ) and
  5450. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5451. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5452. begin
  5453. if taicpu(hp1).oper[0]^.typ = top_const then
  5454. begin
  5455. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5456. if taicpu(hp1).opcode = A_ADD then
  5457. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5458. else
  5459. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5460. Result := True;
  5461. { Handle any overflows }
  5462. case taicpu(p).opsize of
  5463. S_B:
  5464. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5465. S_W:
  5466. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5467. S_L:
  5468. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5469. {$ifdef x86_64}
  5470. S_Q:
  5471. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5472. { Overflow; abort }
  5473. Result := False
  5474. else
  5475. taicpu(p).oper[0]^.val := ThisConst;
  5476. {$endif x86_64}
  5477. else
  5478. InternalError(2021102610);
  5479. end;
  5480. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5481. if Result then
  5482. begin
  5483. if (taicpu(p).oper[0]^.val < 0) and
  5484. (
  5485. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5486. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5487. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5488. ) then
  5489. begin
  5490. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5491. taicpu(p).opcode := A_SUB;
  5492. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5493. end
  5494. else
  5495. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5496. RemoveInstruction(hp1);
  5497. end;
  5498. end
  5499. else
  5500. begin
  5501. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5502. TransferUsedRegs(TmpUsedRegs);
  5503. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5504. hp2 := p;
  5505. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5506. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5507. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5508. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5509. begin
  5510. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5511. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5512. Asml.Remove(p);
  5513. Asml.InsertAfter(p, hp1);
  5514. p := hp1;
  5515. Result := True;
  5516. Exit;
  5517. end;
  5518. end;
  5519. end;
  5520. if DoArithCombineOpt(p) then
  5521. Result:=true;
  5522. end;
  5523. end;
  5524. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5525. var
  5526. hp1, hp2: tai;
  5527. ref: Integer;
  5528. saveref: treference;
  5529. offsetcalc: Int64;
  5530. TempReg: TRegister;
  5531. Multiple: TCGInt;
  5532. Adjacent, IntermediateRegDiscarded: Boolean;
  5533. begin
  5534. Result:=false;
  5535. { play save and throw an error if LEA uses a seg register prefix,
  5536. this is most likely an error somewhere else }
  5537. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5538. internalerror(2022022001);
  5539. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5540. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5541. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5542. (
  5543. { do not mess with leas accessing the stack pointer
  5544. unless it's a null operation }
  5545. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5546. (
  5547. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5548. (taicpu(p).oper[0]^.ref^.offset = 0)
  5549. )
  5550. ) and
  5551. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5552. begin
  5553. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5554. begin
  5555. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5556. begin
  5557. taicpu(p).opcode := A_MOV;
  5558. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5559. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5560. end
  5561. else
  5562. begin
  5563. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5564. RemoveCurrentP(p);
  5565. end;
  5566. Result:=true;
  5567. exit;
  5568. end
  5569. else if (
  5570. { continue to use lea to adjust the stack pointer,
  5571. it is the recommended way, but only if not optimizing for size }
  5572. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5573. (cs_opt_size in current_settings.optimizerswitches)
  5574. ) and
  5575. { If the flags register is in use, don't change the instruction
  5576. to an ADD otherwise this will scramble the flags. [Kit] }
  5577. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5578. ConvertLEA(taicpu(p)) then
  5579. begin
  5580. Result:=true;
  5581. exit;
  5582. end;
  5583. end;
  5584. { Don't optimise if the stack or frame pointer is the destination register }
  5585. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5586. Exit;
  5587. if GetNextInstruction(p,hp1) and
  5588. (hp1.typ=ait_instruction) then
  5589. begin
  5590. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5591. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5592. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5593. begin
  5594. TransferUsedRegs(TmpUsedRegs);
  5595. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5596. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5597. begin
  5598. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5599. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5600. RemoveInstruction(hp1);
  5601. result:=true;
  5602. exit;
  5603. end;
  5604. end;
  5605. { changes
  5606. lea <ref1>, reg1
  5607. <op> ...,<ref. with reg1>,...
  5608. to
  5609. <op> ...,<ref1>,... }
  5610. { find a reference which uses reg1 }
  5611. 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
  5612. ref:=0
  5613. 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
  5614. ref:=1
  5615. else
  5616. ref:=-1;
  5617. if (ref<>-1) and
  5618. { reg1 must be either the base or the index }
  5619. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5620. begin
  5621. { reg1 can be removed from the reference }
  5622. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5623. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5624. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5625. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5626. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5627. else
  5628. Internalerror(2019111201);
  5629. { check if the can insert all data of the lea into the second instruction }
  5630. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5631. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5632. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5633. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5634. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5635. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5636. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5637. {$ifdef x86_64}
  5638. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5639. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5640. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5641. )
  5642. {$endif x86_64}
  5643. then
  5644. begin
  5645. { reg1 might not used by the second instruction after it is remove from the reference }
  5646. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5647. begin
  5648. TransferUsedRegs(TmpUsedRegs);
  5649. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5650. { reg1 is not updated so it might not be used afterwards }
  5651. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5652. begin
  5653. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5654. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5655. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5656. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5657. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5658. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5659. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5660. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5661. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5662. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5663. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5664. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5665. RemoveCurrentP(p, hp1);
  5666. result:=true;
  5667. exit;
  5668. end
  5669. end;
  5670. end;
  5671. { recover }
  5672. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5673. end;
  5674. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5675. if Adjacent or
  5676. { Check further ahead (up to 2 instructions ahead for -O2) }
  5677. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5678. begin
  5679. { Check common LEA/LEA conditions }
  5680. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5681. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5682. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5683. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5684. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5685. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5686. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5687. (
  5688. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5689. calling it (since it calls GetNextInstruction) }
  5690. Adjacent or
  5691. (
  5692. (
  5693. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5694. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5695. ) and (
  5696. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5697. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5698. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5699. )
  5700. )
  5701. ) then
  5702. begin
  5703. TransferUsedRegs(TmpUsedRegs);
  5704. hp2 := p;
  5705. repeat
  5706. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5707. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5708. IntermediateRegDiscarded :=
  5709. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5710. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5711. { changes
  5712. lea offset1(regX,scale), reg1
  5713. lea offset2(reg1,reg1), reg2
  5714. to
  5715. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5716. and
  5717. lea offset1(regX,scale1), reg1
  5718. lea offset2(reg1,scale2), reg2
  5719. to
  5720. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5721. and
  5722. lea offset1(regX,scale1), reg1
  5723. lea offset2(reg3,reg1,scale2), reg2
  5724. to
  5725. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5726. ... so long as the final scale does not exceed 8
  5727. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5728. }
  5729. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5730. (
  5731. { Don't optimise if size is a concern and the intermediate register remains in use }
  5732. IntermediateRegDiscarded or
  5733. not (cs_opt_size in current_settings.optimizerswitches)
  5734. ) and
  5735. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5736. (
  5737. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5738. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5739. ) and (
  5740. (
  5741. { lea (reg1,scale2), reg2 variant }
  5742. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5743. (
  5744. Adjacent or
  5745. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5746. ) and
  5747. (
  5748. (
  5749. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5750. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5751. ) or (
  5752. { lea (regX,regX), reg1 variant }
  5753. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5754. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5755. )
  5756. )
  5757. ) or (
  5758. { lea (reg1,reg1), reg1 variant }
  5759. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5760. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5761. )
  5762. ) then
  5763. begin
  5764. { Make everything homogeneous to make calculations easier }
  5765. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5766. begin
  5767. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5768. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5769. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5770. else
  5771. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5772. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5773. end;
  5774. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5775. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5776. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5777. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5778. begin
  5779. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5780. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5781. begin
  5782. { Put the register to change in the index register }
  5783. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5784. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5785. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5786. end;
  5787. { Change lea (reg,reg) to lea(,reg,2) }
  5788. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5789. begin
  5790. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5791. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5792. end;
  5793. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5794. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5795. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5796. { Just to prevent miscalculations }
  5797. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5798. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5799. else
  5800. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5801. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5802. if IntermediateRegDiscarded then
  5803. begin
  5804. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5805. RemoveCurrentP(p);
  5806. end
  5807. else
  5808. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5809. result:=true;
  5810. exit;
  5811. end;
  5812. end;
  5813. { changes
  5814. lea offset1(regX), reg1
  5815. lea offset2(reg1), reg2
  5816. to
  5817. lea offset1+offset2(regX), reg2 }
  5818. if (
  5819. { Don't optimise if size is a concern and the intermediate register remains in use }
  5820. IntermediateRegDiscarded or
  5821. not (cs_opt_size in current_settings.optimizerswitches)
  5822. ) and
  5823. (
  5824. (
  5825. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5826. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5827. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5828. ) or (
  5829. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5830. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5831. (
  5832. (
  5833. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5834. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5835. ) or (
  5836. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5837. (
  5838. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5839. (
  5840. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5841. (
  5842. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5843. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5844. )
  5845. )
  5846. )
  5847. )
  5848. )
  5849. )
  5850. ) then
  5851. begin
  5852. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5853. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5854. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5855. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5856. begin
  5857. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5858. begin
  5859. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5860. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5861. { if the register is used as index and base, we have to increase for base as well
  5862. and adapt base }
  5863. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5864. begin
  5865. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5866. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5867. end;
  5868. end
  5869. else
  5870. begin
  5871. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5872. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5873. end;
  5874. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5875. begin
  5876. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5877. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5878. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5879. { Catch the situation where the base = index
  5880. and treat this as *2. The scalefactor of
  5881. p will be 0 or 1 due to the conditional
  5882. checks above. Fixes i40647 }
  5883. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5884. else
  5885. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5886. end;
  5887. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5888. if IntermediateRegDiscarded then
  5889. begin
  5890. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5891. RemoveCurrentP(p);
  5892. end
  5893. else
  5894. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5895. result:=true;
  5896. exit;
  5897. end;
  5898. end;
  5899. end;
  5900. { Change:
  5901. leal/q $x(%reg1),%reg2
  5902. ...
  5903. shll/q $y,%reg2
  5904. To:
  5905. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5906. }
  5907. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5908. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5909. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5910. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5911. (taicpu(hp1).oper[0]^.val <= 3) then
  5912. begin
  5913. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5914. TransferUsedRegs(TmpUsedRegs);
  5915. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5916. if
  5917. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5918. (this works even if scalefactor is zero) }
  5919. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5920. { Ensure offset doesn't go out of bounds }
  5921. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5922. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5923. (
  5924. (
  5925. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5926. (
  5927. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5928. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5929. (
  5930. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5931. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5932. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5933. )
  5934. )
  5935. ) or (
  5936. (
  5937. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5938. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5939. ) and
  5940. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5941. )
  5942. ) then
  5943. begin
  5944. repeat
  5945. with taicpu(p).oper[0]^.ref^ do
  5946. begin
  5947. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5948. if index = base then
  5949. begin
  5950. if Multiple > 4 then
  5951. { Optimisation will no longer work because resultant
  5952. scale factor will exceed 8 }
  5953. Break;
  5954. base := NR_NO;
  5955. scalefactor := 2;
  5956. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5957. end
  5958. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5959. begin
  5960. { Scale factor only works on the index register }
  5961. index := base;
  5962. base := NR_NO;
  5963. end;
  5964. { For safety }
  5965. if scalefactor <= 1 then
  5966. begin
  5967. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5968. scalefactor := Multiple;
  5969. end
  5970. else
  5971. begin
  5972. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5973. scalefactor := scalefactor * Multiple;
  5974. end;
  5975. offset := offset * Multiple;
  5976. end;
  5977. RemoveInstruction(hp1);
  5978. Result := True;
  5979. Exit;
  5980. { This repeat..until loop exists for the benefit of Break }
  5981. until True;
  5982. end;
  5983. end;
  5984. end;
  5985. end;
  5986. end;
  5987. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5988. var
  5989. hp1 : tai;
  5990. SubInstr: Boolean;
  5991. ThisConst: TCGInt;
  5992. const
  5993. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5994. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5995. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5996. begin
  5997. Result := False;
  5998. if taicpu(p).oper[0]^.typ <> top_const then
  5999. { Should have been confirmed before calling }
  6000. InternalError(2021102601);
  6001. SubInstr := (taicpu(p).opcode = A_SUB);
  6002. if GetLastInstruction(p, hp1) and
  6003. (hp1.typ = ait_instruction) and
  6004. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6005. begin
  6006. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6007. { Bad size }
  6008. InternalError(2022042001);
  6009. case taicpu(hp1).opcode Of
  6010. A_INC:
  6011. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6012. begin
  6013. if SubInstr then
  6014. ThisConst := taicpu(p).oper[0]^.val - 1
  6015. else
  6016. ThisConst := taicpu(p).oper[0]^.val + 1;
  6017. end
  6018. else
  6019. Exit;
  6020. A_DEC:
  6021. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6022. begin
  6023. if SubInstr then
  6024. ThisConst := taicpu(p).oper[0]^.val + 1
  6025. else
  6026. ThisConst := taicpu(p).oper[0]^.val - 1;
  6027. end
  6028. else
  6029. Exit;
  6030. A_SUB:
  6031. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6032. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6033. begin
  6034. if SubInstr then
  6035. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6036. else
  6037. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6038. end
  6039. else
  6040. Exit;
  6041. A_ADD:
  6042. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6043. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6044. begin
  6045. if SubInstr then
  6046. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6047. else
  6048. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6049. end
  6050. else
  6051. Exit;
  6052. else
  6053. Exit;
  6054. end;
  6055. { Check that the values are in range }
  6056. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6057. { Overflow; abort }
  6058. Exit;
  6059. if (ThisConst = 0) then
  6060. begin
  6061. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6062. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6063. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6064. RemoveInstruction(hp1);
  6065. hp1 := tai(p.next);
  6066. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6067. if not GetLastInstruction(hp1, p) then
  6068. p := hp1;
  6069. end
  6070. else
  6071. begin
  6072. if taicpu(hp1).opercnt=1 then
  6073. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6074. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6075. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6076. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6077. else
  6078. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6079. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6080. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6081. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6082. RemoveInstruction(hp1);
  6083. taicpu(p).loadconst(0, ThisConst);
  6084. end;
  6085. Result := True;
  6086. end;
  6087. end;
  6088. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6089. begin
  6090. Result := False;
  6091. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6092. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6093. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6094. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6095. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6096. (
  6097. (
  6098. (taicpu(hp1).opcode = A_TEST)
  6099. ) or (
  6100. (taicpu(hp1).opcode = A_CMP) and
  6101. { A sanity check more than anything }
  6102. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6103. )
  6104. ) then
  6105. begin
  6106. { change
  6107. mov mem, %reg
  6108. ...
  6109. cmp/test x, %reg / test %reg,%reg
  6110. (reg deallocated)
  6111. to
  6112. cmp/test x, mem / cmp 0, mem
  6113. }
  6114. TransferUsedRegs(TmpUsedRegs);
  6115. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6116. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6117. begin
  6118. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6119. if (taicpu(hp1).opcode = A_TEST) and
  6120. (
  6121. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6122. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6123. ) then
  6124. begin
  6125. taicpu(hp1).opcode := A_CMP;
  6126. taicpu(hp1).loadconst(0, 0);
  6127. end;
  6128. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6129. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6130. RemoveCurrentP(p);
  6131. if (p <> hp1) then
  6132. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6133. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6134. { Make sure the flags are allocated across the CMP instruction }
  6135. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6136. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6137. Result := True;
  6138. Exit;
  6139. end;
  6140. end;
  6141. end;
  6142. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6143. var
  6144. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6145. ThisReg, SecondReg: TRegister;
  6146. JumpLoc: TAsmLabel;
  6147. NewSize: TOpSize;
  6148. begin
  6149. Result := False;
  6150. {
  6151. Convert:
  6152. j<c> .L1
  6153. .L2:
  6154. mov 1,reg
  6155. jmp .L3 (or ret, although it might not be a RET yet)
  6156. .L1:
  6157. mov 0,reg
  6158. jmp .L3 (or ret)
  6159. ( As long as .L3 <> .L1 or .L2)
  6160. To:
  6161. mov 0,reg
  6162. set<not(c)> reg
  6163. jmp .L3 (or ret)
  6164. .L2:
  6165. mov 1,reg
  6166. jmp .L3 (or ret)
  6167. .L1:
  6168. mov 0,reg
  6169. jmp .L3 (or ret)
  6170. }
  6171. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6172. Exit;
  6173. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6174. if GetNextInstruction(hp_label, hp2) and
  6175. MatchInstruction(hp2,A_MOV,[]) and
  6176. (taicpu(hp2).oper[0]^.typ = top_const) and
  6177. (
  6178. (
  6179. (taicpu(hp2).oper[1]^.typ = top_reg)
  6180. {$ifdef i386}
  6181. { Under i386, ESI, EDI, EBP and ESP
  6182. don't have an 8-bit representation }
  6183. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6184. {$endif i386}
  6185. ) or (
  6186. {$ifdef i386}
  6187. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6188. {$endif i386}
  6189. (taicpu(hp2).opsize = S_B)
  6190. )
  6191. ) and
  6192. GetNextInstruction(hp2, hp3) and
  6193. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6194. (
  6195. (taicpu(hp3).opcode=A_RET) or
  6196. (
  6197. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6198. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6199. )
  6200. ) and
  6201. GetNextInstruction(hp3, hp4) and
  6202. (hp4.typ=ait_label) and
  6203. (tai_label(hp4).labsym=JumpLoc) and
  6204. (
  6205. not (cs_opt_size in current_settings.optimizerswitches) or
  6206. { If the initial jump is the label's only reference, then it will
  6207. become a dead label if the other conditions are met and hence
  6208. remove at least 2 instructions, including a jump }
  6209. (JumpLoc.getrefs = 1)
  6210. ) and
  6211. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6212. that will be optimised out }
  6213. GetNextInstruction(hp4, hp5) and
  6214. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6215. (taicpu(hp5).oper[0]^.typ = top_const) and
  6216. (
  6217. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6218. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6219. ) and
  6220. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6221. GetNextInstruction(hp5,hp6) and
  6222. (
  6223. (hp6.typ<>ait_label) or
  6224. SkipLabels(hp6, hp6)
  6225. ) and
  6226. (hp6.typ=ait_instruction) then
  6227. begin
  6228. { First, let's look at the two jumps that are hp3 and hp6 }
  6229. if not
  6230. (
  6231. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6232. (
  6233. (taicpu(hp6).opcode=A_RET) or
  6234. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6235. )
  6236. ) then
  6237. { If condition is False, then the JMP/RET instructions matched conventionally }
  6238. begin
  6239. { See if one of the jumps can be instantly converted into a RET }
  6240. if (taicpu(hp3).opcode=A_JMP) then
  6241. begin
  6242. { Reuse hp5 }
  6243. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6244. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6245. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6246. Exit;
  6247. if MatchInstruction(hp5, A_RET, []) then
  6248. begin
  6249. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6250. ConvertJumpToRET(hp3, hp5);
  6251. Result := True;
  6252. end
  6253. else
  6254. Exit;
  6255. end;
  6256. if (taicpu(hp6).opcode=A_JMP) then
  6257. begin
  6258. { Reuse hp5 }
  6259. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6260. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6261. Exit;
  6262. if MatchInstruction(hp5, A_RET, []) then
  6263. begin
  6264. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6265. ConvertJumpToRET(hp6, hp5);
  6266. Result := True;
  6267. end
  6268. else
  6269. Exit;
  6270. end;
  6271. if not
  6272. (
  6273. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6274. (
  6275. (taicpu(hp6).opcode=A_RET) or
  6276. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6277. )
  6278. ) then
  6279. { Still doesn't match }
  6280. Exit;
  6281. end;
  6282. if (taicpu(hp2).oper[0]^.val = 1) then
  6283. begin
  6284. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6285. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6286. end
  6287. else
  6288. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6289. if taicpu(hp2).opsize=S_B then
  6290. begin
  6291. if taicpu(hp2).oper[1]^.typ = top_reg then
  6292. begin
  6293. SecondReg := taicpu(hp2).oper[1]^.reg;
  6294. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6295. end
  6296. else
  6297. begin
  6298. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6299. SecondReg := NR_NO;
  6300. end;
  6301. hp_pos := p;
  6302. hp_allocstart := hp4;
  6303. end
  6304. else
  6305. begin
  6306. { Will be a register because the size can't be S_B otherwise }
  6307. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6308. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6309. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6310. if (cs_opt_size in current_settings.optimizerswitches) then
  6311. begin
  6312. { Favour using MOVZX when optimising for size }
  6313. case taicpu(hp2).opsize of
  6314. S_W:
  6315. NewSize := S_BW;
  6316. S_L:
  6317. NewSize := S_BL;
  6318. {$ifdef x86_64}
  6319. S_Q:
  6320. begin
  6321. NewSize := S_BL;
  6322. { Will implicitly zero-extend to 64-bit }
  6323. setsubreg(SecondReg, R_SUBD);
  6324. end;
  6325. {$endif x86_64}
  6326. else
  6327. InternalError(2022101301);
  6328. end;
  6329. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6330. { Inserting it right before p will guarantee that the flags are also tracked }
  6331. Asml.InsertBefore(hp5, p);
  6332. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6333. hp_pos := hp5;
  6334. hp_allocstart := hp4;
  6335. end
  6336. else
  6337. begin
  6338. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6339. { Inserting it right before p will guarantee that the flags are also tracked }
  6340. Asml.InsertBefore(hp5, p);
  6341. hp_pos := p;
  6342. hp_allocstart := hp5;
  6343. end;
  6344. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6345. end;
  6346. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6347. taicpu(hp4).condition := taicpu(p).condition;
  6348. asml.InsertBefore(hp4, hp_pos);
  6349. if taicpu(hp3).is_jmp then
  6350. begin
  6351. JumpLoc.decrefs;
  6352. MakeUnconditional(taicpu(p));
  6353. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6354. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6355. end
  6356. else
  6357. ConvertJumpToRET(p, hp3);
  6358. if SecondReg <> NR_NO then
  6359. { Ensure the destination register is allocated over this region }
  6360. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6361. if (JumpLoc.getrefs = 0) then
  6362. RemoveDeadCodeAfterJump(hp3);
  6363. Result:=true;
  6364. exit;
  6365. end;
  6366. end;
  6367. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6368. var
  6369. hp1, hp2: tai;
  6370. ActiveReg: TRegister;
  6371. OldOffset: asizeint;
  6372. ThisConst: TCGInt;
  6373. function RegDeallocated: Boolean;
  6374. begin
  6375. TransferUsedRegs(TmpUsedRegs);
  6376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6377. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6378. end;
  6379. begin
  6380. Result:=false;
  6381. hp1 := nil;
  6382. { replace
  6383. subX const,%reg1
  6384. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6385. dealloc %reg1
  6386. by
  6387. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6388. }
  6389. if MatchOpType(taicpu(p),top_const,top_reg) then
  6390. begin
  6391. ActiveReg := taicpu(p).oper[1]^.reg;
  6392. { Ensures the entire register was updated }
  6393. if (taicpu(p).opsize >= S_L) and
  6394. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6395. MatchInstruction(hp1,A_LEA,[]) and
  6396. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6397. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6398. (
  6399. { Cover the case where the register in the reference is also the destination register }
  6400. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6401. (
  6402. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6403. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6404. RegDeallocated
  6405. )
  6406. ) then
  6407. begin
  6408. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6409. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6410. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6411. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6412. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6413. {$ifdef x86_64}
  6414. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6415. begin
  6416. { Overflow; abort }
  6417. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6418. end
  6419. else
  6420. {$endif x86_64}
  6421. begin
  6422. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6423. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6424. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6425. RemoveCurrentP(p, hp1)
  6426. else
  6427. RemoveCurrentP(p);
  6428. result:=true;
  6429. Exit;
  6430. end;
  6431. end;
  6432. if (
  6433. { Save calling GetNextInstructionUsingReg again }
  6434. Assigned(hp1) or
  6435. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6436. ) and
  6437. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6438. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6439. begin
  6440. if taicpu(hp1).oper[0]^.typ = top_const then
  6441. begin
  6442. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6443. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6444. Result := True;
  6445. { Handle any overflows }
  6446. case taicpu(p).opsize of
  6447. S_B:
  6448. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6449. S_W:
  6450. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6451. S_L:
  6452. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6453. {$ifdef x86_64}
  6454. S_Q:
  6455. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6456. { Overflow; abort }
  6457. Result := False
  6458. else
  6459. taicpu(p).oper[0]^.val := ThisConst;
  6460. {$endif x86_64}
  6461. else
  6462. InternalError(2021102611);
  6463. end;
  6464. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6465. if Result then
  6466. begin
  6467. if (taicpu(p).oper[0]^.val < 0) and
  6468. (
  6469. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6470. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6471. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6472. ) then
  6473. begin
  6474. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6475. taicpu(p).opcode := A_SUB;
  6476. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6477. end
  6478. else
  6479. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6480. RemoveInstruction(hp1);
  6481. end;
  6482. end
  6483. else
  6484. begin
  6485. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6486. TransferUsedRegs(TmpUsedRegs);
  6487. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6488. hp2 := p;
  6489. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6490. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6491. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6492. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6493. begin
  6494. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6495. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6496. Asml.Remove(p);
  6497. Asml.InsertAfter(p, hp1);
  6498. p := hp1;
  6499. Result := True;
  6500. Exit;
  6501. end;
  6502. end;
  6503. end;
  6504. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6505. { * change "sub/add const1, reg" or "dec reg" followed by
  6506. "sub const2, reg" to one "sub ..., reg" }
  6507. {$ifdef i386}
  6508. if (taicpu(p).oper[0]^.val = 2) and
  6509. (ActiveReg = NR_ESP) and
  6510. { Don't do the sub/push optimization if the sub }
  6511. { comes from setting up the stack frame (JM) }
  6512. (not(GetLastInstruction(p,hp1)) or
  6513. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6514. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6515. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6516. begin
  6517. hp1 := tai(p.next);
  6518. while Assigned(hp1) and
  6519. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6520. not RegReadByInstruction(NR_ESP,hp1) and
  6521. not RegModifiedByInstruction(NR_ESP,hp1) do
  6522. hp1 := tai(hp1.next);
  6523. if Assigned(hp1) and
  6524. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6525. begin
  6526. taicpu(hp1).changeopsize(S_L);
  6527. if taicpu(hp1).oper[0]^.typ=top_reg then
  6528. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6529. hp1 := tai(p.next);
  6530. RemoveCurrentp(p, hp1);
  6531. Result:=true;
  6532. exit;
  6533. end;
  6534. end;
  6535. {$endif i386}
  6536. if DoArithCombineOpt(p) then
  6537. Result:=true;
  6538. end;
  6539. end;
  6540. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6541. var
  6542. TmpBool1,TmpBool2 : Boolean;
  6543. tmpref : treference;
  6544. hp1,hp2: tai;
  6545. mask, shiftval: tcgint;
  6546. begin
  6547. Result:=false;
  6548. { All these optimisations work on "shl/sal const,%reg" }
  6549. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6550. Exit;
  6551. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6552. (taicpu(p).oper[0]^.val <= 3) then
  6553. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6554. begin
  6555. { should we check the next instruction? }
  6556. TmpBool1 := True;
  6557. { have we found an add/sub which could be
  6558. integrated in the lea? }
  6559. TmpBool2 := False;
  6560. reference_reset(tmpref,2,[]);
  6561. TmpRef.index := taicpu(p).oper[1]^.reg;
  6562. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6563. while TmpBool1 and
  6564. GetNextInstruction(p, hp1) and
  6565. (tai(hp1).typ = ait_instruction) and
  6566. ((((taicpu(hp1).opcode = A_ADD) or
  6567. (taicpu(hp1).opcode = A_SUB)) and
  6568. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6569. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6570. (((taicpu(hp1).opcode = A_INC) or
  6571. (taicpu(hp1).opcode = A_DEC)) and
  6572. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6573. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6574. ((taicpu(hp1).opcode = A_LEA) and
  6575. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6576. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6577. (not GetNextInstruction(hp1,hp2) or
  6578. not instrReadsFlags(hp2)) Do
  6579. begin
  6580. TmpBool1 := False;
  6581. if taicpu(hp1).opcode=A_LEA then
  6582. begin
  6583. if (TmpRef.base = NR_NO) and
  6584. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6585. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6586. { Segment register isn't a concern here }
  6587. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6588. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6589. begin
  6590. TmpBool1 := True;
  6591. TmpBool2 := True;
  6592. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6593. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6594. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6595. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6596. RemoveInstruction(hp1);
  6597. end
  6598. end
  6599. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6600. begin
  6601. TmpBool1 := True;
  6602. TmpBool2 := True;
  6603. case taicpu(hp1).opcode of
  6604. A_ADD:
  6605. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6606. A_SUB:
  6607. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6608. else
  6609. internalerror(2019050536);
  6610. end;
  6611. RemoveInstruction(hp1);
  6612. end
  6613. else
  6614. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6615. (((taicpu(hp1).opcode = A_ADD) and
  6616. (TmpRef.base = NR_NO)) or
  6617. (taicpu(hp1).opcode = A_INC) or
  6618. (taicpu(hp1).opcode = A_DEC)) then
  6619. begin
  6620. TmpBool1 := True;
  6621. TmpBool2 := True;
  6622. case taicpu(hp1).opcode of
  6623. A_ADD:
  6624. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6625. A_INC:
  6626. inc(TmpRef.offset);
  6627. A_DEC:
  6628. dec(TmpRef.offset);
  6629. else
  6630. internalerror(2019050535);
  6631. end;
  6632. RemoveInstruction(hp1);
  6633. end;
  6634. end;
  6635. if TmpBool2
  6636. {$ifndef x86_64}
  6637. or
  6638. ((current_settings.optimizecputype < cpu_Pentium2) and
  6639. (taicpu(p).oper[0]^.val <= 3) and
  6640. not(cs_opt_size in current_settings.optimizerswitches))
  6641. {$endif x86_64}
  6642. then
  6643. begin
  6644. if not(TmpBool2) and
  6645. (taicpu(p).oper[0]^.val=1) then
  6646. begin
  6647. taicpu(p).opcode := A_ADD;
  6648. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6649. end
  6650. else
  6651. begin
  6652. taicpu(p).opcode := A_LEA;
  6653. taicpu(p).loadref(0, TmpRef);
  6654. end;
  6655. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6656. Result := True;
  6657. end;
  6658. end
  6659. {$ifndef x86_64}
  6660. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6661. begin
  6662. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6663. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6664. (unlike shl, which is only Tairable in the U pipe) }
  6665. if taicpu(p).oper[0]^.val=1 then
  6666. begin
  6667. taicpu(p).opcode := A_ADD;
  6668. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6669. Result := True;
  6670. end
  6671. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6672. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6673. else if (taicpu(p).opsize = S_L) and
  6674. (taicpu(p).oper[0]^.val<= 3) then
  6675. begin
  6676. reference_reset(tmpref,2,[]);
  6677. TmpRef.index := taicpu(p).oper[1]^.reg;
  6678. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6679. taicpu(p).opcode := A_LEA;
  6680. taicpu(p).loadref(0, TmpRef);
  6681. Result := True;
  6682. end;
  6683. end
  6684. {$endif x86_64}
  6685. else if
  6686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6687. (
  6688. (
  6689. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6690. SetAndTest(hp1, hp2)
  6691. {$ifdef x86_64}
  6692. ) or
  6693. (
  6694. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6695. GetNextInstruction(hp1, hp2) and
  6696. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6697. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6698. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6699. {$endif x86_64}
  6700. )
  6701. ) and
  6702. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6703. begin
  6704. { Change:
  6705. shl x, %reg1
  6706. mov -(1<<x), %reg2
  6707. and %reg2, %reg1
  6708. Or:
  6709. shl x, %reg1
  6710. and -(1<<x), %reg1
  6711. To just:
  6712. shl x, %reg1
  6713. Since the and operation only zeroes bits that are already zero from the shl operation
  6714. }
  6715. case taicpu(p).oper[0]^.val of
  6716. 8:
  6717. mask:=$FFFFFFFFFFFFFF00;
  6718. 16:
  6719. mask:=$FFFFFFFFFFFF0000;
  6720. 32:
  6721. mask:=$FFFFFFFF00000000;
  6722. 63:
  6723. { Constant pre-calculated to prevent overflow errors with Int64 }
  6724. mask:=$8000000000000000;
  6725. else
  6726. begin
  6727. if taicpu(p).oper[0]^.val >= 64 then
  6728. { Shouldn't happen realistically, since the register
  6729. is guaranteed to be set to zero at this point }
  6730. mask := 0
  6731. else
  6732. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6733. end;
  6734. end;
  6735. if taicpu(hp1).oper[0]^.val = mask then
  6736. begin
  6737. { Everything checks out, perform the optimisation, as long as
  6738. the FLAGS register isn't being used}
  6739. TransferUsedRegs(TmpUsedRegs);
  6740. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6741. {$ifdef x86_64}
  6742. if (hp1 <> hp2) then
  6743. begin
  6744. { "shl/mov/and" version }
  6745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6746. { Don't do the optimisation if the FLAGS register is in use }
  6747. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6748. begin
  6749. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6750. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6751. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6752. begin
  6753. RemoveInstruction(hp1);
  6754. Result := True;
  6755. end;
  6756. { Only set Result to True if the 'mov' instruction was removed }
  6757. RemoveInstruction(hp2);
  6758. end;
  6759. end
  6760. else
  6761. {$endif x86_64}
  6762. begin
  6763. { "shl/and" version }
  6764. { Don't do the optimisation if the FLAGS register is in use }
  6765. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6766. begin
  6767. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6768. RemoveInstruction(hp1);
  6769. Result := True;
  6770. end;
  6771. end;
  6772. Exit;
  6773. end
  6774. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6775. begin
  6776. { Even if the mask doesn't allow for its removal, we might be
  6777. able to optimise the mask for the "shl/and" version, which
  6778. may permit other peephole optimisations }
  6779. {$ifdef DEBUG_AOPTCPU}
  6780. mask := taicpu(hp1).oper[0]^.val and mask;
  6781. if taicpu(hp1).oper[0]^.val <> mask then
  6782. begin
  6783. DebugMsg(
  6784. SPeepholeOptimization +
  6785. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6786. ' to $' + debug_tostr(mask) +
  6787. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6788. taicpu(hp1).oper[0]^.val := mask;
  6789. end;
  6790. {$else DEBUG_AOPTCPU}
  6791. { If debugging is off, just set the operand even if it's the same }
  6792. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6793. {$endif DEBUG_AOPTCPU}
  6794. end;
  6795. end;
  6796. {
  6797. change
  6798. shl/sal const,reg
  6799. <op> ...(...,reg,1),...
  6800. into
  6801. <op> ...(...,reg,1 shl const),...
  6802. if const in 1..3
  6803. }
  6804. if MatchOpType(taicpu(p), top_const, top_reg) and
  6805. (taicpu(p).oper[0]^.val in [1..3]) and
  6806. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6807. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6808. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6809. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6810. MatchOpType(taicpu(hp1),top_ref))
  6811. ) and
  6812. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6813. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6814. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6815. begin
  6816. TransferUsedRegs(TmpUsedRegs);
  6817. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6818. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6819. begin
  6820. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6821. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6822. RemoveCurrentP(p);
  6823. Result:=true;
  6824. exit;
  6825. end;
  6826. end;
  6827. if MatchOpType(taicpu(p), top_const, top_reg) and
  6828. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6829. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6830. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6831. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6832. begin
  6833. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6834. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6835. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6836. {$ifdef x86_64}
  6837. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6838. {$endif x86_64}
  6839. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6840. begin
  6841. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6842. taicpu(hp1).opcode:=A_MOV;
  6843. taicpu(hp1).oper[0]^.val:=0;
  6844. end
  6845. else
  6846. begin
  6847. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6848. taicpu(hp1).oper[0]^.val:=shiftval;
  6849. end;
  6850. RemoveCurrentP(p);
  6851. Result:=true;
  6852. exit;
  6853. end;
  6854. end;
  6855. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6856. begin
  6857. case shr_size of
  6858. S_B:
  6859. { No valid combinations }
  6860. Result := False;
  6861. S_W:
  6862. Result := (Shift >= 8) and (movz_size = S_BW);
  6863. S_L:
  6864. Result :=
  6865. (Shift >= 24) { Any opsize is valid for this shift } or
  6866. ((Shift >= 16) and (movz_size = S_WL));
  6867. {$ifdef x86_64}
  6868. S_Q:
  6869. Result :=
  6870. (Shift >= 56) { Any opsize is valid for this shift } or
  6871. ((Shift >= 48) and (movz_size = S_WL));
  6872. {$endif x86_64}
  6873. else
  6874. InternalError(2022081510);
  6875. end;
  6876. end;
  6877. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6878. var
  6879. hp1, hp2: tai;
  6880. Shift: TCGInt;
  6881. LimitSize: Topsize;
  6882. DoNotMerge: Boolean;
  6883. begin
  6884. Result := False;
  6885. { All these optimisations work on "shr const,%reg" }
  6886. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6887. Exit;
  6888. DoNotMerge := False;
  6889. Shift := taicpu(p).oper[0]^.val;
  6890. LimitSize := taicpu(p).opsize;
  6891. hp1 := p;
  6892. repeat
  6893. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6894. Exit;
  6895. case taicpu(hp1).opcode of
  6896. A_TEST, A_CMP, A_Jcc:
  6897. { Skip over conditional jumps and relevant comparisons }
  6898. Continue;
  6899. A_MOVZX:
  6900. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6901. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6902. begin
  6903. { Since the original register is being read as is, subsequent
  6904. SHRs must not be merged at this point }
  6905. DoNotMerge := True;
  6906. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6907. begin
  6908. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6909. begin
  6910. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6911. taicpu(hp1).opcode := A_MOV;
  6912. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6913. case taicpu(hp1).opsize of
  6914. S_BW:
  6915. taicpu(hp1).opsize := S_W;
  6916. S_BL, S_WL:
  6917. taicpu(hp1).opsize := S_L;
  6918. else
  6919. InternalError(2022081503);
  6920. end;
  6921. { p itself hasn't changed, so no need to set Result to True }
  6922. Include(OptsToCheck, aoc_ForceNewIteration);
  6923. { See if there's anything afterwards that can be
  6924. optimised, since the input register hasn't changed }
  6925. Continue;
  6926. end;
  6927. { NOTE: If the MOVZX instruction reads and writes the same
  6928. register, defer this to the post-peephole optimisation stage }
  6929. Exit;
  6930. end;
  6931. end;
  6932. A_SHL, A_SAL, A_SHR:
  6933. if (taicpu(hp1).opsize <= LimitSize) and
  6934. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6935. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6936. begin
  6937. { Make sure the sizes don't exceed the register size limit
  6938. (measured by the shift value falling below the limit) }
  6939. if taicpu(hp1).opsize < LimitSize then
  6940. LimitSize := taicpu(hp1).opsize;
  6941. if taicpu(hp1).opcode = A_SHR then
  6942. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6943. else
  6944. begin
  6945. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6946. DoNotMerge := True;
  6947. end;
  6948. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6949. Exit;
  6950. { Since we've established that the combined shift is within
  6951. limits, we can actually combine the adjacent SHR
  6952. instructions even if they're different sizes }
  6953. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6954. begin
  6955. hp2 := tai(hp1.Previous);
  6956. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6957. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6958. RemoveInstruction(hp1);
  6959. hp1 := hp2;
  6960. { Though p has changed, only the constant has, and its
  6961. effects can still be detected on the next iteration of
  6962. the repeat..until loop }
  6963. Include(OptsToCheck, aoc_ForceNewIteration);
  6964. end;
  6965. { Move onto the next instruction }
  6966. Continue;
  6967. end;
  6968. else
  6969. ;
  6970. end;
  6971. Break;
  6972. until False;
  6973. end;
  6974. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6975. var
  6976. CurrentRef: TReference;
  6977. FullReg: TRegister;
  6978. hp1, hp2: tai;
  6979. begin
  6980. Result := False;
  6981. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6982. Exit;
  6983. { We assume you've checked if the operand is actually a reference by
  6984. this point. If it isn't, you'll most likely get an access violation }
  6985. CurrentRef := first_mov.oper[1]^.ref^;
  6986. { Memory must be aligned }
  6987. if (CurrentRef.offset mod 4) <> 0 then
  6988. Exit;
  6989. Inc(CurrentRef.offset);
  6990. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6991. if MatchOperand(second_mov.oper[0]^, 0) and
  6992. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6993. GetNextInstruction(second_mov, hp1) and
  6994. (hp1.typ = ait_instruction) and
  6995. (taicpu(hp1).opcode = A_MOV) and
  6996. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6997. (taicpu(hp1).oper[0]^.val = 0) then
  6998. begin
  6999. Inc(CurrentRef.offset);
  7000. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7001. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7002. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7003. begin
  7004. case taicpu(hp1).opsize of
  7005. S_B:
  7006. if GetNextInstruction(hp1, hp2) and
  7007. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7008. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7009. (taicpu(hp2).oper[0]^.val = 0) then
  7010. begin
  7011. Inc(CurrentRef.offset);
  7012. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7013. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7014. (taicpu(hp2).opsize = S_B) then
  7015. begin
  7016. RemoveInstruction(hp1);
  7017. RemoveInstruction(hp2);
  7018. first_mov.opsize := S_L;
  7019. if first_mov.oper[0]^.typ = top_reg then
  7020. begin
  7021. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7022. { Reuse second_mov as a MOVZX instruction }
  7023. second_mov.opcode := A_MOVZX;
  7024. second_mov.opsize := S_BL;
  7025. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7026. second_mov.loadreg(1, FullReg);
  7027. first_mov.oper[0]^.reg := FullReg;
  7028. asml.Remove(second_mov);
  7029. asml.InsertBefore(second_mov, first_mov);
  7030. end
  7031. else
  7032. { It's a value }
  7033. begin
  7034. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7035. RemoveInstruction(second_mov);
  7036. end;
  7037. Result := True;
  7038. Exit;
  7039. end;
  7040. end;
  7041. S_W:
  7042. begin
  7043. RemoveInstruction(hp1);
  7044. first_mov.opsize := S_L;
  7045. if first_mov.oper[0]^.typ = top_reg then
  7046. begin
  7047. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7048. { Reuse second_mov as a MOVZX instruction }
  7049. second_mov.opcode := A_MOVZX;
  7050. second_mov.opsize := S_BL;
  7051. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7052. second_mov.loadreg(1, FullReg);
  7053. first_mov.oper[0]^.reg := FullReg;
  7054. asml.Remove(second_mov);
  7055. asml.InsertBefore(second_mov, first_mov);
  7056. end
  7057. else
  7058. { It's a value }
  7059. begin
  7060. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7061. RemoveInstruction(second_mov);
  7062. end;
  7063. Result := True;
  7064. Exit;
  7065. end;
  7066. else
  7067. ;
  7068. end;
  7069. end;
  7070. end;
  7071. end;
  7072. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7073. { returns true if a "continue" should be done after this optimization }
  7074. var
  7075. hp1, hp2, hp3: tai;
  7076. begin
  7077. Result := false;
  7078. hp3 := nil;
  7079. if MatchOpType(taicpu(p),top_ref) and
  7080. GetNextInstruction(p, hp1) and
  7081. (hp1.typ = ait_instruction) and
  7082. (((taicpu(hp1).opcode = A_FLD) and
  7083. (taicpu(p).opcode = A_FSTP)) or
  7084. ((taicpu(p).opcode = A_FISTP) and
  7085. (taicpu(hp1).opcode = A_FILD))) and
  7086. MatchOpType(taicpu(hp1),top_ref) and
  7087. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7088. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7089. begin
  7090. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7091. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7092. GetNextInstruction(hp1, hp2) and
  7093. (((hp2.typ = ait_instruction) and
  7094. IsExitCode(hp2) and
  7095. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7096. not(assigned(current_procinfo.procdef.funcretsym) and
  7097. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7098. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7099. { fstp <temp>
  7100. fld <temp>
  7101. <dealloc> <temp>
  7102. }
  7103. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7104. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7105. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7106. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7107. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7108. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7109. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7110. )
  7111. )
  7112. ) then
  7113. begin
  7114. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7115. RemoveInstruction(hp1);
  7116. RemoveCurrentP(p, hp2);
  7117. { first case: exit code }
  7118. if hp2.typ = ait_instruction then
  7119. RemoveLastDeallocForFuncRes(p);
  7120. Result := true;
  7121. end
  7122. else
  7123. { we can do this only in fast math mode as fstp is rounding ...
  7124. ... still disabled as it breaks the compiler and/or rtl }
  7125. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7126. { ... or if another fstp equal to the first one follows }
  7127. GetNextInstruction(hp1,hp2) and
  7128. (hp2.typ = ait_instruction) and
  7129. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7130. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7131. begin
  7132. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7133. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7134. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7135. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7136. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7137. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7138. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7139. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7140. ) then
  7141. begin
  7142. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7143. RemoveCurrentP(p,hp2);
  7144. RemoveInstruction(hp1);
  7145. Result := true;
  7146. end
  7147. else if { fst can't store an extended/comp value }
  7148. (taicpu(p).opsize <> S_FX) and
  7149. (taicpu(p).opsize <> S_IQ) then
  7150. begin
  7151. if (taicpu(p).opcode = A_FSTP) then
  7152. taicpu(p).opcode := A_FST
  7153. else
  7154. taicpu(p).opcode := A_FIST;
  7155. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7156. RemoveInstruction(hp1);
  7157. Result := true;
  7158. end;
  7159. end;
  7160. end;
  7161. end;
  7162. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7163. var
  7164. hp1, hp2, hp3: tai;
  7165. begin
  7166. result:=false;
  7167. if MatchOpType(taicpu(p),top_reg) and
  7168. GetNextInstruction(p, hp1) and
  7169. (hp1.typ = Ait_Instruction) and
  7170. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7171. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7172. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7173. { change to
  7174. fld reg fxxx reg,st
  7175. fxxxp st, st1 (hp1)
  7176. Remark: non commutative operations must be reversed!
  7177. }
  7178. begin
  7179. case taicpu(hp1).opcode Of
  7180. A_FMULP,A_FADDP,
  7181. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7182. begin
  7183. case taicpu(hp1).opcode Of
  7184. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7185. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7186. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7187. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7188. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7189. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7190. else
  7191. internalerror(2019050534);
  7192. end;
  7193. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7194. taicpu(hp1).oper[1]^.reg := NR_ST;
  7195. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7196. RemoveCurrentP(p, hp1);
  7197. Result:=true;
  7198. exit;
  7199. end;
  7200. else
  7201. ;
  7202. end;
  7203. end
  7204. else
  7205. if MatchOpType(taicpu(p),top_ref) and
  7206. GetNextInstruction(p, hp2) and
  7207. (hp2.typ = Ait_Instruction) and
  7208. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7209. (taicpu(p).opsize in [S_FS, S_FL]) and
  7210. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7211. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7212. if GetLastInstruction(p, hp1) and
  7213. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7214. MatchOpType(taicpu(hp1),top_ref) and
  7215. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7216. if ((taicpu(hp2).opcode = A_FMULP) or
  7217. (taicpu(hp2).opcode = A_FADDP)) then
  7218. { change to
  7219. fld/fst mem1 (hp1) fld/fst mem1
  7220. fld mem1 (p) fadd/
  7221. faddp/ fmul st, st
  7222. fmulp st, st1 (hp2) }
  7223. begin
  7224. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7225. RemoveCurrentP(p, hp1);
  7226. if (taicpu(hp2).opcode = A_FADDP) then
  7227. taicpu(hp2).opcode := A_FADD
  7228. else
  7229. taicpu(hp2).opcode := A_FMUL;
  7230. taicpu(hp2).oper[1]^.reg := NR_ST;
  7231. end
  7232. else
  7233. { change to
  7234. fld/fst mem1 (hp1) fld/fst mem1
  7235. fld mem1 (p) fld st
  7236. }
  7237. begin
  7238. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7239. taicpu(p).changeopsize(S_FL);
  7240. taicpu(p).loadreg(0,NR_ST);
  7241. end
  7242. else
  7243. begin
  7244. case taicpu(hp2).opcode Of
  7245. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7246. { change to
  7247. fld/fst mem1 (hp1) fld/fst mem1
  7248. fld mem2 (p) fxxx mem2
  7249. fxxxp st, st1 (hp2) }
  7250. begin
  7251. case taicpu(hp2).opcode Of
  7252. A_FADDP: taicpu(p).opcode := A_FADD;
  7253. A_FMULP: taicpu(p).opcode := A_FMUL;
  7254. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7255. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7256. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7257. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7258. else
  7259. internalerror(2019050533);
  7260. end;
  7261. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7262. RemoveInstruction(hp2);
  7263. end
  7264. else
  7265. ;
  7266. end
  7267. end
  7268. end;
  7269. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7270. begin
  7271. Result := condition_in(cond1, cond2) or
  7272. { Not strictly subsets due to the actual flags checked, but because we're
  7273. comparing integers, E is a subset of AE and GE and their aliases }
  7274. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7275. end;
  7276. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7277. var
  7278. v: TCGInt;
  7279. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7280. FirstMatch, TempBool: Boolean;
  7281. NewReg: TRegister;
  7282. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7283. begin
  7284. Result:=false;
  7285. { All these optimisations need a next instruction }
  7286. if not GetNextInstruction(p, hp1) then
  7287. Exit;
  7288. true_hp1 := hp1;
  7289. { Search for:
  7290. cmp ###,###
  7291. j(c1) @lbl1
  7292. ...
  7293. @lbl:
  7294. cmp ###,### (same comparison as above)
  7295. j(c2) @lbl2
  7296. If c1 is a subset of c2, change to:
  7297. cmp ###,###
  7298. j(c1) @lbl2
  7299. (@lbl1 may become a dead label as a result)
  7300. }
  7301. { Also handle cases where there are multiple jumps in a row }
  7302. p_jump := hp1;
  7303. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7304. begin
  7305. Prefetch(p_jump.Next);
  7306. if IsJumpToLabel(taicpu(p_jump)) then
  7307. begin
  7308. { Do jump optimisations first in case the condition becomes
  7309. unnecessary }
  7310. TempBool := True;
  7311. if DoJumpOptimizations(p_jump, TempBool) or
  7312. not TempBool then
  7313. begin
  7314. if Assigned(p_jump) then
  7315. begin
  7316. { CollapseZeroDistJump will be set to the label or an align
  7317. before it after the jump if it optimises, whether or not
  7318. the label is live or dead }
  7319. if (p_jump.typ = ait_align) or
  7320. (
  7321. (p_jump.typ = ait_label) and
  7322. not (tai_label(p_jump).labsym.is_used)
  7323. ) then
  7324. GetNextInstruction(p_jump, p_jump);
  7325. end;
  7326. TransferUsedRegs(TmpUsedRegs);
  7327. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7328. if not Assigned(p_jump) or
  7329. (
  7330. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7331. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7332. ) then
  7333. begin
  7334. { No more conditional jumps; conditional statement is no longer required }
  7335. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7336. RemoveCurrentP(p);
  7337. Result := True;
  7338. Exit;
  7339. end;
  7340. hp1 := p_jump;
  7341. Include(OptsToCheck, aoc_ForceNewIteration);
  7342. Continue;
  7343. end;
  7344. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7345. if GetNextInstruction(p_jump, hp2) and
  7346. (
  7347. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7348. not TempBool
  7349. ) then
  7350. begin
  7351. hp1 := p_jump;
  7352. Include(OptsToCheck, aoc_ForceNewIteration);
  7353. Continue;
  7354. end;
  7355. p_label := nil;
  7356. if Assigned(JumpLabel) then
  7357. p_label := getlabelwithsym(JumpLabel);
  7358. if Assigned(p_label) and
  7359. GetNextInstruction(p_label, p_dist) and
  7360. MatchInstruction(p_dist, A_CMP, []) and
  7361. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7362. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7363. GetNextInstruction(p_dist, hp1_dist) and
  7364. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7365. begin
  7366. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7367. if JumpLabel = JumpLabel_dist then
  7368. { This is an infinite loop }
  7369. Exit;
  7370. { Best optimisation when the first condition is a subset (or equal) of the second }
  7371. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7372. begin
  7373. { Any registers used here will already be allocated }
  7374. if Assigned(JumpLabel) then
  7375. JumpLabel.DecRefs;
  7376. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7377. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7378. Include(OptsToCheck, aoc_ForceNewIteration);
  7379. { Don't exit yet. Since p and p_jump haven't actually been
  7380. removed, we can check for more on this iteration }
  7381. end
  7382. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7383. GetNextInstruction(hp1_dist, hp1_label) and
  7384. (hp1_label.typ = ait_label) then
  7385. begin
  7386. JumpLabel_far := tai_label(hp1_label).labsym;
  7387. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7388. { This is an infinite loop }
  7389. Exit;
  7390. if Assigned(JumpLabel_far) then
  7391. begin
  7392. { In this situation, if the first jump branches, the second one will never,
  7393. branch so change the destination label to after the second jump }
  7394. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7395. if Assigned(JumpLabel) then
  7396. JumpLabel.DecRefs;
  7397. JumpLabel_far.IncRefs;
  7398. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7399. Result := True;
  7400. { Don't exit yet. Since p and p_jump haven't actually been
  7401. removed, we can check for more on this iteration }
  7402. Continue;
  7403. end;
  7404. end;
  7405. end;
  7406. end;
  7407. { Search for:
  7408. cmp ###,###
  7409. j(c1) @lbl1
  7410. cmp ###,### (same as first)
  7411. Remove second cmp
  7412. }
  7413. if GetNextInstruction(p_jump, hp2) and
  7414. (
  7415. (
  7416. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7417. (
  7418. (
  7419. MatchOpType(taicpu(p), top_const, top_reg) and
  7420. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7421. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7422. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7423. ) or (
  7424. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7425. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7426. )
  7427. )
  7428. ) or (
  7429. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7430. MatchOperand(taicpu(p).oper[0]^, 0) and
  7431. (taicpu(p).oper[1]^.typ = top_reg) and
  7432. MatchInstruction(hp2, A_TEST, []) and
  7433. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7434. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7435. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7436. )
  7437. ) then
  7438. begin
  7439. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7440. TransferUsedRegs(TmpUsedRegs);
  7441. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7442. RemoveInstruction(hp2);
  7443. Result := True;
  7444. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7445. end
  7446. else
  7447. begin
  7448. { hp2 is the next instruction, so save time and just set p_jump
  7449. to it instead of calling GetNextInstruction below }
  7450. p_jump := hp2;
  7451. Continue;
  7452. end;
  7453. GetNextInstruction(p_jump, p_jump);
  7454. end;
  7455. if (
  7456. { Don't call GetNextInstruction again if we already have it }
  7457. (true_hp1 = p_jump) or
  7458. GetNextInstruction(p, hp1)
  7459. ) and
  7460. MatchInstruction(hp1, A_Jcc, []) and
  7461. IsJumpToLabel(taicpu(hp1)) and
  7462. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7463. GetNextInstruction(hp1, hp2) then
  7464. begin
  7465. {
  7466. cmp x, y (or "cmp y, x")
  7467. je @lbl
  7468. mov x, y
  7469. @lbl:
  7470. (x and y can be constants, registers or references)
  7471. Change to:
  7472. mov x, y (x and y will always be equal in the end)
  7473. @lbl: (may beceome a dead label)
  7474. Also:
  7475. cmp x, y (or "cmp y, x")
  7476. jne @lbl
  7477. mov x, y
  7478. @lbl:
  7479. (x and y can be constants, registers or references)
  7480. Change to:
  7481. Absolutely nothing! (Except @lbl if it's still live)
  7482. }
  7483. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7484. (
  7485. (
  7486. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7487. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7488. ) or (
  7489. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7490. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7491. )
  7492. ) and
  7493. GetNextInstruction(hp2, hp1_label) and
  7494. (hp1_label.typ = ait_label) and
  7495. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7496. begin
  7497. tai_label(hp1_label).labsym.DecRefs;
  7498. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7499. begin
  7500. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7501. RemoveInstruction(hp2);
  7502. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7503. end
  7504. else
  7505. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7506. RemoveInstruction(hp1);
  7507. RemoveCurrentp(p, hp2);
  7508. Result := True;
  7509. Exit;
  7510. end;
  7511. {
  7512. Try to optimise the following:
  7513. cmp $x,### ($x and $y can be registers or constants)
  7514. je @lbl1 (only reference)
  7515. cmp $y,### (### are identical)
  7516. @Lbl:
  7517. sete %reg1
  7518. Change to:
  7519. cmp $x,###
  7520. sete %reg2 (allocate new %reg2)
  7521. cmp $y,###
  7522. sete %reg1
  7523. orb %reg2,%reg1
  7524. (dealloc %reg2)
  7525. This adds an instruction (so don't perform under -Os), but it removes
  7526. a conditional branch.
  7527. }
  7528. if not (cs_opt_size in current_settings.optimizerswitches) and
  7529. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7530. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7531. { The first operand of CMP instructions can only be a register or
  7532. immediate anyway, so no need to check }
  7533. GetNextInstruction(hp2, p_label) and
  7534. (p_label.typ = ait_label) and
  7535. (tai_label(p_label).labsym.getrefs = 1) and
  7536. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7537. GetNextInstruction(p_label, p_dist) and
  7538. MatchInstruction(p_dist, A_SETcc, []) and
  7539. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7540. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7541. begin
  7542. TransferUsedRegs(TmpUsedRegs);
  7543. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7544. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7545. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7546. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7547. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7548. { Get the instruction after the SETcc instruction so we can
  7549. allocate a new register over the entire range }
  7550. GetNextInstruction(p_dist, hp1_dist) then
  7551. begin
  7552. { Register can appear in p if it's not used afterwards, so only
  7553. allocate between hp1 and hp1_dist }
  7554. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7555. if NewReg <> NR_NO then
  7556. begin
  7557. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7558. { Change the jump instruction into a SETcc instruction }
  7559. taicpu(hp1).opcode := A_SETcc;
  7560. taicpu(hp1).opsize := S_B;
  7561. taicpu(hp1).loadreg(0, NewReg);
  7562. { This is now a dead label }
  7563. tai_label(p_label).labsym.decrefs;
  7564. { Prefer adding before the next instruction so the FLAGS
  7565. register is deallicated first }
  7566. AsmL.InsertBefore(
  7567. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7568. hp1_dist
  7569. );
  7570. Result := True;
  7571. { Don't exit yet, as p wasn't changed and hp1, while
  7572. modified, is still intact and might be optimised by the
  7573. SETcc optimisation below }
  7574. end;
  7575. end;
  7576. end;
  7577. end;
  7578. if (taicpu(p).oper[0]^.typ = top_const) and
  7579. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7580. begin
  7581. if (taicpu(p).oper[0]^.val = 0) and
  7582. (taicpu(p).oper[1]^.typ = top_reg) then
  7583. begin
  7584. hp2 := p;
  7585. FirstMatch := True;
  7586. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7587. anything meaningful once it's converted to "test %reg,%reg";
  7588. additionally, some jumps will always (or never) branch, so
  7589. evaluate every jump immediately following the
  7590. comparison, optimising the conditions if possible.
  7591. Similarly with SETcc... those that are always set to 0 or 1
  7592. are changed to MOV instructions }
  7593. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7594. (
  7595. GetNextInstruction(hp2, hp1) and
  7596. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7597. ) do
  7598. begin
  7599. Prefetch(hp1.Next);
  7600. FirstMatch := False;
  7601. case taicpu(hp1).condition of
  7602. C_B, C_C, C_NAE, C_O:
  7603. { For B/NAE:
  7604. Will never branch since an unsigned integer can never be below zero
  7605. For C/O:
  7606. Result cannot overflow because 0 is being subtracted
  7607. }
  7608. begin
  7609. if taicpu(hp1).opcode = A_Jcc then
  7610. begin
  7611. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7612. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7613. RemoveInstruction(hp1);
  7614. { Since hp1 was deleted, hp2 must not be updated }
  7615. Continue;
  7616. end
  7617. else
  7618. begin
  7619. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7620. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7621. taicpu(hp1).opcode := A_MOV;
  7622. taicpu(hp1).ops := 2;
  7623. taicpu(hp1).condition := C_None;
  7624. taicpu(hp1).opsize := S_B;
  7625. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7626. taicpu(hp1).loadconst(0, 0);
  7627. end;
  7628. end;
  7629. C_BE, C_NA:
  7630. begin
  7631. { Will only branch if equal to zero }
  7632. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7633. taicpu(hp1).condition := C_E;
  7634. end;
  7635. C_A, C_NBE:
  7636. begin
  7637. { Will only branch if not equal to zero }
  7638. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7639. taicpu(hp1).condition := C_NE;
  7640. end;
  7641. C_AE, C_NB, C_NC, C_NO:
  7642. begin
  7643. { Will always branch }
  7644. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7645. if taicpu(hp1).opcode = A_Jcc then
  7646. begin
  7647. MakeUnconditional(taicpu(hp1));
  7648. { Any jumps/set that follow will now be dead code }
  7649. RemoveDeadCodeAfterJump(taicpu(hp1));
  7650. Break;
  7651. end
  7652. else
  7653. begin
  7654. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7655. taicpu(hp1).opcode := A_MOV;
  7656. taicpu(hp1).ops := 2;
  7657. taicpu(hp1).condition := C_None;
  7658. taicpu(hp1).opsize := S_B;
  7659. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7660. taicpu(hp1).loadconst(0, 1);
  7661. end;
  7662. end;
  7663. C_None:
  7664. InternalError(2020012201);
  7665. C_P, C_PE, C_NP, C_PO:
  7666. { We can't handle parity checks and they should never be generated
  7667. after a general-purpose CMP (it's used in some floating-point
  7668. comparisons that don't use CMP) }
  7669. InternalError(2020012202);
  7670. else
  7671. { Zero/Equality, Sign, their complements and all of the
  7672. signed comparisons do not need to be converted };
  7673. end;
  7674. hp2 := hp1;
  7675. end;
  7676. { Convert the instruction to a TEST }
  7677. taicpu(p).opcode := A_TEST;
  7678. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7679. Result := True;
  7680. Exit;
  7681. end
  7682. else
  7683. begin
  7684. TransferUsedRegs(TmpUsedRegs);
  7685. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7686. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7687. begin
  7688. if (taicpu(p).oper[0]^.val = 1) and
  7689. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7690. begin
  7691. { Convert; To:
  7692. cmp $1,r/m cmp $0,r/m
  7693. jl @lbl jle @lbl
  7694. (Also do inverted conditions)
  7695. }
  7696. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7697. taicpu(p).oper[0]^.val := 0;
  7698. if taicpu(hp1).condition in [C_L, C_NGE] then
  7699. taicpu(hp1).condition := C_LE
  7700. else
  7701. taicpu(hp1).condition := C_NLE;
  7702. { If the instruction is now "cmp $0,%reg", convert it to a
  7703. TEST (and effectively do the work of the "cmp $0,%reg" in
  7704. the block above)
  7705. }
  7706. if (taicpu(p).oper[1]^.typ = top_reg) then
  7707. begin
  7708. taicpu(p).opcode := A_TEST;
  7709. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7710. end;
  7711. Result := True;
  7712. Exit;
  7713. end
  7714. else if (taicpu(p).oper[1]^.typ = top_reg)
  7715. {$ifdef x86_64}
  7716. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7717. {$endif x86_64}
  7718. then
  7719. begin
  7720. { cmp register,$8000 neg register
  7721. je target --> jo target
  7722. .... only if register is deallocated before jump.}
  7723. case Taicpu(p).opsize of
  7724. S_B: v:=$80;
  7725. S_W: v:=$8000;
  7726. S_L: v:=qword($80000000);
  7727. else
  7728. internalerror(2013112905);
  7729. end;
  7730. if (taicpu(p).oper[0]^.val=v) and
  7731. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7732. begin
  7733. TransferUsedRegs(TmpUsedRegs);
  7734. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7735. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7736. begin
  7737. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7738. Taicpu(p).opcode:=A_NEG;
  7739. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7740. Taicpu(p).clearop(1);
  7741. Taicpu(p).ops:=1;
  7742. if Taicpu(hp1).condition=C_E then
  7743. Taicpu(hp1).condition:=C_O
  7744. else
  7745. Taicpu(hp1).condition:=C_NO;
  7746. Result:=true;
  7747. exit;
  7748. end;
  7749. end;
  7750. end;
  7751. end;
  7752. end;
  7753. end;
  7754. if TrySwapMovCmp(p, hp1) then
  7755. begin
  7756. Result := True;
  7757. Exit;
  7758. end;
  7759. end;
  7760. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7761. var
  7762. hp1: tai;
  7763. begin
  7764. {
  7765. remove the second (v)pxor from
  7766. pxor reg,reg
  7767. ...
  7768. pxor reg,reg
  7769. }
  7770. Result:=false;
  7771. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7772. MatchOpType(taicpu(p),top_reg,top_reg) and
  7773. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7774. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7775. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7776. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7777. begin
  7778. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7779. RemoveInstruction(hp1);
  7780. Result:=true;
  7781. Exit;
  7782. end
  7783. {
  7784. replace
  7785. pxor reg1,reg1
  7786. movapd/s reg1,reg2
  7787. dealloc reg1
  7788. by
  7789. pxor reg2,reg2
  7790. }
  7791. else if GetNextInstruction(p,hp1) and
  7792. { we mix single and double opperations here because we assume that the compiler
  7793. generates vmovapd only after double operations and vmovaps only after single operations }
  7794. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7795. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7796. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7797. (taicpu(p).oper[0]^.typ=top_reg) then
  7798. begin
  7799. TransferUsedRegs(TmpUsedRegs);
  7800. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7801. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7802. begin
  7803. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7804. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7805. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7806. RemoveInstruction(hp1);
  7807. result:=true;
  7808. end;
  7809. end;
  7810. end;
  7811. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7812. var
  7813. hp1: tai;
  7814. begin
  7815. {
  7816. remove the second (v)pxor from
  7817. (v)pxor reg,reg
  7818. ...
  7819. (v)pxor reg,reg
  7820. }
  7821. Result:=false;
  7822. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7823. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7824. begin
  7825. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7826. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7827. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7828. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7829. begin
  7830. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7831. RemoveInstruction(hp1);
  7832. Result:=true;
  7833. Exit;
  7834. end;
  7835. {$ifdef x86_64}
  7836. {
  7837. replace
  7838. vpxor reg1,reg1,reg1
  7839. vmov reg,mem
  7840. by
  7841. movq $0,mem
  7842. }
  7843. if GetNextInstruction(p,hp1) and
  7844. MatchInstruction(hp1,A_VMOVSD,[]) and
  7845. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7846. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7847. begin
  7848. TransferUsedRegs(TmpUsedRegs);
  7849. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7850. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7851. begin
  7852. taicpu(hp1).loadconst(0,0);
  7853. taicpu(hp1).opcode:=A_MOV;
  7854. taicpu(hp1).opsize:=S_Q;
  7855. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7856. RemoveCurrentP(p);
  7857. result:=true;
  7858. Exit;
  7859. end;
  7860. end;
  7861. {$endif x86_64}
  7862. end
  7863. {
  7864. replace
  7865. vpxor reg1,reg1,reg2
  7866. by
  7867. vpxor reg2,reg2,reg2
  7868. to avoid unncessary data dependencies
  7869. }
  7870. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7871. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7872. begin
  7873. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7874. { avoid unncessary data dependency }
  7875. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7876. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7877. result:=true;
  7878. exit;
  7879. end;
  7880. Result:=OptPass1VOP(p);
  7881. end;
  7882. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7883. var
  7884. hp1 : tai;
  7885. begin
  7886. result:=false;
  7887. { replace
  7888. IMul const,%mreg1,%mreg2
  7889. Mov %reg2,%mreg3
  7890. dealloc %mreg3
  7891. by
  7892. Imul const,%mreg1,%mreg23
  7893. }
  7894. if (taicpu(p).ops=3) and
  7895. GetNextInstruction(p,hp1) and
  7896. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7897. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7898. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7899. begin
  7900. TransferUsedRegs(TmpUsedRegs);
  7901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7902. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7903. begin
  7904. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7905. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7906. RemoveInstruction(hp1);
  7907. result:=true;
  7908. end;
  7909. end;
  7910. end;
  7911. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7912. var
  7913. hp1 : tai;
  7914. begin
  7915. result:=false;
  7916. { replace
  7917. IMul %reg0,%reg1,%reg2
  7918. Mov %reg2,%reg3
  7919. dealloc %reg2
  7920. by
  7921. Imul %reg0,%reg1,%reg3
  7922. }
  7923. if GetNextInstruction(p,hp1) and
  7924. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7925. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7926. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7927. begin
  7928. TransferUsedRegs(TmpUsedRegs);
  7929. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7930. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7931. begin
  7932. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7933. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7934. RemoveInstruction(hp1);
  7935. result:=true;
  7936. end;
  7937. end;
  7938. end;
  7939. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7940. var
  7941. hp1: tai;
  7942. begin
  7943. Result:=false;
  7944. { get rid of
  7945. (v)cvtss2sd reg0,<reg1,>reg2
  7946. (v)cvtss2sd reg2,<reg2,>reg0
  7947. }
  7948. if GetNextInstruction(p,hp1) and
  7949. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7950. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7951. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7952. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7953. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7954. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7955. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7956. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7957. )
  7958. ) then
  7959. begin
  7960. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7961. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7962. begin
  7963. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7964. RemoveCurrentP(p);
  7965. RemoveInstruction(hp1);
  7966. end
  7967. else
  7968. begin
  7969. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7970. if taicpu(hp1).opcode=A_CVTSD2SS then
  7971. begin
  7972. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7973. taicpu(p).opcode:=A_MOVAPS;
  7974. end
  7975. else
  7976. begin
  7977. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7978. taicpu(p).opcode:=A_VMOVAPS;
  7979. end;
  7980. taicpu(p).ops:=2;
  7981. RemoveInstruction(hp1);
  7982. end;
  7983. Result:=true;
  7984. Exit;
  7985. end;
  7986. end;
  7987. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7988. var
  7989. hp1, hp2, hp3, hp4, hp5: tai;
  7990. ThisReg: TRegister;
  7991. begin
  7992. Result := False;
  7993. if not GetNextInstruction(p,hp1) then
  7994. Exit;
  7995. {
  7996. convert
  7997. j<c> .L1
  7998. mov 1,reg
  7999. jmp .L2
  8000. .L1
  8001. mov 0,reg
  8002. .L2
  8003. into
  8004. mov 0,reg
  8005. set<not(c)> reg
  8006. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8007. would destroy the flag contents
  8008. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8009. executed at the same time as a previous comparison.
  8010. set<not(c)> reg
  8011. movzx reg, reg
  8012. }
  8013. if MatchInstruction(hp1,A_MOV,[]) and
  8014. (taicpu(hp1).oper[0]^.typ = top_const) and
  8015. (
  8016. (
  8017. (taicpu(hp1).oper[1]^.typ = top_reg)
  8018. {$ifdef i386}
  8019. { Under i386, ESI, EDI, EBP and ESP
  8020. don't have an 8-bit representation }
  8021. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8022. {$endif i386}
  8023. ) or (
  8024. {$ifdef i386}
  8025. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8026. {$endif i386}
  8027. (taicpu(hp1).opsize = S_B)
  8028. )
  8029. ) and
  8030. GetNextInstruction(hp1,hp2) and
  8031. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8032. GetNextInstruction(hp2,hp3) and
  8033. (hp3.typ=ait_label) and
  8034. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8035. GetNextInstruction(hp3,hp4) and
  8036. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8037. (taicpu(hp4).oper[0]^.typ = top_const) and
  8038. (
  8039. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8040. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8041. ) and
  8042. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8043. GetNextInstruction(hp4,hp5) and
  8044. (hp5.typ=ait_label) and
  8045. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  8046. begin
  8047. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8048. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8049. tai_label(hp3).labsym.DecRefs;
  8050. { If this isn't the only reference to the middle label, we can
  8051. still make a saving - only that the first jump and everything
  8052. that follows will remain. }
  8053. if (tai_label(hp3).labsym.getrefs = 0) then
  8054. begin
  8055. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8056. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8057. else
  8058. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8059. { remove jump, first label and second MOV (also catching any aligns) }
  8060. repeat
  8061. if not GetNextInstruction(hp2, hp3) then
  8062. InternalError(2021040810);
  8063. RemoveInstruction(hp2);
  8064. hp2 := hp3;
  8065. until hp2 = hp5;
  8066. { Don't decrement reference count before the removal loop
  8067. above, otherwise GetNextInstruction won't stop on the
  8068. the label }
  8069. tai_label(hp5).labsym.DecRefs;
  8070. end
  8071. else
  8072. begin
  8073. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8074. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8075. else
  8076. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8077. end;
  8078. taicpu(p).opcode:=A_SETcc;
  8079. taicpu(p).opsize:=S_B;
  8080. taicpu(p).is_jmp:=False;
  8081. if taicpu(hp1).opsize=S_B then
  8082. begin
  8083. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8084. if taicpu(hp1).oper[1]^.typ = top_reg then
  8085. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8086. RemoveInstruction(hp1);
  8087. end
  8088. else
  8089. begin
  8090. { Will be a register because the size can't be S_B otherwise }
  8091. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8092. taicpu(p).loadreg(0, ThisReg);
  8093. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8094. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8095. begin
  8096. case taicpu(hp1).opsize of
  8097. S_W:
  8098. taicpu(hp1).opsize := S_BW;
  8099. S_L:
  8100. taicpu(hp1).opsize := S_BL;
  8101. {$ifdef x86_64}
  8102. S_Q:
  8103. begin
  8104. taicpu(hp1).opsize := S_BL;
  8105. { Change the destination register to 32-bit }
  8106. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8107. end;
  8108. {$endif x86_64}
  8109. else
  8110. InternalError(2021040820);
  8111. end;
  8112. taicpu(hp1).opcode := A_MOVZX;
  8113. taicpu(hp1).loadreg(0, ThisReg);
  8114. end
  8115. else
  8116. begin
  8117. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8118. { hp1 is already a MOV instruction with the correct register }
  8119. taicpu(hp1).loadconst(0, 0);
  8120. { Inserting it right before p will guarantee that the flags are also tracked }
  8121. asml.Remove(hp1);
  8122. asml.InsertBefore(hp1, p);
  8123. end;
  8124. end;
  8125. Result:=true;
  8126. exit;
  8127. end
  8128. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8129. Result := TryJccStcClcOpt(p, hp1)
  8130. else if (hp1.typ = ait_label) then
  8131. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8132. end;
  8133. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8134. var
  8135. hp1, hp2, hp3: tai;
  8136. SourceRef, TargetRef: TReference;
  8137. CurrentReg: TRegister;
  8138. begin
  8139. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8140. if not UseAVX then
  8141. InternalError(2021100501);
  8142. Result := False;
  8143. { Look for the following to simplify:
  8144. vmovdqa/u x(mem1), %xmmreg
  8145. vmovdqa/u %xmmreg, y(mem2)
  8146. vmovdqa/u x+16(mem1), %xmmreg
  8147. vmovdqa/u %xmmreg, y+16(mem2)
  8148. Change to:
  8149. vmovdqa/u x(mem1), %ymmreg
  8150. vmovdqa/u %ymmreg, y(mem2)
  8151. vpxor %ymmreg, %ymmreg, %ymmreg
  8152. ( The VPXOR instruction is to zero the upper half, thus removing the
  8153. need to call the potentially expensive VZEROUPPER instruction. Other
  8154. peephole optimisations can remove VPXOR if it's unnecessary )
  8155. }
  8156. TransferUsedRegs(TmpUsedRegs);
  8157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8158. { NOTE: In the optimisations below, if the references dictate that an
  8159. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8160. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8161. if (taicpu(p).opsize = S_XMM) and
  8162. MatchOpType(taicpu(p), top_ref, top_reg) and
  8163. GetNextInstruction(p, hp1) and
  8164. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8165. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8166. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8167. begin
  8168. SourceRef := taicpu(p).oper[0]^.ref^;
  8169. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8170. if GetNextInstruction(hp1, hp2) and
  8171. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8172. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8173. begin
  8174. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8175. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8176. Inc(SourceRef.offset, 16);
  8177. { Reuse the register in the first block move }
  8178. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8179. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8180. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8181. begin
  8182. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8183. Inc(TargetRef.offset, 16);
  8184. if GetNextInstruction(hp2, hp3) and
  8185. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8186. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8187. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8188. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8189. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8190. begin
  8191. { Update the register tracking to the new size }
  8192. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8193. { Remember that the offsets are 16 ahead }
  8194. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8195. if not (
  8196. ((SourceRef.offset mod 32) = 16) and
  8197. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8198. ) then
  8199. taicpu(p).opcode := A_VMOVDQU;
  8200. taicpu(p).opsize := S_YMM;
  8201. taicpu(p).oper[1]^.reg := CurrentReg;
  8202. if not (
  8203. ((TargetRef.offset mod 32) = 16) and
  8204. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8205. ) then
  8206. taicpu(hp1).opcode := A_VMOVDQU;
  8207. taicpu(hp1).opsize := S_YMM;
  8208. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8209. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8210. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8211. if (pi_uses_ymm in current_procinfo.flags) then
  8212. RemoveInstruction(hp2)
  8213. else
  8214. begin
  8215. taicpu(hp2).opcode := A_VPXOR;
  8216. taicpu(hp2).opsize := S_YMM;
  8217. taicpu(hp2).loadreg(0, CurrentReg);
  8218. taicpu(hp2).loadreg(1, CurrentReg);
  8219. taicpu(hp2).loadreg(2, CurrentReg);
  8220. taicpu(hp2).ops := 3;
  8221. end;
  8222. RemoveInstruction(hp3);
  8223. Result := True;
  8224. Exit;
  8225. end;
  8226. end
  8227. else
  8228. begin
  8229. { See if the next references are 16 less rather than 16 greater }
  8230. Dec(SourceRef.offset, 32); { -16 the other way }
  8231. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8232. begin
  8233. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8234. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8235. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8236. GetNextInstruction(hp2, hp3) and
  8237. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8238. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8239. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8240. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8241. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8242. begin
  8243. { Update the register tracking to the new size }
  8244. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8245. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8246. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8247. if not(
  8248. ((SourceRef.offset mod 32) = 0) and
  8249. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8250. ) then
  8251. taicpu(hp2).opcode := A_VMOVDQU;
  8252. taicpu(hp2).opsize := S_YMM;
  8253. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8254. if not (
  8255. ((TargetRef.offset mod 32) = 0) and
  8256. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8257. ) then
  8258. taicpu(hp3).opcode := A_VMOVDQU;
  8259. taicpu(hp3).opsize := S_YMM;
  8260. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8261. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8262. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8263. if (pi_uses_ymm in current_procinfo.flags) then
  8264. RemoveInstruction(hp1)
  8265. else
  8266. begin
  8267. taicpu(hp1).opcode := A_VPXOR;
  8268. taicpu(hp1).opsize := S_YMM;
  8269. taicpu(hp1).loadreg(0, CurrentReg);
  8270. taicpu(hp1).loadreg(1, CurrentReg);
  8271. taicpu(hp1).loadreg(2, CurrentReg);
  8272. taicpu(hp1).ops := 3;
  8273. Asml.Remove(hp1);
  8274. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8275. end;
  8276. RemoveCurrentP(p, hp2);
  8277. Result := True;
  8278. Exit;
  8279. end;
  8280. end;
  8281. end;
  8282. end;
  8283. end;
  8284. end;
  8285. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8286. var
  8287. hp2, hp3, first_assignment: tai;
  8288. IncCount, OperIdx: Integer;
  8289. OrigLabel: TAsmLabel;
  8290. begin
  8291. Count := 0;
  8292. Result := False;
  8293. first_assignment := nil;
  8294. if (LoopCount >= 20) then
  8295. begin
  8296. { Guard against infinite loops }
  8297. Exit;
  8298. end;
  8299. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8300. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8301. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8302. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8303. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8304. Exit;
  8305. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8306. {
  8307. change
  8308. jmp .L1
  8309. ...
  8310. .L1:
  8311. mov ##, ## ( multiple movs possible )
  8312. jmp/ret
  8313. into
  8314. mov ##, ##
  8315. jmp/ret
  8316. }
  8317. if not Assigned(hp1) then
  8318. begin
  8319. hp1 := GetLabelWithSym(OrigLabel);
  8320. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8321. Exit;
  8322. end;
  8323. hp2 := hp1;
  8324. while Assigned(hp2) do
  8325. begin
  8326. if Assigned(hp2) and (hp2.typ = ait_label) then
  8327. SkipLabels(hp2,hp2);
  8328. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8329. Break;
  8330. case taicpu(hp2).opcode of
  8331. A_MOVSD:
  8332. begin
  8333. if taicpu(hp2).ops = 0 then
  8334. { Wrong MOVSD }
  8335. Break;
  8336. Inc(Count);
  8337. if Count >= 5 then
  8338. { Too many to be worthwhile }
  8339. Break;
  8340. GetNextInstruction(hp2, hp2);
  8341. Continue;
  8342. end;
  8343. A_MOV,
  8344. A_MOVD,
  8345. A_MOVQ,
  8346. A_MOVSX,
  8347. {$ifdef x86_64}
  8348. A_MOVSXD,
  8349. {$endif x86_64}
  8350. A_MOVZX,
  8351. A_MOVAPS,
  8352. A_MOVUPS,
  8353. A_MOVSS,
  8354. A_MOVAPD,
  8355. A_MOVUPD,
  8356. A_MOVDQA,
  8357. A_MOVDQU,
  8358. A_VMOVSS,
  8359. A_VMOVAPS,
  8360. A_VMOVUPS,
  8361. A_VMOVSD,
  8362. A_VMOVAPD,
  8363. A_VMOVUPD,
  8364. A_VMOVDQA,
  8365. A_VMOVDQU:
  8366. begin
  8367. Inc(Count);
  8368. if Count >= 5 then
  8369. { Too many to be worthwhile }
  8370. Break;
  8371. GetNextInstruction(hp2, hp2);
  8372. Continue;
  8373. end;
  8374. A_JMP:
  8375. begin
  8376. { Guard against infinite loops }
  8377. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8378. Exit;
  8379. { Analyse this jump first in case it also duplicates assignments }
  8380. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8381. begin
  8382. { Something did change! }
  8383. Result := True;
  8384. Inc(Count, IncCount);
  8385. if Count >= 5 then
  8386. begin
  8387. { Too many to be worthwhile }
  8388. Exit;
  8389. end;
  8390. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8391. Break;
  8392. end;
  8393. Result := True;
  8394. Break;
  8395. end;
  8396. A_RET:
  8397. begin
  8398. Result := True;
  8399. Break;
  8400. end;
  8401. else
  8402. Break;
  8403. end;
  8404. end;
  8405. if Result then
  8406. begin
  8407. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8408. if Count = 0 then
  8409. begin
  8410. Result := False;
  8411. Exit;
  8412. end;
  8413. TransferUsedRegs(TmpUsedRegs);
  8414. hp3 := p;
  8415. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8416. while True do
  8417. begin
  8418. if Assigned(hp1) and (hp1.typ = ait_label) then
  8419. SkipLabels(hp1,hp1);
  8420. case hp1.typ of
  8421. ait_regalloc:
  8422. if tai_regalloc(hp1).ratype = ra_dealloc then
  8423. begin
  8424. { Duplicate the register deallocation... }
  8425. hp3:=tai(hp1.getcopy);
  8426. if first_assignment = nil then
  8427. first_assignment := hp3;
  8428. asml.InsertBefore(hp3, p);
  8429. { ... but also reallocate it after the jump }
  8430. hp3:=tai(hp1.getcopy);
  8431. tai_regalloc(hp3).ratype := ra_alloc;
  8432. asml.InsertAfter(hp3, p);
  8433. end;
  8434. ait_instruction:
  8435. case taicpu(hp1).opcode of
  8436. A_JMP:
  8437. begin
  8438. { Change the original jump to the new destination }
  8439. OrigLabel.decrefs;
  8440. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8441. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8442. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8443. if not Assigned(first_assignment) then
  8444. InternalError(2021040810)
  8445. else
  8446. p := first_assignment;
  8447. Exit;
  8448. end;
  8449. A_RET:
  8450. begin
  8451. { Now change the jump into a RET instruction }
  8452. ConvertJumpToRET(p, hp1);
  8453. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8454. if not Assigned(first_assignment) then
  8455. InternalError(2021040811)
  8456. else
  8457. p := first_assignment;
  8458. Exit;
  8459. end;
  8460. else
  8461. begin
  8462. { Duplicate the MOV instruction }
  8463. hp3:=tai(hp1.getcopy);
  8464. if first_assignment = nil then
  8465. first_assignment := hp3;
  8466. asml.InsertBefore(hp3, p);
  8467. { Make sure the compiler knows about any final registers written here }
  8468. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8469. with taicpu(hp3).oper[OperIdx]^ do
  8470. begin
  8471. case typ of
  8472. top_ref:
  8473. begin
  8474. if (ref^.base <> NR_NO) and
  8475. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8476. (
  8477. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8478. (
  8479. { Allow the frame pointer if it's not being used by the procedure as such }
  8480. Assigned(current_procinfo) and
  8481. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8482. )
  8483. )
  8484. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8485. then
  8486. begin
  8487. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8488. if not Assigned(first_assignment) then
  8489. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8490. end;
  8491. if (ref^.index <> NR_NO) and
  8492. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8493. (
  8494. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8495. (
  8496. { Allow the frame pointer if it's not being used by the procedure as such }
  8497. Assigned(current_procinfo) and
  8498. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8499. )
  8500. )
  8501. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8502. (ref^.index <> ref^.base) then
  8503. begin
  8504. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8505. if not Assigned(first_assignment) then
  8506. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8507. end;
  8508. end;
  8509. top_reg:
  8510. begin
  8511. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8512. if not Assigned(first_assignment) then
  8513. IncludeRegInUsedRegs(reg, UsedRegs);
  8514. end;
  8515. else
  8516. ;
  8517. end;
  8518. end;
  8519. end;
  8520. end;
  8521. else
  8522. InternalError(2021040720);
  8523. end;
  8524. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8525. { Should have dropped out earlier }
  8526. InternalError(2021040710);
  8527. end;
  8528. end;
  8529. end;
  8530. const
  8531. WriteOp: array[0..3] of set of TInsChange = (
  8532. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8533. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8534. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8535. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8536. RegWriteFlags: array[0..7] of set of TInsChange = (
  8537. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8538. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8539. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8540. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8541. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8542. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8543. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8544. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8545. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8546. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8547. var
  8548. hp2: tai;
  8549. X: Integer;
  8550. begin
  8551. { If we have something like:
  8552. op ###,###
  8553. mov ###,###
  8554. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8555. interfere in regards to what they write to.
  8556. NOTE: p must be a 2-operand instruction
  8557. }
  8558. Result := False;
  8559. if (hp1.typ <> ait_instruction) or
  8560. taicpu(hp1).is_jmp or
  8561. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8562. Exit;
  8563. { NOP is a pipeline fence, likely marking the beginning of the function
  8564. epilogue, so drop out. Similarly, drop out if POP or RET are
  8565. encountered }
  8566. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8567. Exit;
  8568. if (taicpu(hp1).opcode = A_MOVSD) and
  8569. (taicpu(hp1).ops = 0) then
  8570. { Wrong MOVSD }
  8571. Exit;
  8572. { Check for writes to specific registers first }
  8573. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8574. for X := 0 to 7 do
  8575. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8576. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8577. Exit;
  8578. for X := 0 to taicpu(hp1).ops - 1 do
  8579. begin
  8580. { Check to see if this operand writes to something }
  8581. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8582. { And matches something in the CMP/TEST instruction }
  8583. (
  8584. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8585. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8586. (
  8587. { If it's a register, make sure the register written to doesn't
  8588. appear in the cmp instruction as part of a reference }
  8589. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8590. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8591. )
  8592. ) then
  8593. Exit;
  8594. end;
  8595. { Check p to make sure it doesn't write to something that affects hp1 }
  8596. { Check for writes to specific registers first }
  8597. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8598. for X := 0 to 7 do
  8599. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8600. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8601. Exit;
  8602. for X := 0 to taicpu(p).ops - 1 do
  8603. begin
  8604. { Check to see if this operand writes to something }
  8605. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8606. { And matches something in hp1 }
  8607. (taicpu(p).oper[X]^.typ = top_reg) and
  8608. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8609. Exit;
  8610. end;
  8611. { The instruction can be safely moved }
  8612. asml.Remove(hp1);
  8613. { Try to insert after the last instructions where the FLAGS register is not
  8614. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8615. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8616. asml.InsertBefore(hp1, hp2)
  8617. { Failing that, try to insert after the last instructions where the
  8618. FLAGS register is not yet in use }
  8619. else if GetLastInstruction(p, hp2) and
  8620. (
  8621. (hp2.typ <> ait_instruction) or
  8622. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8623. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8624. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8625. ) then
  8626. asml.InsertAfter(hp1, hp2)
  8627. else
  8628. { Note, if p.Previous is nil (even if it should logically never be the
  8629. case), FindRegAllocBackward immediately exits with False and so we
  8630. safely land here (we can't just pass p because FindRegAllocBackward
  8631. immediately exits on an instruction). [Kit] }
  8632. asml.InsertBefore(hp1, p);
  8633. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8634. { We can't trust UsedRegs because we're looking backwards, although we
  8635. know the registers are allocated after p at the very least, so manually
  8636. create tai_regalloc objects if needed }
  8637. for X := 0 to taicpu(hp1).ops - 1 do
  8638. case taicpu(hp1).oper[X]^.typ of
  8639. top_reg:
  8640. begin
  8641. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8642. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8643. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8644. end;
  8645. top_ref:
  8646. begin
  8647. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8648. begin
  8649. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8650. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8651. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8652. end;
  8653. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8654. begin
  8655. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8656. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8657. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8658. end;
  8659. end;
  8660. else
  8661. ;
  8662. end;
  8663. Result := True;
  8664. end;
  8665. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8666. var
  8667. hp2: tai;
  8668. X: Integer;
  8669. begin
  8670. { If we have something like:
  8671. cmp ###,%reg1
  8672. mov 0,%reg2
  8673. And no modified registers are shared, move the instruction to before
  8674. the comparison as this means it can be optimised without worrying
  8675. about the FLAGS register. (CMP/MOV is generated by
  8676. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8677. As long as the second instruction doesn't use the flags or one of the
  8678. registers used by CMP or TEST (also check any references that use the
  8679. registers), then it can be moved prior to the comparison.
  8680. }
  8681. Result := False;
  8682. if not TrySwapMovOp(p, hp1) then
  8683. Exit;
  8684. if taicpu(hp1).opcode = A_LEA then
  8685. { The flags will be overwritten by the CMP/TEST instruction }
  8686. ConvertLEA(taicpu(hp1));
  8687. Result := True;
  8688. { Can we move it one further back? }
  8689. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8690. { Check to see if CMP/TEST is a comparison against zero }
  8691. (
  8692. (
  8693. (taicpu(p).opcode = A_CMP) and
  8694. MatchOperand(taicpu(p).oper[0]^, 0)
  8695. ) or
  8696. (
  8697. (taicpu(p).opcode = A_TEST) and
  8698. (
  8699. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8700. MatchOperand(taicpu(p).oper[0]^, -1)
  8701. )
  8702. )
  8703. ) and
  8704. { These instructions set the zero flag if the result is zero }
  8705. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8706. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8707. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8708. TrySwapMovOp(hp2, hp1);
  8709. end;
  8710. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8711. var
  8712. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8713. JumpLabel: TAsmLabel;
  8714. TmpBool: Boolean;
  8715. begin
  8716. Result := False;
  8717. { Look for:
  8718. stc/clc
  8719. j(c) .L1
  8720. ...
  8721. .L1:
  8722. set(n)cb %reg
  8723. (flags deallocated)
  8724. j(c) .L2
  8725. Change to:
  8726. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8727. j(c) .L2
  8728. }
  8729. p_last := p;
  8730. while GetNextInstruction(p_last, hp1) and
  8731. (hp1.typ = ait_instruction) and
  8732. IsJumpToLabel(taicpu(hp1)) do
  8733. begin
  8734. if DoJumpOptimizations(hp1, TmpBool) then
  8735. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8736. Continue;
  8737. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8738. if not Assigned(JumpLabel) then
  8739. InternalError(2024012801);
  8740. { Optimise the J(c); stc/clc optimisation first since this will
  8741. get missed if the main optimisation takes place }
  8742. if (taicpu(hp1).opcode = A_JCC) then
  8743. begin
  8744. if GetNextInstruction(hp1, hp2) and
  8745. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8746. TryJccStcClcOpt(hp1, hp2) then
  8747. begin
  8748. Result := True;
  8749. Exit;
  8750. end;
  8751. hp2 := nil; { Suppress compiler warning }
  8752. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8753. { Make sure the flags aren't used again }
  8754. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8755. begin
  8756. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8757. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8758. begin
  8759. if (taicpu(p).opcode = A_STC) then
  8760. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8761. else
  8762. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8763. MakeUnconditional(taicpu(hp1));
  8764. { Move the jump to after the flag deallocations }
  8765. Asml.Remove(hp1);
  8766. Asml.InsertAfter(hp1, hp2);
  8767. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8768. Result := True;
  8769. Exit;
  8770. end
  8771. else
  8772. begin
  8773. if (taicpu(p).opcode = A_STC) then
  8774. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8775. else
  8776. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8777. { In this case, the jump is deterministic in that it will never be taken }
  8778. JumpLabel.DecRefs;
  8779. RemoveInstruction(hp1);
  8780. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8781. Result := True;
  8782. Exit;
  8783. end;
  8784. end;
  8785. end;
  8786. hp2 := nil; { Suppress compiler warning }
  8787. if
  8788. { Make sure the carry flag doesn't appear in the jump conditions }
  8789. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8790. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8791. GetNextInstruction(hp2, p_dist) and
  8792. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8793. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8794. begin
  8795. case taicpu(p_dist).opcode of
  8796. A_Jcc:
  8797. begin
  8798. if DoJumpOptimizations(p_dist, TmpBool) then
  8799. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8800. Continue;
  8801. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8802. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8803. begin
  8804. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8805. JumpLabel.decrefs;
  8806. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8807. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8808. Result := True;
  8809. Exit;
  8810. end
  8811. else if GetNextInstruction(p_dist, hp1_dist) and
  8812. (hp1_dist.typ = ait_label) then
  8813. begin
  8814. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8815. JumpLabel.decrefs;
  8816. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8817. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8818. Result := True;
  8819. Exit;
  8820. end;
  8821. end;
  8822. A_SETcc:
  8823. if { Make sure the flags aren't used again }
  8824. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8825. GetNextInstruction(hp2, hp1_dist) and
  8826. (hp1_dist.typ = ait_instruction) and
  8827. IsJumpToLabel(taicpu(hp1_dist)) and
  8828. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8829. { This works if hp1_dist or both are regular JMP instructions }
  8830. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8831. (
  8832. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8833. { Make sure the register isn't still in use, otherwise it
  8834. may get corrupted (fixes #40659) }
  8835. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8836. ) then
  8837. begin
  8838. taicpu(p).allocate_oper(2);
  8839. taicpu(p).ops := 2;
  8840. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8841. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8842. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8843. taicpu(p).opcode := A_MOV;
  8844. taicpu(p).opsize := S_B;
  8845. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8846. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8847. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8848. JumpLabel.decrefs;
  8849. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8850. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8851. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8852. (tai_regalloc(hp2).ratype = ra_alloc) then
  8853. begin
  8854. Asml.Remove(hp2);
  8855. Asml.InsertAfter(hp2, p);
  8856. end;
  8857. Result := True;
  8858. Exit;
  8859. end;
  8860. else
  8861. ;
  8862. end;
  8863. end;
  8864. p_last := hp1;
  8865. end;
  8866. end;
  8867. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8868. var
  8869. hp2, hp3: tai;
  8870. TempBool: Boolean;
  8871. begin
  8872. Result := False;
  8873. {
  8874. j(c) .L1
  8875. stc/clc
  8876. .L1:
  8877. jc/jnc .L2
  8878. (Flags deallocated)
  8879. Change to:
  8880. j)c) .L1
  8881. jmp .L2
  8882. .L1:
  8883. jc/jnc .L2
  8884. Then call DoJumpOptimizations to convert to:
  8885. j(nc) .L2
  8886. .L1: (may become a dead label)
  8887. jc/jnc .L2
  8888. }
  8889. if GetNextInstruction(hp1, hp2) and
  8890. (hp2.typ = ait_label) and
  8891. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8892. GetNextInstruction(hp2, hp3) and
  8893. MatchInstruction(hp3, A_Jcc, []) and
  8894. (
  8895. (
  8896. (taicpu(hp3).condition = C_C) and
  8897. (taicpu(hp1).opcode = A_STC)
  8898. ) or (
  8899. (taicpu(hp3).condition = C_NC) and
  8900. (taicpu(hp1).opcode = A_CLC)
  8901. )
  8902. ) and
  8903. { Make sure the flags aren't used again }
  8904. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8905. begin
  8906. taicpu(hp1).allocate_oper(1);
  8907. taicpu(hp1).ops := 1;
  8908. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8909. taicpu(hp1).opcode := A_JMP;
  8910. taicpu(hp1).is_jmp := True;
  8911. TempBool := True; { Prevent compiler warnings }
  8912. if DoJumpOptimizations(p, TempBool) then
  8913. Result := True
  8914. else
  8915. Include(OptsToCheck, aoc_ForceNewIteration);
  8916. end;
  8917. end;
  8918. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8919. begin
  8920. { This generally only executes under -O3 and above }
  8921. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8922. end;
  8923. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8924. var
  8925. hp1, hp2: tai;
  8926. FoundComparison: Boolean;
  8927. begin
  8928. { Run the pass 1 optimisations as well, since they may have some effect
  8929. after the CMOV blocks are created in OptPass2Jcc }
  8930. Result := False;
  8931. { Result := OptPass1CMOVcc(p);
  8932. if Result then
  8933. Exit;}
  8934. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8935. and make a slightly inefficent result on branching-type blocks, notably
  8936. when setting a function result then jumping to the function epilogue.
  8937. In this case, change:
  8938. cmov(c) %reg1,%reg2
  8939. j(c) @lbl
  8940. (%reg2 deallocated)
  8941. To:
  8942. mov %reg11,%reg2
  8943. j(c) @lbl
  8944. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8945. jump because if it's not present, we may end up with a jump that's
  8946. completely unrelated.
  8947. }
  8948. hp1 := p;
  8949. while GetNextInstruction(hp1, hp1) and
  8950. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8951. if (hp1.typ = ait_instruction) and
  8952. (taicpu(hp1).opcode = A_Jcc) and
  8953. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8954. begin
  8955. TransferUsedRegs(TmpUsedRegs);
  8956. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8957. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8958. (
  8959. { See if we can find a more distant instruction that overwrites
  8960. the destination register }
  8961. (cs_opt_level3 in current_settings.optimizerswitches) and
  8962. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8963. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8964. ) then
  8965. begin
  8966. if (taicpu(p).oper[0]^.typ = top_reg) then
  8967. begin
  8968. { Search backwards to see if the source register is set to a
  8969. constant }
  8970. FoundComparison := False;
  8971. hp1 := p;
  8972. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8973. begin
  8974. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8975. begin
  8976. FoundComparison := True;
  8977. Continue;
  8978. end;
  8979. { Once we find the CMP, TEST or similar instruction, we
  8980. have to stop if we find anything other than a MOV }
  8981. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8982. Break;
  8983. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8984. { Destination register was modified }
  8985. Break;
  8986. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8987. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8988. begin
  8989. { Found a constant! }
  8990. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8991. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8992. { The source register is no longer in use }
  8993. RemoveInstruction(hp1);
  8994. Break;
  8995. end;
  8996. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8997. { Some other instruction has modified the source register }
  8998. Break;
  8999. end;
  9000. end;
  9001. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9002. taicpu(p).opcode := A_MOV;
  9003. taicpu(p).condition := C_None;
  9004. { Rely on the post peephole stage to put the MOV before the
  9005. CMP/TEST instruction that appears prior }
  9006. Result := True;
  9007. Exit;
  9008. end;
  9009. end;
  9010. end;
  9011. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9012. function IsXCHGAcceptable: Boolean; inline;
  9013. begin
  9014. { Always accept if optimising for size }
  9015. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9016. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9017. than 3, so it becomes a saving compared to three MOVs with two of
  9018. them able to execute simultaneously. [Kit] }
  9019. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9020. end;
  9021. var
  9022. NewRef: TReference;
  9023. hp1, hp2, hp3, hp4: Tai;
  9024. {$ifndef x86_64}
  9025. OperIdx: Integer;
  9026. {$endif x86_64}
  9027. NewInstr : Taicpu;
  9028. NewAligh : Tai_align;
  9029. DestLabel: TAsmLabel;
  9030. TempTracking: TAllUsedRegs;
  9031. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9032. var
  9033. NextInstr: tai;
  9034. begin
  9035. Result := False;
  9036. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9037. if not GetNextInstruction(InputInstr, NextInstr) or
  9038. (
  9039. { The FLAGS register isn't always tracked properly, so do not
  9040. perform this optimisation if a conditional statement follows }
  9041. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9042. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9043. ) then
  9044. begin
  9045. reference_reset(NewRef, 1, []);
  9046. NewRef.base := taicpu(p).oper[0]^.reg;
  9047. NewRef.scalefactor := 1;
  9048. if taicpu(InputInstr).opcode = A_ADD then
  9049. begin
  9050. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9051. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9052. end
  9053. else
  9054. begin
  9055. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9056. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9057. end;
  9058. taicpu(p).opcode := A_LEA;
  9059. taicpu(p).loadref(0, NewRef);
  9060. { For the sake of debugging, have the line info match the
  9061. arithmetic instruction rather than the MOV instruction }
  9062. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9063. RemoveInstruction(InputInstr);
  9064. Result := True;
  9065. end;
  9066. end;
  9067. begin
  9068. Result:=false;
  9069. { This optimisation adds an instruction, so only do it for speed }
  9070. if not (cs_opt_size in current_settings.optimizerswitches) and
  9071. MatchOpType(taicpu(p), top_const, top_reg) and
  9072. (taicpu(p).oper[0]^.val = 0) then
  9073. begin
  9074. { To avoid compiler warning }
  9075. DestLabel := nil;
  9076. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9077. InternalError(2021040750);
  9078. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9079. Exit;
  9080. case hp1.typ of
  9081. ait_label:
  9082. begin
  9083. { Change:
  9084. mov $0,%reg mov $0,%reg
  9085. @Lbl1: @Lbl1:
  9086. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9087. je @Lbl2 jne @Lbl2
  9088. To: To:
  9089. mov $0,%reg mov $0,%reg
  9090. jmp @Lbl2 jmp @Lbl3
  9091. (align) (align)
  9092. @Lbl1: @Lbl1:
  9093. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9094. je @Lbl2 je @Lbl2
  9095. @Lbl3: <-- Only if label exists
  9096. (Not if it's optimised for size)
  9097. }
  9098. if not GetNextInstruction(hp1, hp2) then
  9099. Exit;
  9100. if (hp2.typ = ait_instruction) and
  9101. (
  9102. { Register sizes must exactly match }
  9103. (
  9104. (taicpu(hp2).opcode = A_CMP) and
  9105. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9106. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9107. ) or (
  9108. (taicpu(hp2).opcode = A_TEST) and
  9109. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9110. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9111. )
  9112. ) and GetNextInstruction(hp2, hp3) and
  9113. (hp3.typ = ait_instruction) and
  9114. (taicpu(hp3).opcode = A_JCC) and
  9115. (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
  9116. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9117. begin
  9118. { Check condition of jump }
  9119. { Always true? }
  9120. if condition_in(C_E, taicpu(hp3).condition) then
  9121. begin
  9122. { Copy label symbol and obtain matching label entry for the
  9123. conditional jump, as this will be our destination}
  9124. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9125. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9126. Result := True;
  9127. end
  9128. { Always false? }
  9129. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9130. begin
  9131. { This is only worth it if there's a jump to take }
  9132. case hp2.typ of
  9133. ait_instruction:
  9134. begin
  9135. if taicpu(hp2).opcode = A_JMP then
  9136. begin
  9137. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9138. { An unconditional jump follows the conditional jump which will always be false,
  9139. so use this jump's destination for the new jump }
  9140. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9141. Result := True;
  9142. end
  9143. else if taicpu(hp2).opcode = A_JCC then
  9144. begin
  9145. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9146. if condition_in(C_E, taicpu(hp2).condition) then
  9147. begin
  9148. { A second conditional jump follows the conditional jump which will always be false,
  9149. while the second jump is always True, so use this jump's destination for the new jump }
  9150. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9151. Result := True;
  9152. end;
  9153. { Don't risk it if the jump isn't always true (Result remains False) }
  9154. end;
  9155. end;
  9156. else
  9157. { If anything else don't optimise };
  9158. end;
  9159. end;
  9160. if Result then
  9161. begin
  9162. { Just so we have something to insert as a paremeter}
  9163. reference_reset(NewRef, 1, []);
  9164. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9165. { Now actually load the correct parameter (this also
  9166. increases the reference count) }
  9167. NewInstr.loadsymbol(0, DestLabel, 0);
  9168. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9169. begin
  9170. { Get instruction before original label (may not be p under -O3) }
  9171. if not GetLastInstruction(hp1, hp2) then
  9172. { Shouldn't fail here }
  9173. InternalError(2021040701);
  9174. end
  9175. else
  9176. hp2 := p;
  9177. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9178. AsmL.InsertAfter(NewInstr, hp2);
  9179. { Add new alignment field }
  9180. (* AsmL.InsertAfter(
  9181. cai_align.create_max(
  9182. current_settings.alignment.jumpalign,
  9183. current_settings.alignment.jumpalignskipmax
  9184. ),
  9185. NewInstr
  9186. ); *)
  9187. end;
  9188. Exit;
  9189. end;
  9190. end;
  9191. else
  9192. ;
  9193. end;
  9194. end;
  9195. if not GetNextInstruction(p, hp1) then
  9196. Exit;
  9197. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9198. begin
  9199. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9200. begin
  9201. Result := True;
  9202. Exit;
  9203. end;
  9204. { This optimisation is only effective on a second run of Pass 2,
  9205. hence -O3 or above.
  9206. Change:
  9207. mov %reg1,%reg2
  9208. cmp/test (contains %reg1)
  9209. mov x, %reg1
  9210. (another mov or a j(c))
  9211. To:
  9212. mov %reg1,%reg2
  9213. mov x, %reg1
  9214. cmp (%reg1 replaced with %reg2)
  9215. (another mov or a j(c))
  9216. The requirement of an additional MOV or a jump ensures there
  9217. isn't performance loss, since a j(c) will permit macro-fusion
  9218. with the cmp instruction, while another MOV likely means it's
  9219. not all being executed in a single cycle due to parallelisation.
  9220. }
  9221. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9222. MatchOpType(taicpu(p), top_reg, top_reg) and
  9223. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9224. GetNextInstruction(hp1, hp2) and
  9225. MatchInstruction(hp2, A_MOV, []) and
  9226. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9227. { Registers don't have to be the same size in this case }
  9228. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9229. GetNextInstruction(hp2, hp3) and
  9230. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9231. { Make sure the operands in the camparison can be safely replaced }
  9232. (
  9233. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9234. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9235. ) and
  9236. (
  9237. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9238. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9239. ) then
  9240. begin
  9241. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9242. AsmL.Remove(hp2);
  9243. AsmL.InsertAfter(hp2, p);
  9244. Result := True;
  9245. Exit;
  9246. end;
  9247. end;
  9248. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9249. begin
  9250. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9251. further, but we can't just put this jump optimisation in pass 1
  9252. because it tends to perform worse when conditional jumps are
  9253. nearby (e.g. when converting CMOV instructions). [Kit] }
  9254. CopyUsedRegs(TempTracking);
  9255. UpdateUsedRegs(tai(p.Next));
  9256. if OptPass2JMP(hp1) then
  9257. begin
  9258. { Restore register state }
  9259. RestoreUsedRegs(TempTracking);
  9260. ReleaseUsedRegs(TempTracking);
  9261. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9262. OptPass1MOV(p);
  9263. Result := True;
  9264. Exit;
  9265. end;
  9266. { If OptPass2JMP returned False, no optimisations were done to
  9267. the jump and there are no further optimisations that can be done
  9268. to the MOV instruction on this pass other than FuncMov2Func }
  9269. { Restore register state }
  9270. RestoreUsedRegs(TempTracking);
  9271. ReleaseUsedRegs(TempTracking);
  9272. Result := FuncMov2Func(p, hp1);
  9273. Exit;
  9274. end;
  9275. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9276. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9277. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9278. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9279. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9280. begin
  9281. { Change:
  9282. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9283. addl/q $x,%reg2 subl/q $x,%reg2
  9284. To:
  9285. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9286. }
  9287. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9288. { be lazy, checking separately for sub would be slightly better }
  9289. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9290. begin
  9291. TransferUsedRegs(TmpUsedRegs);
  9292. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9293. if TryMovArith2Lea(hp1) then
  9294. begin
  9295. Result := True;
  9296. Exit;
  9297. end
  9298. end
  9299. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9300. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9301. { Same as above, but also adds or subtracts to %reg2 in between.
  9302. It's still valid as long as the flags aren't in use }
  9303. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9304. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9305. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9306. { be lazy, checking separately for sub would be slightly better }
  9307. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9308. begin
  9309. TransferUsedRegs(TmpUsedRegs);
  9310. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9311. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9312. if TryMovArith2Lea(hp2) then
  9313. begin
  9314. Result := True;
  9315. Exit;
  9316. end;
  9317. end;
  9318. end;
  9319. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9320. {$ifdef x86_64}
  9321. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9322. {$else x86_64}
  9323. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9324. {$endif x86_64}
  9325. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9326. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9327. { mov reg1, reg2 mov reg1, reg2
  9328. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9329. begin
  9330. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9331. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9332. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9333. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9334. TransferUsedRegs(TmpUsedRegs);
  9335. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9336. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9337. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9338. then
  9339. begin
  9340. RemoveCurrentP(p, hp1);
  9341. Result:=true;
  9342. end;
  9343. Exit;
  9344. end;
  9345. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9346. IsXCHGAcceptable and
  9347. { XCHG doesn't support 8-bit registers }
  9348. (taicpu(p).opsize <> S_B) and
  9349. MatchInstruction(hp1, A_MOV, []) and
  9350. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9351. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9352. GetNextInstruction(hp1, hp2) and
  9353. MatchInstruction(hp2, A_MOV, []) and
  9354. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9355. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9356. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9357. begin
  9358. { mov %reg1,%reg2
  9359. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9360. mov %reg2,%reg3
  9361. (%reg2 not used afterwards)
  9362. Note that xchg takes 3 cycles to execute, and generally mov's take
  9363. only one cycle apiece, but the first two mov's can be executed in
  9364. parallel, only taking 2 cycles overall. Older processors should
  9365. therefore only optimise for size. [Kit]
  9366. }
  9367. TransferUsedRegs(TmpUsedRegs);
  9368. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9369. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9370. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9371. begin
  9372. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9373. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9374. taicpu(hp1).opcode := A_XCHG;
  9375. RemoveCurrentP(p, hp1);
  9376. RemoveInstruction(hp2);
  9377. Result := True;
  9378. Exit;
  9379. end;
  9380. end;
  9381. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9382. MatchInstruction(hp1, A_SAR, []) then
  9383. begin
  9384. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9385. begin
  9386. { the use of %edx also covers the opsize being S_L }
  9387. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9388. begin
  9389. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9390. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9391. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9392. begin
  9393. { Change:
  9394. movl %eax,%edx
  9395. sarl $31,%edx
  9396. To:
  9397. cltd
  9398. }
  9399. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9400. RemoveInstruction(hp1);
  9401. taicpu(p).opcode := A_CDQ;
  9402. taicpu(p).opsize := S_NO;
  9403. taicpu(p).clearop(1);
  9404. taicpu(p).clearop(0);
  9405. taicpu(p).ops:=0;
  9406. Result := True;
  9407. Exit;
  9408. end
  9409. else if (cs_opt_size in current_settings.optimizerswitches) and
  9410. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9411. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9412. begin
  9413. { Change:
  9414. movl %edx,%eax
  9415. sarl $31,%edx
  9416. To:
  9417. movl %edx,%eax
  9418. cltd
  9419. Note that this creates a dependency between the two instructions,
  9420. so only perform if optimising for size.
  9421. }
  9422. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9423. taicpu(hp1).opcode := A_CDQ;
  9424. taicpu(hp1).opsize := S_NO;
  9425. taicpu(hp1).clearop(1);
  9426. taicpu(hp1).clearop(0);
  9427. taicpu(hp1).ops:=0;
  9428. Include(OptsToCheck, aoc_ForceNewIteration);
  9429. Exit;
  9430. end;
  9431. {$ifndef x86_64}
  9432. end
  9433. { Don't bother if CMOV is supported, because a more optimal
  9434. sequence would have been generated for the Abs() intrinsic }
  9435. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9436. { the use of %eax also covers the opsize being S_L }
  9437. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9438. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9439. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9440. GetNextInstruction(hp1, hp2) and
  9441. MatchInstruction(hp2, A_XOR, [S_L]) and
  9442. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9443. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9444. GetNextInstruction(hp2, hp3) and
  9445. MatchInstruction(hp3, A_SUB, [S_L]) and
  9446. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9447. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9448. begin
  9449. { Change:
  9450. movl %eax,%edx
  9451. sarl $31,%eax
  9452. xorl %eax,%edx
  9453. subl %eax,%edx
  9454. (Instruction that uses %edx)
  9455. (%eax deallocated)
  9456. (%edx deallocated)
  9457. To:
  9458. cltd
  9459. xorl %edx,%eax <-- Note the registers have swapped
  9460. subl %edx,%eax
  9461. (Instruction that uses %eax) <-- %eax rather than %edx
  9462. }
  9463. TransferUsedRegs(TmpUsedRegs);
  9464. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9465. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9466. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9467. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9468. begin
  9469. if GetNextInstruction(hp3, hp4) and
  9470. not RegModifiedByInstruction(NR_EDX, hp4) and
  9471. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9472. begin
  9473. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9474. taicpu(p).opcode := A_CDQ;
  9475. taicpu(p).clearop(1);
  9476. taicpu(p).clearop(0);
  9477. taicpu(p).ops:=0;
  9478. RemoveInstruction(hp1);
  9479. taicpu(hp2).loadreg(0, NR_EDX);
  9480. taicpu(hp2).loadreg(1, NR_EAX);
  9481. taicpu(hp3).loadreg(0, NR_EDX);
  9482. taicpu(hp3).loadreg(1, NR_EAX);
  9483. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9484. { Convert references in the following instruction (hp4) from %edx to %eax }
  9485. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9486. with taicpu(hp4).oper[OperIdx]^ do
  9487. case typ of
  9488. top_reg:
  9489. if getsupreg(reg) = RS_EDX then
  9490. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9491. top_ref:
  9492. begin
  9493. if getsupreg(reg) = RS_EDX then
  9494. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9495. if getsupreg(reg) = RS_EDX then
  9496. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9497. end;
  9498. else
  9499. ;
  9500. end;
  9501. Result := True;
  9502. Exit;
  9503. end;
  9504. end;
  9505. {$else x86_64}
  9506. end;
  9507. end
  9508. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9509. { the use of %rdx also covers the opsize being S_Q }
  9510. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9511. begin
  9512. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9513. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9514. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9515. begin
  9516. { Change:
  9517. movq %rax,%rdx
  9518. sarq $63,%rdx
  9519. To:
  9520. cqto
  9521. }
  9522. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9523. RemoveInstruction(hp1);
  9524. taicpu(p).opcode := A_CQO;
  9525. taicpu(p).opsize := S_NO;
  9526. taicpu(p).clearop(1);
  9527. taicpu(p).clearop(0);
  9528. taicpu(p).ops:=0;
  9529. Result := True;
  9530. Exit;
  9531. end
  9532. else if (cs_opt_size in current_settings.optimizerswitches) and
  9533. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9534. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9535. begin
  9536. { Change:
  9537. movq %rdx,%rax
  9538. sarq $63,%rdx
  9539. To:
  9540. movq %rdx,%rax
  9541. cqto
  9542. Note that this creates a dependency between the two instructions,
  9543. so only perform if optimising for size.
  9544. }
  9545. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9546. taicpu(hp1).opcode := A_CQO;
  9547. taicpu(hp1).opsize := S_NO;
  9548. taicpu(hp1).clearop(1);
  9549. taicpu(hp1).clearop(0);
  9550. taicpu(hp1).ops:=0;
  9551. Include(OptsToCheck, aoc_ForceNewIteration);
  9552. Exit;
  9553. {$endif x86_64}
  9554. end;
  9555. end;
  9556. end;
  9557. if MatchInstruction(hp1, A_MOV, []) and
  9558. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9559. { Though "GetNextInstruction" could be factored out, along with
  9560. the instructions that depend on hp2, it is an expensive call that
  9561. should be delayed for as long as possible, hence we do cheaper
  9562. checks first that are likely to be False. [Kit] }
  9563. begin
  9564. if (
  9565. (
  9566. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9567. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9568. (
  9569. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9570. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9571. )
  9572. ) or
  9573. (
  9574. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9575. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9576. (
  9577. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9578. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9579. )
  9580. )
  9581. ) and
  9582. GetNextInstruction(hp1, hp2) and
  9583. MatchInstruction(hp2, A_SAR, []) and
  9584. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9585. begin
  9586. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9587. begin
  9588. { Change:
  9589. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9590. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9591. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9592. To:
  9593. movl r/m,%eax <- Note the change in register
  9594. cltd
  9595. }
  9596. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9597. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9598. taicpu(p).loadreg(1, NR_EAX);
  9599. taicpu(hp1).opcode := A_CDQ;
  9600. taicpu(hp1).clearop(1);
  9601. taicpu(hp1).clearop(0);
  9602. taicpu(hp1).ops:=0;
  9603. RemoveInstruction(hp2);
  9604. Include(OptsToCheck, aoc_ForceNewIteration);
  9605. (*
  9606. {$ifdef x86_64}
  9607. end
  9608. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9609. { This code sequence does not get generated - however it might become useful
  9610. if and when 128-bit signed integer types make an appearance, so the code
  9611. is kept here for when it is eventually needed. [Kit] }
  9612. (
  9613. (
  9614. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9615. (
  9616. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9617. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9618. )
  9619. ) or
  9620. (
  9621. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9622. (
  9623. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9624. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9625. )
  9626. )
  9627. ) and
  9628. GetNextInstruction(hp1, hp2) and
  9629. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9630. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9631. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9632. begin
  9633. { Change:
  9634. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9635. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9636. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9637. To:
  9638. movq r/m,%rax <- Note the change in register
  9639. cqto
  9640. }
  9641. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9642. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9643. taicpu(p).loadreg(1, NR_RAX);
  9644. taicpu(hp1).opcode := A_CQO;
  9645. taicpu(hp1).clearop(1);
  9646. taicpu(hp1).clearop(0);
  9647. taicpu(hp1).ops:=0;
  9648. RemoveInstruction(hp2);
  9649. Include(OptsToCheck, aoc_ForceNewIteration);
  9650. {$endif x86_64}
  9651. *)
  9652. end;
  9653. end;
  9654. {$ifdef x86_64}
  9655. end;
  9656. if (taicpu(p).opsize = S_L) and
  9657. (taicpu(p).oper[1]^.typ = top_reg) and
  9658. (
  9659. MatchInstruction(hp1, A_MOV,[]) and
  9660. (taicpu(hp1).opsize = S_L) and
  9661. (taicpu(hp1).oper[1]^.typ = top_reg)
  9662. ) and (
  9663. GetNextInstruction(hp1, hp2) and
  9664. (tai(hp2).typ=ait_instruction) and
  9665. (taicpu(hp2).opsize = S_Q) and
  9666. (
  9667. (
  9668. MatchInstruction(hp2, A_ADD,[]) and
  9669. (taicpu(hp2).opsize = S_Q) and
  9670. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9671. (
  9672. (
  9673. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9674. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9675. ) or (
  9676. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9677. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9678. )
  9679. )
  9680. ) or (
  9681. MatchInstruction(hp2, A_LEA,[]) and
  9682. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9683. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9684. (
  9685. (
  9686. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9687. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9688. ) or (
  9689. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9690. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9691. )
  9692. ) and (
  9693. (
  9694. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9695. ) or (
  9696. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9697. )
  9698. )
  9699. )
  9700. )
  9701. ) and (
  9702. GetNextInstruction(hp2, hp3) and
  9703. MatchInstruction(hp3, A_SHR,[]) and
  9704. (taicpu(hp3).opsize = S_Q) and
  9705. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9706. (taicpu(hp3).oper[0]^.val = 1) and
  9707. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9708. ) then
  9709. begin
  9710. { Change movl x, reg1d movl x, reg1d
  9711. movl y, reg2d movl y, reg2d
  9712. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9713. shrq $1, reg1q shrq $1, reg1q
  9714. ( reg1d and reg2d can be switched around in the first two instructions )
  9715. To movl x, reg1d
  9716. addl y, reg1d
  9717. rcrl $1, reg1d
  9718. This corresponds to the common expression (x + y) shr 1, where
  9719. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9720. smaller code, but won't account for x + y causing an overflow). [Kit]
  9721. }
  9722. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9723. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9724. begin
  9725. { Change first MOV command to have the same register as the final output }
  9726. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9727. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9728. Result := True;
  9729. end
  9730. else
  9731. begin
  9732. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9733. Include(OptsToCheck, aoc_ForceNewIteration);
  9734. end;
  9735. { Change second MOV command to an ADD command. This is easier than
  9736. converting the existing command because it means we don't have to
  9737. touch 'y', which might be a complicated reference, and also the
  9738. fact that the third command might either be ADD or LEA. [Kit] }
  9739. taicpu(hp1).opcode := A_ADD;
  9740. { Delete old ADD/LEA instruction }
  9741. RemoveInstruction(hp2);
  9742. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9743. taicpu(hp3).opcode := A_RCR;
  9744. taicpu(hp3).changeopsize(S_L);
  9745. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9746. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9747. called, so FuncMov2Func below is safe to call }
  9748. {$endif x86_64}
  9749. end;
  9750. if FuncMov2Func(p, hp1) then
  9751. begin
  9752. Result := True;
  9753. Exit;
  9754. end;
  9755. end;
  9756. {$push}
  9757. {$q-}{$r-}
  9758. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9759. var
  9760. ThisReg: TRegister;
  9761. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9762. TargetSubReg: TSubRegister;
  9763. hp1, hp2: tai;
  9764. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9765. { Store list of found instructions so we don't have to call
  9766. GetNextInstructionUsingReg multiple times }
  9767. InstrList: array of taicpu;
  9768. InstrMax, Index: Integer;
  9769. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9770. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9771. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9772. WorkingValue: TCgInt;
  9773. PreMessage: string;
  9774. { Data flow analysis }
  9775. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9776. BitwiseOnly, OrXorUsed,
  9777. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9778. function CheckOverflowConditions: Boolean;
  9779. begin
  9780. Result := True;
  9781. if (TestValSignedMax > SignedUpperLimit) then
  9782. UpperSignedOverflow := True;
  9783. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9784. LowerSignedOverflow := True;
  9785. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9786. LowerUnsignedOverflow := True;
  9787. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9788. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9789. begin
  9790. { Absolute overflow }
  9791. Result := False;
  9792. Exit;
  9793. end;
  9794. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9795. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9796. ShiftDownOverflow := True;
  9797. if (TestValMin < 0) or (TestValMax < 0) then
  9798. begin
  9799. LowerUnsignedOverflow := True;
  9800. UpperUnsignedOverflow := True;
  9801. end;
  9802. end;
  9803. function AdjustInitialLoadAndSize: Boolean;
  9804. begin
  9805. Result := False;
  9806. if not p_removed then
  9807. begin
  9808. if TargetSize = MinSize then
  9809. begin
  9810. { Convert the input MOVZX to a MOV }
  9811. if (taicpu(p).oper[0]^.typ = top_reg) and
  9812. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9813. begin
  9814. { Or remove it completely! }
  9815. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9816. RemoveCurrentP(p);
  9817. p_removed := True;
  9818. end
  9819. else
  9820. begin
  9821. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9822. taicpu(p).opcode := A_MOV;
  9823. taicpu(p).oper[1]^.reg := ThisReg;
  9824. taicpu(p).opsize := TargetSize;
  9825. end;
  9826. Result := True;
  9827. end
  9828. else if TargetSize <> MaxSize then
  9829. begin
  9830. case MaxSize of
  9831. S_L:
  9832. if TargetSize = S_W then
  9833. begin
  9834. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9835. taicpu(p).opsize := S_BW;
  9836. taicpu(p).oper[1]^.reg := ThisReg;
  9837. Result := True;
  9838. end
  9839. else
  9840. InternalError(2020112341);
  9841. S_W:
  9842. if TargetSize = S_L then
  9843. begin
  9844. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9845. taicpu(p).opsize := S_BL;
  9846. taicpu(p).oper[1]^.reg := ThisReg;
  9847. Result := True;
  9848. end
  9849. else
  9850. InternalError(2020112342);
  9851. else
  9852. ;
  9853. end;
  9854. end
  9855. else if not hp1_removed and not RegInUse then
  9856. begin
  9857. { If we have something like:
  9858. movzbl (oper),%regd
  9859. add x, %regd
  9860. movzbl %regb, %regd
  9861. We can reduce the register size to the input of the final
  9862. movzbl instruction. Overflows won't have any effect.
  9863. }
  9864. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9865. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9866. begin
  9867. TargetSize := S_B;
  9868. setsubreg(ThisReg, R_SUBL);
  9869. Result := True;
  9870. end
  9871. else if (taicpu(p).opsize = S_WL) and
  9872. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9873. begin
  9874. TargetSize := S_W;
  9875. setsubreg(ThisReg, R_SUBW);
  9876. Result := True;
  9877. end;
  9878. if Result then
  9879. begin
  9880. { Convert the input MOVZX to a MOV }
  9881. if (taicpu(p).oper[0]^.typ = top_reg) and
  9882. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9883. begin
  9884. { Or remove it completely! }
  9885. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9886. RemoveCurrentP(p);
  9887. p_removed := True;
  9888. end
  9889. else
  9890. begin
  9891. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9892. taicpu(p).opcode := A_MOV;
  9893. taicpu(p).oper[1]^.reg := ThisReg;
  9894. taicpu(p).opsize := TargetSize;
  9895. end;
  9896. end;
  9897. end;
  9898. end;
  9899. end;
  9900. procedure AdjustFinalLoad;
  9901. begin
  9902. if not LowerUnsignedOverflow then
  9903. begin
  9904. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9905. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9906. begin
  9907. { Convert the output MOVZX to a MOV }
  9908. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9909. begin
  9910. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9911. if (MinSize = S_B) or
  9912. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9913. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9914. begin
  9915. { Remove it completely! }
  9916. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9917. { Be careful; if p = hp1 and p was also removed, p
  9918. will become a dangling pointer }
  9919. if p = hp1 then
  9920. begin
  9921. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9922. p_removed := True;
  9923. end
  9924. else
  9925. RemoveInstruction(hp1);
  9926. hp1_removed := True;
  9927. end;
  9928. end
  9929. else
  9930. begin
  9931. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9932. taicpu(hp1).opcode := A_MOV;
  9933. taicpu(hp1).oper[0]^.reg := ThisReg;
  9934. taicpu(hp1).opsize := TargetSize;
  9935. end;
  9936. end
  9937. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9938. begin
  9939. { Need to change the size of the output }
  9940. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9941. taicpu(hp1).oper[0]^.reg := ThisReg;
  9942. taicpu(hp1).opsize := S_BL;
  9943. end;
  9944. end;
  9945. end;
  9946. function CompressInstructions: Boolean;
  9947. var
  9948. LocalIndex: Integer;
  9949. begin
  9950. Result := False;
  9951. { The objective here is to try to find a combination that
  9952. removes one of the MOV/Z instructions. }
  9953. if (
  9954. (taicpu(p).oper[0]^.typ <> top_reg) or
  9955. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9956. ) and
  9957. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9958. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9959. begin
  9960. { Make a preference to remove the second MOVZX instruction }
  9961. case taicpu(hp1).opsize of
  9962. S_BL, S_WL:
  9963. begin
  9964. TargetSize := S_L;
  9965. TargetSubReg := R_SUBD;
  9966. end;
  9967. S_BW:
  9968. begin
  9969. TargetSize := S_W;
  9970. TargetSubReg := R_SUBW;
  9971. end;
  9972. else
  9973. InternalError(2020112302);
  9974. end;
  9975. end
  9976. else
  9977. begin
  9978. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9979. begin
  9980. { Exceeded lower bound but not upper bound }
  9981. TargetSize := MaxSize;
  9982. end
  9983. else if not LowerUnsignedOverflow then
  9984. begin
  9985. { Size didn't exceed lower bound }
  9986. TargetSize := MinSize;
  9987. end
  9988. else
  9989. Exit;
  9990. end;
  9991. case TargetSize of
  9992. S_B:
  9993. TargetSubReg := R_SUBL;
  9994. S_W:
  9995. TargetSubReg := R_SUBW;
  9996. S_L:
  9997. TargetSubReg := R_SUBD;
  9998. else
  9999. InternalError(2020112350);
  10000. end;
  10001. { Update the register to its new size }
  10002. setsubreg(ThisReg, TargetSubReg);
  10003. RegInUse := False;
  10004. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10005. begin
  10006. { Check to see if the active register is used afterwards;
  10007. if not, we can change it and make a saving. }
  10008. TransferUsedRegs(TmpUsedRegs);
  10009. { The target register may be marked as in use to cross
  10010. a jump to a distant label, so exclude it }
  10011. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10012. hp2 := p;
  10013. repeat
  10014. { Explicitly check for the excluded register (don't include the first
  10015. instruction as it may be reading from here }
  10016. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10017. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10018. begin
  10019. RegInUse := True;
  10020. Break;
  10021. end;
  10022. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10023. if not GetNextInstruction(hp2, hp2) then
  10024. InternalError(2020112340);
  10025. until (hp2 = hp1);
  10026. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10027. { We might still be able to get away with this }
  10028. RegInUse := not
  10029. (
  10030. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10031. (hp2.typ = ait_instruction) and
  10032. (
  10033. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10034. instruction that doesn't actually contain ThisReg }
  10035. (cs_opt_level3 in current_settings.optimizerswitches) or
  10036. RegInInstruction(ThisReg, hp2)
  10037. ) and
  10038. RegLoadedWithNewValue(ThisReg, hp2)
  10039. );
  10040. if not RegInUse then
  10041. begin
  10042. { Force the register size to the same as this instruction so it can be removed}
  10043. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10044. begin
  10045. TargetSize := S_L;
  10046. TargetSubReg := R_SUBD;
  10047. end
  10048. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10049. begin
  10050. TargetSize := S_W;
  10051. TargetSubReg := R_SUBW;
  10052. end;
  10053. ThisReg := taicpu(hp1).oper[1]^.reg;
  10054. setsubreg(ThisReg, TargetSubReg);
  10055. RegChanged := True;
  10056. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10057. TransferUsedRegs(TmpUsedRegs);
  10058. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10059. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10060. if p = hp1 then
  10061. begin
  10062. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10063. p_removed := True;
  10064. end
  10065. else
  10066. RemoveInstruction(hp1);
  10067. hp1_removed := True;
  10068. { Instruction will become "mov %reg,%reg" }
  10069. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10070. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10071. begin
  10072. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10073. RemoveCurrentP(p);
  10074. p_removed := True;
  10075. end
  10076. else
  10077. taicpu(p).oper[1]^.reg := ThisReg;
  10078. Result := True;
  10079. end
  10080. else
  10081. begin
  10082. if TargetSize <> MaxSize then
  10083. begin
  10084. { Since the register is in use, we have to force it to
  10085. MaxSize otherwise part of it may become undefined later on }
  10086. TargetSize := MaxSize;
  10087. case TargetSize of
  10088. S_B:
  10089. TargetSubReg := R_SUBL;
  10090. S_W:
  10091. TargetSubReg := R_SUBW;
  10092. S_L:
  10093. TargetSubReg := R_SUBD;
  10094. else
  10095. InternalError(2020112351);
  10096. end;
  10097. setsubreg(ThisReg, TargetSubReg);
  10098. end;
  10099. AdjustFinalLoad;
  10100. end;
  10101. end
  10102. else
  10103. AdjustFinalLoad;
  10104. Result := AdjustInitialLoadAndSize or Result;
  10105. { Now go through every instruction we found and change the
  10106. size. If TargetSize = MaxSize, then almost no changes are
  10107. needed and Result can remain False if it hasn't been set
  10108. yet.
  10109. If RegChanged is True, then the register requires changing
  10110. and so the point about TargetSize = MaxSize doesn't apply. }
  10111. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10112. begin
  10113. for LocalIndex := 0 to InstrMax do
  10114. begin
  10115. { If p_removed is true, then the original MOV/Z was removed
  10116. and removing the AND instruction may not be safe if it
  10117. appears first }
  10118. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10119. InternalError(2020112310);
  10120. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10121. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10122. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10123. InstrList[LocalIndex].opsize := TargetSize;
  10124. end;
  10125. Result := True;
  10126. end;
  10127. end;
  10128. begin
  10129. Result := False;
  10130. p_removed := False;
  10131. hp1_removed := False;
  10132. ThisReg := taicpu(p).oper[1]^.reg;
  10133. { Check for:
  10134. movs/z ###,%ecx (or %cx or %rcx)
  10135. ...
  10136. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10137. (dealloc %ecx)
  10138. Change to:
  10139. mov ###,%cl (if ### = %cl, then remove completely)
  10140. ...
  10141. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10142. }
  10143. if (getsupreg(ThisReg) = RS_ECX) and
  10144. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10145. (hp1.typ = ait_instruction) and
  10146. (
  10147. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10148. instruction that doesn't actually contain ECX }
  10149. (cs_opt_level3 in current_settings.optimizerswitches) or
  10150. RegInInstruction(NR_ECX, hp1) or
  10151. (
  10152. { It's common for the shift/rotate's read/write register to be
  10153. initialised in between, so under -O2 and under, search ahead
  10154. one more instruction
  10155. }
  10156. GetNextInstruction(hp1, hp1) and
  10157. (hp1.typ = ait_instruction) and
  10158. RegInInstruction(NR_ECX, hp1)
  10159. )
  10160. ) and
  10161. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10162. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10163. begin
  10164. TransferUsedRegs(TmpUsedRegs);
  10165. hp2 := p;
  10166. repeat
  10167. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10168. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10169. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10170. begin
  10171. case taicpu(p).opsize of
  10172. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10173. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10174. begin
  10175. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10176. RemoveCurrentP(p);
  10177. end
  10178. else
  10179. begin
  10180. taicpu(p).opcode := A_MOV;
  10181. taicpu(p).opsize := S_B;
  10182. taicpu(p).oper[1]^.reg := NR_CL;
  10183. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10184. end;
  10185. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10186. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10187. begin
  10188. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10189. RemoveCurrentP(p);
  10190. end
  10191. else
  10192. begin
  10193. taicpu(p).opcode := A_MOV;
  10194. taicpu(p).opsize := S_W;
  10195. taicpu(p).oper[1]^.reg := NR_CX;
  10196. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10197. end;
  10198. {$ifdef x86_64}
  10199. S_LQ:
  10200. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10201. begin
  10202. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10203. RemoveCurrentP(p);
  10204. end
  10205. else
  10206. begin
  10207. taicpu(p).opcode := A_MOV;
  10208. taicpu(p).opsize := S_L;
  10209. taicpu(p).oper[1]^.reg := NR_ECX;
  10210. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10211. end;
  10212. {$endif x86_64}
  10213. else
  10214. InternalError(2021120401);
  10215. end;
  10216. Result := True;
  10217. Exit;
  10218. end;
  10219. end;
  10220. { This is anything but quick! }
  10221. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10222. Exit;
  10223. SetLength(InstrList, 0);
  10224. InstrMax := -1;
  10225. case taicpu(p).opsize of
  10226. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10227. begin
  10228. {$if defined(i386) or defined(i8086)}
  10229. { If the target size is 8-bit, make sure we can actually encode it }
  10230. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10231. Exit;
  10232. {$endif i386 or i8086}
  10233. LowerLimit := $FF;
  10234. SignedLowerLimit := $7F;
  10235. SignedLowerLimitBottom := -128;
  10236. MinSize := S_B;
  10237. if taicpu(p).opsize = S_BW then
  10238. begin
  10239. MaxSize := S_W;
  10240. UpperLimit := $FFFF;
  10241. SignedUpperLimit := $7FFF;
  10242. SignedUpperLimitBottom := -32768;
  10243. end
  10244. else
  10245. begin
  10246. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10247. MaxSize := S_L;
  10248. UpperLimit := $FFFFFFFF;
  10249. SignedUpperLimit := $7FFFFFFF;
  10250. SignedUpperLimitBottom := -2147483648;
  10251. end;
  10252. end;
  10253. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10254. begin
  10255. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10256. LowerLimit := $FFFF;
  10257. SignedLowerLimit := $7FFF;
  10258. SignedLowerLimitBottom := -32768;
  10259. UpperLimit := $FFFFFFFF;
  10260. SignedUpperLimit := $7FFFFFFF;
  10261. SignedUpperLimitBottom := -2147483648;
  10262. MinSize := S_W;
  10263. MaxSize := S_L;
  10264. end;
  10265. {$ifdef x86_64}
  10266. S_LQ:
  10267. begin
  10268. { Both the lower and upper limits are set to 32-bit. If a limit
  10269. is breached, then optimisation is impossible }
  10270. LowerLimit := $FFFFFFFF;
  10271. SignedLowerLimit := $7FFFFFFF;
  10272. SignedLowerLimitBottom := -2147483648;
  10273. UpperLimit := $FFFFFFFF;
  10274. SignedUpperLimit := $7FFFFFFF;
  10275. SignedUpperLimitBottom := -2147483648;
  10276. MinSize := S_L;
  10277. MaxSize := S_L;
  10278. end;
  10279. {$endif x86_64}
  10280. else
  10281. InternalError(2020112301);
  10282. end;
  10283. TestValMin := 0;
  10284. TestValMax := LowerLimit;
  10285. TestValSignedMax := SignedLowerLimit;
  10286. TryShiftDownLimit := LowerLimit;
  10287. TryShiftDown := S_NO;
  10288. ShiftDownOverflow := False;
  10289. RegChanged := False;
  10290. BitwiseOnly := True;
  10291. OrXorUsed := False;
  10292. UpperSignedOverflow := False;
  10293. LowerSignedOverflow := False;
  10294. UpperUnsignedOverflow := False;
  10295. LowerUnsignedOverflow := False;
  10296. hp1 := p;
  10297. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10298. (hp1.typ = ait_instruction) and
  10299. (
  10300. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10301. instruction that doesn't actually contain ThisReg }
  10302. (cs_opt_level3 in current_settings.optimizerswitches) or
  10303. { This allows this Movx optimisation to work through the SETcc instructions
  10304. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10305. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10306. skip over these SETcc instructions). }
  10307. (taicpu(hp1).opcode = A_SETcc) or
  10308. RegInInstruction(ThisReg, hp1)
  10309. ) do
  10310. begin
  10311. case taicpu(hp1).opcode of
  10312. A_INC,A_DEC:
  10313. begin
  10314. { Has to be an exact match on the register }
  10315. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10316. Break;
  10317. if taicpu(hp1).opcode = A_INC then
  10318. begin
  10319. Inc(TestValMin);
  10320. Inc(TestValMax);
  10321. Inc(TestValSignedMax);
  10322. end
  10323. else
  10324. begin
  10325. Dec(TestValMin);
  10326. Dec(TestValMax);
  10327. Dec(TestValSignedMax);
  10328. end;
  10329. end;
  10330. A_TEST, A_CMP:
  10331. begin
  10332. if (
  10333. { Too high a risk of non-linear behaviour that breaks DFA
  10334. here, unless it's cmp $0,%reg, which is equivalent to
  10335. test %reg,%reg }
  10336. OrXorUsed and
  10337. (taicpu(hp1).opcode = A_CMP) and
  10338. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10339. ) or
  10340. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10341. { Has to be an exact match on the register }
  10342. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10343. (
  10344. { Permit "test %reg,%reg" }
  10345. (taicpu(hp1).opcode = A_TEST) and
  10346. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10347. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10348. ) or
  10349. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10350. { Make sure the comparison value is not smaller than the
  10351. smallest allowed signed value for the minimum size (e.g.
  10352. -128 for 8-bit) }
  10353. not (
  10354. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10355. { Is it in the negative range? }
  10356. (
  10357. (taicpu(hp1).oper[0]^.val < 0) and
  10358. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10359. )
  10360. ) then
  10361. Break;
  10362. { Check to see if the active register is used afterwards }
  10363. TransferUsedRegs(TmpUsedRegs);
  10364. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10365. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10366. begin
  10367. { Make sure the comparison or any previous instructions
  10368. hasn't pushed the test values outside of the range of
  10369. MinSize }
  10370. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10371. begin
  10372. { Exceeded lower bound but not upper bound }
  10373. Exit;
  10374. end
  10375. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10376. begin
  10377. { Size didn't exceed lower bound }
  10378. TargetSize := MinSize;
  10379. end
  10380. else
  10381. Break;
  10382. case TargetSize of
  10383. S_B:
  10384. TargetSubReg := R_SUBL;
  10385. S_W:
  10386. TargetSubReg := R_SUBW;
  10387. S_L:
  10388. TargetSubReg := R_SUBD;
  10389. else
  10390. InternalError(2021051002);
  10391. end;
  10392. if TargetSize <> MaxSize then
  10393. begin
  10394. { Update the register to its new size }
  10395. setsubreg(ThisReg, TargetSubReg);
  10396. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10397. taicpu(hp1).oper[1]^.reg := ThisReg;
  10398. taicpu(hp1).opsize := TargetSize;
  10399. { Convert the input MOVZX to a MOV if necessary }
  10400. AdjustInitialLoadAndSize;
  10401. if (InstrMax >= 0) then
  10402. begin
  10403. for Index := 0 to InstrMax do
  10404. begin
  10405. { If p_removed is true, then the original MOV/Z was removed
  10406. and removing the AND instruction may not be safe if it
  10407. appears first }
  10408. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10409. InternalError(2020112311);
  10410. if InstrList[Index].oper[0]^.typ = top_reg then
  10411. InstrList[Index].oper[0]^.reg := ThisReg;
  10412. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10413. InstrList[Index].opsize := MinSize;
  10414. end;
  10415. end;
  10416. Result := True;
  10417. end;
  10418. Exit;
  10419. end;
  10420. end;
  10421. A_SETcc:
  10422. begin
  10423. { This allows this Movx optimisation to work through the SETcc instructions
  10424. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10425. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10426. skip over these SETcc instructions). }
  10427. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10428. { Of course, break out if the current register is used }
  10429. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10430. Break
  10431. else
  10432. { We must use Continue so the instruction doesn't get added
  10433. to InstrList }
  10434. Continue;
  10435. end;
  10436. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10437. begin
  10438. if
  10439. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10440. { Has to be an exact match on the register }
  10441. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10442. (
  10443. (
  10444. (taicpu(hp1).oper[0]^.typ = top_const) and
  10445. (
  10446. (
  10447. (taicpu(hp1).opcode = A_SHL) and
  10448. (
  10449. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10450. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10451. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10452. )
  10453. ) or (
  10454. (taicpu(hp1).opcode <> A_SHL) and
  10455. (
  10456. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10457. { Is it in the negative range? }
  10458. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10459. )
  10460. )
  10461. )
  10462. ) or (
  10463. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10464. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10465. )
  10466. ) then
  10467. Break;
  10468. { Only process OR and XOR if there are only bitwise operations,
  10469. since otherwise they can too easily fool the data flow
  10470. analysis (they can cause non-linear behaviour) }
  10471. case taicpu(hp1).opcode of
  10472. A_ADD:
  10473. begin
  10474. if OrXorUsed then
  10475. { Too high a risk of non-linear behaviour that breaks DFA here }
  10476. Break
  10477. else
  10478. BitwiseOnly := False;
  10479. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10480. begin
  10481. TestValMin := TestValMin * 2;
  10482. TestValMax := TestValMax * 2;
  10483. TestValSignedMax := TestValSignedMax * 2;
  10484. end
  10485. else
  10486. begin
  10487. WorkingValue := taicpu(hp1).oper[0]^.val;
  10488. TestValMin := TestValMin + WorkingValue;
  10489. TestValMax := TestValMax + WorkingValue;
  10490. TestValSignedMax := TestValSignedMax + WorkingValue;
  10491. end;
  10492. end;
  10493. A_SUB:
  10494. begin
  10495. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10496. begin
  10497. TestValMin := 0;
  10498. TestValMax := 0;
  10499. TestValSignedMax := 0;
  10500. end
  10501. else
  10502. begin
  10503. if OrXorUsed then
  10504. { Too high a risk of non-linear behaviour that breaks DFA here }
  10505. Break
  10506. else
  10507. BitwiseOnly := False;
  10508. WorkingValue := taicpu(hp1).oper[0]^.val;
  10509. TestValMin := TestValMin - WorkingValue;
  10510. TestValMax := TestValMax - WorkingValue;
  10511. TestValSignedMax := TestValSignedMax - WorkingValue;
  10512. end;
  10513. end;
  10514. A_AND:
  10515. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10516. begin
  10517. { we might be able to go smaller if AND appears first }
  10518. if InstrMax = -1 then
  10519. case MinSize of
  10520. S_B:
  10521. ;
  10522. S_W:
  10523. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10524. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10525. begin
  10526. TryShiftDown := S_B;
  10527. TryShiftDownLimit := $FF;
  10528. end;
  10529. S_L:
  10530. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10531. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10532. begin
  10533. TryShiftDown := S_B;
  10534. TryShiftDownLimit := $FF;
  10535. end
  10536. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10537. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10538. begin
  10539. TryShiftDown := S_W;
  10540. TryShiftDownLimit := $FFFF;
  10541. end;
  10542. else
  10543. InternalError(2020112320);
  10544. end;
  10545. WorkingValue := taicpu(hp1).oper[0]^.val;
  10546. TestValMin := TestValMin and WorkingValue;
  10547. TestValMax := TestValMax and WorkingValue;
  10548. TestValSignedMax := TestValSignedMax and WorkingValue;
  10549. end;
  10550. A_OR:
  10551. begin
  10552. if not BitwiseOnly then
  10553. Break;
  10554. OrXorUsed := True;
  10555. WorkingValue := taicpu(hp1).oper[0]^.val;
  10556. TestValMin := TestValMin or WorkingValue;
  10557. TestValMax := TestValMax or WorkingValue;
  10558. TestValSignedMax := TestValSignedMax or WorkingValue;
  10559. end;
  10560. A_XOR:
  10561. begin
  10562. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10563. begin
  10564. TestValMin := 0;
  10565. TestValMax := 0;
  10566. TestValSignedMax := 0;
  10567. end
  10568. else
  10569. begin
  10570. if not BitwiseOnly then
  10571. Break;
  10572. OrXorUsed := True;
  10573. WorkingValue := taicpu(hp1).oper[0]^.val;
  10574. TestValMin := TestValMin xor WorkingValue;
  10575. TestValMax := TestValMax xor WorkingValue;
  10576. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10577. end;
  10578. end;
  10579. A_SHL:
  10580. begin
  10581. BitwiseOnly := False;
  10582. WorkingValue := taicpu(hp1).oper[0]^.val;
  10583. TestValMin := TestValMin shl WorkingValue;
  10584. TestValMax := TestValMax shl WorkingValue;
  10585. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10586. end;
  10587. A_SHR,
  10588. { The first instruction was MOVZX, so the value won't be negative }
  10589. A_SAR:
  10590. begin
  10591. if InstrMax <> -1 then
  10592. BitwiseOnly := False
  10593. else
  10594. { we might be able to go smaller if SHR appears first }
  10595. case MinSize of
  10596. S_B:
  10597. ;
  10598. S_W:
  10599. if (taicpu(hp1).oper[0]^.val >= 8) then
  10600. begin
  10601. TryShiftDown := S_B;
  10602. TryShiftDownLimit := $FF;
  10603. TryShiftDownSignedLimit := $7F;
  10604. TryShiftDownSignedLimitLower := -128;
  10605. end;
  10606. S_L:
  10607. if (taicpu(hp1).oper[0]^.val >= 24) then
  10608. begin
  10609. TryShiftDown := S_B;
  10610. TryShiftDownLimit := $FF;
  10611. TryShiftDownSignedLimit := $7F;
  10612. TryShiftDownSignedLimitLower := -128;
  10613. end
  10614. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10615. begin
  10616. TryShiftDown := S_W;
  10617. TryShiftDownLimit := $FFFF;
  10618. TryShiftDownSignedLimit := $7FFF;
  10619. TryShiftDownSignedLimitLower := -32768;
  10620. end;
  10621. else
  10622. InternalError(2020112321);
  10623. end;
  10624. WorkingValue := taicpu(hp1).oper[0]^.val;
  10625. if taicpu(hp1).opcode = A_SAR then
  10626. begin
  10627. TestValMin := SarInt64(TestValMin, WorkingValue);
  10628. TestValMax := SarInt64(TestValMax, WorkingValue);
  10629. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10630. end
  10631. else
  10632. begin
  10633. TestValMin := TestValMin shr WorkingValue;
  10634. TestValMax := TestValMax shr WorkingValue;
  10635. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10636. end;
  10637. end;
  10638. else
  10639. InternalError(2020112303);
  10640. end;
  10641. end;
  10642. (*
  10643. A_IMUL:
  10644. case taicpu(hp1).ops of
  10645. 2:
  10646. begin
  10647. if not MatchOpType(hp1, top_reg, top_reg) or
  10648. { Has to be an exact match on the register }
  10649. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10650. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10651. Break;
  10652. TestValMin := TestValMin * TestValMin;
  10653. TestValMax := TestValMax * TestValMax;
  10654. TestValSignedMax := TestValSignedMax * TestValMax;
  10655. end;
  10656. 3:
  10657. begin
  10658. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10659. { Has to be an exact match on the register }
  10660. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10661. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10662. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10663. { Is it in the negative range? }
  10664. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10665. Break;
  10666. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10667. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10668. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10669. end;
  10670. else
  10671. Break;
  10672. end;
  10673. A_IDIV:
  10674. case taicpu(hp1).ops of
  10675. 3:
  10676. begin
  10677. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10678. { Has to be an exact match on the register }
  10679. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10680. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10681. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10682. { Is it in the negative range? }
  10683. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10684. Break;
  10685. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10686. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10687. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10688. end;
  10689. else
  10690. Break;
  10691. end;
  10692. *)
  10693. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10694. begin
  10695. { If there are no instructions in between, then we might be able to make a saving }
  10696. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10697. Break;
  10698. { We have something like:
  10699. movzbw %dl,%dx
  10700. ...
  10701. movswl %dx,%edx
  10702. Change the latter to a zero-extension then enter the
  10703. A_MOVZX case branch.
  10704. }
  10705. {$ifdef x86_64}
  10706. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10707. begin
  10708. { this becomes a zero extension from 32-bit to 64-bit, but
  10709. the upper 32 bits are already zero, so just delete the
  10710. instruction }
  10711. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10712. RemoveInstruction(hp1);
  10713. Result := True;
  10714. Exit;
  10715. end
  10716. else
  10717. {$endif x86_64}
  10718. begin
  10719. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10720. taicpu(hp1).opcode := A_MOVZX;
  10721. {$ifdef x86_64}
  10722. case taicpu(hp1).opsize of
  10723. S_BQ:
  10724. begin
  10725. taicpu(hp1).opsize := S_BL;
  10726. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10727. end;
  10728. S_WQ:
  10729. begin
  10730. taicpu(hp1).opsize := S_WL;
  10731. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10732. end;
  10733. S_LQ:
  10734. begin
  10735. taicpu(hp1).opcode := A_MOV;
  10736. taicpu(hp1).opsize := S_L;
  10737. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10738. { In this instance, we need to break out because the
  10739. instruction is no longer MOVZX or MOVSXD }
  10740. Result := True;
  10741. Exit;
  10742. end;
  10743. else
  10744. ;
  10745. end;
  10746. {$endif x86_64}
  10747. Result := CompressInstructions;
  10748. Exit;
  10749. end;
  10750. end;
  10751. A_MOVZX:
  10752. begin
  10753. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10754. Break;
  10755. if (InstrMax = -1) then
  10756. begin
  10757. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10758. begin
  10759. { Optimise around i40003 }
  10760. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10761. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10762. {$ifndef x86_64}
  10763. and (
  10764. (taicpu(p).oper[0]^.typ <> top_reg) or
  10765. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10766. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10767. )
  10768. {$endif not x86_64}
  10769. then
  10770. begin
  10771. if (taicpu(p).oper[0]^.typ = top_reg) then
  10772. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10773. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10774. taicpu(p).opsize := S_BL;
  10775. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10776. RemoveInstruction(hp1);
  10777. Result := True;
  10778. Exit;
  10779. end;
  10780. end
  10781. else
  10782. begin
  10783. { Will return false if the second parameter isn't ThisReg
  10784. (can happen on -O2 and under) }
  10785. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10786. begin
  10787. { The two MOVZX instructions are adjacent, so remove the first one }
  10788. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10789. RemoveCurrentP(p);
  10790. Result := True;
  10791. Exit;
  10792. end;
  10793. Break;
  10794. end;
  10795. end;
  10796. Result := CompressInstructions;
  10797. Exit;
  10798. end;
  10799. else
  10800. { This includes ADC, SBB and IDIV }
  10801. Break;
  10802. end;
  10803. if not CheckOverflowConditions then
  10804. Break;
  10805. { Contains highest index (so instruction count - 1) }
  10806. Inc(InstrMax);
  10807. if InstrMax > High(InstrList) then
  10808. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10809. InstrList[InstrMax] := taicpu(hp1);
  10810. end;
  10811. end;
  10812. {$pop}
  10813. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10814. var
  10815. hp1 : tai;
  10816. begin
  10817. Result:=false;
  10818. if (taicpu(p).ops >= 2) and
  10819. ((taicpu(p).oper[0]^.typ = top_const) or
  10820. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10821. (taicpu(p).oper[1]^.typ = top_reg) and
  10822. ((taicpu(p).ops = 2) or
  10823. ((taicpu(p).oper[2]^.typ = top_reg) and
  10824. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10825. GetLastInstruction(p,hp1) and
  10826. MatchInstruction(hp1,A_MOV,[]) and
  10827. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10828. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10829. begin
  10830. TransferUsedRegs(TmpUsedRegs);
  10831. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10832. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10833. { change
  10834. mov reg1,reg2
  10835. imul y,reg2 to imul y,reg1,reg2 }
  10836. begin
  10837. taicpu(p).ops := 3;
  10838. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10839. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10840. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10841. RemoveInstruction(hp1);
  10842. result:=true;
  10843. end;
  10844. end;
  10845. end;
  10846. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10847. var
  10848. ThisLabel: TAsmLabel;
  10849. begin
  10850. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10851. ThisLabel.decrefs;
  10852. taicpu(p).condition := C_None;
  10853. taicpu(p).opcode := A_RET;
  10854. taicpu(p).is_jmp := false;
  10855. taicpu(p).ops := taicpu(ret_p).ops;
  10856. case taicpu(ret_p).ops of
  10857. 0:
  10858. taicpu(p).clearop(0);
  10859. 1:
  10860. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10861. else
  10862. internalerror(2016041301);
  10863. end;
  10864. { If the original label is now dead, it might turn out that the label
  10865. immediately follows p. As a result, everything beyond it, which will
  10866. be just some final register configuration and a RET instruction, is
  10867. now dead code. [Kit] }
  10868. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10869. running RemoveDeadCodeAfterJump for each RET instruction, because
  10870. this optimisation rarely happens and most RETs appear at the end of
  10871. routines where there is nothing that can be stripped. [Kit] }
  10872. if not ThisLabel.is_used then
  10873. RemoveDeadCodeAfterJump(p);
  10874. end;
  10875. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10876. var
  10877. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10878. Unconditional, PotentialModified: Boolean;
  10879. OperPtr: POper;
  10880. NewRef: TReference;
  10881. InstrList: array of taicpu;
  10882. InstrMax, Index: Integer;
  10883. const
  10884. {$ifdef DEBUG_AOPTCPU}
  10885. SNoFlags: shortstring = ' so the flags aren''t modified';
  10886. {$else DEBUG_AOPTCPU}
  10887. SNoFlags = '';
  10888. {$endif DEBUG_AOPTCPU}
  10889. begin
  10890. Result:=false;
  10891. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10892. begin
  10893. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10894. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10895. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10896. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10897. GetNextInstruction(hp1, hp2) and
  10898. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10899. { Change from: To:
  10900. set(C) %reg j(~C) label
  10901. test %reg,%reg/cmp $0,%reg
  10902. je label
  10903. set(C) %reg j(C) label
  10904. test %reg,%reg/cmp $0,%reg
  10905. jne label
  10906. (Also do something similar with sete/setne instead of je/jne)
  10907. }
  10908. begin
  10909. { Before we do anything else, we need to check the instructions
  10910. in between SETcc and TEST to make sure they don't modify the
  10911. FLAGS register - if -O2 or under, there won't be any
  10912. instructions between SET and TEST }
  10913. TransferUsedRegs(TmpUsedRegs);
  10914. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10915. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10916. begin
  10917. next := p;
  10918. SetLength(InstrList, 0);
  10919. InstrMax := -1;
  10920. PotentialModified := False;
  10921. { Make a note of every instruction that modifies the FLAGS
  10922. register }
  10923. while GetNextInstruction(next, next) and (next <> hp1) do
  10924. begin
  10925. if next.typ <> ait_instruction then
  10926. { GetNextInstructionUsingReg should have returned False }
  10927. InternalError(2021051701);
  10928. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10929. begin
  10930. case taicpu(next).opcode of
  10931. A_SETcc,
  10932. A_CMOVcc,
  10933. A_Jcc:
  10934. begin
  10935. if PotentialModified then
  10936. { Not safe because the flags were modified earlier }
  10937. Exit
  10938. else
  10939. { Condition is the same as the initial SETcc, so this is safe
  10940. (don't add to instruction list though) }
  10941. Continue;
  10942. end;
  10943. A_ADD:
  10944. begin
  10945. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10946. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10947. (taicpu(next).oper[1]^.typ <> top_reg) or
  10948. { Must write to a register }
  10949. (taicpu(next).oper[0]^.typ = top_ref) then
  10950. { Require a constant or a register }
  10951. Exit;
  10952. PotentialModified := True;
  10953. end;
  10954. A_SUB:
  10955. begin
  10956. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10957. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10958. (taicpu(next).oper[1]^.typ <> top_reg) or
  10959. { Must write to a register }
  10960. (taicpu(next).oper[0]^.typ <> top_const) or
  10961. (taicpu(next).oper[0]^.val = $80000000) then
  10962. { Can't subtract a register with LEA - also
  10963. check that the value isn't -2^31, as this
  10964. can't be negated }
  10965. Exit;
  10966. PotentialModified := True;
  10967. end;
  10968. A_SAL,
  10969. A_SHL:
  10970. begin
  10971. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10972. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10973. (taicpu(next).oper[1]^.typ <> top_reg) or
  10974. { Must write to a register }
  10975. (taicpu(next).oper[0]^.typ <> top_const) or
  10976. (taicpu(next).oper[0]^.val < 0) or
  10977. (taicpu(next).oper[0]^.val > 3) then
  10978. Exit;
  10979. PotentialModified := True;
  10980. end;
  10981. A_IMUL:
  10982. begin
  10983. if (taicpu(next).ops <> 3) or
  10984. (taicpu(next).oper[1]^.typ <> top_reg) or
  10985. { Must write to a register }
  10986. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10987. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10988. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10989. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10990. Exit
  10991. else
  10992. PotentialModified := True;
  10993. end;
  10994. else
  10995. { Don't know how to change this, so abort }
  10996. Exit;
  10997. end;
  10998. { Contains highest index (so instruction count - 1) }
  10999. Inc(InstrMax);
  11000. if InstrMax > High(InstrList) then
  11001. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11002. InstrList[InstrMax] := taicpu(next);
  11003. end;
  11004. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11005. end;
  11006. if not Assigned(next) or (next <> hp1) then
  11007. { It should be equal to hp1 }
  11008. InternalError(2021051702);
  11009. { Cycle through each instruction and check to see if we can
  11010. change them to versions that don't modify the flags }
  11011. if (InstrMax >= 0) then
  11012. begin
  11013. for Index := 0 to InstrMax do
  11014. case InstrList[Index].opcode of
  11015. A_ADD:
  11016. begin
  11017. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11018. InstrList[Index].opcode := A_LEA;
  11019. reference_reset(NewRef, 1, []);
  11020. NewRef.base := InstrList[Index].oper[1]^.reg;
  11021. if InstrList[Index].oper[0]^.typ = top_reg then
  11022. begin
  11023. NewRef.index := InstrList[Index].oper[0]^.reg;
  11024. NewRef.scalefactor := 1;
  11025. end
  11026. else
  11027. NewRef.offset := InstrList[Index].oper[0]^.val;
  11028. InstrList[Index].loadref(0, NewRef);
  11029. end;
  11030. A_SUB:
  11031. begin
  11032. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11033. InstrList[Index].opcode := A_LEA;
  11034. reference_reset(NewRef, 1, []);
  11035. NewRef.base := InstrList[Index].oper[1]^.reg;
  11036. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11037. InstrList[Index].loadref(0, NewRef);
  11038. end;
  11039. A_SHL,
  11040. A_SAL:
  11041. begin
  11042. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11043. InstrList[Index].opcode := A_LEA;
  11044. reference_reset(NewRef, 1, []);
  11045. NewRef.index := InstrList[Index].oper[1]^.reg;
  11046. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11047. InstrList[Index].loadref(0, NewRef);
  11048. end;
  11049. A_IMUL:
  11050. begin
  11051. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11052. InstrList[Index].opcode := A_LEA;
  11053. reference_reset(NewRef, 1, []);
  11054. NewRef.index := InstrList[Index].oper[1]^.reg;
  11055. case InstrList[Index].oper[0]^.val of
  11056. 2, 4, 8:
  11057. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11058. else {3, 5 and 9}
  11059. begin
  11060. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11061. NewRef.base := InstrList[Index].oper[1]^.reg;
  11062. end;
  11063. end;
  11064. InstrList[Index].loadref(0, NewRef);
  11065. end;
  11066. else
  11067. InternalError(2021051710);
  11068. end;
  11069. end;
  11070. { Mark the FLAGS register as used across this whole block }
  11071. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11072. end;
  11073. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11074. JumpC := taicpu(hp2).condition;
  11075. Unconditional := False;
  11076. if conditions_equal(JumpC, C_E) then
  11077. SetC := inverse_cond(taicpu(p).condition)
  11078. else if conditions_equal(JumpC, C_NE) then
  11079. SetC := taicpu(p).condition
  11080. else
  11081. { We've got something weird here (and inefficent) }
  11082. begin
  11083. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11084. SetC := C_NONE;
  11085. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11086. if condition_in(C_AE, JumpC) then
  11087. Unconditional := True
  11088. else
  11089. { Not sure what to do with this jump - drop out }
  11090. Exit;
  11091. end;
  11092. RemoveInstruction(hp1);
  11093. if Unconditional then
  11094. MakeUnconditional(taicpu(hp2))
  11095. else
  11096. begin
  11097. if SetC = C_NONE then
  11098. InternalError(2018061402);
  11099. taicpu(hp2).SetCondition(SetC);
  11100. end;
  11101. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11102. TmpUsedRegs }
  11103. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11104. begin
  11105. RemoveCurrentp(p, hp2);
  11106. if taicpu(hp2).opcode = A_SETcc then
  11107. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11108. else
  11109. begin
  11110. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11111. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11112. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11113. end;
  11114. end
  11115. else
  11116. if taicpu(hp2).opcode = A_SETcc then
  11117. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11118. else
  11119. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11120. Result := True;
  11121. end
  11122. else if
  11123. { Make sure the instructions are adjacent }
  11124. (
  11125. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11126. GetNextInstruction(p, hp1)
  11127. ) and
  11128. MatchInstruction(hp1, A_MOV, [S_B]) and
  11129. { Writing to memory is allowed }
  11130. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11131. begin
  11132. {
  11133. Watch out for sequences such as:
  11134. set(c)b %regb
  11135. movb %regb,(ref)
  11136. movb $0,1(ref)
  11137. movb $0,2(ref)
  11138. movb $0,3(ref)
  11139. Much more efficient to turn it into:
  11140. movl $0,%regl
  11141. set(c)b %regb
  11142. movl %regl,(ref)
  11143. Or:
  11144. set(c)b %regb
  11145. movzbl %regb,%regl
  11146. movl %regl,(ref)
  11147. }
  11148. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11149. GetNextInstruction(hp1, hp2) and
  11150. MatchInstruction(hp2, A_MOV, [S_B]) and
  11151. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11152. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11153. begin
  11154. { Don't do anything else except set Result to True }
  11155. end
  11156. else
  11157. begin
  11158. if taicpu(p).oper[0]^.typ = top_reg then
  11159. begin
  11160. TransferUsedRegs(TmpUsedRegs);
  11161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11162. end;
  11163. { If it's not a register, it's a memory address }
  11164. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11165. begin
  11166. { Even if the register is still in use, we can minimise the
  11167. pipeline stall by changing the MOV into another SETcc. }
  11168. taicpu(hp1).opcode := A_SETcc;
  11169. taicpu(hp1).condition := taicpu(p).condition;
  11170. if taicpu(hp1).oper[1]^.typ = top_ref then
  11171. begin
  11172. { Swapping the operand pointers like this is probably a
  11173. bit naughty, but it is far faster than using loadoper
  11174. to transfer the reference from oper[1] to oper[0] if
  11175. you take into account the extra procedure calls and
  11176. the memory allocation and deallocation required }
  11177. OperPtr := taicpu(hp1).oper[1];
  11178. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11179. taicpu(hp1).oper[0] := OperPtr;
  11180. end
  11181. else
  11182. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11183. taicpu(hp1).clearop(1);
  11184. taicpu(hp1).ops := 1;
  11185. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11186. end
  11187. else
  11188. begin
  11189. if taicpu(hp1).oper[1]^.typ = top_reg then
  11190. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11191. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11192. RemoveInstruction(hp1);
  11193. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11194. end
  11195. end;
  11196. Result := True;
  11197. end;
  11198. end;
  11199. end;
  11200. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11201. var
  11202. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11203. TargetReg: TRegister;
  11204. condition, inverted_condition: TAsmCond;
  11205. FoundMOV: Boolean;
  11206. begin
  11207. Result := False;
  11208. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11209. create the most optimial instructions possible due to limited
  11210. register availability, and there are situations where two
  11211. complementary "simple" CMOV blocks are created which, after the fact
  11212. can be merged into a "double" block. For example:
  11213. movw $257,%ax
  11214. movw $2,%r8w
  11215. xorl r9d,%r9d
  11216. testw $16,18(%rcx)
  11217. cmovew %ax,%dx
  11218. cmovew %r8w,%bx
  11219. cmovel %r9d,%r14d
  11220. movw $1283,%ax
  11221. movw $4,%r8w
  11222. movl $9,%r9d
  11223. cmovnew %ax,%dx
  11224. cmovnew %r8w,%bx
  11225. cmovnel %r9d,%r14d
  11226. The CMOVNE instructions at the end can be removed, and the
  11227. destination registers copied into the MOV instructions directly
  11228. above them, before finally being moved to before the first CMOVE
  11229. instructions, to produce:
  11230. movw $257,%ax
  11231. movw $2,%r8w
  11232. xorl r9d,%r9d
  11233. testw $16,18(%rcx)
  11234. movw $1283,%dx
  11235. movw $4,%bx
  11236. movl $9,%r14d
  11237. cmovew %ax,%dx
  11238. cmovew %r8w,%bx
  11239. cmovel %r9d,%r14d
  11240. Which can then be later optimised to:
  11241. movw $257,%ax
  11242. movw $2,%r8w
  11243. xorl r9d,%r9d
  11244. movw $1283,%dx
  11245. movw $4,%bx
  11246. movl $9,%r14d
  11247. testw $16,18(%rcx)
  11248. cmovew %ax,%dx
  11249. cmovew %r8w,%bx
  11250. cmovel %r9d,%r14d
  11251. }
  11252. TargetReg := taicpu(hp1).oper[1]^.reg;
  11253. condition := taicpu(hp1).condition;
  11254. inverted_condition := inverse_cond(condition);
  11255. pFirstMov := nil;
  11256. pLastMov := nil;
  11257. pCMOV := nil;
  11258. if (p.typ = ait_instruction) then
  11259. pCond := p
  11260. else if not GetNextInstruction(p, pCond) then
  11261. InternalError(2024012501);
  11262. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11263. { We should get the CMP or TEST instructeion }
  11264. InternalError(2024012502);
  11265. if (
  11266. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11267. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11268. ) then
  11269. begin
  11270. { We have to tread carefully here, hence why we're not using
  11271. GetNextInstructionUsingReg... we can only accept MOV and other
  11272. CMOV instructions. Anything else and we must drop out}
  11273. hp2 := hp1;
  11274. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11275. begin
  11276. if (hp2.typ <> ait_instruction) then
  11277. Exit;
  11278. case taicpu(hp2).opcode of
  11279. A_MOV:
  11280. begin
  11281. if not Assigned(pFirstMov) then
  11282. pFirstMov := hp2;
  11283. pLastMOV := hp2;
  11284. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11285. { Something different - drop out }
  11286. Exit;
  11287. { Otherwise, leave it for now }
  11288. end;
  11289. A_CMOVcc:
  11290. begin
  11291. if taicpu(hp2).condition = inverted_condition then
  11292. begin
  11293. { We found what we're looking for }
  11294. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11295. begin
  11296. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11297. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11298. begin
  11299. pCMOV := hp2;
  11300. Break;
  11301. end
  11302. else
  11303. { Unsafe reference - drop out }
  11304. Exit;
  11305. end;
  11306. end
  11307. else if taicpu(hp2).condition <> condition then
  11308. { Something weird - drop out }
  11309. Exit;
  11310. end;
  11311. else
  11312. { Invalid }
  11313. Exit;
  11314. end;
  11315. end;
  11316. if not Assigned(pCMOV) then
  11317. { No complementary CMOV found }
  11318. Exit;
  11319. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11320. begin
  11321. { Don't need to do anything special or search for a matching MOV }
  11322. Asml.Remove(pCMOV);
  11323. if RegInInstruction(TargetReg, pCond) then
  11324. { Make sure we don't overwrite the register if it's being used in the condition }
  11325. Asml.InsertAfter(pCMOV, pCond)
  11326. else
  11327. Asml.InsertBefore(pCMOV, pCond);
  11328. taicpu(pCMOV).opcode := A_MOV;
  11329. taicpu(pCMOV).condition := C_None;
  11330. { Don't need to worry about allocating new registers in these cases }
  11331. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11332. Result := True;
  11333. Exit;
  11334. end
  11335. else
  11336. begin
  11337. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11338. FoundMOV := False;
  11339. { Search for the MOV that sets the target register }
  11340. hp2 := pFirstMov;
  11341. repeat
  11342. if (taicpu(hp2).opcode = A_MOV) and
  11343. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11344. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11345. begin
  11346. { Change the destination }
  11347. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11348. if not FoundMOV then
  11349. begin
  11350. FoundMOV := True;
  11351. { Make sure the register is allocated }
  11352. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11353. end;
  11354. hp1 := tai(hp2.Previous);
  11355. Asml.Remove(hp2);
  11356. if RegInInstruction(TargetReg, pCond) then
  11357. { Make sure we don't overwrite the register if it's being used in the condition }
  11358. Asml.InsertAfter(hp2, pCond)
  11359. else
  11360. Asml.InsertBefore(hp2, pCond);
  11361. if (hp2 = pLastMov) then
  11362. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11363. Break;
  11364. hp2 := hp1;
  11365. end;
  11366. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11367. if FoundMOV then
  11368. { Delete the CMOV }
  11369. RemoveInstruction(pCMOV)
  11370. else
  11371. begin
  11372. { If no MOV was found, we have to actually move and transmute the CMOV }
  11373. Asml.Remove(pCMOV);
  11374. if RegInInstruction(TargetReg, pCond) then
  11375. { Make sure we don't overwrite the register if it's being used in the condition }
  11376. Asml.InsertAfter(pCMOV, pCond)
  11377. else
  11378. Asml.InsertBefore(pCMOV, pCond);
  11379. taicpu(pCMOV).opcode := A_MOV;
  11380. taicpu(pCMOV).condition := C_None;
  11381. end;
  11382. Result := True;
  11383. Exit;
  11384. end;
  11385. end;
  11386. end;
  11387. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11388. var
  11389. hp1, hp2, pCond: tai;
  11390. begin
  11391. Result := False;
  11392. { Search ahead for CMOV instructions }
  11393. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11394. begin
  11395. hp1 := p;
  11396. hp2 := p;
  11397. pCond := nil; { To prevent compiler warnings }
  11398. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11399. DEFAULTFLAGS }
  11400. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11401. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11402. pCond := p;
  11403. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11404. begin
  11405. if (hp1.typ <> ait_instruction) then
  11406. { Break out on markers and labels etc. }
  11407. Break;
  11408. case taicpu(hp1).opcode of
  11409. A_MOV:
  11410. { Ignore regular MOVs unless they are obviously not related
  11411. to a CMOV block }
  11412. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11413. Break;
  11414. A_CMOVcc:
  11415. if TryCmpCMovOpts(pCond, hp1) then
  11416. begin
  11417. hp1 := hp2;
  11418. { p itself isn't changed, and we're still inside a
  11419. while loop to catch subsequent CMOVs, so just flag
  11420. a new iteration }
  11421. Include(OptsToCheck, aoc_ForceNewIteration);
  11422. Continue;
  11423. end;
  11424. else
  11425. { Drop out if we find anything else }
  11426. Break;
  11427. end;
  11428. hp2 := hp1;
  11429. end;
  11430. end;
  11431. end;
  11432. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11433. var
  11434. hp1, hp2, pCond: tai;
  11435. SourceReg, TargetReg: TRegister;
  11436. begin
  11437. Result := False;
  11438. { In some situations, we end up with an inefficient arrangement of
  11439. instructions in the form of:
  11440. or %reg1,%reg2
  11441. (%reg1 deallocated)
  11442. test %reg2,%reg2
  11443. mov x,%reg2
  11444. we may be able to swap and rearrange the registers to produce:
  11445. or %reg2,%reg1
  11446. mov x,%reg2
  11447. test %reg1,%reg1
  11448. (%reg1 deallocated)
  11449. }
  11450. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11451. (taicpu(p).oper[1]^.typ = top_reg) and
  11452. (
  11453. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11454. MatchOperand(taicpu(p).oper[0]^, -1)
  11455. ) and
  11456. GetNextInstruction(p, hp1) and
  11457. MatchInstruction(hp1, A_MOV, []) and
  11458. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11459. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11460. begin
  11461. TargetReg := taicpu(p).oper[1]^.reg;
  11462. { Now look backwards to find a simple commutative operation: ADD,
  11463. IMUL (2-register version), OR, AND or XOR - whose destination
  11464. register is the same as TEST }
  11465. hp2 := p;
  11466. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11467. if RegInInstruction(TargetReg, hp2) then
  11468. begin
  11469. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11470. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11471. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11472. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11473. begin
  11474. SourceReg := taicpu(hp2).oper[0]^.reg;
  11475. if
  11476. { Make sure the MOV doesn't use the other register }
  11477. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11478. { And make sure the source register is not used afterwards }
  11479. not RegInUsedRegs(SourceReg, UsedRegs) then
  11480. begin
  11481. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11482. taicpu(hp2).oper[0]^.reg := TargetReg;
  11483. taicpu(hp2).oper[1]^.reg := SourceReg;
  11484. if taicpu(p).oper[0]^.typ = top_reg then
  11485. taicpu(p).oper[0]^.reg := SourceReg;
  11486. taicpu(p).oper[1]^.reg := SourceReg;
  11487. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11488. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11489. Include(OptsToCheck, aoc_ForceNewIteration);
  11490. { We can still check the following optimisations since
  11491. the instruction is still a TEST }
  11492. end;
  11493. end;
  11494. Break;
  11495. end;
  11496. end;
  11497. { Search ahead3 for CMOV instructions }
  11498. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11499. begin
  11500. hp1 := p;
  11501. hp2 := p;
  11502. pCond := nil; { To prevent compiler warnings }
  11503. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11504. DEFAULTFLAGS }
  11505. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11506. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11507. pCond := p;
  11508. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11509. begin
  11510. if (hp1.typ <> ait_instruction) then
  11511. { Break out on markers and labels etc. }
  11512. Break;
  11513. case taicpu(hp1).opcode of
  11514. A_MOV:
  11515. { Ignore regular MOVs unless they are obviously not related
  11516. to a CMOV block }
  11517. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11518. Break;
  11519. A_CMOVcc:
  11520. if TryCmpCMovOpts(pCond, hp1) then
  11521. begin
  11522. hp1 := hp2;
  11523. { p itself isn't changed, and we're still inside a
  11524. while loop to catch subsequent CMOVs, so just flag
  11525. a new iteration }
  11526. Include(OptsToCheck, aoc_ForceNewIteration);
  11527. Continue;
  11528. end;
  11529. else
  11530. { Drop out if we find anything else }
  11531. Break;
  11532. end;
  11533. hp2 := hp1;
  11534. end;
  11535. end;
  11536. end;
  11537. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11538. var
  11539. hp1: tai;
  11540. Count: Integer;
  11541. OrigLabel: TAsmLabel;
  11542. begin
  11543. result := False;
  11544. { Sometimes, the optimisations below can permit this }
  11545. RemoveDeadCodeAfterJump(p);
  11546. 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
  11547. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11548. begin
  11549. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11550. { Also a side-effect of optimisations }
  11551. if CollapseZeroDistJump(p, OrigLabel) then
  11552. begin
  11553. Result := True;
  11554. Exit;
  11555. end;
  11556. hp1 := GetLabelWithSym(OrigLabel);
  11557. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11558. begin
  11559. if taicpu(hp1).opcode = A_RET then
  11560. begin
  11561. {
  11562. change
  11563. jmp .L1
  11564. ...
  11565. .L1:
  11566. ret
  11567. into
  11568. ret
  11569. }
  11570. begin
  11571. ConvertJumpToRET(p, hp1);
  11572. result:=true;
  11573. end;
  11574. end
  11575. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11576. not (cs_opt_size in current_settings.optimizerswitches) and
  11577. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11578. begin
  11579. Result := True;
  11580. Exit;
  11581. end;
  11582. end;
  11583. end;
  11584. end;
  11585. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11586. begin
  11587. Result := assigned(p) and
  11588. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11589. (taicpu(p).oper[1]^.typ = top_reg) and
  11590. (
  11591. (taicpu(p).oper[0]^.typ = top_reg) or
  11592. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11593. it is not expected that this can cause a seg. violation }
  11594. (
  11595. (taicpu(p).oper[0]^.typ = top_ref) and
  11596. { TODO: Can we detect which references become constants at this
  11597. stage so we don't have to do a blanket ban? }
  11598. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11599. (
  11600. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11601. (
  11602. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11603. not RefModified and
  11604. { If the reference also appears in the condition, then we know it's safe, otherwise
  11605. any kind of access violation would have occurred already }
  11606. Assigned(cond_p) and
  11607. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11608. (cond_p.typ = ait_instruction) and
  11609. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11610. { Just consider 2-operand comparison instructions for now to be safe }
  11611. (taicpu(cond_p).ops = 2) and
  11612. (
  11613. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11614. (
  11615. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11616. { Don't risk identical registers but different offsets, as we may have constructs
  11617. such as buffer streams with things like length fields that indicate whether
  11618. any more data follows. And there are probably some contrived examples where
  11619. writing to offsets behind the one being read also lead to access violations }
  11620. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11621. (
  11622. { Check that we're not modifying a register that appears in the reference }
  11623. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11624. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11625. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11626. )
  11627. )
  11628. )
  11629. )
  11630. )
  11631. )
  11632. );
  11633. end;
  11634. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11635. begin
  11636. { Update integer registers, ignoring deallocations }
  11637. repeat
  11638. while assigned(p) and
  11639. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11640. (p.typ = ait_label) or
  11641. ((p.typ = ait_marker) and
  11642. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11643. p := tai(p.next);
  11644. while assigned(p) and
  11645. (p.typ=ait_RegAlloc) Do
  11646. begin
  11647. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11648. begin
  11649. case tai_regalloc(p).ratype of
  11650. ra_alloc :
  11651. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11652. else
  11653. ;
  11654. end;
  11655. end;
  11656. p := tai(p.next);
  11657. end;
  11658. until not(assigned(p)) or
  11659. (not(p.typ in SkipInstr) and
  11660. not((p.typ = ait_label) and
  11661. labelCanBeSkipped(tai_label(p))));
  11662. end;
  11663. {$ifndef 8086}
  11664. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11665. begin
  11666. Result := False;
  11667. EndJump := nil;
  11668. BlockStop := nil;
  11669. while (BlockStart <> fOptimizer.BlockEnd) and
  11670. { stop on labels }
  11671. (BlockStart.typ <> ait_label) do
  11672. begin
  11673. { Keep track of all integer registers that are used }
  11674. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11675. if BlockStart.typ = ait_instruction then
  11676. begin
  11677. if (taicpu(BlockStart).opcode = A_JMP) then
  11678. begin
  11679. if not IsJumpToLabel(taicpu(BlockStart)) or
  11680. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11681. Exit;
  11682. EndJump := BlockStart;
  11683. Break;
  11684. end
  11685. { Check to see if we have a valid MOV instruction instead }
  11686. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11687. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11688. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11689. begin
  11690. Exit;
  11691. end
  11692. else
  11693. { This will be a valid MOV }
  11694. fAllocationRange := BlockStart;
  11695. end;
  11696. OneBeforeBlock := BlockStart;
  11697. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11698. end;
  11699. if (BlockStart = fOptimizer.BlockEnd) then
  11700. Exit;
  11701. BlockStop := BlockStart;
  11702. Result := True;
  11703. end;
  11704. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11705. var
  11706. hp1: tai;
  11707. RefModified: Boolean;
  11708. begin
  11709. Result := 0;
  11710. hp1 := BlockStart;
  11711. RefModified := False; { As long as the condition is inverted, this can be reset }
  11712. while assigned(hp1) and
  11713. (hp1 <> BlockStop) do
  11714. begin
  11715. case hp1.typ of
  11716. ait_instruction:
  11717. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11718. begin
  11719. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11720. begin
  11721. Inc(Result);
  11722. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11723. Assigned(fCondition) and
  11724. { Will have 2 operands }
  11725. (
  11726. (
  11727. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11728. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11729. ) or
  11730. (
  11731. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11732. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11733. )
  11734. ) then
  11735. { It is no longer safe to use the reference in the condition.
  11736. this prevents problems such as:
  11737. mov (%reg),%reg
  11738. mov (%reg),...
  11739. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11740. (fixes #40165)
  11741. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11742. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11743. }
  11744. RefModified := True;
  11745. end
  11746. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11747. { CMOV with constants grows the code size }
  11748. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11749. begin
  11750. { Register was reserved by TryCMOVConst and
  11751. stored on ConstRegs }
  11752. end
  11753. else
  11754. begin
  11755. Result := -1;
  11756. Exit;
  11757. end;
  11758. end
  11759. else
  11760. begin
  11761. Result := -1;
  11762. Exit;
  11763. end;
  11764. else
  11765. { Most likely an align };
  11766. end;
  11767. fOptimizer.GetNextInstruction(hp1, hp1);
  11768. end;
  11769. end;
  11770. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11771. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11772. (this is done as a separate stage because the double types are extensions of the branching type,
  11773. but we can't discount the conditional jump until the last step) }
  11774. procedure EvaluateBranchingType;
  11775. begin
  11776. Inc(CMOVScore);
  11777. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11778. { Too many instructions to be worthwhile }
  11779. fState := tsInvalid;
  11780. end;
  11781. var
  11782. hp1: tai;
  11783. Count: Integer;
  11784. begin
  11785. { Table of valid CMOV block types
  11786. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11787. ---------- --------- --------- --------- --------- ---------
  11788. tsSimple X Yes X X X
  11789. tsDetour = 1st X X X X
  11790. tsBranching <> Mid Yes X X X
  11791. tsDouble End-label Yes * Yes X Yes
  11792. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11793. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11794. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11795. * Only one reference allowed
  11796. }
  11797. hp1 := nil; { To prevent compiler warnings }
  11798. Optimizer.CopyUsedRegs(RegisterTracking);
  11799. fOptimizer := Optimizer;
  11800. fLabel := AFirstLabel;
  11801. CMOVScore := 0;
  11802. ConstCount := 0;
  11803. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11804. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11805. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11806. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11807. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11808. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11809. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11810. fInsertionPoint := p_initialjump;
  11811. fCondition := nil;
  11812. fInitialJump := p_initialjump;
  11813. fFirstMovBlock := p_initialmov;
  11814. fFirstMovBlockStop := nil;
  11815. fSecondJump := nil;
  11816. fSecondMovBlock := nil;
  11817. fSecondMovBlockStop := nil;
  11818. fMidLabel := nil;
  11819. fSecondJump := nil;
  11820. fSecondMovBlock := nil;
  11821. fEndLabel := nil;
  11822. fAllocationRange := nil;
  11823. { Assume it all goes horribly wrong! }
  11824. fState := tsInvalid;
  11825. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11826. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11827. 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
  11828. begin
  11829. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11830. for Count := 0 to 1 do
  11831. with taicpu(fCondition).oper[Count]^ do
  11832. case typ of
  11833. top_reg:
  11834. if getregtype(reg) = R_INTREGISTER then
  11835. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11836. top_ref:
  11837. begin
  11838. if
  11839. {$ifdef x86_64}
  11840. (ref^.base <> NR_RIP) and
  11841. {$endif x86_64}
  11842. (ref^.base <> NR_NO) then
  11843. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11844. if (ref^.index <> NR_NO) then
  11845. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11846. end
  11847. else
  11848. ;
  11849. end;
  11850. { When inserting instructions before hp_prev, try to insert them
  11851. before the allocation of the FLAGS register }
  11852. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11853. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11854. { If not found, set it equal to the condition so it's something sensible }
  11855. fInsertionPoint := fCondition;
  11856. { When dealing with a comparison against zero, take note of the
  11857. instruction before it to see if we can move instructions further
  11858. back in order to benefit PostPeepholeOptTestOr.
  11859. }
  11860. if (
  11861. (
  11862. (taicpu(fCondition).opcode = A_CMP) and
  11863. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11864. ) or
  11865. (
  11866. (taicpu(fCondition).opcode = A_TEST) and
  11867. (
  11868. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11869. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11870. )
  11871. )
  11872. ) and
  11873. Optimizer.GetLastInstruction(fCondition, hp1) then
  11874. begin
  11875. { These instructions set the zero flag if the result is zero }
  11876. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11877. begin
  11878. fInsertionPoint := hp1;
  11879. { Also mark all the registers in this previous instruction
  11880. as 'in use', even if they've just been deallocated }
  11881. for Count := 0 to 1 do
  11882. with taicpu(hp1).oper[Count]^ do
  11883. case typ of
  11884. top_reg:
  11885. if getregtype(reg) = R_INTREGISTER then
  11886. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11887. top_ref:
  11888. begin
  11889. if
  11890. {$ifdef x86_64}
  11891. (ref^.base <> NR_RIP) and
  11892. {$endif x86_64}
  11893. (ref^.base <> NR_NO) then
  11894. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11895. if (ref^.index <> NR_NO) then
  11896. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11897. end
  11898. else
  11899. ;
  11900. end;
  11901. end;
  11902. end;
  11903. end
  11904. else
  11905. fCondition := nil;
  11906. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11907. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11908. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11909. { If not found, set it equal to p so it's something sensible }
  11910. fInsertionPoint := hp1;
  11911. hp1 := p_initialmov;
  11912. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11913. Exit;
  11914. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11915. if (hp1.typ <> ait_label) then { should be on a jump }
  11916. begin
  11917. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11918. { Need a label afterwards }
  11919. Exit;
  11920. end
  11921. else
  11922. fMidLabel := hp1;
  11923. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11924. { Not the correct label }
  11925. fMidLabel := nil;
  11926. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11927. { If there's neither a 2nd jump nor correct label, then it's invalid
  11928. (see above table) }
  11929. Exit;
  11930. { Analyse the first block of MOVs more closely }
  11931. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11932. if Assigned(fSecondJump) then
  11933. begin
  11934. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11935. begin
  11936. fState := tsDetour
  11937. end
  11938. else
  11939. begin
  11940. { Need the correct mid-label for this one }
  11941. if not Assigned(fMidLabel) then
  11942. Exit;
  11943. fState := tsBranching;
  11944. end;
  11945. end
  11946. else
  11947. { No jump. but mid-label is present }
  11948. fState := tsSimple;
  11949. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11950. begin
  11951. { Invalid or too many instructions to be worthwhile }
  11952. fState := tsInvalid;
  11953. Exit;
  11954. end;
  11955. { check further for
  11956. jCC xxx
  11957. <several movs 1>
  11958. jmp yyy
  11959. xxx:
  11960. <several movs 2>
  11961. yyy:
  11962. etc.
  11963. }
  11964. if (fState = tsBranching) and
  11965. { Estimate for required savings for extra jump }
  11966. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11967. { Only one reference is allowed for double blocks }
  11968. (AFirstLabel.getrefs = 1) then
  11969. begin
  11970. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11971. fSecondMovBlock := hp1;
  11972. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11973. begin
  11974. EvaluateBranchingType;
  11975. Exit;
  11976. end;
  11977. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11978. if (hp1.typ <> ait_label) then { should be on a jump }
  11979. begin
  11980. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11981. begin
  11982. { Need a label afterwards }
  11983. EvaluateBranchingType;
  11984. Exit;
  11985. end;
  11986. end
  11987. else
  11988. fEndLabel := hp1;
  11989. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11990. { Second jump doesn't go to the end }
  11991. fEndLabel := nil;
  11992. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11993. begin
  11994. { If there's neither a 3rd jump nor correct end label, then it's
  11995. not a invalid double block, but is a valid single branching
  11996. block (see above table) }
  11997. EvaluateBranchingType;
  11998. Exit;
  11999. end;
  12000. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12001. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12002. { Invalid or too many instructions to be worthwhile }
  12003. Exit;
  12004. Inc(CMOVScore, Count);
  12005. if Assigned(fThirdJump) then
  12006. begin
  12007. if not Assigned(fSecondJump) then
  12008. fState := tsDoubleSecondBranching
  12009. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12010. fState := tsDoubleBranchSame
  12011. else
  12012. fState := tsDoubleBranchDifferent;
  12013. end
  12014. else
  12015. fState := tsDouble;
  12016. end;
  12017. if fState = tsBranching then
  12018. EvaluateBranchingType;
  12019. end;
  12020. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12021. new register to store the constant }
  12022. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12023. var
  12024. RegSize: TSubRegister;
  12025. CurrentVal: TCGInt;
  12026. ANewReg: TRegister;
  12027. X: ShortInt;
  12028. begin
  12029. Result := False;
  12030. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12031. Exit;
  12032. if ConstCount >= MAX_CMOV_REGISTERS then
  12033. { Arrays are full }
  12034. Exit;
  12035. { Remember that CMOV can't encode 8-bit registers }
  12036. case taicpu(p).opsize of
  12037. S_W:
  12038. RegSize := R_SUBW;
  12039. S_L:
  12040. RegSize := R_SUBD;
  12041. {$ifdef x86_64}
  12042. S_Q:
  12043. RegSize := R_SUBQ;
  12044. {$endif x86_64}
  12045. else
  12046. InternalError(2021100401);
  12047. end;
  12048. { See if the value has already been reserved for another CMOV instruction }
  12049. CurrentVal := taicpu(p).oper[0]^.val;
  12050. for X := 0 to ConstCount - 1 do
  12051. if ConstVals[X] = CurrentVal then
  12052. begin
  12053. ConstRegs[ConstCount] := ConstRegs[X];
  12054. ConstSizes[ConstCount] := RegSize;
  12055. ConstVals[ConstCount] := CurrentVal;
  12056. Inc(ConstCount);
  12057. Inc(Count);
  12058. Result := True;
  12059. Exit;
  12060. end;
  12061. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12062. if ANewReg = NR_NO then
  12063. { No free registers }
  12064. Exit;
  12065. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12066. up vying for the same register }
  12067. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12068. ConstRegs[ConstCount] := ANewReg;
  12069. ConstSizes[ConstCount] := RegSize;
  12070. ConstVals[ConstCount] := CurrentVal;
  12071. Inc(ConstCount);
  12072. Inc(Count);
  12073. Result := True;
  12074. end;
  12075. destructor TCMOVTracking.Done;
  12076. begin
  12077. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12078. end;
  12079. procedure TCMOVTracking.Process(out new_p: tai);
  12080. var
  12081. Count, Writes: LongInt;
  12082. RegMatch: Boolean;
  12083. hp1, hp_new: tai;
  12084. inverted_condition, condition: TAsmCond;
  12085. begin
  12086. if (fState in [tsInvalid, tsProcessed]) then
  12087. InternalError(2023110701);
  12088. { Repurpose RegisterTracking to mark registers that we've defined }
  12089. RegisterTracking[R_INTREGISTER].Clear;
  12090. Count := 0;
  12091. Writes := 0;
  12092. condition := taicpu(fInitialJump).condition;
  12093. inverted_condition := inverse_cond(condition);
  12094. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12095. doesn't get CMOVs in this case }
  12096. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12097. begin
  12098. { Include the jump in the flag tracking }
  12099. if Assigned(fThirdJump) then
  12100. begin
  12101. if (fState = tsDoubleBranchSame) then
  12102. begin
  12103. { Will be an unconditional jump, so track to the instruction before it }
  12104. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12105. InternalError(2023110710);
  12106. end
  12107. else
  12108. hp1 := fThirdJump;
  12109. end
  12110. else
  12111. hp1 := fSecondMovBlockStop;
  12112. end
  12113. else
  12114. begin
  12115. { Include a conditional jump in the flag tracking }
  12116. if Assigned(fSecondJump) then
  12117. begin
  12118. if (fState = tsDetour) then
  12119. begin
  12120. { Will be an unconditional jump, so track to the instruction before it }
  12121. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12122. InternalError(2023110711);
  12123. end
  12124. else
  12125. hp1 := fSecondJump;
  12126. end
  12127. else
  12128. hp1 := fFirstMovBlockStop;
  12129. end;
  12130. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12131. { Process the second set of MOVs first, because if a destination
  12132. register is shared between the first and second MOV sets, it is more
  12133. efficient to turn the first one into a MOV instruction and place it
  12134. before the CMP if possible, but we won't know which registers are
  12135. shared until we've processed at least one list, so we might as well
  12136. make it the second one since that won't be modified again. }
  12137. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12138. begin
  12139. hp1 := fSecondMovBlock;
  12140. repeat
  12141. if not Assigned(hp1) then
  12142. InternalError(2018062902);
  12143. if (hp1.typ = ait_instruction) then
  12144. begin
  12145. { Extra safeguard }
  12146. if (taicpu(hp1).opcode <> A_MOV) then
  12147. InternalError(2018062903);
  12148. { Note: tsDoubleBranchDifferent is essentially identical to
  12149. tsBranching and the 2nd block is best left largely
  12150. untouched, but we need to evaluate which registers the MOVs
  12151. write to in order to track what would be complementary CMOV
  12152. pairs that can be further optimised. [Kit] }
  12153. if fState <> tsDoubleBranchDifferent then
  12154. begin
  12155. if taicpu(hp1).oper[0]^.typ = top_const then
  12156. begin
  12157. RegMatch := False;
  12158. for Count := 0 to ConstCount - 1 do
  12159. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12160. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12161. begin
  12162. RegMatch := True;
  12163. { If it's in RegisterTracking, then this register
  12164. is being used more than once and hence has
  12165. already had its value defined (it gets added to
  12166. UsedRegs through AllocRegBetween below) }
  12167. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12168. begin
  12169. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12170. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12171. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12172. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12173. ConstMovs[Count] := hp_new;
  12174. end
  12175. else
  12176. { We just need an instruction between hp_prev and hp1
  12177. where we know the register is marked as in use }
  12178. hp_new := fSecondMovBlock;
  12179. { Keep track of largest write for this register so it can be optimised later }
  12180. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12181. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12182. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12183. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12184. Break;
  12185. end;
  12186. if not RegMatch then
  12187. InternalError(2021100411);
  12188. end;
  12189. taicpu(hp1).opcode := A_CMOVcc;
  12190. taicpu(hp1).condition := condition;
  12191. end;
  12192. { Store these writes to search for duplicates later on }
  12193. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12194. Inc(Writes);
  12195. end;
  12196. fOptimizer.GetNextInstruction(hp1, hp1);
  12197. until (hp1 = fSecondMovBlockStop);
  12198. end;
  12199. { Now do the first set of MOVs }
  12200. hp1 := fFirstMovBlock;
  12201. repeat
  12202. if not Assigned(hp1) then
  12203. InternalError(2018062904);
  12204. if (hp1.typ = ait_instruction) then
  12205. begin
  12206. RegMatch := False;
  12207. { Extra safeguard }
  12208. if (taicpu(hp1).opcode <> A_MOV) then
  12209. InternalError(2018062905);
  12210. { Search through the RegWrites list to see if there are any
  12211. opposing CMOV pairs that write to the same register }
  12212. for Count := 0 to Writes - 1 do
  12213. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12214. begin
  12215. { We have a match. Keep this as a MOV }
  12216. { Move ahead in preparation }
  12217. fOptimizer.GetNextInstruction(hp1, hp1);
  12218. RegMatch := True;
  12219. Break;
  12220. end;
  12221. if RegMatch then
  12222. Continue;
  12223. if taicpu(hp1).oper[0]^.typ = top_const then
  12224. begin
  12225. for Count := 0 to ConstCount - 1 do
  12226. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12227. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12228. begin
  12229. RegMatch := True;
  12230. { If it's in RegisterTracking, then this register is
  12231. being used more than once and hence has already had
  12232. its value defined (it gets added to UsedRegs through
  12233. AllocRegBetween below) }
  12234. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12235. begin
  12236. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12237. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12238. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12239. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12240. ConstMovs[Count] := hp_new;
  12241. end
  12242. else
  12243. { We just need an instruction between hp_prev and hp1
  12244. where we know the register is marked as in use }
  12245. hp_new := fFirstMovBlock;
  12246. { Keep track of largest write for this register so it can be optimised later }
  12247. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12248. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12249. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12250. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12251. Break;
  12252. end;
  12253. if not RegMatch then
  12254. InternalError(2021100412);
  12255. end;
  12256. taicpu(hp1).opcode := A_CMOVcc;
  12257. taicpu(hp1).condition := inverted_condition;
  12258. if (fState = tsDoubleBranchDifferent) then
  12259. begin
  12260. { Store these writes to search for duplicates later on }
  12261. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12262. Inc(Writes);
  12263. end;
  12264. end;
  12265. fOptimizer.GetNextInstruction(hp1, hp1);
  12266. until (hp1 = fFirstMovBlockStop);
  12267. { Update initialisation MOVs to the smallest possible size }
  12268. for Count := 0 to ConstCount - 1 do
  12269. if Assigned(ConstMovs[Count]) then
  12270. begin
  12271. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12272. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12273. end;
  12274. case fState of
  12275. tsSimple:
  12276. begin
  12277. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12278. { No branch to delete }
  12279. end;
  12280. tsDetour:
  12281. begin
  12282. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12283. { Preserve jump }
  12284. end;
  12285. tsBranching, tsDoubleBranchDifferent:
  12286. begin
  12287. if (fState = tsBranching) then
  12288. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12289. else
  12290. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12291. taicpu(fSecondJump).opcode := A_JCC;
  12292. taicpu(fSecondJump).condition := inverted_condition;
  12293. end;
  12294. tsDouble, tsDoubleBranchSame:
  12295. begin
  12296. if (fState = tsDouble) then
  12297. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12298. else
  12299. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12300. { Delete second jump }
  12301. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12302. fOptimizer.RemoveInstruction(fSecondJump);
  12303. end;
  12304. tsDoubleSecondBranching:
  12305. begin
  12306. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12307. { Delete second jump, preserve third jump as conditional }
  12308. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12309. fOptimizer.RemoveInstruction(fSecondJump);
  12310. taicpu(fThirdJump).opcode := A_JCC;
  12311. taicpu(fThirdJump).condition := condition;
  12312. end;
  12313. else
  12314. InternalError(2023110720);
  12315. end;
  12316. { Now we can safely decrement the reference count }
  12317. tasmlabel(fLabel).decrefs;
  12318. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12319. { Remove the original jump }
  12320. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12321. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12322. fState := tsProcessed;
  12323. end;
  12324. {$endif 8086}
  12325. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12326. var
  12327. hp1,hp2: tai;
  12328. carryadd_opcode : TAsmOp;
  12329. symbol: TAsmSymbol;
  12330. increg, tmpreg: TRegister;
  12331. {$ifndef i8086}
  12332. CMOVTracking: PCMOVTracking;
  12333. hp3,hp4,hp5: tai;
  12334. {$endif i8086}
  12335. TempBool: Boolean;
  12336. begin
  12337. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12338. DoJumpOptimizations(p, TempBool) then
  12339. Exit(True);
  12340. result:=false;
  12341. if GetNextInstruction(p,hp1) then
  12342. begin
  12343. if (hp1.typ=ait_label) then
  12344. begin
  12345. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12346. Exit;
  12347. end
  12348. else if (hp1.typ<>ait_instruction) then
  12349. Exit;
  12350. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12351. if (
  12352. (
  12353. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12354. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12355. (Taicpu(hp1).oper[0]^.val=1)
  12356. ) or
  12357. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12358. ) and
  12359. GetNextInstruction(hp1,hp2) and
  12360. (hp2.typ = ait_label) and
  12361. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12362. { jb @@1 cmc
  12363. inc/dec operand --> adc/sbb operand,0
  12364. @@1:
  12365. ... and ...
  12366. jnb @@1
  12367. inc/dec operand --> adc/sbb operand,0
  12368. @@1: }
  12369. begin
  12370. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12371. begin
  12372. case taicpu(hp1).opcode of
  12373. A_INC,
  12374. A_ADD:
  12375. carryadd_opcode:=A_ADC;
  12376. A_DEC,
  12377. A_SUB:
  12378. carryadd_opcode:=A_SBB;
  12379. else
  12380. InternalError(2021011001);
  12381. end;
  12382. Taicpu(p).clearop(0);
  12383. Taicpu(p).ops:=0;
  12384. Taicpu(p).is_jmp:=false;
  12385. Taicpu(p).opcode:=A_CMC;
  12386. Taicpu(p).condition:=C_NONE;
  12387. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12388. Taicpu(hp1).ops:=2;
  12389. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12390. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12391. else
  12392. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12393. Taicpu(hp1).loadconst(0,0);
  12394. Taicpu(hp1).opcode:=carryadd_opcode;
  12395. result:=true;
  12396. exit;
  12397. end
  12398. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12399. begin
  12400. case taicpu(hp1).opcode of
  12401. A_INC,
  12402. A_ADD:
  12403. carryadd_opcode:=A_ADC;
  12404. A_DEC,
  12405. A_SUB:
  12406. carryadd_opcode:=A_SBB;
  12407. else
  12408. InternalError(2021011002);
  12409. end;
  12410. Taicpu(hp1).ops:=2;
  12411. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12412. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12413. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12414. else
  12415. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12416. Taicpu(hp1).loadconst(0,0);
  12417. Taicpu(hp1).opcode:=carryadd_opcode;
  12418. RemoveCurrentP(p, hp1);
  12419. result:=true;
  12420. exit;
  12421. end
  12422. {
  12423. jcc @@1 setcc tmpreg
  12424. inc/dec/add/sub operand -> (movzx tmpreg)
  12425. @@1: add/sub tmpreg,operand
  12426. While this increases code size slightly, it makes the code much faster if the
  12427. jump is unpredictable
  12428. }
  12429. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12430. begin
  12431. { search for an available register which is volatile }
  12432. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12433. if increg <> NR_NO then
  12434. begin
  12435. { We don't need to check if tmpreg is in hp1 or not, because
  12436. it will be marked as in use at p (if not, this is
  12437. indictive of a compiler bug). }
  12438. TAsmLabel(symbol).decrefs;
  12439. Taicpu(p).clearop(0);
  12440. Taicpu(p).ops:=1;
  12441. Taicpu(p).is_jmp:=false;
  12442. Taicpu(p).opcode:=A_SETcc;
  12443. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12444. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12445. Taicpu(p).loadreg(0,increg);
  12446. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12447. begin
  12448. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12449. R_SUBW:
  12450. begin
  12451. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12452. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12453. end;
  12454. R_SUBD:
  12455. begin
  12456. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12457. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12458. end;
  12459. {$ifdef x86_64}
  12460. R_SUBQ:
  12461. begin
  12462. { MOVZX doesn't have a 64-bit variant, because
  12463. the 32-bit version implicitly zeroes the
  12464. upper 32-bits of the destination register }
  12465. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12466. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12467. setsubreg(tmpreg, R_SUBQ);
  12468. end;
  12469. {$endif x86_64}
  12470. else
  12471. Internalerror(2020030601);
  12472. end;
  12473. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12474. asml.InsertAfter(hp2,p);
  12475. end
  12476. else
  12477. tmpreg := increg;
  12478. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12479. begin
  12480. Taicpu(hp1).ops:=2;
  12481. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12482. end;
  12483. Taicpu(hp1).loadreg(0,tmpreg);
  12484. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12485. Result := True;
  12486. { p is no longer a Jcc instruction, so exit }
  12487. Exit;
  12488. end;
  12489. end;
  12490. end;
  12491. { Detect the following:
  12492. jmp<cond> @Lbl1
  12493. jmp @Lbl2
  12494. ...
  12495. @Lbl1:
  12496. ret
  12497. Change to:
  12498. jmp<inv_cond> @Lbl2
  12499. ret
  12500. }
  12501. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12502. begin
  12503. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12504. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12505. MatchInstruction(hp2,A_RET,[S_NO]) then
  12506. begin
  12507. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12508. { Change label address to that of the unconditional jump }
  12509. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12510. TAsmLabel(symbol).DecRefs;
  12511. taicpu(hp1).opcode := A_RET;
  12512. taicpu(hp1).is_jmp := false;
  12513. taicpu(hp1).ops := taicpu(hp2).ops;
  12514. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12515. case taicpu(hp2).ops of
  12516. 0:
  12517. taicpu(hp1).clearop(0);
  12518. 1:
  12519. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12520. else
  12521. internalerror(2016041302);
  12522. end;
  12523. end;
  12524. {$ifndef i8086}
  12525. end
  12526. {
  12527. convert
  12528. j<c> .L1
  12529. mov 1,reg
  12530. jmp .L2
  12531. .L1
  12532. mov 0,reg
  12533. .L2
  12534. into
  12535. mov 0,reg
  12536. set<not(c)> reg
  12537. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12538. would destroy the flag contents
  12539. }
  12540. else if MatchInstruction(hp1,A_MOV,[]) and
  12541. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12542. {$ifdef i386}
  12543. (
  12544. { Under i386, ESI, EDI, EBP and ESP
  12545. don't have an 8-bit representation }
  12546. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12547. ) and
  12548. {$endif i386}
  12549. (taicpu(hp1).oper[0]^.val=1) and
  12550. GetNextInstruction(hp1,hp2) and
  12551. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12552. GetNextInstruction(hp2,hp3) and
  12553. (hp3.typ=ait_label) and
  12554. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12555. (tai_label(hp3).labsym.getrefs=1) and
  12556. GetNextInstruction(hp3,hp4) and
  12557. MatchInstruction(hp4,A_MOV,[]) and
  12558. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12559. (taicpu(hp4).oper[0]^.val=0) and
  12560. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12561. GetNextInstruction(hp4,hp5) and
  12562. (hp5.typ=ait_label) and
  12563. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12564. (tai_label(hp5).labsym.getrefs=1) then
  12565. begin
  12566. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12567. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12568. { remove last label }
  12569. RemoveInstruction(hp5);
  12570. { remove second label }
  12571. RemoveInstruction(hp3);
  12572. { remove jmp }
  12573. RemoveInstruction(hp2);
  12574. if taicpu(hp1).opsize=S_B then
  12575. RemoveInstruction(hp1)
  12576. else
  12577. taicpu(hp1).loadconst(0,0);
  12578. taicpu(hp4).opcode:=A_SETcc;
  12579. taicpu(hp4).opsize:=S_B;
  12580. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12581. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12582. taicpu(hp4).opercnt:=1;
  12583. taicpu(hp4).ops:=1;
  12584. taicpu(hp4).freeop(1);
  12585. RemoveCurrentP(p);
  12586. Result:=true;
  12587. exit;
  12588. end
  12589. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12590. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12591. begin
  12592. { check for
  12593. jCC xxx
  12594. <several movs>
  12595. xxx:
  12596. Also spot:
  12597. Jcc xxx
  12598. <several movs>
  12599. jmp xxx
  12600. Change to:
  12601. <several cmovs with inverted condition>
  12602. jmp xxx (only for the 2nd case)
  12603. }
  12604. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12605. if CMOVTracking^.State <> tsInvalid then
  12606. begin
  12607. CMovTracking^.Process(p);
  12608. Result := True;
  12609. end;
  12610. CMOVTracking^.Done;
  12611. {$endif i8086}
  12612. end;
  12613. end;
  12614. end;
  12615. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12616. var
  12617. hp1,hp2,hp3: tai;
  12618. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12619. NewSize: TOpSize;
  12620. NewRegSize: TSubRegister;
  12621. Limit: TCgInt;
  12622. SwapOper: POper;
  12623. begin
  12624. result:=false;
  12625. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12626. GetNextInstruction(p,hp1) and
  12627. (hp1.typ = ait_instruction);
  12628. if reg_and_hp1_is_instr and
  12629. (
  12630. (taicpu(hp1).opcode <> A_LEA) or
  12631. { If the LEA instruction can be converted into an arithmetic instruction,
  12632. it may be possible to then fold it. }
  12633. (
  12634. { If the flags register is in use, don't change the instruction
  12635. to an ADD otherwise this will scramble the flags. [Kit] }
  12636. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12637. ConvertLEA(taicpu(hp1))
  12638. )
  12639. ) and
  12640. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12641. GetNextInstruction(hp1,hp2) and
  12642. MatchInstruction(hp2,A_MOV,[]) and
  12643. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12644. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12645. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12646. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12647. {$ifdef i386}
  12648. { not all registers have byte size sub registers on i386 }
  12649. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12650. {$endif i386}
  12651. (((taicpu(hp1).ops=2) and
  12652. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12653. ((taicpu(hp1).ops=1) and
  12654. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12655. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12656. begin
  12657. { change movsX/movzX reg/ref, reg2
  12658. add/sub/or/... reg3/$const, reg2
  12659. mov reg2 reg/ref
  12660. to add/sub/or/... reg3/$const, reg/ref }
  12661. { by example:
  12662. movswl %si,%eax movswl %si,%eax p
  12663. decl %eax addl %edx,%eax hp1
  12664. movw %ax,%si movw %ax,%si hp2
  12665. ->
  12666. movswl %si,%eax movswl %si,%eax p
  12667. decw %eax addw %edx,%eax hp1
  12668. movw %ax,%si movw %ax,%si hp2
  12669. }
  12670. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12671. {
  12672. ->
  12673. movswl %si,%eax movswl %si,%eax p
  12674. decw %si addw %dx,%si hp1
  12675. movw %ax,%si movw %ax,%si hp2
  12676. }
  12677. case taicpu(hp1).ops of
  12678. 1:
  12679. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12680. 2:
  12681. begin
  12682. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12683. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12684. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12685. end;
  12686. else
  12687. internalerror(2008042702);
  12688. end;
  12689. {
  12690. ->
  12691. decw %si addw %dx,%si p
  12692. }
  12693. DebugMsg(SPeepholeOptimization + 'var3',p);
  12694. RemoveCurrentP(p, hp1);
  12695. RemoveInstruction(hp2);
  12696. Result := True;
  12697. Exit;
  12698. end;
  12699. if reg_and_hp1_is_instr and
  12700. (taicpu(hp1).opcode = A_MOV) and
  12701. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12702. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12703. {$ifdef x86_64}
  12704. { check for implicit extension to 64 bit }
  12705. or
  12706. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12707. (taicpu(hp1).opsize=S_Q) and
  12708. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12709. )
  12710. {$endif x86_64}
  12711. )
  12712. then
  12713. begin
  12714. { change
  12715. movx %reg1,%reg2
  12716. mov %reg2,%reg3
  12717. dealloc %reg2
  12718. into
  12719. movx %reg,%reg3
  12720. }
  12721. TransferUsedRegs(TmpUsedRegs);
  12722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12723. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12724. begin
  12725. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12726. {$ifdef x86_64}
  12727. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12728. (taicpu(hp1).opsize=S_Q) then
  12729. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12730. else
  12731. {$endif x86_64}
  12732. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12733. RemoveInstruction(hp1);
  12734. Result := True;
  12735. Exit;
  12736. end;
  12737. end;
  12738. if reg_and_hp1_is_instr and
  12739. ((taicpu(hp1).opcode=A_MOV) or
  12740. (taicpu(hp1).opcode=A_ADD) or
  12741. (taicpu(hp1).opcode=A_SUB) or
  12742. (taicpu(hp1).opcode=A_CMP) or
  12743. (taicpu(hp1).opcode=A_OR) or
  12744. (taicpu(hp1).opcode=A_XOR) or
  12745. (taicpu(hp1).opcode=A_AND)
  12746. ) and
  12747. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12748. begin
  12749. AndTest := (taicpu(hp1).opcode=A_AND) and
  12750. GetNextInstruction(hp1, hp2) and
  12751. (hp2.typ = ait_instruction) and
  12752. (
  12753. (
  12754. (taicpu(hp2).opcode=A_TEST) and
  12755. (
  12756. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12757. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12758. (
  12759. { If the AND and TEST instructions share a constant, this is also valid }
  12760. (taicpu(hp1).oper[0]^.typ = top_const) and
  12761. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12762. )
  12763. ) and
  12764. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12765. ) or
  12766. (
  12767. (taicpu(hp2).opcode=A_CMP) and
  12768. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12769. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12770. )
  12771. );
  12772. { change
  12773. movx (oper),%reg2
  12774. and $x,%reg2
  12775. test %reg2,%reg2
  12776. dealloc %reg2
  12777. into
  12778. op %reg1,%reg3
  12779. if the second op accesses only the bits stored in reg1
  12780. }
  12781. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12782. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12783. (taicpu(hp1).oper[0]^.typ = top_const) and
  12784. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12785. AndTest then
  12786. begin
  12787. { Check if the AND constant is in range }
  12788. case taicpu(p).opsize of
  12789. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12790. begin
  12791. NewSize := S_B;
  12792. Limit := $FF;
  12793. end;
  12794. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12795. begin
  12796. NewSize := S_W;
  12797. Limit := $FFFF;
  12798. end;
  12799. {$ifdef x86_64}
  12800. S_LQ:
  12801. begin
  12802. NewSize := S_L;
  12803. Limit := $FFFFFFFF;
  12804. end;
  12805. {$endif x86_64}
  12806. else
  12807. InternalError(2021120303);
  12808. end;
  12809. if (
  12810. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12811. { Check for negative operands }
  12812. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12813. ) and
  12814. GetNextInstruction(hp2,hp3) and
  12815. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12816. (taicpu(hp3).condition in [C_E,C_NE]) then
  12817. begin
  12818. TransferUsedRegs(TmpUsedRegs);
  12819. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12820. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12821. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12822. begin
  12823. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12824. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12825. taicpu(hp1).opcode := A_TEST;
  12826. taicpu(hp1).opsize := NewSize;
  12827. RemoveInstruction(hp2);
  12828. RemoveCurrentP(p, hp1);
  12829. Result:=true;
  12830. exit;
  12831. end;
  12832. end;
  12833. end;
  12834. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12835. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12836. (taicpu(hp1).opsize=S_B)) or
  12837. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12838. (taicpu(hp1).opsize=S_W))
  12839. {$ifdef x86_64}
  12840. or ((taicpu(p).opsize=S_LQ) and
  12841. (taicpu(hp1).opsize=S_L))
  12842. {$endif x86_64}
  12843. ) and
  12844. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12845. begin
  12846. { change
  12847. movx %reg1,%reg2
  12848. op %reg2,%reg3
  12849. dealloc %reg2
  12850. into
  12851. op %reg1,%reg3
  12852. if the second op accesses only the bits stored in reg1
  12853. }
  12854. TransferUsedRegs(TmpUsedRegs);
  12855. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12856. if AndTest then
  12857. begin
  12858. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12859. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12860. end
  12861. else
  12862. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12863. if not RegUsed then
  12864. begin
  12865. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12866. if taicpu(p).oper[0]^.typ=top_reg then
  12867. begin
  12868. case taicpu(hp1).opsize of
  12869. S_B:
  12870. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12871. S_W:
  12872. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12873. S_L:
  12874. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12875. else
  12876. Internalerror(2020102301);
  12877. end;
  12878. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12879. end
  12880. else
  12881. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12882. RemoveCurrentP(p);
  12883. if AndTest then
  12884. RemoveInstruction(hp2);
  12885. result:=true;
  12886. exit;
  12887. end;
  12888. end
  12889. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12890. (
  12891. { Bitwise operations only }
  12892. (taicpu(hp1).opcode=A_AND) or
  12893. (taicpu(hp1).opcode=A_TEST) or
  12894. (
  12895. (taicpu(hp1).oper[0]^.typ = top_const) and
  12896. (
  12897. (taicpu(hp1).opcode=A_OR) or
  12898. (taicpu(hp1).opcode=A_XOR)
  12899. )
  12900. )
  12901. ) and
  12902. (
  12903. (taicpu(hp1).oper[0]^.typ = top_const) or
  12904. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12905. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12906. ) then
  12907. begin
  12908. { change
  12909. movx %reg2,%reg2
  12910. op const,%reg2
  12911. into
  12912. op const,%reg2 (smaller version)
  12913. movx %reg2,%reg2
  12914. also change
  12915. movx %reg1,%reg2
  12916. and/test (oper),%reg2
  12917. dealloc %reg2
  12918. into
  12919. and/test (oper),%reg1
  12920. }
  12921. case taicpu(p).opsize of
  12922. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12923. begin
  12924. NewSize := S_B;
  12925. NewRegSize := R_SUBL;
  12926. Limit := $FF;
  12927. end;
  12928. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12929. begin
  12930. NewSize := S_W;
  12931. NewRegSize := R_SUBW;
  12932. Limit := $FFFF;
  12933. end;
  12934. {$ifdef x86_64}
  12935. S_LQ:
  12936. begin
  12937. NewSize := S_L;
  12938. NewRegSize := R_SUBD;
  12939. Limit := $FFFFFFFF;
  12940. end;
  12941. {$endif x86_64}
  12942. else
  12943. Internalerror(2021120302);
  12944. end;
  12945. TransferUsedRegs(TmpUsedRegs);
  12946. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12947. if AndTest then
  12948. begin
  12949. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12950. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12951. end
  12952. else
  12953. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12954. if
  12955. (
  12956. (taicpu(p).opcode = A_MOVZX) and
  12957. (
  12958. (taicpu(hp1).opcode=A_AND) or
  12959. (taicpu(hp1).opcode=A_TEST)
  12960. ) and
  12961. not (
  12962. { If both are references, then the final instruction will have
  12963. both operands as references, which is not allowed }
  12964. (taicpu(p).oper[0]^.typ = top_ref) and
  12965. (taicpu(hp1).oper[0]^.typ = top_ref)
  12966. ) and
  12967. not RegUsed
  12968. ) or
  12969. (
  12970. (
  12971. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12972. not RegUsed
  12973. ) and
  12974. (taicpu(p).oper[0]^.typ = top_reg) and
  12975. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12976. (taicpu(hp1).oper[0]^.typ = top_const) and
  12977. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12978. ) then
  12979. begin
  12980. {$if defined(i386) or defined(i8086)}
  12981. { If the target size is 8-bit, make sure we can actually encode it }
  12982. 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
  12983. Exit;
  12984. {$endif i386 or i8086}
  12985. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12986. taicpu(hp1).opsize := NewSize;
  12987. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12988. if AndTest then
  12989. begin
  12990. RemoveInstruction(hp2);
  12991. if not RegUsed then
  12992. begin
  12993. taicpu(hp1).opcode := A_TEST;
  12994. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12995. begin
  12996. { Make sure the reference is the second operand }
  12997. SwapOper := taicpu(hp1).oper[0];
  12998. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12999. taicpu(hp1).oper[1] := SwapOper;
  13000. end;
  13001. end;
  13002. end;
  13003. case taicpu(hp1).oper[0]^.typ of
  13004. top_reg:
  13005. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13006. top_const:
  13007. { For the AND/TEST case }
  13008. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13009. else
  13010. ;
  13011. end;
  13012. if RegUsed then
  13013. begin
  13014. AsmL.Remove(p);
  13015. AsmL.InsertAfter(p, hp1);
  13016. p := hp1;
  13017. end
  13018. else
  13019. RemoveCurrentP(p, hp1);
  13020. result:=true;
  13021. exit;
  13022. end;
  13023. end;
  13024. end;
  13025. if reg_and_hp1_is_instr and
  13026. (taicpu(p).oper[0]^.typ = top_reg) and
  13027. (
  13028. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13029. ) and
  13030. (taicpu(hp1).oper[0]^.typ = top_const) and
  13031. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13032. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13033. { Minimum shift value allowed is the bit difference between the sizes }
  13034. (taicpu(hp1).oper[0]^.val >=
  13035. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13036. 8 * (
  13037. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13038. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13039. )
  13040. ) then
  13041. begin
  13042. { For:
  13043. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13044. shl/sal ##, %reg1
  13045. Remove the movsx/movzx instruction if the shift overwrites the
  13046. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13047. }
  13048. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13049. RemoveCurrentP(p, hp1);
  13050. Result := True;
  13051. Exit;
  13052. end
  13053. else if reg_and_hp1_is_instr and
  13054. (taicpu(p).oper[0]^.typ = top_reg) and
  13055. (
  13056. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13057. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13058. ) and
  13059. (taicpu(hp1).oper[0]^.typ = top_const) and
  13060. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13061. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13062. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13063. (taicpu(hp1).oper[0]^.val <
  13064. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13065. 8 * (
  13066. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13067. )
  13068. ) then
  13069. begin
  13070. { For:
  13071. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13072. sar ##, %reg1 shr ##, %reg1
  13073. Move the shift to before the movx instruction if the shift value
  13074. is not too large.
  13075. }
  13076. asml.Remove(hp1);
  13077. asml.InsertBefore(hp1, p);
  13078. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13079. case taicpu(p).opsize of
  13080. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13081. taicpu(hp1).opsize := S_B;
  13082. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13083. taicpu(hp1).opsize := S_W;
  13084. {$ifdef x86_64}
  13085. S_LQ:
  13086. taicpu(hp1).opsize := S_L;
  13087. {$endif}
  13088. else
  13089. InternalError(2020112401);
  13090. end;
  13091. if (taicpu(hp1).opcode = A_SHR) then
  13092. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13093. else
  13094. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13095. Result := True;
  13096. end;
  13097. if reg_and_hp1_is_instr and
  13098. (taicpu(p).oper[0]^.typ = top_reg) and
  13099. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13100. (
  13101. (taicpu(hp1).opcode = taicpu(p).opcode)
  13102. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13103. {$ifdef x86_64}
  13104. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13105. {$endif x86_64}
  13106. ) then
  13107. begin
  13108. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13109. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13110. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13111. begin
  13112. {
  13113. For example:
  13114. movzbw %al,%ax
  13115. movzwl %ax,%eax
  13116. Compress into:
  13117. movzbl %al,%eax
  13118. }
  13119. RegUsed := False;
  13120. case taicpu(p).opsize of
  13121. S_BW:
  13122. case taicpu(hp1).opsize of
  13123. S_WL:
  13124. begin
  13125. taicpu(p).opsize := S_BL;
  13126. RegUsed := True;
  13127. end;
  13128. {$ifdef x86_64}
  13129. S_WQ:
  13130. begin
  13131. if taicpu(p).opcode = A_MOVZX then
  13132. begin
  13133. taicpu(p).opsize := S_BL;
  13134. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13135. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13136. end
  13137. else
  13138. taicpu(p).opsize := S_BQ;
  13139. RegUsed := True;
  13140. end;
  13141. {$endif x86_64}
  13142. else
  13143. ;
  13144. end;
  13145. {$ifdef x86_64}
  13146. S_BL:
  13147. case taicpu(hp1).opsize of
  13148. S_LQ:
  13149. begin
  13150. if taicpu(p).opcode = A_MOVZX then
  13151. begin
  13152. taicpu(p).opsize := S_BL;
  13153. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13154. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13155. end
  13156. else
  13157. taicpu(p).opsize := S_BQ;
  13158. RegUsed := True;
  13159. end;
  13160. else
  13161. ;
  13162. end;
  13163. S_WL:
  13164. case taicpu(hp1).opsize of
  13165. S_LQ:
  13166. begin
  13167. if taicpu(p).opcode = A_MOVZX then
  13168. begin
  13169. taicpu(p).opsize := S_WL;
  13170. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13171. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13172. end
  13173. else
  13174. taicpu(p).opsize := S_WQ;
  13175. RegUsed := True;
  13176. end;
  13177. else
  13178. ;
  13179. end;
  13180. {$endif x86_64}
  13181. else
  13182. ;
  13183. end;
  13184. if RegUsed then
  13185. begin
  13186. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13187. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13188. RemoveInstruction(hp1);
  13189. Result := True;
  13190. Exit;
  13191. end;
  13192. end;
  13193. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13194. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13195. GetNextInstruction(hp1, hp2) and
  13196. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13197. (
  13198. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13199. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13200. {$ifdef x86_64}
  13201. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13202. {$endif x86_64}
  13203. ) and
  13204. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13205. (
  13206. (
  13207. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13208. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13209. ) or
  13210. (
  13211. { Only allow the operands in reverse order for TEST instructions }
  13212. (taicpu(hp2).opcode = A_TEST) and
  13213. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13214. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13215. )
  13216. ) then
  13217. begin
  13218. {
  13219. For example:
  13220. movzbl %al,%eax
  13221. movzbl (ref),%edx
  13222. andl %edx,%eax
  13223. (%edx deallocated)
  13224. Change to:
  13225. andb (ref),%al
  13226. movzbl %al,%eax
  13227. Rules are:
  13228. - First two instructions have the same opcode and opsize
  13229. - First instruction's operands are the same super-register
  13230. - Second instruction operates on a different register
  13231. - Third instruction is AND, OR, XOR or TEST
  13232. - Third instruction's operands are the destination registers of the first two instructions
  13233. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13234. - Second instruction's destination register is deallocated afterwards
  13235. }
  13236. TransferUsedRegs(TmpUsedRegs);
  13237. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13238. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13239. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13240. begin
  13241. case taicpu(p).opsize of
  13242. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13243. NewSize := S_B;
  13244. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13245. NewSize := S_W;
  13246. {$ifdef x86_64}
  13247. S_LQ:
  13248. NewSize := S_L;
  13249. {$endif x86_64}
  13250. else
  13251. InternalError(2021120301);
  13252. end;
  13253. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13254. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13255. taicpu(hp2).opsize := NewSize;
  13256. RemoveInstruction(hp1);
  13257. { With TEST, it's best to keep the MOVX instruction at the top }
  13258. if (taicpu(hp2).opcode <> A_TEST) then
  13259. begin
  13260. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13261. asml.Remove(p);
  13262. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13263. asml.InsertAfter(p, hp2);
  13264. p := hp2;
  13265. end
  13266. else
  13267. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13268. Result := True;
  13269. Exit;
  13270. end;
  13271. end;
  13272. end;
  13273. if taicpu(p).opcode=A_MOVZX then
  13274. begin
  13275. { removes superfluous And's after movzx's }
  13276. if reg_and_hp1_is_instr and
  13277. (taicpu(hp1).opcode = A_AND) and
  13278. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13279. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13280. {$ifdef x86_64}
  13281. { check for implicit extension to 64 bit }
  13282. or
  13283. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13284. (taicpu(hp1).opsize=S_Q) and
  13285. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13286. )
  13287. {$endif x86_64}
  13288. )
  13289. then
  13290. begin
  13291. case taicpu(p).opsize Of
  13292. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13293. if (taicpu(hp1).oper[0]^.val = $ff) then
  13294. begin
  13295. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13296. RemoveInstruction(hp1);
  13297. Result:=true;
  13298. exit;
  13299. end;
  13300. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13301. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13302. begin
  13303. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13304. RemoveInstruction(hp1);
  13305. Result:=true;
  13306. exit;
  13307. end;
  13308. {$ifdef x86_64}
  13309. S_LQ:
  13310. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13311. begin
  13312. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13313. RemoveInstruction(hp1);
  13314. Result:=true;
  13315. exit;
  13316. end;
  13317. {$endif x86_64}
  13318. else
  13319. ;
  13320. end;
  13321. { we cannot get rid of the and, but can we get rid of the movz ?}
  13322. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13323. begin
  13324. case taicpu(p).opsize Of
  13325. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13326. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13327. begin
  13328. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13329. RemoveCurrentP(p,hp1);
  13330. Result:=true;
  13331. exit;
  13332. end;
  13333. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13334. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13335. begin
  13336. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13337. RemoveCurrentP(p,hp1);
  13338. Result:=true;
  13339. exit;
  13340. end;
  13341. {$ifdef x86_64}
  13342. S_LQ:
  13343. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13344. begin
  13345. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13346. RemoveCurrentP(p,hp1);
  13347. Result:=true;
  13348. exit;
  13349. end;
  13350. {$endif x86_64}
  13351. else
  13352. ;
  13353. end;
  13354. end;
  13355. end;
  13356. { changes some movzx constructs to faster synonyms (all examples
  13357. are given with eax/ax, but are also valid for other registers)}
  13358. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13359. begin
  13360. case taicpu(p).opsize of
  13361. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13362. (the machine code is equivalent to movzbl %al,%eax), but the
  13363. code generator still generates that assembler instruction and
  13364. it is silently converted. This should probably be checked.
  13365. [Kit] }
  13366. S_BW:
  13367. begin
  13368. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13369. (
  13370. not IsMOVZXAcceptable
  13371. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13372. or (
  13373. (cs_opt_size in current_settings.optimizerswitches) and
  13374. (taicpu(p).oper[1]^.reg = NR_AX)
  13375. )
  13376. ) then
  13377. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13378. begin
  13379. DebugMsg(SPeepholeOptimization + 'var7',p);
  13380. taicpu(p).opcode := A_AND;
  13381. taicpu(p).changeopsize(S_W);
  13382. taicpu(p).loadConst(0,$ff);
  13383. Result := True;
  13384. end
  13385. else if not IsMOVZXAcceptable and
  13386. GetNextInstruction(p, hp1) and
  13387. (tai(hp1).typ = ait_instruction) and
  13388. (taicpu(hp1).opcode = A_AND) and
  13389. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13390. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13391. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13392. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13393. begin
  13394. DebugMsg(SPeepholeOptimization + 'var8',p);
  13395. taicpu(p).opcode := A_MOV;
  13396. taicpu(p).changeopsize(S_W);
  13397. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13398. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13399. Result := True;
  13400. end;
  13401. end;
  13402. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13403. S_BL:
  13404. if not IsMOVZXAcceptable then
  13405. begin
  13406. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13407. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13408. begin
  13409. DebugMsg(SPeepholeOptimization + 'var9',p);
  13410. taicpu(p).opcode := A_AND;
  13411. taicpu(p).changeopsize(S_L);
  13412. taicpu(p).loadConst(0,$ff);
  13413. Result := True;
  13414. end
  13415. else if GetNextInstruction(p, hp1) and
  13416. (tai(hp1).typ = ait_instruction) and
  13417. (taicpu(hp1).opcode = A_AND) and
  13418. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13419. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13420. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13421. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13422. begin
  13423. DebugMsg(SPeepholeOptimization + 'var10',p);
  13424. taicpu(p).opcode := A_MOV;
  13425. taicpu(p).changeopsize(S_L);
  13426. { do not use R_SUBWHOLE
  13427. as movl %rdx,%eax
  13428. is invalid in assembler PM }
  13429. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13430. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13431. Result := True;
  13432. end;
  13433. end;
  13434. {$endif i8086}
  13435. S_WL:
  13436. if not IsMOVZXAcceptable then
  13437. begin
  13438. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13439. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13440. begin
  13441. DebugMsg(SPeepholeOptimization + 'var11',p);
  13442. taicpu(p).opcode := A_AND;
  13443. taicpu(p).changeopsize(S_L);
  13444. taicpu(p).loadConst(0,$ffff);
  13445. Result := True;
  13446. end
  13447. else if GetNextInstruction(p, hp1) and
  13448. (tai(hp1).typ = ait_instruction) and
  13449. (taicpu(hp1).opcode = A_AND) and
  13450. (taicpu(hp1).oper[0]^.typ = top_const) and
  13451. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13452. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13453. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13454. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13455. begin
  13456. DebugMsg(SPeepholeOptimization + 'var12',p);
  13457. taicpu(p).opcode := A_MOV;
  13458. taicpu(p).changeopsize(S_L);
  13459. { do not use R_SUBWHOLE
  13460. as movl %rdx,%eax
  13461. is invalid in assembler PM }
  13462. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13463. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13464. Result := True;
  13465. end;
  13466. end;
  13467. else
  13468. InternalError(2017050705);
  13469. end;
  13470. end
  13471. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13472. begin
  13473. if GetNextInstruction(p, hp1) and
  13474. (tai(hp1).typ = ait_instruction) and
  13475. (taicpu(hp1).opcode = A_AND) and
  13476. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13477. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13478. begin
  13479. case taicpu(p).opsize Of
  13480. S_BL:
  13481. if (taicpu(hp1).opsize <> S_L) or
  13482. (taicpu(hp1).oper[0]^.val > $FF) then
  13483. begin
  13484. DebugMsg(SPeepholeOptimization + 'var13',p);
  13485. taicpu(hp1).changeopsize(S_L);
  13486. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13487. Include(OptsToCheck, aoc_ForceNewIteration);
  13488. end;
  13489. S_WL:
  13490. if (taicpu(hp1).opsize <> S_L) or
  13491. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13492. begin
  13493. DebugMsg(SPeepholeOptimization + 'var14',p);
  13494. taicpu(hp1).changeopsize(S_L);
  13495. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13496. Include(OptsToCheck, aoc_ForceNewIteration);
  13497. end;
  13498. S_BW:
  13499. if (taicpu(hp1).opsize <> S_W) or
  13500. (taicpu(hp1).oper[0]^.val > $FF) then
  13501. begin
  13502. DebugMsg(SPeepholeOptimization + 'var15',p);
  13503. taicpu(hp1).changeopsize(S_W);
  13504. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13505. Include(OptsToCheck, aoc_ForceNewIteration);
  13506. end;
  13507. else
  13508. Internalerror(2017050704)
  13509. end;
  13510. end;
  13511. end;
  13512. end;
  13513. end;
  13514. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13515. var
  13516. hp1, hp2 : tai;
  13517. MaskLength : Cardinal;
  13518. MaskedBits : TCgInt;
  13519. ActiveReg : TRegister;
  13520. begin
  13521. Result:=false;
  13522. { There are no optimisations for reference targets }
  13523. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13524. Exit;
  13525. while GetNextInstruction(p, hp1) and
  13526. (hp1.typ = ait_instruction) do
  13527. begin
  13528. if (taicpu(p).oper[0]^.typ = top_const) then
  13529. begin
  13530. case taicpu(hp1).opcode of
  13531. A_AND:
  13532. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13533. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13534. { the second register must contain the first one, so compare their subreg types }
  13535. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13536. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13537. { change
  13538. and const1, reg
  13539. and const2, reg
  13540. to
  13541. and (const1 and const2), reg
  13542. }
  13543. begin
  13544. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13545. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13546. RemoveCurrentP(p, hp1);
  13547. Result:=true;
  13548. exit;
  13549. end;
  13550. A_CMP:
  13551. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13552. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13553. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13554. { Just check that the condition on the next instruction is compatible }
  13555. GetNextInstruction(hp1, hp2) and
  13556. (hp2.typ = ait_instruction) and
  13557. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13558. then
  13559. { change
  13560. and 2^n, reg
  13561. cmp 2^n, reg
  13562. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13563. to
  13564. and 2^n, reg
  13565. test reg, reg
  13566. j(~c) / set(~c) / cmov(~c)
  13567. }
  13568. begin
  13569. { Keep TEST instruction in, rather than remove it, because
  13570. it may trigger other optimisations such as MovAndTest2Test }
  13571. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13572. taicpu(hp1).opcode := A_TEST;
  13573. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13574. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13575. Result := True;
  13576. Exit;
  13577. end
  13578. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13579. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13580. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13581. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13582. { change
  13583. and $ff/$ff/$ffff, reg
  13584. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13585. dealloc reg
  13586. to
  13587. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13588. }
  13589. begin
  13590. TransferUsedRegs(TmpUsedRegs);
  13591. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13592. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13593. begin
  13594. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13595. case taicpu(p).oper[0]^.val of
  13596. $ff:
  13597. begin
  13598. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13599. taicpu(hp1).opsize:=S_B;
  13600. end;
  13601. $ffff:
  13602. begin
  13603. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13604. taicpu(hp1).opsize:=S_W;
  13605. end;
  13606. $ffffffff:
  13607. begin
  13608. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13609. taicpu(hp1).opsize:=S_L;
  13610. end;
  13611. else
  13612. Internalerror(2023030401);
  13613. end;
  13614. RemoveCurrentP(p);
  13615. Result := True;
  13616. Exit;
  13617. end;
  13618. end;
  13619. A_MOVZX:
  13620. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13621. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13622. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13623. (
  13624. (
  13625. (taicpu(p).opsize=S_W) and
  13626. (taicpu(hp1).opsize=S_BW)
  13627. ) or
  13628. (
  13629. (taicpu(p).opsize=S_L) and
  13630. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13631. )
  13632. {$ifdef x86_64}
  13633. or
  13634. (
  13635. (taicpu(p).opsize=S_Q) and
  13636. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13637. )
  13638. {$endif x86_64}
  13639. ) then
  13640. begin
  13641. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13642. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13643. ) or
  13644. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13645. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13646. then
  13647. begin
  13648. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13649. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13650. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13651. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13652. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13653. }
  13654. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13655. RemoveInstruction(hp1);
  13656. { See if there are other optimisations possible }
  13657. Continue;
  13658. end;
  13659. end;
  13660. A_SHL:
  13661. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13662. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13663. begin
  13664. {$ifopt R+}
  13665. {$define RANGE_WAS_ON}
  13666. {$R-}
  13667. {$endif}
  13668. { get length of potential and mask }
  13669. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13670. { really a mask? }
  13671. {$ifdef RANGE_WAS_ON}
  13672. {$R+}
  13673. {$endif}
  13674. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13675. { unmasked part shifted out? }
  13676. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13677. begin
  13678. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13679. RemoveCurrentP(p, hp1);
  13680. Result:=true;
  13681. exit;
  13682. end;
  13683. end;
  13684. A_SHR:
  13685. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13686. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13687. (taicpu(hp1).oper[0]^.val <= 63) then
  13688. begin
  13689. { Does SHR combined with the AND cover all the bits?
  13690. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13691. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13692. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13693. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13694. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13695. begin
  13696. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13697. RemoveCurrentP(p, hp1);
  13698. Result := True;
  13699. Exit;
  13700. end;
  13701. end;
  13702. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13703. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13704. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13705. begin
  13706. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13707. (
  13708. (
  13709. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13710. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13711. ) or (
  13712. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13713. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13714. {$ifdef x86_64}
  13715. ) or (
  13716. (taicpu(hp1).opsize = S_LQ) and
  13717. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13718. {$endif x86_64}
  13719. )
  13720. ) then
  13721. begin
  13722. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13723. begin
  13724. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13725. RemoveInstruction(hp1);
  13726. { See if there are other optimisations possible }
  13727. Continue;
  13728. end;
  13729. { The super-registers are the same though.
  13730. Note that this change by itself doesn't improve
  13731. code speed, but it opens up other optimisations. }
  13732. {$ifdef x86_64}
  13733. { Convert 64-bit register to 32-bit }
  13734. case taicpu(hp1).opsize of
  13735. S_BQ:
  13736. begin
  13737. taicpu(hp1).opsize := S_BL;
  13738. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13739. end;
  13740. S_WQ:
  13741. begin
  13742. taicpu(hp1).opsize := S_WL;
  13743. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13744. end
  13745. else
  13746. ;
  13747. end;
  13748. {$endif x86_64}
  13749. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13750. taicpu(hp1).opcode := A_MOVZX;
  13751. { See if there are other optimisations possible }
  13752. Continue;
  13753. end;
  13754. end;
  13755. else
  13756. ;
  13757. end;
  13758. end
  13759. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13760. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13761. begin
  13762. {$ifdef x86_64}
  13763. if (taicpu(p).opsize = S_Q) then
  13764. begin
  13765. { Never necessary }
  13766. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13767. RemoveCurrentP(p, hp1);
  13768. Result := True;
  13769. Exit;
  13770. end;
  13771. {$endif x86_64}
  13772. { Forward check to determine necessity of and %reg,%reg }
  13773. TransferUsedRegs(TmpUsedRegs);
  13774. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13775. { Saves on a bunch of dereferences }
  13776. ActiveReg := taicpu(p).oper[1]^.reg;
  13777. case taicpu(hp1).opcode of
  13778. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13779. if (
  13780. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13781. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13782. ) and
  13783. (
  13784. (taicpu(hp1).opcode <> A_MOV) or
  13785. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13786. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13787. ) and
  13788. not (
  13789. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13790. (taicpu(hp1).opcode = A_MOV) and
  13791. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13792. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13793. ) and
  13794. (
  13795. (
  13796. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13797. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13798. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13799. ) or
  13800. (
  13801. {$ifdef x86_64}
  13802. (
  13803. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13804. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13805. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13806. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13807. ) and
  13808. {$endif x86_64}
  13809. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13810. )
  13811. ) then
  13812. begin
  13813. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13814. RemoveCurrentP(p, hp1);
  13815. Result := True;
  13816. Exit;
  13817. end;
  13818. A_ADD,
  13819. A_AND,
  13820. A_BSF,
  13821. A_BSR,
  13822. A_BTC,
  13823. A_BTR,
  13824. A_BTS,
  13825. A_OR,
  13826. A_SUB,
  13827. A_XOR:
  13828. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13829. if (
  13830. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13831. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13832. ) and
  13833. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13834. begin
  13835. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13836. RemoveCurrentP(p, hp1);
  13837. Result := True;
  13838. Exit;
  13839. end;
  13840. A_CMP,
  13841. A_TEST:
  13842. if (
  13843. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13844. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13845. ) and
  13846. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13847. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13848. begin
  13849. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13850. RemoveCurrentP(p, hp1);
  13851. Result := True;
  13852. Exit;
  13853. end;
  13854. A_BSWAP,
  13855. A_NEG,
  13856. A_NOT:
  13857. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13858. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13859. begin
  13860. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13861. RemoveCurrentP(p, hp1);
  13862. Result := True;
  13863. Exit;
  13864. end;
  13865. else
  13866. ;
  13867. end;
  13868. end;
  13869. if (taicpu(hp1).is_jmp) and
  13870. (taicpu(hp1).opcode<>A_JMP) and
  13871. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13872. begin
  13873. { change
  13874. and x, reg
  13875. jxx
  13876. to
  13877. test x, reg
  13878. jxx
  13879. if reg is deallocated before the
  13880. jump, but only if it's a conditional jump (PFV)
  13881. }
  13882. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13883. taicpu(p).opcode := A_TEST;
  13884. Exit;
  13885. end;
  13886. Break;
  13887. end;
  13888. { Lone AND tests }
  13889. if (taicpu(p).oper[0]^.typ = top_const) then
  13890. begin
  13891. {
  13892. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13893. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13894. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13895. }
  13896. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13897. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13898. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13899. begin
  13900. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13901. if taicpu(p).opsize = S_L then
  13902. begin
  13903. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13904. Result := True;
  13905. end;
  13906. end;
  13907. end;
  13908. { Backward check to determine necessity of and %reg,%reg }
  13909. if (taicpu(p).oper[0]^.typ = top_reg) and
  13910. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13911. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13912. GetLastInstruction(p, hp2) and
  13913. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13914. { Check size of adjacent instruction to determine if the AND is
  13915. effectively a null operation }
  13916. (
  13917. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13918. { Note: Don't include S_Q }
  13919. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13920. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13921. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13922. ) then
  13923. begin
  13924. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13925. { If GetNextInstruction returned False, hp1 will be nil }
  13926. RemoveCurrentP(p, hp1);
  13927. Result := True;
  13928. Exit;
  13929. end;
  13930. end;
  13931. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13932. var
  13933. hp1, hp2: tai;
  13934. NewRef: TReference;
  13935. Distance: Cardinal;
  13936. TempTracking: TAllUsedRegs;
  13937. { This entire nested function is used in an if-statement below, but we
  13938. want to avoid all the used reg transfers and GetNextInstruction calls
  13939. until we really have to check }
  13940. function MemRegisterNotUsedLater: Boolean; inline;
  13941. var
  13942. hp2: tai;
  13943. begin
  13944. TransferUsedRegs(TmpUsedRegs);
  13945. hp2 := p;
  13946. repeat
  13947. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13948. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13949. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13950. end;
  13951. begin
  13952. Result := False;
  13953. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13954. (taicpu(p).oper[1]^.typ = top_reg) then
  13955. begin
  13956. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13957. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13958. (hp1.typ <> ait_instruction) or
  13959. not
  13960. (
  13961. (cs_opt_level3 in current_settings.optimizerswitches) or
  13962. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13963. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13964. ) then
  13965. Exit;
  13966. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13967. addq $x, %rax
  13968. movq %rax, %rdx
  13969. sarq $63, %rdx
  13970. (%rax still in use)
  13971. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13972. leaq $x(%rax),%rdx
  13973. addq $x, %rax
  13974. sarq $63, %rdx
  13975. ...which is okay since it breaks the dependency chain between
  13976. addq and movq, but if OptPass2MOV is called first:
  13977. addq $x, %rax
  13978. cqto
  13979. ...which is better in all ways, taking only 2 cycles to execute
  13980. and much smaller in code size.
  13981. }
  13982. { The extra register tracking is quite strenuous }
  13983. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13984. MatchInstruction(hp1, A_MOV, []) then
  13985. begin
  13986. { Update the register tracking to the MOV instruction }
  13987. CopyUsedRegs(TempTracking);
  13988. hp2 := p;
  13989. repeat
  13990. UpdateUsedRegs(tai(hp2.Next));
  13991. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13992. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13993. OptPass2ADD get called again }
  13994. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13995. begin
  13996. { Reset the tracking to the current instruction }
  13997. RestoreUsedRegs(TempTracking);
  13998. ReleaseUsedRegs(TempTracking);
  13999. Result := True;
  14000. Exit;
  14001. end;
  14002. { Reset the tracking to the current instruction }
  14003. RestoreUsedRegs(TempTracking);
  14004. ReleaseUsedRegs(TempTracking);
  14005. { If OptPass2MOV returned True, we don't need to set Result to
  14006. True if hp1 didn't change because the ADD instruction didn't
  14007. get modified and we'll be evaluating hp1 again when the
  14008. peephole optimizer reaches it }
  14009. end;
  14010. { Change:
  14011. add %reg2,%reg1
  14012. (%reg2 not modified in between)
  14013. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14014. To:
  14015. mov/s/z #(%reg1,%reg2),%reg1
  14016. }
  14017. if (taicpu(p).oper[0]^.typ = top_reg) and
  14018. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14019. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14020. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14021. (
  14022. (
  14023. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14024. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14025. { r/esp cannot be an index }
  14026. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14027. ) or (
  14028. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14029. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14030. )
  14031. ) and (
  14032. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14033. (
  14034. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14035. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14036. MemRegisterNotUsedLater
  14037. )
  14038. ) then
  14039. begin
  14040. if (
  14041. { Instructions are guaranteed to be adjacent on -O2 and under }
  14042. (cs_opt_level3 in current_settings.optimizerswitches) and
  14043. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14044. ) then
  14045. begin
  14046. { If the other register is used in between, move the MOV
  14047. instruction to right after the ADD instruction so a
  14048. saving can still be made }
  14049. Asml.Remove(hp1);
  14050. Asml.InsertAfter(hp1, p);
  14051. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14052. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14053. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14054. RemoveCurrentp(p, hp1);
  14055. end
  14056. else
  14057. begin
  14058. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14059. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14060. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14061. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14062. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14063. { hp1 may not be the immediate next instruction under -O3 }
  14064. RemoveCurrentp(p)
  14065. else
  14066. RemoveCurrentp(p, hp1);
  14067. end;
  14068. Result := True;
  14069. Exit;
  14070. end;
  14071. { Change:
  14072. addl/q $x,%reg1
  14073. movl/q %reg1,%reg2
  14074. To:
  14075. leal/q $x(%reg1),%reg2
  14076. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14077. Breaks the dependency chain.
  14078. }
  14079. if (taicpu(p).oper[0]^.typ = top_const) and
  14080. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14081. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14082. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14083. (
  14084. { Instructions are guaranteed to be adjacent on -O2 and under }
  14085. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14086. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14087. ) then
  14088. begin
  14089. TransferUsedRegs(TmpUsedRegs);
  14090. hp2 := p;
  14091. repeat
  14092. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14093. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14094. if (
  14095. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14096. not (cs_opt_size in current_settings.optimizerswitches) or
  14097. (
  14098. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14099. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14100. )
  14101. ) then
  14102. begin
  14103. { Change the MOV instruction to a LEA instruction, and update the
  14104. first operand }
  14105. reference_reset(NewRef, 1, []);
  14106. NewRef.base := taicpu(p).oper[1]^.reg;
  14107. NewRef.scalefactor := 1;
  14108. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14109. taicpu(hp1).opcode := A_LEA;
  14110. taicpu(hp1).loadref(0, NewRef);
  14111. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14112. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14113. begin
  14114. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14115. { Move what is now the LEA instruction to before the ADD instruction }
  14116. Asml.Remove(hp1);
  14117. Asml.InsertBefore(hp1, p);
  14118. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14119. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14120. p := hp1;
  14121. end
  14122. else
  14123. begin
  14124. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14125. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14126. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14127. { hp1 may not be the immediate next instruction under -O3 }
  14128. RemoveCurrentp(p)
  14129. else
  14130. RemoveCurrentp(p, hp1);
  14131. end;
  14132. Result := True;
  14133. end;
  14134. end;
  14135. end;
  14136. end;
  14137. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14138. var
  14139. SubReg: TSubRegister;
  14140. hp1, hp2: tai;
  14141. CallJmp: Boolean;
  14142. begin
  14143. Result := False;
  14144. CallJmp := False;
  14145. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14146. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14147. with taicpu(p).oper[0]^.ref^ do
  14148. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14149. if (offset = 0) then
  14150. begin
  14151. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14152. begin
  14153. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14154. taicpu(p).opcode := A_ADD;
  14155. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14156. Result := True;
  14157. end
  14158. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14159. begin
  14160. if (base <> NR_NO) then
  14161. begin
  14162. if (scalefactor <= 1) then
  14163. begin
  14164. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14165. taicpu(p).opcode := A_ADD;
  14166. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14167. Result := True;
  14168. end;
  14169. end
  14170. else
  14171. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14172. if (scalefactor in [2, 4, 8]) then
  14173. begin
  14174. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14175. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14176. taicpu(p).opcode := A_SHL;
  14177. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14178. Result := True;
  14179. end;
  14180. end;
  14181. end
  14182. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14183. lot of latency, so break off the offset if %reg3 is used soon
  14184. afterwards }
  14185. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14186. { If 3-component addresses don't have additional latency, don't
  14187. perform this optimisation }
  14188. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14189. GetNextInstruction(p, hp1) and
  14190. (hp1.typ = ait_instruction) and
  14191. (
  14192. (
  14193. { Permit jumps and calls since they have a larger degree of overhead }
  14194. (
  14195. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14196. (
  14197. { ... unless the register specifies the location }
  14198. (taicpu(hp1).ops > 0) and
  14199. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14200. )
  14201. ) and
  14202. (
  14203. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14204. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14205. )
  14206. )
  14207. or
  14208. (
  14209. { Check up to two instructions ahead }
  14210. GetNextInstruction(hp1, hp2) and
  14211. (hp2.typ = ait_instruction) and
  14212. (
  14213. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14214. (
  14215. { Same as above }
  14216. (taicpu(hp2).ops > 0) and
  14217. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14218. )
  14219. ) and
  14220. (
  14221. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14222. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14223. )
  14224. )
  14225. ) then
  14226. begin
  14227. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14228. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14229. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14230. offset := 0;
  14231. if Assigned(symbol) or Assigned(relsymbol) then
  14232. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14233. else
  14234. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14235. { Inserting before the next instruction rather than after the
  14236. current instruction gives more accurate register tracking }
  14237. asml.InsertBefore(hp2, hp1);
  14238. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14239. Result := True;
  14240. end;
  14241. end;
  14242. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14243. var
  14244. hp1, hp2: tai;
  14245. NewRef: TReference;
  14246. Distance: Cardinal;
  14247. TempTracking: TAllUsedRegs;
  14248. begin
  14249. Result := False;
  14250. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14251. MatchOpType(taicpu(p),top_const,top_reg) then
  14252. begin
  14253. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14254. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14255. (hp1.typ <> ait_instruction) or
  14256. not
  14257. (
  14258. (cs_opt_level3 in current_settings.optimizerswitches) or
  14259. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14260. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14261. ) then
  14262. Exit;
  14263. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14264. subq $x, %rax
  14265. movq %rax, %rdx
  14266. sarq $63, %rdx
  14267. (%rax still in use)
  14268. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14269. leaq $-x(%rax),%rdx
  14270. movq $x, %rax
  14271. sarq $63, %rdx
  14272. ...which is okay since it breaks the dependency chain between
  14273. subq and movq, but if OptPass2MOV is called first:
  14274. subq $x, %rax
  14275. cqto
  14276. ...which is better in all ways, taking only 2 cycles to execute
  14277. and much smaller in code size.
  14278. }
  14279. { The extra register tracking is quite strenuous }
  14280. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14281. MatchInstruction(hp1, A_MOV, []) then
  14282. begin
  14283. { Update the register tracking to the MOV instruction }
  14284. CopyUsedRegs(TempTracking);
  14285. hp2 := p;
  14286. repeat
  14287. UpdateUsedRegs(tai(hp2.Next));
  14288. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14289. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14290. OptPass2SUB get called again }
  14291. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14292. begin
  14293. { Reset the tracking to the current instruction }
  14294. RestoreUsedRegs(TempTracking);
  14295. ReleaseUsedRegs(TempTracking);
  14296. Result := True;
  14297. Exit;
  14298. end;
  14299. { Reset the tracking to the current instruction }
  14300. RestoreUsedRegs(TempTracking);
  14301. ReleaseUsedRegs(TempTracking);
  14302. { If OptPass2MOV returned True, we don't need to set Result to
  14303. True if hp1 didn't change because the SUB instruction didn't
  14304. get modified and we'll be evaluating hp1 again when the
  14305. peephole optimizer reaches it }
  14306. end;
  14307. { Change:
  14308. subl/q $x,%reg1
  14309. movl/q %reg1,%reg2
  14310. To:
  14311. leal/q $-x(%reg1),%reg2
  14312. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14313. Breaks the dependency chain and potentially permits the removal of
  14314. a CMP instruction if one follows.
  14315. }
  14316. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14317. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14318. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14319. (
  14320. { Instructions are guaranteed to be adjacent on -O2 and under }
  14321. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14322. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14323. ) then
  14324. begin
  14325. TransferUsedRegs(TmpUsedRegs);
  14326. hp2 := p;
  14327. repeat
  14328. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14329. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14330. if (
  14331. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14332. not (cs_opt_size in current_settings.optimizerswitches) or
  14333. (
  14334. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14335. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14336. )
  14337. ) then
  14338. begin
  14339. { Change the MOV instruction to a LEA instruction, and update the
  14340. first operand }
  14341. reference_reset(NewRef, 1, []);
  14342. NewRef.base := taicpu(p).oper[1]^.reg;
  14343. NewRef.scalefactor := 1;
  14344. NewRef.offset := -taicpu(p).oper[0]^.val;
  14345. taicpu(hp1).opcode := A_LEA;
  14346. taicpu(hp1).loadref(0, NewRef);
  14347. TransferUsedRegs(TmpUsedRegs);
  14348. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14349. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14350. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14351. begin
  14352. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14353. { Move what is now the LEA instruction to before the SUB instruction }
  14354. Asml.Remove(hp1);
  14355. Asml.InsertBefore(hp1, p);
  14356. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14357. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14358. p := hp1;
  14359. end
  14360. else
  14361. begin
  14362. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14363. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14364. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14365. { hp1 may not be the immediate next instruction under -O3 }
  14366. RemoveCurrentp(p)
  14367. else
  14368. RemoveCurrentp(p, hp1);
  14369. end;
  14370. Result := True;
  14371. end;
  14372. end;
  14373. end;
  14374. end;
  14375. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14376. begin
  14377. { we can skip all instructions not messing with the stack pointer }
  14378. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14379. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14380. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14381. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14382. ({(taicpu(hp1).ops=0) or }
  14383. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14384. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14385. ) and }
  14386. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14387. )
  14388. ) do
  14389. GetNextInstruction(hp1,hp1);
  14390. Result:=assigned(hp1);
  14391. end;
  14392. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14393. var
  14394. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14395. begin
  14396. Result:=false;
  14397. hp5:=nil;
  14398. hp6:=nil;
  14399. hp7:=nil;
  14400. hp8:=nil;
  14401. { replace
  14402. leal(q) x(<stackpointer>),<stackpointer>
  14403. <optional .seh_stackalloc ...>
  14404. <optional .seh_endprologue ...>
  14405. call procname
  14406. <optional NOP>
  14407. leal(q) -x(<stackpointer>),<stackpointer>
  14408. <optional VZEROUPPER>
  14409. ret
  14410. by
  14411. jmp procname
  14412. but do it only on level 4 because it destroys stack back traces
  14413. }
  14414. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14415. MatchOpType(taicpu(p),top_ref,top_reg) and
  14416. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14417. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14418. { the -8, -24, -40 are not required, but bail out early if possible,
  14419. higher values are unlikely }
  14420. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14421. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14422. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14423. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14424. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14425. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14426. GetNextInstruction(p, hp1) and
  14427. { Take a copy of hp1 }
  14428. SetAndTest(hp1, hp4) and
  14429. { trick to skip label }
  14430. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14431. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14432. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14433. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14434. SkipSimpleInstructions(hp1) and
  14435. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14436. GetNextInstruction(hp1, hp2) and
  14437. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14438. { skip nop instruction on win64 }
  14439. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14440. SetAndTest(hp2,hp6) and
  14441. GetNextInstruction(hp2,hp2) and
  14442. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14443. ) and
  14444. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14445. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14446. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14447. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14448. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14449. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14450. { Segment register will be NR_NO }
  14451. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14452. GetNextInstruction(hp2, hp3) and
  14453. { trick to skip label }
  14454. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14455. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14456. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14457. SetAndTest(hp3,hp5) and
  14458. GetNextInstruction(hp3,hp3) and
  14459. MatchInstruction(hp3,A_RET,[S_NO])
  14460. )
  14461. ) and
  14462. (taicpu(hp3).ops=0) then
  14463. begin
  14464. taicpu(hp1).opcode := A_JMP;
  14465. taicpu(hp1).is_jmp := true;
  14466. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14467. { search for the stackalloc directive and remove it }
  14468. hp7:=tai(p.next);
  14469. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14470. begin
  14471. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14472. begin
  14473. { sanity check }
  14474. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14475. Internalerror(2024012201);
  14476. hp8:=tai(hp7.next);
  14477. RemoveInstruction(tai(hp7));
  14478. hp7:=hp8;
  14479. break;
  14480. end
  14481. else
  14482. hp7:=tai(hp7.next);
  14483. end;
  14484. RemoveCurrentP(p, hp4);
  14485. RemoveInstruction(hp2);
  14486. RemoveInstruction(hp3);
  14487. { if there is a vzeroupper instruction then move it before the jmp }
  14488. if Assigned(hp5) then
  14489. begin
  14490. AsmL.Remove(hp5);
  14491. ASmL.InsertBefore(hp5,hp1)
  14492. end;
  14493. { remove nop on win64 }
  14494. if Assigned(hp6) then
  14495. RemoveInstruction(hp6);
  14496. Result:=true;
  14497. end;
  14498. end;
  14499. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14500. {$ifdef x86_64}
  14501. var
  14502. hp1, hp2, hp3, hp4, hp5: tai;
  14503. {$endif x86_64}
  14504. begin
  14505. Result:=false;
  14506. {$ifdef x86_64}
  14507. hp5:=nil;
  14508. { replace
  14509. push %rax
  14510. call procname
  14511. pop %rcx
  14512. ret
  14513. by
  14514. jmp procname
  14515. but do it only on level 4 because it destroys stack back traces
  14516. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14517. for all supported calling conventions
  14518. }
  14519. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14520. MatchOpType(taicpu(p),top_reg) and
  14521. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14522. GetNextInstruction(p, hp1) and
  14523. { Take a copy of hp1 }
  14524. SetAndTest(hp1, hp4) and
  14525. { trick to skip label }
  14526. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14527. SkipSimpleInstructions(hp1) and
  14528. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14529. GetNextInstruction(hp1, hp2) and
  14530. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14531. MatchOpType(taicpu(hp2),top_reg) and
  14532. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14533. GetNextInstruction(hp2, hp3) and
  14534. { trick to skip label }
  14535. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14536. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14537. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14538. SetAndTest(hp3,hp5) and
  14539. GetNextInstruction(hp3,hp3) and
  14540. MatchInstruction(hp3,A_RET,[S_NO])
  14541. )
  14542. ) and
  14543. (taicpu(hp3).ops=0) then
  14544. begin
  14545. taicpu(hp1).opcode := A_JMP;
  14546. taicpu(hp1).is_jmp := true;
  14547. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14548. RemoveCurrentP(p, hp4);
  14549. RemoveInstruction(hp2);
  14550. RemoveInstruction(hp3);
  14551. if Assigned(hp5) then
  14552. begin
  14553. AsmL.Remove(hp5);
  14554. ASmL.InsertBefore(hp5,hp1)
  14555. end;
  14556. Result:=true;
  14557. end;
  14558. {$endif x86_64}
  14559. end;
  14560. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14561. var
  14562. Value, RegName: string;
  14563. hp1: tai;
  14564. begin
  14565. Result:=false;
  14566. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14567. begin
  14568. case taicpu(p).oper[0]^.val of
  14569. 0:
  14570. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14571. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14572. (
  14573. { See if we can still convert the instruction }
  14574. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14575. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14576. ) then
  14577. begin
  14578. { change "mov $0,%reg" into "xor %reg,%reg" }
  14579. taicpu(p).opcode := A_XOR;
  14580. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14581. Result := True;
  14582. {$ifdef x86_64}
  14583. end
  14584. else if (taicpu(p).opsize = S_Q) then
  14585. begin
  14586. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14587. { The actual optimization }
  14588. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14589. taicpu(p).changeopsize(S_L);
  14590. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14591. Result := True;
  14592. end;
  14593. $1..$FFFFFFFF:
  14594. begin
  14595. { Code size reduction by J. Gareth "Kit" Moreton }
  14596. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14597. case taicpu(p).opsize of
  14598. S_Q:
  14599. begin
  14600. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14601. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14602. { The actual optimization }
  14603. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14604. taicpu(p).changeopsize(S_L);
  14605. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14606. Result := True;
  14607. end;
  14608. else
  14609. { Do nothing };
  14610. end;
  14611. {$endif x86_64}
  14612. end;
  14613. -1:
  14614. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14615. if (cs_opt_size in current_settings.optimizerswitches) and
  14616. (taicpu(p).opsize <> S_B) and
  14617. (
  14618. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14619. (
  14620. { See if we can still convert the instruction }
  14621. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14622. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14623. )
  14624. ) then
  14625. begin
  14626. { change "mov $-1,%reg" into "or $-1,%reg" }
  14627. { NOTES:
  14628. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14629. - This operation creates a false dependency on the register, so only do it when optimising for size
  14630. - 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
  14631. }
  14632. taicpu(p).opcode := A_OR;
  14633. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14634. Result := True;
  14635. end;
  14636. else
  14637. { Do nothing };
  14638. end;
  14639. end;
  14640. end;
  14641. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14642. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14643. begin
  14644. Result := False;
  14645. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14646. Exit;
  14647. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14648. so don't bother optimising }
  14649. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14650. Exit;
  14651. if (taicpu(p).oper[0]^.typ <> top_const) or
  14652. { If the value can fit into an 8-bit signed integer, a smaller
  14653. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14654. falls within this range }
  14655. (
  14656. (taicpu(p).oper[0]^.val > -128) and
  14657. (taicpu(p).oper[0]^.val <= 127)
  14658. ) then
  14659. Exit;
  14660. { If we're optimising for size, this is acceptable }
  14661. if (cs_opt_size in current_settings.optimizerswitches) then
  14662. Exit(True);
  14663. if (taicpu(p).oper[1]^.typ = top_reg) and
  14664. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14665. Exit(True);
  14666. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14667. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14668. Exit(True);
  14669. end;
  14670. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14671. var
  14672. hp1: tai;
  14673. Value: TCGInt;
  14674. begin
  14675. Result := False;
  14676. if MatchOpType(taicpu(p), top_const, top_reg) then
  14677. begin
  14678. { Detect:
  14679. andw x, %ax (0 <= x < $8000)
  14680. ...
  14681. movzwl %ax,%eax
  14682. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14683. }
  14684. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14685. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14686. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14687. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14688. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14689. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14690. begin
  14691. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14692. taicpu(hp1).opcode := A_CWDE;
  14693. taicpu(hp1).clearop(0);
  14694. taicpu(hp1).clearop(1);
  14695. taicpu(hp1).ops := 0;
  14696. { A change was made, but not with p, so don't set Result, but
  14697. notify the compiler that a change was made }
  14698. Include(OptsToCheck, aoc_ForceNewIteration);
  14699. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14700. end;
  14701. end;
  14702. { If "not x" is a power of 2 (popcnt = 1), change:
  14703. and $x, %reg/ref
  14704. To:
  14705. btr lb(x), %reg/ref
  14706. }
  14707. if IsBTXAcceptable(p) and
  14708. (
  14709. { Make sure a TEST doesn't follow that plays with the register }
  14710. not GetNextInstruction(p, hp1) or
  14711. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14712. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14713. ) then
  14714. begin
  14715. {$push}{$R-}{$Q-}
  14716. { Value is a sign-extended 32-bit integer - just correct it
  14717. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14718. checks to see if this operand is an immediate. }
  14719. Value := not taicpu(p).oper[0]^.val;
  14720. {$pop}
  14721. {$ifdef x86_64}
  14722. if taicpu(p).opsize = S_L then
  14723. {$endif x86_64}
  14724. Value := Value and $FFFFFFFF;
  14725. if (PopCnt(QWord(Value)) = 1) then
  14726. begin
  14727. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14728. taicpu(p).opcode := A_BTR;
  14729. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14730. Result := True;
  14731. Exit;
  14732. end;
  14733. end;
  14734. end;
  14735. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14736. begin
  14737. Result := False;
  14738. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14739. Exit;
  14740. { Convert:
  14741. movswl %ax,%eax -> cwtl
  14742. movslq %eax,%rax -> cdqe
  14743. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14744. refer to the same opcode and depends only on the assembler's
  14745. current operand-size attribute. [Kit]
  14746. }
  14747. with taicpu(p) do
  14748. case opsize of
  14749. S_WL:
  14750. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14751. begin
  14752. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14753. opcode := A_CWDE;
  14754. clearop(0);
  14755. clearop(1);
  14756. ops := 0;
  14757. Result := True;
  14758. end;
  14759. {$ifdef x86_64}
  14760. S_LQ:
  14761. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14762. begin
  14763. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14764. opcode := A_CDQE;
  14765. clearop(0);
  14766. clearop(1);
  14767. ops := 0;
  14768. Result := True;
  14769. end;
  14770. {$endif x86_64}
  14771. else
  14772. ;
  14773. end;
  14774. end;
  14775. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14776. var
  14777. hp1, hp2: tai;
  14778. IdentityMask, Shift: TCGInt;
  14779. LimitSize: Topsize;
  14780. DoNotMerge: Boolean;
  14781. begin
  14782. Result := False;
  14783. { All these optimisations work on "shr const,%reg" }
  14784. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14785. Exit;
  14786. DoNotMerge := False;
  14787. Shift := taicpu(p).oper[0]^.val;
  14788. LimitSize := taicpu(p).opsize;
  14789. hp1 := p;
  14790. repeat
  14791. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14792. Break;
  14793. { Detect:
  14794. shr x, %reg
  14795. and y, %reg
  14796. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14797. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14798. }
  14799. case taicpu(hp1).opcode of
  14800. A_AND:
  14801. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14802. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14803. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14804. begin
  14805. { Make sure the FLAGS register isn't in use }
  14806. TransferUsedRegs(TmpUsedRegs);
  14807. hp2 := p;
  14808. repeat
  14809. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14810. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14811. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14812. begin
  14813. { Generate the identity mask }
  14814. case taicpu(p).opsize of
  14815. S_B:
  14816. IdentityMask := $FF shr Shift;
  14817. S_W:
  14818. IdentityMask := $FFFF shr Shift;
  14819. S_L:
  14820. IdentityMask := $FFFFFFFF shr Shift;
  14821. {$ifdef x86_64}
  14822. S_Q:
  14823. { We need to force the operands to be unsigned 64-bit
  14824. integers otherwise the wrong value is generated }
  14825. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14826. {$endif x86_64}
  14827. else
  14828. InternalError(2022081501);
  14829. end;
  14830. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14831. begin
  14832. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14833. { All the possible 1 bits are covered, so we can remove the AND }
  14834. hp2 := tai(hp1.Previous);
  14835. RemoveInstruction(hp1);
  14836. { p wasn't actually changed, so don't set Result to True,
  14837. but a change was nonetheless made elsewhere }
  14838. Include(OptsToCheck, aoc_ForceNewIteration);
  14839. { Do another pass in case other AND or MOVZX instructions
  14840. follow }
  14841. hp1 := hp2;
  14842. Continue;
  14843. end;
  14844. end;
  14845. end;
  14846. A_TEST, A_CMP, A_Jcc:
  14847. { Skip over conditional jumps and relevant comparisons }
  14848. Continue;
  14849. A_MOVZX:
  14850. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14851. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14852. begin
  14853. { Since the original register is being read as is, subsequent
  14854. SHRs must not be merged at this point }
  14855. DoNotMerge := True;
  14856. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14857. begin
  14858. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14859. begin
  14860. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14861. { All the possible 1 bits are covered, so we can remove the AND }
  14862. hp2 := tai(hp1.Previous);
  14863. RemoveInstruction(hp1);
  14864. hp1 := hp2;
  14865. end
  14866. else { Different register target }
  14867. begin
  14868. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14869. taicpu(hp1).opcode := A_MOV;
  14870. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14871. case taicpu(hp1).opsize of
  14872. S_BW:
  14873. taicpu(hp1).opsize := S_W;
  14874. S_BL, S_WL:
  14875. taicpu(hp1).opsize := S_L;
  14876. else
  14877. InternalError(2022081503);
  14878. end;
  14879. end;
  14880. end
  14881. else if (Shift > 0) and
  14882. (taicpu(p).opsize = S_W) and
  14883. (taicpu(hp1).opsize = S_WL) and
  14884. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14885. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14886. begin
  14887. { Detect:
  14888. shr x, %ax (x > 0)
  14889. ...
  14890. movzwl %ax,%eax
  14891. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14892. }
  14893. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14894. taicpu(hp1).opcode := A_CWDE;
  14895. taicpu(hp1).clearop(0);
  14896. taicpu(hp1).clearop(1);
  14897. taicpu(hp1).ops := 0;
  14898. end;
  14899. { Move onto the next instruction }
  14900. Continue;
  14901. end;
  14902. A_SHL, A_SAL, A_SHR:
  14903. if (taicpu(hp1).opsize <= LimitSize) and
  14904. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14905. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14906. begin
  14907. { Make sure the sizes don't exceed the register size limit
  14908. (measured by the shift value falling below the limit) }
  14909. if taicpu(hp1).opsize < LimitSize then
  14910. LimitSize := taicpu(hp1).opsize;
  14911. if taicpu(hp1).opcode = A_SHR then
  14912. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14913. else
  14914. begin
  14915. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14916. DoNotMerge := True;
  14917. end;
  14918. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14919. Break;
  14920. { Since we've established that the combined shift is within
  14921. limits, we can actually combine the adjacent SHR
  14922. instructions even if they're different sizes }
  14923. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14924. begin
  14925. hp2 := tai(hp1.Previous);
  14926. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14927. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14928. RemoveInstruction(hp1);
  14929. hp1 := hp2;
  14930. end;
  14931. { Move onto the next instruction }
  14932. Continue;
  14933. end;
  14934. else
  14935. ;
  14936. end;
  14937. Break;
  14938. until False;
  14939. { Detect the following (looking backwards):
  14940. shr %cl,%reg
  14941. shr x, %reg
  14942. Swap the two SHR instructions to minimise a pipeline stall.
  14943. }
  14944. if GetLastInstruction(p, hp1) and
  14945. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14946. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14947. { First operand will be %cl }
  14948. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14949. { Just to be sure }
  14950. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14951. begin
  14952. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14953. { Moving the entries this way ensures the register tracking remains correct }
  14954. Asml.Remove(p);
  14955. Asml.InsertBefore(p, hp1);
  14956. p := hp1;
  14957. { Don't set Result to True because the current instruction is now
  14958. "shr %cl,%reg" and there's nothing more we can do with it }
  14959. end;
  14960. end;
  14961. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14962. var
  14963. hp1, hp2: tai;
  14964. Opposite, SecondOpposite: TAsmOp;
  14965. NewCond: TAsmCond;
  14966. begin
  14967. Result := False;
  14968. { Change:
  14969. add/sub 128,(dest)
  14970. To:
  14971. sub/add -128,(dest)
  14972. This generaally takes fewer bytes to encode because -128 can be stored
  14973. in a signed byte, whereas +128 cannot.
  14974. }
  14975. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14976. begin
  14977. if taicpu(p).opcode = A_ADD then
  14978. Opposite := A_SUB
  14979. else
  14980. Opposite := A_ADD;
  14981. { Be careful if the flags are in use, because the CF flag inverts
  14982. when changing from ADD to SUB and vice versa }
  14983. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14984. GetNextInstruction(p, hp1) then
  14985. begin
  14986. TransferUsedRegs(TmpUsedRegs);
  14987. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14988. hp2 := hp1;
  14989. { Scan ahead to check if everything's safe }
  14990. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14991. begin
  14992. if (hp1.typ <> ait_instruction) then
  14993. { Probably unsafe since the flags are still in use }
  14994. Exit;
  14995. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14996. { Stop searching at an unconditional jump }
  14997. Break;
  14998. if not
  14999. (
  15000. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15001. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15002. ) and
  15003. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15004. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15005. Exit;
  15006. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15007. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15008. { Move to the next instruction }
  15009. GetNextInstruction(hp1, hp1);
  15010. end;
  15011. while Assigned(hp2) and (hp2 <> hp1) do
  15012. begin
  15013. NewCond := C_None;
  15014. case taicpu(hp2).condition of
  15015. C_A, C_NBE:
  15016. NewCond := C_BE;
  15017. C_B, C_C, C_NAE:
  15018. NewCond := C_AE;
  15019. C_AE, C_NB, C_NC:
  15020. NewCond := C_B;
  15021. C_BE, C_NA:
  15022. NewCond := C_A;
  15023. else
  15024. { No change needed };
  15025. end;
  15026. if NewCond <> C_None then
  15027. begin
  15028. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15029. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15030. taicpu(hp2).condition := NewCond;
  15031. end
  15032. else
  15033. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15034. begin
  15035. { Because of the flipping of the carry bit, to ensure
  15036. the operation remains equivalent, ADC becomes SBB
  15037. and vice versa, and the constant is not-inverted.
  15038. If multiple ADCs or SBBs appear in a row, each one
  15039. changed causes the carry bit to invert, so they all
  15040. need to be flipped }
  15041. if taicpu(hp2).opcode = A_ADC then
  15042. SecondOpposite := A_SBB
  15043. else
  15044. SecondOpposite := A_ADC;
  15045. if taicpu(hp2).oper[0]^.typ <> top_const then
  15046. { Should have broken out of this optimisation already }
  15047. InternalError(2021112901);
  15048. 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]^) + ' -> ' +
  15049. 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);
  15050. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15051. taicpu(hp2).opcode := SecondOpposite;
  15052. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15053. end;
  15054. { Move to the next instruction }
  15055. GetNextInstruction(hp2, hp2);
  15056. end;
  15057. if (hp2 <> hp1) then
  15058. InternalError(2021111501);
  15059. end;
  15060. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15061. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15062. taicpu(p).opcode := Opposite;
  15063. taicpu(p).oper[0]^.val := -128;
  15064. { No further optimisations can be made on this instruction, so move
  15065. onto the next one to save time }
  15066. p := tai(p.Next);
  15067. UpdateUsedRegs(p);
  15068. Result := True;
  15069. Exit;
  15070. end;
  15071. { Detect:
  15072. add/sub %reg2,(dest)
  15073. add/sub x, (dest)
  15074. (dest can be a register or a reference)
  15075. Swap the instructions to minimise a pipeline stall. This reverses the
  15076. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15077. optimisations could be made.
  15078. }
  15079. if (taicpu(p).oper[0]^.typ = top_reg) and
  15080. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15081. (
  15082. (
  15083. (taicpu(p).oper[1]^.typ = top_reg) and
  15084. { We can try searching further ahead if we're writing to a register }
  15085. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15086. ) or
  15087. (
  15088. (taicpu(p).oper[1]^.typ = top_ref) and
  15089. GetNextInstruction(p, hp1)
  15090. )
  15091. ) and
  15092. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15093. (taicpu(hp1).oper[0]^.typ = top_const) and
  15094. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15095. begin
  15096. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15097. TransferUsedRegs(TmpUsedRegs);
  15098. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15099. hp2 := p;
  15100. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15101. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15102. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15103. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15104. begin
  15105. asml.remove(hp1);
  15106. asml.InsertBefore(hp1, p);
  15107. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15108. Result := True;
  15109. end;
  15110. end;
  15111. end;
  15112. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15113. var
  15114. hp1: tai;
  15115. begin
  15116. Result:=false;
  15117. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15118. while GetNextInstruction(p, hp1) and
  15119. TrySwapMovCmp(p, hp1) do
  15120. begin
  15121. if MatchInstruction(hp1, A_MOV, []) then
  15122. begin
  15123. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15124. begin
  15125. { A little hacky, but since CMP doesn't read the flags, only
  15126. modify them, it's safe if they get scrambled by MOV -> XOR }
  15127. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15128. Result := PostPeepholeOptMov(hp1);
  15129. {$ifdef x86_64}
  15130. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15131. { Used to shrink instruction size }
  15132. PostPeepholeOptXor(hp1);
  15133. {$endif x86_64}
  15134. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15135. end
  15136. else
  15137. begin
  15138. Result := PostPeepholeOptMov(hp1);
  15139. {$ifdef x86_64}
  15140. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15141. { Used to shrink instruction size }
  15142. PostPeepholeOptXor(hp1);
  15143. {$endif x86_64}
  15144. end;
  15145. end;
  15146. { Enabling this flag is actually a null operation, but it marks
  15147. the code as 'modified' during this pass }
  15148. Include(OptsToCheck, aoc_ForceNewIteration);
  15149. end;
  15150. { change "cmp $0, %reg" to "test %reg, %reg" }
  15151. if MatchOpType(taicpu(p),top_const,top_reg) and
  15152. (taicpu(p).oper[0]^.val = 0) then
  15153. begin
  15154. taicpu(p).opcode := A_TEST;
  15155. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15156. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15157. Result:=true;
  15158. end;
  15159. end;
  15160. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15161. var
  15162. IsTestConstX, IsValid : Boolean;
  15163. hp1,hp2 : tai;
  15164. begin
  15165. Result:=false;
  15166. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15167. if (taicpu(p).opcode = A_TEST) then
  15168. while GetNextInstruction(p, hp1) and
  15169. TrySwapMovCmp(p, hp1) do
  15170. begin
  15171. if MatchInstruction(hp1, A_MOV, []) then
  15172. begin
  15173. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15174. begin
  15175. { A little hacky, but since TEST doesn't read the flags, only
  15176. modify them, it's safe if they get scrambled by MOV -> XOR }
  15177. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15178. Result := PostPeepholeOptMov(hp1);
  15179. {$ifdef x86_64}
  15180. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15181. { Used to shrink instruction size }
  15182. PostPeepholeOptXor(hp1);
  15183. {$endif x86_64}
  15184. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15185. end
  15186. else
  15187. begin
  15188. Result := PostPeepholeOptMov(hp1);
  15189. {$ifdef x86_64}
  15190. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15191. { Used to shrink instruction size }
  15192. PostPeepholeOptXor(hp1);
  15193. {$endif x86_64}
  15194. end;
  15195. end;
  15196. { Enabling this flag is actually a null operation, but it marks
  15197. the code as 'modified' during this pass }
  15198. Include(OptsToCheck, aoc_ForceNewIteration);
  15199. end;
  15200. { If x is a power of 2 (popcnt = 1), change:
  15201. or $x, %reg/ref
  15202. To:
  15203. bts lb(x), %reg/ref
  15204. }
  15205. if (taicpu(p).opcode = A_OR) and
  15206. IsBTXAcceptable(p) and
  15207. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15208. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15209. (
  15210. { Don't optimise if a test instruction follows }
  15211. not GetNextInstruction(p, hp1) or
  15212. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15213. ) then
  15214. begin
  15215. 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);
  15216. taicpu(p).opcode := A_BTS;
  15217. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15218. Result := True;
  15219. Exit;
  15220. end;
  15221. { If x is a power of 2 (popcnt = 1), change:
  15222. test $x, %reg/ref
  15223. je / sete / cmove (or jne / setne)
  15224. To:
  15225. bt lb(x), %reg/ref
  15226. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15227. }
  15228. if (taicpu(p).opcode = A_TEST) and
  15229. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15230. (taicpu(p).oper[0]^.typ = top_const) and
  15231. (
  15232. (cs_opt_size in current_settings.optimizerswitches) or
  15233. (
  15234. (taicpu(p).oper[1]^.typ = top_reg) and
  15235. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15236. ) or
  15237. (
  15238. (taicpu(p).oper[1]^.typ <> top_reg) and
  15239. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15240. )
  15241. ) and
  15242. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15243. { For sizes less than S_L, the byte size is equal or larger with BT,
  15244. so don't bother optimising }
  15245. (taicpu(p).opsize >= S_L) then
  15246. begin
  15247. IsValid := True;
  15248. { Check the next set of instructions, watching the FLAGS register
  15249. and the conditions used }
  15250. TransferUsedRegs(TmpUsedRegs);
  15251. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15252. hp1 := p;
  15253. hp2 := nil;
  15254. while GetNextInstruction(hp1, hp1) do
  15255. begin
  15256. if not Assigned(hp2) then
  15257. { The first instruction after TEST }
  15258. hp2 := hp1;
  15259. if (hp1.typ <> ait_instruction) then
  15260. begin
  15261. { If the flags are no longer in use, everything is fine }
  15262. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15263. IsValid := False;
  15264. Break;
  15265. end;
  15266. case taicpu(hp1).condition of
  15267. C_None:
  15268. begin
  15269. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15270. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15271. { Something is not quite normal, so play safe and don't change }
  15272. IsValid := False;
  15273. Break;
  15274. end;
  15275. C_E, C_Z, C_NE, C_NZ:
  15276. { This is fine };
  15277. else
  15278. begin
  15279. { Unsupported condition }
  15280. IsValid := False;
  15281. Break;
  15282. end;
  15283. end;
  15284. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15285. end;
  15286. if IsValid then
  15287. begin
  15288. while hp2 <> hp1 do
  15289. begin
  15290. case taicpu(hp2).condition of
  15291. C_Z, C_E:
  15292. taicpu(hp2).condition := C_NC;
  15293. C_NZ, C_NE:
  15294. taicpu(hp2).condition := C_C;
  15295. else
  15296. { Should not get this by this point }
  15297. InternalError(2022110701);
  15298. end;
  15299. GetNextInstruction(hp2, hp2);
  15300. end;
  15301. 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);
  15302. taicpu(p).opcode := A_BT;
  15303. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15304. Result := True;
  15305. Exit;
  15306. end;
  15307. end;
  15308. { removes the line marked with (x) from the sequence
  15309. and/or/xor/add/sub/... $x, %y
  15310. test/or %y, %y | test $-1, %y (x)
  15311. j(n)z _Label
  15312. as the first instruction already adjusts the ZF
  15313. %y operand may also be a reference }
  15314. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15315. MatchOperand(taicpu(p).oper[0]^,-1);
  15316. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15317. GetLastInstruction(p, hp1) and
  15318. (tai(hp1).typ = ait_instruction) and
  15319. GetNextInstruction(p,hp2) and
  15320. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15321. case taicpu(hp1).opcode Of
  15322. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15323. { These two instructions set the zero flag if the result is zero }
  15324. A_POPCNT, A_LZCNT:
  15325. begin
  15326. if (
  15327. { With POPCNT, an input of zero will set the zero flag
  15328. because the population count of zero is zero }
  15329. (taicpu(hp1).opcode = A_POPCNT) and
  15330. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15331. (
  15332. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15333. { Faster than going through the second half of the 'or'
  15334. condition below }
  15335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15336. )
  15337. ) or (
  15338. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15339. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15340. { and in case of carry for A(E)/B(E)/C/NC }
  15341. (
  15342. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15343. (
  15344. (taicpu(hp1).opcode <> A_ADD) and
  15345. (taicpu(hp1).opcode <> A_SUB) and
  15346. (taicpu(hp1).opcode <> A_LZCNT)
  15347. )
  15348. )
  15349. ) then
  15350. begin
  15351. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15352. RemoveCurrentP(p, hp2);
  15353. Result:=true;
  15354. Exit;
  15355. end;
  15356. end;
  15357. A_SHL, A_SAL, A_SHR, A_SAR:
  15358. begin
  15359. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15360. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15361. { therefore, it's only safe to do this optimization for }
  15362. { shifts by a (nonzero) constant }
  15363. (taicpu(hp1).oper[0]^.typ = top_const) and
  15364. (taicpu(hp1).oper[0]^.val <> 0) and
  15365. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15366. { and in case of carry for A(E)/B(E)/C/NC }
  15367. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15368. begin
  15369. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15370. RemoveCurrentP(p, hp2);
  15371. Result:=true;
  15372. Exit;
  15373. end;
  15374. end;
  15375. A_DEC, A_INC, A_NEG:
  15376. begin
  15377. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15378. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15379. { and in case of carry for A(E)/B(E)/C/NC }
  15380. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15381. begin
  15382. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15383. RemoveCurrentP(p, hp2);
  15384. Result:=true;
  15385. Exit;
  15386. end;
  15387. end;
  15388. A_ANDN, A_BZHI:
  15389. begin
  15390. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15391. { Only the zero and sign flags are consistent with what the result is }
  15392. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15393. begin
  15394. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15395. RemoveCurrentP(p, hp2);
  15396. Result:=true;
  15397. Exit;
  15398. end;
  15399. end;
  15400. A_BEXTR:
  15401. begin
  15402. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15403. { Only the zero flag is set }
  15404. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15405. begin
  15406. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15407. RemoveCurrentP(p, hp2);
  15408. Result:=true;
  15409. Exit;
  15410. end;
  15411. end;
  15412. else
  15413. ;
  15414. end; { case }
  15415. { change "test $-1,%reg" into "test %reg,%reg" }
  15416. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15417. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15418. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15419. if MatchInstruction(p, A_OR, []) and
  15420. { Can only match if they're both registers }
  15421. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15422. begin
  15423. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15424. taicpu(p).opcode := A_TEST;
  15425. { No need to set Result to True, as we've done all the optimisations we can }
  15426. end;
  15427. end;
  15428. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15429. var
  15430. hp1,hp3 : tai;
  15431. {$ifndef x86_64}
  15432. hp2 : taicpu;
  15433. {$endif x86_64}
  15434. begin
  15435. Result:=false;
  15436. hp3:=nil;
  15437. {$ifndef x86_64}
  15438. { don't do this on modern CPUs, this really hurts them due to
  15439. broken call/ret pairing }
  15440. if (current_settings.optimizecputype < cpu_Pentium2) and
  15441. not(cs_create_pic in current_settings.moduleswitches) and
  15442. GetNextInstruction(p, hp1) and
  15443. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15444. MatchOpType(taicpu(hp1),top_ref) and
  15445. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15446. begin
  15447. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15448. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15449. InsertLLItem(p.previous, p, hp2);
  15450. taicpu(p).opcode := A_JMP;
  15451. taicpu(p).is_jmp := true;
  15452. RemoveInstruction(hp1);
  15453. Result:=true;
  15454. end
  15455. else
  15456. {$endif x86_64}
  15457. { replace
  15458. call procname
  15459. ret
  15460. by
  15461. jmp procname
  15462. but do it only on level 4 because it destroys stack back traces
  15463. else if the subroutine is marked as no return, remove the ret
  15464. }
  15465. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15466. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15467. GetNextInstruction(p, hp1) and
  15468. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15469. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15470. SetAndTest(hp1,hp3) and
  15471. GetNextInstruction(hp1,hp1) and
  15472. MatchInstruction(hp1,A_RET,[S_NO])
  15473. )
  15474. ) and
  15475. (taicpu(hp1).ops=0) then
  15476. begin
  15477. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15478. { we might destroy stack alignment here if we do not do a call }
  15479. (target_info.stackalign<=sizeof(SizeUInt)) then
  15480. begin
  15481. taicpu(p).opcode := A_JMP;
  15482. taicpu(p).is_jmp := true;
  15483. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15484. end
  15485. else
  15486. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15487. RemoveInstruction(hp1);
  15488. if Assigned(hp3) then
  15489. begin
  15490. AsmL.Remove(hp3);
  15491. AsmL.InsertBefore(hp3,p)
  15492. end;
  15493. Result:=true;
  15494. end;
  15495. end;
  15496. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15497. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15498. begin
  15499. case OpSize of
  15500. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15501. Result := (Val <= $FF) and (Val >= -128);
  15502. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15503. Result := (Val <= $FFFF) and (Val >= -32768);
  15504. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15505. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15506. else
  15507. Result := True;
  15508. end;
  15509. end;
  15510. var
  15511. hp1, hp2 : tai;
  15512. SizeChange: Boolean;
  15513. PreMessage: string;
  15514. begin
  15515. Result := False;
  15516. if (taicpu(p).oper[0]^.typ = top_reg) and
  15517. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15518. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15519. begin
  15520. { Change (using movzbl %al,%eax as an example):
  15521. movzbl %al, %eax movzbl %al, %eax
  15522. cmpl x, %eax testl %eax,%eax
  15523. To:
  15524. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15525. movzbl %al, %eax movzbl %al, %eax
  15526. Smaller instruction and minimises pipeline stall as the CPU
  15527. doesn't have to wait for the register to get zero-extended. [Kit]
  15528. Also allow if the smaller of the two registers is being checked,
  15529. as this still removes the false dependency.
  15530. }
  15531. if
  15532. (
  15533. (
  15534. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15535. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15536. ) or (
  15537. { If MatchOperand returns True, they must both be registers }
  15538. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15539. )
  15540. ) and
  15541. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15542. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15543. begin
  15544. 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);
  15545. asml.Remove(hp1);
  15546. asml.InsertBefore(hp1, p);
  15547. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15548. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15549. begin
  15550. taicpu(hp1).opcode := A_TEST;
  15551. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15552. end;
  15553. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15554. case taicpu(p).opsize of
  15555. S_BW, S_BL:
  15556. begin
  15557. SizeChange := taicpu(hp1).opsize <> S_B;
  15558. taicpu(hp1).changeopsize(S_B);
  15559. end;
  15560. S_WL:
  15561. begin
  15562. SizeChange := taicpu(hp1).opsize <> S_W;
  15563. taicpu(hp1).changeopsize(S_W);
  15564. end
  15565. else
  15566. InternalError(2020112701);
  15567. end;
  15568. UpdateUsedRegs(tai(p.Next));
  15569. { Check if the register is used aferwards - if not, we can
  15570. remove the movzx instruction completely }
  15571. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15572. begin
  15573. { Hp1 is a better position than p for debugging purposes }
  15574. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15575. RemoveCurrentp(p, hp1);
  15576. Result := True;
  15577. end;
  15578. if SizeChange then
  15579. DebugMsg(SPeepholeOptimization + PreMessage +
  15580. 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)
  15581. else
  15582. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15583. Exit;
  15584. end;
  15585. { Change (using movzwl %ax,%eax as an example):
  15586. movzwl %ax, %eax
  15587. movb %al, (dest) (Register is smaller than read register in movz)
  15588. To:
  15589. movb %al, (dest) (Move one back to avoid a false dependency)
  15590. movzwl %ax, %eax
  15591. }
  15592. if (taicpu(hp1).opcode = A_MOV) and
  15593. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15594. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15595. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15596. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15597. begin
  15598. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15599. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15600. asml.Remove(hp1);
  15601. asml.InsertBefore(hp1, p);
  15602. if taicpu(hp1).oper[1]^.typ = top_reg then
  15603. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15604. { Check if the register is used aferwards - if not, we can
  15605. remove the movzx instruction completely }
  15606. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15607. begin
  15608. { Hp1 is a better position than p for debugging purposes }
  15609. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15610. RemoveCurrentp(p, hp1);
  15611. Result := True;
  15612. end;
  15613. Exit;
  15614. end;
  15615. end;
  15616. end;
  15617. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15618. var
  15619. hp1: tai;
  15620. {$ifdef x86_64}
  15621. PreMessage, RegName: string;
  15622. {$endif x86_64}
  15623. begin
  15624. Result := False;
  15625. { If x is a power of 2 (popcnt = 1), change:
  15626. xor $x, %reg/ref
  15627. To:
  15628. btc lb(x), %reg/ref
  15629. }
  15630. if IsBTXAcceptable(p) and
  15631. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15632. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15633. (
  15634. { Don't optimise if a test instruction follows }
  15635. not GetNextInstruction(p, hp1) or
  15636. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15637. ) then
  15638. begin
  15639. 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);
  15640. taicpu(p).opcode := A_BTC;
  15641. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15642. Result := True;
  15643. Exit;
  15644. end;
  15645. {$ifdef x86_64}
  15646. { Code size reduction by J. Gareth "Kit" Moreton }
  15647. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15648. as this removes the REX prefix }
  15649. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15650. Exit;
  15651. if taicpu(p).oper[0]^.typ <> top_reg then
  15652. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15653. InternalError(2018011500);
  15654. case taicpu(p).opsize of
  15655. S_Q:
  15656. begin
  15657. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15658. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15659. { The actual optimization }
  15660. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15661. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15662. taicpu(p).changeopsize(S_L);
  15663. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15664. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15665. end;
  15666. else
  15667. ;
  15668. end;
  15669. {$endif x86_64}
  15670. end;
  15671. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15672. var
  15673. XReg: TRegister;
  15674. begin
  15675. Result := False;
  15676. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15677. Smaller encoding and slightly faster on some platforms (also works for
  15678. ZMM-sized registers) }
  15679. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15680. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15681. begin
  15682. XReg := taicpu(p).oper[0]^.reg;
  15683. if (taicpu(p).oper[1]^.reg = XReg) then
  15684. begin
  15685. taicpu(p).changeopsize(S_XMM);
  15686. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15687. if (cs_opt_size in current_settings.optimizerswitches) then
  15688. begin
  15689. { Change input registers to %xmm0 to reduce size. Note that
  15690. there's a risk of a false dependency doing this, so only
  15691. optimise for size here }
  15692. XReg := NR_XMM0;
  15693. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15694. end
  15695. else
  15696. begin
  15697. setsubreg(XReg, R_SUBMMX);
  15698. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15699. end;
  15700. taicpu(p).oper[0]^.reg := XReg;
  15701. taicpu(p).oper[1]^.reg := XReg;
  15702. Result := True;
  15703. end;
  15704. end;
  15705. end;
  15706. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15707. var
  15708. OperIdx: Integer;
  15709. begin
  15710. for OperIdx := 0 to p.ops - 1 do
  15711. if p.oper[OperIdx]^.typ = top_ref then
  15712. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15713. end;
  15714. end.