aoptx86.pas 684 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  957. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  958. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  959. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  960. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  961. R_SUBFLAGCARRY:
  962. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  963. R_SUBFLAGPARITY:
  964. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  965. R_SUBFLAGAUXILIARY:
  966. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  967. R_SUBFLAGZERO:
  968. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  969. R_SUBFLAGSIGN:
  970. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  971. R_SUBFLAGOVERFLOW:
  972. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  973. R_SUBFLAGINTERRUPT:
  974. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  975. R_SUBFLAGDIRECTION:
  976. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  977. else
  978. internalerror(2017042602);
  979. end;
  980. exit;
  981. end;
  982. case taicpu(p1).opcode of
  983. A_CALL:
  984. { We could potentially set Result to False if the register in
  985. question is non-volatile for the subroutine's calling convention,
  986. but this would require detecting the calling convention in use and
  987. also assuming that the routine doesn't contain malformed assembly
  988. language, for example... so it could only be done under -O4 as it
  989. would be considered a side-effect. [Kit] }
  990. Result := True;
  991. A_MOVSD:
  992. { special handling for SSE MOVSD }
  993. if (taicpu(p1).ops>0) then
  994. begin
  995. if taicpu(p1).ops<>2 then
  996. internalerror(2017042703);
  997. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  998. end;
  999. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1000. so fix it here (FK)
  1001. }
  1002. A_VMOVSS,
  1003. A_VMOVSD:
  1004. begin
  1005. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1006. exit;
  1007. end;
  1008. A_IMUL:
  1009. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1010. else
  1011. ;
  1012. end;
  1013. if Result then
  1014. exit;
  1015. with insprop[taicpu(p1).opcode] do
  1016. begin
  1017. if getregtype(reg)=R_INTREGISTER then
  1018. begin
  1019. case getsupreg(reg) of
  1020. RS_EAX:
  1021. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_ECX:
  1027. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. RS_EDX:
  1033. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1034. begin
  1035. Result := True;
  1036. exit
  1037. end;
  1038. RS_EBX:
  1039. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1040. begin
  1041. Result := True;
  1042. exit
  1043. end;
  1044. RS_ESP:
  1045. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1046. begin
  1047. Result := True;
  1048. exit
  1049. end;
  1050. RS_EBP:
  1051. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1052. begin
  1053. Result := True;
  1054. exit
  1055. end;
  1056. RS_ESI:
  1057. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1058. begin
  1059. Result := True;
  1060. exit
  1061. end;
  1062. RS_EDI:
  1063. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1064. begin
  1065. Result := True;
  1066. exit
  1067. end;
  1068. end;
  1069. end;
  1070. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1071. if (WriteOps[OperIdx]*Ch<>[]) and
  1072. { The register doesn't get modified inside a reference }
  1073. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1074. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1075. begin
  1076. Result := true;
  1077. exit
  1078. end;
  1079. end;
  1080. end;
  1081. {$ifdef DEBUG_AOPTCPU}
  1082. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1083. begin
  1084. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1085. end;
  1086. function debug_tostr(i: tcgint): string; inline;
  1087. begin
  1088. Result := tostr(i);
  1089. end;
  1090. function debug_hexstr(i: tcgint): string;
  1091. begin
  1092. Result := '0x';
  1093. case i of
  1094. 0..$FF:
  1095. Result := Result + hexstr(i, 2);
  1096. $100..$FFFF:
  1097. Result := Result + hexstr(i, 4);
  1098. $10000..$FFFFFF:
  1099. Result := Result + hexstr(i, 6);
  1100. $1000000..$FFFFFFFF:
  1101. Result := Result + hexstr(i, 8);
  1102. else
  1103. Result := Result + hexstr(i, 16);
  1104. end;
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '%' + std_regname(r);
  1109. end;
  1110. { Debug output function - creates a string representation of an operator }
  1111. function debug_operstr(oper: TOper): string;
  1112. begin
  1113. case oper.typ of
  1114. top_const:
  1115. Result := '$' + debug_tostr(oper.val);
  1116. top_reg:
  1117. Result := debug_regname(oper.reg);
  1118. top_ref:
  1119. begin
  1120. if oper.ref^.offset <> 0 then
  1121. Result := debug_tostr(oper.ref^.offset) + '('
  1122. else
  1123. Result := '(';
  1124. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1125. begin
  1126. Result := Result + debug_regname(oper.ref^.base);
  1127. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1128. Result := Result + ',' + debug_regname(oper.ref^.index);
  1129. end
  1130. else
  1131. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1132. Result := Result + debug_regname(oper.ref^.index);
  1133. if (oper.ref^.scalefactor > 1) then
  1134. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1135. else
  1136. Result := Result + ')';
  1137. end;
  1138. else
  1139. Result := '[UNKNOWN]';
  1140. end;
  1141. end;
  1142. function debug_op2str(opcode: tasmop): string; inline;
  1143. begin
  1144. Result := std_op2str[opcode];
  1145. end;
  1146. function debug_opsize2str(opsize: topsize): string; inline;
  1147. begin
  1148. Result := gas_opsize2str[opsize];
  1149. end;
  1150. {$else DEBUG_AOPTCPU}
  1151. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1152. begin
  1153. end;
  1154. function debug_tostr(i: tcgint): string; inline;
  1155. begin
  1156. Result := '';
  1157. end;
  1158. function debug_hexstr(i: tcgint): string; inline;
  1159. begin
  1160. Result := '';
  1161. end;
  1162. function debug_regname(r: TRegister): string; inline;
  1163. begin
  1164. Result := '';
  1165. end;
  1166. function debug_operstr(oper: TOper): string; inline;
  1167. begin
  1168. Result := '';
  1169. end;
  1170. function debug_op2str(opcode: tasmop): string; inline;
  1171. begin
  1172. Result := '';
  1173. end;
  1174. function debug_opsize2str(opsize: topsize): string; inline;
  1175. begin
  1176. Result := '';
  1177. end;
  1178. {$endif DEBUG_AOPTCPU}
  1179. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1180. begin
  1181. {$ifdef x86_64}
  1182. { Always fine on x86-64 }
  1183. Result := True;
  1184. {$else x86_64}
  1185. Result :=
  1186. {$ifdef i8086}
  1187. (current_settings.cputype >= cpu_386) and
  1188. {$endif i8086}
  1189. (
  1190. { Always accept if optimising for size }
  1191. (cs_opt_size in current_settings.optimizerswitches) or
  1192. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1193. (current_settings.optimizecputype >= cpu_Pentium2)
  1194. );
  1195. {$endif x86_64}
  1196. end;
  1197. { Attempts to allocate a volatile integer register for use between p and hp,
  1198. using AUsedRegs for the current register usage information. Returns NR_NO
  1199. if no free register could be found }
  1200. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1201. var
  1202. RegSet: TCPURegisterSet;
  1203. CurrentSuperReg: Integer;
  1204. CurrentReg: TRegister;
  1205. Currentp: tai;
  1206. Breakout: Boolean;
  1207. begin
  1208. Result := NR_NO;
  1209. RegSet :=
  1210. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1211. current_procinfo.saved_regs_int;
  1212. (*
  1213. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1214. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1215. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1216. *)
  1217. for CurrentSuperReg in RegSet do
  1218. begin
  1219. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1220. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1221. {$if defined(i386) or defined(i8086)}
  1222. { If the target size is 8-bit, make sure we can actually encode it }
  1223. and (
  1224. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1225. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1226. )
  1227. {$endif i386 or i8086}
  1228. then
  1229. begin
  1230. Currentp := p;
  1231. Breakout := False;
  1232. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1233. begin
  1234. case Currentp.typ of
  1235. ait_instruction:
  1236. begin
  1237. if RegInInstruction(CurrentReg, Currentp) then
  1238. begin
  1239. Breakout := True;
  1240. Break;
  1241. end;
  1242. { Cannot allocate across an unconditional jump }
  1243. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1244. Exit;
  1245. end;
  1246. ait_marker:
  1247. { Don't try anything more if a marker is hit }
  1248. Exit;
  1249. ait_regalloc:
  1250. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1251. begin
  1252. Breakout := True;
  1253. Break;
  1254. end;
  1255. else
  1256. ;
  1257. end;
  1258. end;
  1259. if Breakout then
  1260. { Try the next register }
  1261. Continue;
  1262. { We have a free register available }
  1263. Result := CurrentReg;
  1264. if not DontAlloc then
  1265. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1266. Exit;
  1267. end;
  1268. end;
  1269. end;
  1270. { Attempts to allocate a volatile MM register for use between p and hp,
  1271. using AUsedRegs for the current register usage information. Returns NR_NO
  1272. if no free register could be found }
  1273. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1274. var
  1275. RegSet: TCPURegisterSet;
  1276. CurrentSuperReg: Integer;
  1277. CurrentReg: TRegister;
  1278. Currentp: tai;
  1279. Breakout: Boolean;
  1280. begin
  1281. Result := NR_NO;
  1282. RegSet :=
  1283. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1284. current_procinfo.saved_regs_mm;
  1285. for CurrentSuperReg in RegSet do
  1286. begin
  1287. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1288. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1289. begin
  1290. Currentp := p;
  1291. Breakout := False;
  1292. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1293. begin
  1294. case Currentp.typ of
  1295. ait_instruction:
  1296. begin
  1297. if RegInInstruction(CurrentReg, Currentp) then
  1298. begin
  1299. Breakout := True;
  1300. Break;
  1301. end;
  1302. { Cannot allocate across an unconditional jump }
  1303. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1304. Exit;
  1305. end;
  1306. ait_marker:
  1307. { Don't try anything more if a marker is hit }
  1308. Exit;
  1309. ait_regalloc:
  1310. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1311. begin
  1312. Breakout := True;
  1313. Break;
  1314. end;
  1315. else
  1316. ;
  1317. end;
  1318. end;
  1319. if Breakout then
  1320. { Try the next register }
  1321. Continue;
  1322. { We have a free register available }
  1323. Result := CurrentReg;
  1324. if not DontAlloc then
  1325. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1326. Exit;
  1327. end;
  1328. end;
  1329. end;
  1330. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1331. begin
  1332. if not SuperRegistersEqual(reg1,reg2) then
  1333. exit(false);
  1334. if getregtype(reg1)<>R_INTREGISTER then
  1335. exit(true); {because SuperRegisterEqual is true}
  1336. case getsubreg(reg1) of
  1337. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1338. higher, it preserves the high bits, so the new value depends on
  1339. reg2's previous value. In other words, it is equivalent to doing:
  1340. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1341. R_SUBL:
  1342. exit(getsubreg(reg2)=R_SUBL);
  1343. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1344. higher, it actually does a:
  1345. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1346. R_SUBH:
  1347. exit(getsubreg(reg2)=R_SUBH);
  1348. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1349. bits of reg2:
  1350. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1351. R_SUBW:
  1352. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1353. { a write to R_SUBD always overwrites every other subregister,
  1354. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1355. R_SUBD,
  1356. R_SUBQ:
  1357. exit(true);
  1358. else
  1359. internalerror(2017042801);
  1360. end;
  1361. end;
  1362. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1363. begin
  1364. if not SuperRegistersEqual(reg1,reg2) then
  1365. exit(false);
  1366. if getregtype(reg1)<>R_INTREGISTER then
  1367. exit(true); {because SuperRegisterEqual is true}
  1368. case getsubreg(reg1) of
  1369. R_SUBL:
  1370. exit(getsubreg(reg2)<>R_SUBH);
  1371. R_SUBH:
  1372. exit(getsubreg(reg2)<>R_SUBL);
  1373. R_SUBW,
  1374. R_SUBD,
  1375. R_SUBQ:
  1376. exit(true);
  1377. else
  1378. internalerror(2017042802);
  1379. end;
  1380. end;
  1381. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1382. var
  1383. hp1 : tai;
  1384. l : TCGInt;
  1385. begin
  1386. result:=false;
  1387. if not(GetNextInstruction(p, hp1)) then
  1388. exit;
  1389. { changes the code sequence
  1390. shr/sar const1, x
  1391. shl const2, x
  1392. to
  1393. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1394. if (taicpu(p).oper[0]^.typ = top_const) and
  1395. MatchInstruction(hp1,A_SHL,[]) and
  1396. (taicpu(hp1).oper[0]^.typ = top_const) and
  1397. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1398. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1399. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1400. begin
  1401. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1402. not(cs_opt_size in current_settings.optimizerswitches) then
  1403. begin
  1404. { shr/sar const1, %reg
  1405. shl const2, %reg
  1406. with const1 > const2 }
  1407. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1408. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1409. taicpu(hp1).opcode := A_AND;
  1410. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1411. case taicpu(p).opsize Of
  1412. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1413. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1414. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1415. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1416. else
  1417. Internalerror(2017050703)
  1418. end;
  1419. end
  1420. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1421. not(cs_opt_size in current_settings.optimizerswitches) then
  1422. begin
  1423. { shr/sar const1, %reg
  1424. shl const2, %reg
  1425. with const1 < const2 }
  1426. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1427. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1428. taicpu(p).opcode := A_AND;
  1429. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1430. case taicpu(p).opsize Of
  1431. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1432. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1433. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1434. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1435. else
  1436. Internalerror(2017050702)
  1437. end;
  1438. end
  1439. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1440. begin
  1441. { shr/sar const1, %reg
  1442. shl const2, %reg
  1443. with const1 = const2 }
  1444. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1445. taicpu(p).opcode := A_AND;
  1446. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1447. case taicpu(p).opsize Of
  1448. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1449. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1450. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1451. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1452. else
  1453. Internalerror(2017050701)
  1454. end;
  1455. RemoveInstruction(hp1);
  1456. end;
  1457. end;
  1458. end;
  1459. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1460. var
  1461. opsize : topsize;
  1462. hp1, hp2 : tai;
  1463. tmpref : treference;
  1464. ShiftValue : Cardinal;
  1465. BaseValue : TCGInt;
  1466. begin
  1467. result:=false;
  1468. opsize:=taicpu(p).opsize;
  1469. { changes certain "imul const, %reg"'s to lea sequences }
  1470. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1471. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1472. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1473. if (taicpu(p).oper[0]^.val = 1) then
  1474. if (taicpu(p).ops = 2) then
  1475. { remove "imul $1, reg" }
  1476. begin
  1477. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1478. Result := RemoveCurrentP(p);
  1479. end
  1480. else
  1481. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1482. begin
  1483. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1484. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1485. asml.InsertAfter(hp1, p);
  1486. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1487. RemoveCurrentP(p, hp1);
  1488. Result := True;
  1489. end
  1490. else if ((taicpu(p).ops <= 2) or
  1491. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1492. not(cs_opt_size in current_settings.optimizerswitches) and
  1493. (not(GetNextInstruction(p, hp1)) or
  1494. not((tai(hp1).typ = ait_instruction) and
  1495. ((taicpu(hp1).opcode=A_Jcc) and
  1496. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1497. begin
  1498. {
  1499. imul X, reg1, reg2 to
  1500. lea (reg1,reg1,Y), reg2
  1501. shl ZZ,reg2
  1502. imul XX, reg1 to
  1503. lea (reg1,reg1,YY), reg1
  1504. shl ZZ,reg2
  1505. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1506. it does not exist as a separate optimization target in FPC though.
  1507. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1508. at most two zeros
  1509. }
  1510. reference_reset(tmpref,1,[]);
  1511. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1512. begin
  1513. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1514. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1515. TmpRef.base := taicpu(p).oper[1]^.reg;
  1516. TmpRef.index := taicpu(p).oper[1]^.reg;
  1517. if not(BaseValue in [3,5,9]) then
  1518. Internalerror(2018110101);
  1519. TmpRef.ScaleFactor := BaseValue-1;
  1520. if (taicpu(p).ops = 2) then
  1521. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1522. else
  1523. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1524. AsmL.InsertAfter(hp1,p);
  1525. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1526. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1527. RemoveCurrentP(p, hp1);
  1528. if ShiftValue>0 then
  1529. begin
  1530. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1531. AsmL.InsertAfter(hp2,hp1);
  1532. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1533. end;
  1534. Result := True;
  1535. end;
  1536. end;
  1537. end;
  1538. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1539. begin
  1540. Result := False;
  1541. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1542. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1543. begin
  1544. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1545. taicpu(p).opcode := A_MOV;
  1546. Result := True;
  1547. end;
  1548. end;
  1549. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1550. var
  1551. p: taicpu absolute hp; { Implicit typecast }
  1552. i: Integer;
  1553. begin
  1554. Result := False;
  1555. if not assigned(hp) or
  1556. (hp.typ <> ait_instruction) then
  1557. Exit;
  1558. Prefetch(insprop[p.opcode]);
  1559. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1560. with insprop[p.opcode] do
  1561. begin
  1562. case getsubreg(reg) of
  1563. R_SUBW,R_SUBD,R_SUBQ:
  1564. Result:=
  1565. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1566. uncommon flags are checked first }
  1567. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1568. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1569. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1570. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1571. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1572. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1573. R_SUBFLAGCARRY:
  1574. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1575. R_SUBFLAGPARITY:
  1576. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1577. R_SUBFLAGAUXILIARY:
  1578. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1579. R_SUBFLAGZERO:
  1580. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1581. R_SUBFLAGSIGN:
  1582. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1583. R_SUBFLAGOVERFLOW:
  1584. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1585. R_SUBFLAGINTERRUPT:
  1586. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1587. R_SUBFLAGDIRECTION:
  1588. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1589. else
  1590. internalerror(2017050501);
  1591. end;
  1592. exit;
  1593. end;
  1594. { Handle special cases first }
  1595. case p.opcode of
  1596. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1597. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1598. begin
  1599. Result :=
  1600. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1601. (p.oper[1]^.typ = top_reg) and
  1602. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1603. (
  1604. (p.oper[0]^.typ = top_const) or
  1605. (
  1606. (p.oper[0]^.typ = top_reg) and
  1607. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1608. ) or (
  1609. (p.oper[0]^.typ = top_ref) and
  1610. not RegInRef(reg,p.oper[0]^.ref^)
  1611. )
  1612. );
  1613. end;
  1614. A_MUL, A_IMUL:
  1615. Result :=
  1616. (
  1617. (p.ops=3) and { IMUL only }
  1618. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1619. (
  1620. (
  1621. (p.oper[1]^.typ=top_reg) and
  1622. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1623. ) or (
  1624. (p.oper[1]^.typ=top_ref) and
  1625. not RegInRef(reg,p.oper[1]^.ref^)
  1626. )
  1627. )
  1628. ) or (
  1629. (
  1630. (p.ops=1) and
  1631. (
  1632. (
  1633. (
  1634. (p.oper[0]^.typ=top_reg) and
  1635. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1636. )
  1637. ) or (
  1638. (p.oper[0]^.typ=top_ref) and
  1639. not RegInRef(reg,p.oper[0]^.ref^)
  1640. )
  1641. ) and (
  1642. (
  1643. (p.opsize=S_B) and
  1644. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1645. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1646. ) or (
  1647. (p.opsize=S_W) and
  1648. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1649. ) or (
  1650. (p.opsize=S_L) and
  1651. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1652. {$ifdef x86_64}
  1653. ) or (
  1654. (p.opsize=S_Q) and
  1655. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1656. {$endif x86_64}
  1657. )
  1658. )
  1659. )
  1660. );
  1661. A_CBW:
  1662. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1663. {$ifndef x86_64}
  1664. A_LDS:
  1665. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1666. A_LES:
  1667. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1668. {$endif not x86_64}
  1669. A_LFS:
  1670. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1671. A_LGS:
  1672. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1673. A_LSS:
  1674. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1675. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1676. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1677. A_LODSB:
  1678. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1679. A_LODSW:
  1680. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1681. {$ifdef x86_64}
  1682. A_LODSQ:
  1683. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1684. {$endif x86_64}
  1685. A_LODSD:
  1686. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1687. A_FSTSW, A_FNSTSW:
  1688. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1689. else
  1690. begin
  1691. with insprop[p.opcode] do
  1692. begin
  1693. if (
  1694. { xor %reg,%reg etc. is classed as a new value }
  1695. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1696. MatchOpType(p, top_reg, top_reg) and
  1697. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1698. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1699. ) then
  1700. begin
  1701. Result := True;
  1702. Exit;
  1703. end;
  1704. { Make sure the entire register is overwritten }
  1705. if (getregtype(reg) = R_INTREGISTER) then
  1706. begin
  1707. if (p.ops > 0) then
  1708. begin
  1709. if RegInOp(reg, p.oper[0]^) then
  1710. begin
  1711. if (p.oper[0]^.typ = top_ref) then
  1712. begin
  1713. if RegInRef(reg, p.oper[0]^.ref^) then
  1714. begin
  1715. Result := False;
  1716. Exit;
  1717. end;
  1718. end
  1719. else if (p.oper[0]^.typ = top_reg) then
  1720. begin
  1721. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1722. begin
  1723. Result := False;
  1724. Exit;
  1725. end
  1726. else if ([Ch_WOp1]*Ch<>[]) then
  1727. begin
  1728. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1729. Result := True
  1730. else
  1731. begin
  1732. Result := False;
  1733. Exit;
  1734. end;
  1735. end;
  1736. end;
  1737. end;
  1738. if (p.ops > 1) then
  1739. begin
  1740. if RegInOp(reg, p.oper[1]^) then
  1741. begin
  1742. if (p.oper[1]^.typ = top_ref) then
  1743. begin
  1744. if RegInRef(reg, p.oper[1]^.ref^) then
  1745. begin
  1746. Result := False;
  1747. Exit;
  1748. end;
  1749. end
  1750. else if (p.oper[1]^.typ = top_reg) then
  1751. begin
  1752. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1753. begin
  1754. Result := False;
  1755. Exit;
  1756. end
  1757. else if ([Ch_WOp2]*Ch<>[]) then
  1758. begin
  1759. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1760. Result := True
  1761. else
  1762. begin
  1763. Result := False;
  1764. Exit;
  1765. end;
  1766. end;
  1767. end;
  1768. end;
  1769. if (p.ops > 2) then
  1770. begin
  1771. if RegInOp(reg, p.oper[2]^) then
  1772. begin
  1773. if (p.oper[2]^.typ = top_ref) then
  1774. begin
  1775. if RegInRef(reg, p.oper[2]^.ref^) then
  1776. begin
  1777. Result := False;
  1778. Exit;
  1779. end;
  1780. end
  1781. else if (p.oper[2]^.typ = top_reg) then
  1782. begin
  1783. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1784. begin
  1785. Result := False;
  1786. Exit;
  1787. end
  1788. else if ([Ch_WOp3]*Ch<>[]) then
  1789. begin
  1790. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1791. Result := True
  1792. else
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end;
  1798. end;
  1799. end;
  1800. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1801. begin
  1802. if (p.oper[3]^.typ = top_ref) then
  1803. begin
  1804. if RegInRef(reg, p.oper[3]^.ref^) then
  1805. begin
  1806. Result := False;
  1807. Exit;
  1808. end;
  1809. end
  1810. else if (p.oper[3]^.typ = top_reg) then
  1811. begin
  1812. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1813. begin
  1814. Result := False;
  1815. Exit;
  1816. end
  1817. else if ([Ch_WOp4]*Ch<>[]) then
  1818. begin
  1819. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1820. Result := True
  1821. else
  1822. begin
  1823. Result := False;
  1824. Exit;
  1825. end;
  1826. end;
  1827. end;
  1828. end;
  1829. end;
  1830. end;
  1831. end;
  1832. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1833. case getsupreg(reg) of
  1834. RS_EAX:
  1835. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1836. begin
  1837. Result := True;
  1838. Exit;
  1839. end;
  1840. RS_ECX:
  1841. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1842. begin
  1843. Result := True;
  1844. Exit;
  1845. end;
  1846. RS_EDX:
  1847. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1848. begin
  1849. Result := True;
  1850. Exit;
  1851. end;
  1852. RS_EBX:
  1853. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1854. begin
  1855. Result := True;
  1856. Exit;
  1857. end;
  1858. RS_ESP:
  1859. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1860. begin
  1861. Result := True;
  1862. Exit;
  1863. end;
  1864. RS_EBP:
  1865. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1866. begin
  1867. Result := True;
  1868. Exit;
  1869. end;
  1870. RS_ESI:
  1871. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1872. begin
  1873. Result := True;
  1874. Exit;
  1875. end;
  1876. RS_EDI:
  1877. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1878. begin
  1879. Result := True;
  1880. Exit;
  1881. end;
  1882. else
  1883. ;
  1884. end;
  1885. end;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1891. var
  1892. hp2,hp3 : tai;
  1893. begin
  1894. { some x86-64 issue a NOP before the real exit code }
  1895. if MatchInstruction(p,A_NOP,[]) then
  1896. GetNextInstruction(p,p);
  1897. result:=assigned(p) and (p.typ=ait_instruction) and
  1898. ((taicpu(p).opcode = A_RET) or
  1899. ((taicpu(p).opcode=A_LEAVE) and
  1900. GetNextInstruction(p,hp2) and
  1901. MatchInstruction(hp2,A_RET,[S_NO])
  1902. ) or
  1903. (((taicpu(p).opcode=A_LEA) and
  1904. MatchOpType(taicpu(p),top_ref,top_reg) and
  1905. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1906. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1907. ) and
  1908. GetNextInstruction(p,hp2) and
  1909. MatchInstruction(hp2,A_RET,[S_NO])
  1910. ) or
  1911. ((((taicpu(p).opcode=A_MOV) and
  1912. MatchOpType(taicpu(p),top_reg,top_reg) and
  1913. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1914. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1915. ((taicpu(p).opcode=A_LEA) and
  1916. MatchOpType(taicpu(p),top_ref,top_reg) and
  1917. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1918. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1919. )
  1920. ) and
  1921. GetNextInstruction(p,hp2) and
  1922. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1923. MatchOpType(taicpu(hp2),top_reg) and
  1924. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1925. GetNextInstruction(hp2,hp3) and
  1926. MatchInstruction(hp3,A_RET,[S_NO])
  1927. )
  1928. );
  1929. end;
  1930. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1931. begin
  1932. isFoldableArithOp := False;
  1933. case hp1.opcode of
  1934. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1935. isFoldableArithOp :=
  1936. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1937. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1938. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1939. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1940. (taicpu(hp1).oper[1]^.reg = reg);
  1941. A_INC,A_DEC,A_NEG,A_NOT:
  1942. isFoldableArithOp :=
  1943. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1944. (taicpu(hp1).oper[0]^.reg = reg);
  1945. else
  1946. ;
  1947. end;
  1948. end;
  1949. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1950. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1951. var
  1952. hp2: tai;
  1953. begin
  1954. hp2 := p;
  1955. repeat
  1956. hp2 := tai(hp2.previous);
  1957. if assigned(hp2) and
  1958. (hp2.typ = ait_regalloc) and
  1959. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1960. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1961. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1962. begin
  1963. RemoveInstruction(hp2);
  1964. break;
  1965. end;
  1966. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1967. end;
  1968. begin
  1969. case current_procinfo.procdef.returndef.typ of
  1970. arraydef,recorddef,pointerdef,
  1971. stringdef,enumdef,procdef,objectdef,errordef,
  1972. filedef,setdef,procvardef,
  1973. classrefdef,forwarddef:
  1974. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1975. orddef:
  1976. if current_procinfo.procdef.returndef.size <> 0 then
  1977. begin
  1978. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1979. { for int64/qword }
  1980. if current_procinfo.procdef.returndef.size = 8 then
  1981. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1982. end;
  1983. else
  1984. ;
  1985. end;
  1986. end;
  1987. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1988. var
  1989. hp1,hp2 : tai;
  1990. begin
  1991. result:=false;
  1992. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1993. begin
  1994. { vmova* reg1,reg1
  1995. =>
  1996. <nop> }
  1997. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  1998. begin
  1999. RemoveCurrentP(p);
  2000. result:=true;
  2001. exit;
  2002. end;
  2003. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2004. begin
  2005. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2006. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2007. begin
  2008. { vmova* reg1,reg2
  2009. vmova* reg2,reg3
  2010. dealloc reg2
  2011. =>
  2012. vmova* reg1,reg3 }
  2013. TransferUsedRegs(TmpUsedRegs);
  2014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2015. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2016. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2017. begin
  2018. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2019. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2020. RemoveInstruction(hp1);
  2021. result:=true;
  2022. exit;
  2023. end;
  2024. { special case:
  2025. vmova* reg1,<op>
  2026. vmova* <op>,reg1
  2027. =>
  2028. vmova* reg1,<op> }
  2029. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2030. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2031. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2032. ) then
  2033. begin
  2034. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2035. RemoveInstruction(hp1);
  2036. result:=true;
  2037. exit;
  2038. end
  2039. end
  2040. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2041. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2042. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2043. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2044. ) and
  2045. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2046. begin
  2047. { vmova* reg1,reg2
  2048. vmovs* reg2,<op>
  2049. dealloc reg2
  2050. =>
  2051. vmovs* reg1,reg3 }
  2052. TransferUsedRegs(TmpUsedRegs);
  2053. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2054. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2055. begin
  2056. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2057. taicpu(p).opcode:=taicpu(hp1).opcode;
  2058. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2059. RemoveInstruction(hp1);
  2060. result:=true;
  2061. exit;
  2062. end
  2063. end;
  2064. end;
  2065. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2066. begin
  2067. if MatchInstruction(hp1,[A_VFMADDPD,
  2068. A_VFMADD132PD,
  2069. A_VFMADD132PS,
  2070. A_VFMADD132SD,
  2071. A_VFMADD132SS,
  2072. A_VFMADD213PD,
  2073. A_VFMADD213PS,
  2074. A_VFMADD213SD,
  2075. A_VFMADD213SS,
  2076. A_VFMADD231PD,
  2077. A_VFMADD231PS,
  2078. A_VFMADD231SD,
  2079. A_VFMADD231SS,
  2080. A_VFMADDSUB132PD,
  2081. A_VFMADDSUB132PS,
  2082. A_VFMADDSUB213PD,
  2083. A_VFMADDSUB213PS,
  2084. A_VFMADDSUB231PD,
  2085. A_VFMADDSUB231PS,
  2086. A_VFMSUB132PD,
  2087. A_VFMSUB132PS,
  2088. A_VFMSUB132SD,
  2089. A_VFMSUB132SS,
  2090. A_VFMSUB213PD,
  2091. A_VFMSUB213PS,
  2092. A_VFMSUB213SD,
  2093. A_VFMSUB213SS,
  2094. A_VFMSUB231PD,
  2095. A_VFMSUB231PS,
  2096. A_VFMSUB231SD,
  2097. A_VFMSUB231SS,
  2098. A_VFMSUBADD132PD,
  2099. A_VFMSUBADD132PS,
  2100. A_VFMSUBADD213PD,
  2101. A_VFMSUBADD213PS,
  2102. A_VFMSUBADD231PD,
  2103. A_VFMSUBADD231PS,
  2104. A_VFNMADD132PD,
  2105. A_VFNMADD132PS,
  2106. A_VFNMADD132SD,
  2107. A_VFNMADD132SS,
  2108. A_VFNMADD213PD,
  2109. A_VFNMADD213PS,
  2110. A_VFNMADD213SD,
  2111. A_VFNMADD213SS,
  2112. A_VFNMADD231PD,
  2113. A_VFNMADD231PS,
  2114. A_VFNMADD231SD,
  2115. A_VFNMADD231SS,
  2116. A_VFNMSUB132PD,
  2117. A_VFNMSUB132PS,
  2118. A_VFNMSUB132SD,
  2119. A_VFNMSUB132SS,
  2120. A_VFNMSUB213PD,
  2121. A_VFNMSUB213PS,
  2122. A_VFNMSUB213SD,
  2123. A_VFNMSUB213SS,
  2124. A_VFNMSUB231PD,
  2125. A_VFNMSUB231PS,
  2126. A_VFNMSUB231SD,
  2127. A_VFNMSUB231SS],[S_NO]) and
  2128. { we mix single and double opperations here because we assume that the compiler
  2129. generates vmovapd only after double operations and vmovaps only after single operations }
  2130. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2131. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2132. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2133. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2134. begin
  2135. TransferUsedRegs(TmpUsedRegs);
  2136. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2137. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2138. begin
  2139. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2140. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2141. RemoveCurrentP(p)
  2142. else
  2143. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2144. RemoveInstruction(hp2);
  2145. end;
  2146. end
  2147. else if (hp1.typ = ait_instruction) and
  2148. (((taicpu(p).opcode=A_MOVAPS) and
  2149. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2150. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2151. ((taicpu(p).opcode=A_MOVAPD) and
  2152. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2153. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2154. ) and
  2155. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2156. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2157. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2158. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2159. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2160. { change
  2161. movapX reg,reg2
  2162. addsX/subsX/... reg3, reg2
  2163. movapX reg2,reg
  2164. to
  2165. addsX/subsX/... reg3,reg
  2166. }
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2173. debug_op2str(taicpu(p).opcode)+' '+
  2174. debug_op2str(taicpu(hp1).opcode)+' '+
  2175. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2176. { we cannot eliminate the first move if
  2177. the operations uses the same register for source and dest }
  2178. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2179. { Remember that hp1 is not necessarily the immediate
  2180. next instruction }
  2181. RemoveCurrentP(p);
  2182. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2183. RemoveInstruction(hp2);
  2184. result:=true;
  2185. end;
  2186. end
  2187. else if (hp1.typ = ait_instruction) and
  2188. (((taicpu(p).opcode=A_VMOVAPD) and
  2189. (taicpu(hp1).opcode=A_VCOMISD)) or
  2190. ((taicpu(p).opcode=A_VMOVAPS) and
  2191. ((taicpu(hp1).opcode=A_VCOMISS))
  2192. )
  2193. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2194. { change
  2195. movapX reg,reg1
  2196. vcomisX reg1,reg1
  2197. to
  2198. vcomisX reg,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2208. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2209. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2210. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2211. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2212. RemoveCurrentP(p);
  2213. result:=true;
  2214. exit;
  2215. end;
  2216. end
  2217. end;
  2218. end;
  2219. end;
  2220. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2221. var
  2222. hp1 : tai;
  2223. begin
  2224. result:=false;
  2225. { replace
  2226. V<Op>X %mreg1,%mreg2,%mreg3
  2227. VMovX %mreg3,%mreg4
  2228. dealloc %mreg3
  2229. by
  2230. V<Op>X %mreg1,%mreg2,%mreg4
  2231. ?
  2232. }
  2233. if GetNextInstruction(p,hp1) and
  2234. { we mix single and double operations here because we assume that the compiler
  2235. generates vmovapd only after double operations and vmovaps only after single operations }
  2236. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2237. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2238. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2239. begin
  2240. TransferUsedRegs(TmpUsedRegs);
  2241. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2242. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2243. begin
  2244. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2245. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2246. RemoveInstruction(hp1);
  2247. result:=true;
  2248. end;
  2249. end;
  2250. end;
  2251. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2252. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2253. begin
  2254. Result := False;
  2255. { For safety reasons, only check for exact register matches }
  2256. { Check base register }
  2257. if (ref.base = AOldReg) then
  2258. begin
  2259. ref.base := ANewReg;
  2260. Result := True;
  2261. end;
  2262. { Check index register }
  2263. if (ref.index = AOldReg) then
  2264. begin
  2265. ref.index := ANewReg;
  2266. Result := True;
  2267. end;
  2268. end;
  2269. { Replaces all references to AOldReg in an operand to ANewReg }
  2270. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2271. var
  2272. OldSupReg, NewSupReg: TSuperRegister;
  2273. OldSubReg, NewSubReg: TSubRegister;
  2274. OldRegType: TRegisterType;
  2275. ThisOper: POper;
  2276. begin
  2277. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2278. Result := False;
  2279. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2280. InternalError(2020011801);
  2281. OldSupReg := getsupreg(AOldReg);
  2282. OldSubReg := getsubreg(AOldReg);
  2283. OldRegType := getregtype(AOldReg);
  2284. NewSupReg := getsupreg(ANewReg);
  2285. NewSubReg := getsubreg(ANewReg);
  2286. if OldRegType <> getregtype(ANewReg) then
  2287. InternalError(2020011802);
  2288. if OldSubReg <> NewSubReg then
  2289. InternalError(2020011803);
  2290. case ThisOper^.typ of
  2291. top_reg:
  2292. if (
  2293. (ThisOper^.reg = AOldReg) or
  2294. (
  2295. (OldRegType = R_INTREGISTER) and
  2296. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2297. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2298. (
  2299. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2300. {$ifndef x86_64}
  2301. and (
  2302. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2303. don't have an 8-bit representation }
  2304. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2305. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2306. )
  2307. {$endif x86_64}
  2308. )
  2309. )
  2310. ) then
  2311. begin
  2312. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2313. Result := True;
  2314. end;
  2315. top_ref:
  2316. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2317. Result := True;
  2318. else
  2319. ;
  2320. end;
  2321. end;
  2322. { Replaces all references to AOldReg in an instruction to ANewReg }
  2323. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2324. const
  2325. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2326. var
  2327. OperIdx: Integer;
  2328. begin
  2329. Result := False;
  2330. for OperIdx := 0 to p.ops - 1 do
  2331. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2332. begin
  2333. { The shift and rotate instructions can only use CL }
  2334. if not (
  2335. (OperIdx = 0) and
  2336. { This second condition just helps to avoid unnecessarily
  2337. calling MatchInstruction for 10 different opcodes }
  2338. (p.oper[0]^.reg = NR_CL) and
  2339. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2340. ) then
  2341. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2342. end
  2343. else if p.oper[OperIdx]^.typ = top_ref then
  2344. { It's okay to replace registers in references that get written to }
  2345. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2346. end;
  2347. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2348. begin
  2349. Result :=
  2350. (ref^.index = NR_NO) and
  2351. (
  2352. {$ifdef x86_64}
  2353. (
  2354. (ref^.base = NR_RIP) and
  2355. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2356. ) or
  2357. {$endif x86_64}
  2358. (ref^.refaddr = addr_full) or
  2359. (ref^.base = NR_STACK_POINTER_REG) or
  2360. (ref^.base = current_procinfo.framepointer)
  2361. );
  2362. end;
  2363. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2364. var
  2365. l: asizeint;
  2366. begin
  2367. Result := False;
  2368. { Should have been checked previously }
  2369. if p.opcode <> A_LEA then
  2370. InternalError(2020072501);
  2371. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2372. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2373. not(cs_opt_size in current_settings.optimizerswitches) then
  2374. exit;
  2375. with p.oper[0]^.ref^ do
  2376. begin
  2377. if (base <> p.oper[1]^.reg) or
  2378. (index <> NR_NO) or
  2379. assigned(symbol) then
  2380. exit;
  2381. l:=offset;
  2382. if (l=1) and UseIncDec then
  2383. begin
  2384. p.opcode:=A_INC;
  2385. p.loadreg(0,p.oper[1]^.reg);
  2386. p.ops:=1;
  2387. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2388. end
  2389. else if (l=-1) and UseIncDec then
  2390. begin
  2391. p.opcode:=A_DEC;
  2392. p.loadreg(0,p.oper[1]^.reg);
  2393. p.ops:=1;
  2394. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2395. end
  2396. else
  2397. begin
  2398. if (l<0) and (l<>-2147483648) then
  2399. begin
  2400. p.opcode:=A_SUB;
  2401. p.loadConst(0,-l);
  2402. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2403. end
  2404. else
  2405. begin
  2406. p.opcode:=A_ADD;
  2407. p.loadConst(0,l);
  2408. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2409. end;
  2410. end;
  2411. end;
  2412. Result := True;
  2413. end;
  2414. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2415. var
  2416. CurrentReg, ReplaceReg: TRegister;
  2417. begin
  2418. Result := False;
  2419. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2420. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2421. case hp.opcode of
  2422. A_FSTSW, A_FNSTSW,
  2423. A_IN, A_INS, A_OUT, A_OUTS,
  2424. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2425. { These routines have explicit operands, but they are restricted in
  2426. what they can be (e.g. IN and OUT can only read from AL, AX or
  2427. EAX. }
  2428. Exit;
  2429. A_IMUL:
  2430. begin
  2431. { The 1-operand version writes to implicit registers
  2432. The 2-operand version reads from the first operator, and reads
  2433. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2434. the 3-operand version reads from a register that it doesn't write to
  2435. }
  2436. case hp.ops of
  2437. 1:
  2438. if (
  2439. (
  2440. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2441. ) or
  2442. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2443. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2444. begin
  2445. Result := True;
  2446. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2447. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2448. end;
  2449. 2:
  2450. { Only modify the first parameter }
  2451. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2452. begin
  2453. Result := True;
  2454. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2455. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2456. end;
  2457. 3:
  2458. { Only modify the second parameter }
  2459. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2460. begin
  2461. Result := True;
  2462. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2463. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2464. end;
  2465. else
  2466. InternalError(2020012901);
  2467. end;
  2468. end;
  2469. else
  2470. if (hp.ops > 0) and
  2471. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2472. begin
  2473. Result := True;
  2474. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2475. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2476. end;
  2477. end;
  2478. end;
  2479. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2480. var
  2481. hp2: tai;
  2482. p_SourceReg, p_TargetReg: TRegister;
  2483. begin
  2484. Result := False;
  2485. { Backward optimisation. If we have:
  2486. func. %reg1,%reg2
  2487. mov %reg2,%reg3
  2488. (dealloc %reg2)
  2489. Change to:
  2490. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2491. Perform similar optimisations with 1, 3 and 4-operand instructions
  2492. that only have one output.
  2493. }
  2494. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2495. begin
  2496. p_SourceReg := taicpu(p).oper[0]^.reg;
  2497. p_TargetReg := taicpu(p).oper[1]^.reg;
  2498. TransferUsedRegs(TmpUsedRegs);
  2499. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2500. GetLastInstruction(p, hp2) and
  2501. (hp2.typ = ait_instruction) and
  2502. { Have to make sure it's an instruction that only reads from
  2503. the first operands and only writes (not reads or modifies) to
  2504. the last one; in essence, a pure function such as BSR, POPCNT
  2505. or ANDN }
  2506. (
  2507. (
  2508. (taicpu(hp2).ops = 1) and
  2509. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2510. ) or
  2511. (
  2512. (taicpu(hp2).ops = 2) and
  2513. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2514. ) or
  2515. (
  2516. (taicpu(hp2).ops = 3) and
  2517. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2518. ) or
  2519. (
  2520. (taicpu(hp2).ops = 4) and
  2521. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2522. )
  2523. ) and
  2524. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2525. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2526. begin
  2527. case taicpu(hp2).opcode of
  2528. A_FSTSW, A_FNSTSW,
  2529. A_IN, A_INS, A_OUT, A_OUTS,
  2530. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2531. { These routines have explicit operands, but they are restricted in
  2532. what they can be (e.g. IN and OUT can only read from AL, AX or
  2533. EAX. }
  2534. ;
  2535. else
  2536. begin
  2537. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2538. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2539. if not RegInInstruction(p_TargetReg, hp2) then
  2540. begin
  2541. { Since we're allocating from an earlier point, we
  2542. need to remove the register from the tracking }
  2543. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2544. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2545. end;
  2546. RemoveCurrentp(p, hp1);
  2547. { If the Func was another MOV instruction, we might get
  2548. "mov %reg,%reg" that doesn't get removed in Pass 2
  2549. otherwise, so deal with it here (also do something
  2550. similar with lea (%reg),%reg}
  2551. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2552. begin
  2553. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2554. if p = hp2 then
  2555. RemoveCurrentp(p)
  2556. else
  2557. RemoveInstruction(hp2);
  2558. end;
  2559. Result := True;
  2560. Exit;
  2561. end;
  2562. end;
  2563. end;
  2564. end;
  2565. end;
  2566. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2567. var
  2568. hp1, hp2, hp3: tai;
  2569. DoOptimisation, TempBool: Boolean;
  2570. {$ifdef x86_64}
  2571. NewConst: TCGInt;
  2572. {$endif x86_64}
  2573. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2574. begin
  2575. if taicpu(hp1).opcode = signed_movop then
  2576. begin
  2577. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2578. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2579. end
  2580. else
  2581. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2582. end;
  2583. function TryConstMerge(var p1, p2: tai): Boolean;
  2584. var
  2585. ThisRef: TReference;
  2586. begin
  2587. Result := False;
  2588. ThisRef := taicpu(p2).oper[1]^.ref^;
  2589. { Only permit writes to the stack, since we can guarantee alignment with that }
  2590. if (ThisRef.index = NR_NO) and
  2591. (
  2592. (ThisRef.base = NR_STACK_POINTER_REG) or
  2593. (ThisRef.base = current_procinfo.framepointer)
  2594. ) then
  2595. begin
  2596. case taicpu(p).opsize of
  2597. S_B:
  2598. begin
  2599. { Word writes must be on a 2-byte boundary }
  2600. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2601. begin
  2602. { Reduce offset of second reference to see if it is sequential with the first }
  2603. Dec(ThisRef.offset, 1);
  2604. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2605. begin
  2606. { Make sure the constants aren't represented as a
  2607. negative number, as these won't merge properly }
  2608. taicpu(p1).opsize := S_W;
  2609. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2610. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2611. RemoveInstruction(p2);
  2612. Result := True;
  2613. end;
  2614. end;
  2615. end;
  2616. S_W:
  2617. begin
  2618. { Longword writes must be on a 4-byte boundary }
  2619. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2620. begin
  2621. { Reduce offset of second reference to see if it is sequential with the first }
  2622. Dec(ThisRef.offset, 2);
  2623. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2624. begin
  2625. { Make sure the constants aren't represented as a
  2626. negative number, as these won't merge properly }
  2627. taicpu(p1).opsize := S_L;
  2628. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2629. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2630. RemoveInstruction(p2);
  2631. Result := True;
  2632. end;
  2633. end;
  2634. end;
  2635. {$ifdef x86_64}
  2636. S_L:
  2637. begin
  2638. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2639. see if the constants can be encoded this way. }
  2640. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2641. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2642. { Quadword writes must be on an 8-byte boundary }
  2643. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2644. begin
  2645. { Reduce offset of second reference to see if it is sequential with the first }
  2646. Dec(ThisRef.offset, 4);
  2647. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2648. begin
  2649. { Make sure the constants aren't represented as a
  2650. negative number, as these won't merge properly }
  2651. taicpu(p1).opsize := S_Q;
  2652. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2653. taicpu(p1).oper[0]^.val := NewConst;
  2654. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2655. RemoveInstruction(p2);
  2656. Result := True;
  2657. end;
  2658. end;
  2659. end;
  2660. {$endif x86_64}
  2661. else
  2662. ;
  2663. end;
  2664. end;
  2665. end;
  2666. var
  2667. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2668. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2669. NewSize: topsize; NewOffset: asizeint;
  2670. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2671. SourceRef, TargetRef: TReference;
  2672. MovAligned, MovUnaligned: TAsmOp;
  2673. ThisRef: TReference;
  2674. JumpTracking: TLinkedList;
  2675. begin
  2676. Result:=false;
  2677. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2678. { remove mov reg1,reg1? }
  2679. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2680. then
  2681. begin
  2682. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2683. { take care of the register (de)allocs following p }
  2684. RemoveCurrentP(p, hp1);
  2685. Result:=true;
  2686. exit;
  2687. end;
  2688. { All the next optimisations require a next instruction }
  2689. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2690. Exit;
  2691. { Prevent compiler warnings }
  2692. p_TargetReg := NR_NO;
  2693. if taicpu(p).oper[1]^.typ = top_reg then
  2694. begin
  2695. { Saves on a large number of dereferences }
  2696. p_TargetReg := taicpu(p).oper[1]^.reg;
  2697. { Look for:
  2698. mov %reg1,%reg2
  2699. ??? %reg2,r/m
  2700. Change to:
  2701. mov %reg1,%reg2
  2702. ??? %reg1,r/m
  2703. }
  2704. if taicpu(p).oper[0]^.typ = top_reg then
  2705. begin
  2706. if RegReadByInstruction(p_TargetReg, hp1) and
  2707. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2708. begin
  2709. { A change has occurred, just not in p }
  2710. Result := True;
  2711. TransferUsedRegs(TmpUsedRegs);
  2712. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2713. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2714. { Just in case something didn't get modified (e.g. an
  2715. implicit register) }
  2716. not RegReadByInstruction(p_TargetReg, hp1) then
  2717. begin
  2718. { We can remove the original MOV }
  2719. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2720. RemoveCurrentp(p, hp1);
  2721. { UsedRegs got updated by RemoveCurrentp }
  2722. Result := True;
  2723. Exit;
  2724. end;
  2725. { If we know a MOV instruction has become a null operation, we might as well
  2726. get rid of it now to save time. }
  2727. if (taicpu(hp1).opcode = A_MOV) and
  2728. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2729. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2730. { Just being a register is enough to confirm it's a null operation }
  2731. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2732. begin
  2733. Result := True;
  2734. { Speed-up to reduce a pipeline stall... if we had something like...
  2735. movl %eax,%edx
  2736. movw %dx,%ax
  2737. ... the second instruction would change to movw %ax,%ax, but
  2738. given that it is now %ax that's active rather than %eax,
  2739. penalties might occur due to a partial register write, so instead,
  2740. change it to a MOVZX instruction when optimising for speed.
  2741. }
  2742. if not (cs_opt_size in current_settings.optimizerswitches) and
  2743. IsMOVZXAcceptable and
  2744. (taicpu(hp1).opsize < taicpu(p).opsize)
  2745. {$ifdef x86_64}
  2746. { operations already implicitly set the upper 64 bits to zero }
  2747. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2748. {$endif x86_64}
  2749. then
  2750. begin
  2751. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2752. case taicpu(p).opsize of
  2753. S_W:
  2754. if taicpu(hp1).opsize = S_B then
  2755. taicpu(hp1).opsize := S_BL
  2756. else
  2757. InternalError(2020012911);
  2758. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2759. case taicpu(hp1).opsize of
  2760. S_B:
  2761. taicpu(hp1).opsize := S_BL;
  2762. S_W:
  2763. taicpu(hp1).opsize := S_WL;
  2764. else
  2765. InternalError(2020012912);
  2766. end;
  2767. else
  2768. InternalError(2020012910);
  2769. end;
  2770. taicpu(hp1).opcode := A_MOVZX;
  2771. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2772. end
  2773. else
  2774. begin
  2775. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2776. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2777. RemoveInstruction(hp1);
  2778. { The instruction after what was hp1 is now the immediate next instruction,
  2779. so we can continue to make optimisations if it's present }
  2780. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2781. Exit;
  2782. hp1 := hp2;
  2783. end;
  2784. end;
  2785. end;
  2786. end;
  2787. end;
  2788. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2789. overwrites the original destination register. e.g.
  2790. movl ###,%reg2d
  2791. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2792. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2793. }
  2794. if (taicpu(p).oper[1]^.typ = top_reg) and
  2795. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2796. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2797. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2798. begin
  2799. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2800. begin
  2801. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2802. case taicpu(p).oper[0]^.typ of
  2803. top_const:
  2804. { We have something like:
  2805. movb $x, %regb
  2806. movzbl %regb,%regd
  2807. Change to:
  2808. movl $x, %regd
  2809. }
  2810. begin
  2811. case taicpu(hp1).opsize of
  2812. S_BW:
  2813. begin
  2814. convert_mov_value(A_MOVSX, $FF);
  2815. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2816. taicpu(p).opsize := S_W;
  2817. end;
  2818. S_BL:
  2819. begin
  2820. convert_mov_value(A_MOVSX, $FF);
  2821. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2822. taicpu(p).opsize := S_L;
  2823. end;
  2824. S_WL:
  2825. begin
  2826. convert_mov_value(A_MOVSX, $FFFF);
  2827. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2828. taicpu(p).opsize := S_L;
  2829. end;
  2830. {$ifdef x86_64}
  2831. S_BQ:
  2832. begin
  2833. convert_mov_value(A_MOVSX, $FF);
  2834. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2835. taicpu(p).opsize := S_Q;
  2836. end;
  2837. S_WQ:
  2838. begin
  2839. convert_mov_value(A_MOVSX, $FFFF);
  2840. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2841. taicpu(p).opsize := S_Q;
  2842. end;
  2843. S_LQ:
  2844. begin
  2845. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2846. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2847. taicpu(p).opsize := S_Q;
  2848. end;
  2849. {$endif x86_64}
  2850. else
  2851. { If hp1 was a MOV instruction, it should have been
  2852. optimised already }
  2853. InternalError(2020021001);
  2854. end;
  2855. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2856. RemoveInstruction(hp1);
  2857. Result := True;
  2858. Exit;
  2859. end;
  2860. top_ref:
  2861. begin
  2862. { We have something like:
  2863. movb mem, %regb
  2864. movzbl %regb,%regd
  2865. Change to:
  2866. movzbl mem, %regd
  2867. }
  2868. ThisRef := taicpu(p).oper[0]^.ref^;
  2869. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2870. begin
  2871. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2872. taicpu(hp1).loadref(0, ThisRef);
  2873. { Make sure any registers in the references are properly tracked }
  2874. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2875. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2876. if (ThisRef.index <> NR_NO) then
  2877. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2878. RemoveCurrentP(p, hp1);
  2879. Result := True;
  2880. Exit;
  2881. end;
  2882. end;
  2883. else
  2884. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2885. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2886. Exit;
  2887. end;
  2888. end
  2889. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2890. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2891. optimised }
  2892. else
  2893. begin
  2894. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2895. RemoveCurrentP(p, hp1);
  2896. Result := True;
  2897. Exit;
  2898. end;
  2899. end;
  2900. if (taicpu(hp1).opcode = A_AND) and
  2901. (taicpu(p).oper[1]^.typ = top_reg) and
  2902. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2903. begin
  2904. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2905. begin
  2906. case taicpu(p).opsize of
  2907. S_L:
  2908. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2909. begin
  2910. { Optimize out:
  2911. mov x, %reg
  2912. and ffffffffh, %reg
  2913. }
  2914. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2915. RemoveInstruction(hp1);
  2916. Result:=true;
  2917. exit;
  2918. end;
  2919. S_Q: { TODO: Confirm if this is even possible }
  2920. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2921. begin
  2922. { Optimize out:
  2923. mov x, %reg
  2924. and ffffffffffffffffh, %reg
  2925. }
  2926. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2927. RemoveInstruction(hp1);
  2928. Result:=true;
  2929. exit;
  2930. end;
  2931. else
  2932. ;
  2933. end;
  2934. if (
  2935. (taicpu(p).oper[0]^.typ=top_reg) or
  2936. (
  2937. (taicpu(p).oper[0]^.typ=top_ref) and
  2938. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2939. )
  2940. ) and
  2941. GetNextInstruction(hp1,hp2) and
  2942. MatchInstruction(hp2,A_TEST,[]) and
  2943. (
  2944. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2945. (
  2946. { If the register being tested is smaller than the one
  2947. that received a bitwise AND, permit it if the constant
  2948. fits into the smaller size }
  2949. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2950. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2951. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2952. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2953. (
  2954. (
  2955. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2956. (taicpu(hp1).oper[0]^.val <= $FF)
  2957. ) or
  2958. (
  2959. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2960. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2961. {$ifdef x86_64}
  2962. ) or
  2963. (
  2964. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2965. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2966. {$endif x86_64}
  2967. )
  2968. )
  2969. )
  2970. ) and
  2971. (
  2972. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2973. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2974. ) and
  2975. GetNextInstruction(hp2,hp3) and
  2976. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2977. (taicpu(hp3).condition in [C_E,C_NE]) then
  2978. begin
  2979. TransferUsedRegs(TmpUsedRegs);
  2980. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2981. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2982. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2983. begin
  2984. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2985. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2986. taicpu(hp1).opcode:=A_TEST;
  2987. { Shrink the TEST instruction down to the smallest possible size }
  2988. case taicpu(hp1).oper[0]^.val of
  2989. 0..255:
  2990. if (taicpu(hp1).opsize <> S_B)
  2991. {$ifndef x86_64}
  2992. and (
  2993. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2994. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2995. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2996. )
  2997. {$endif x86_64}
  2998. then
  2999. begin
  3000. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3001. { Only print debug message if the TEST instruction
  3002. is a different size before and after }
  3003. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3004. taicpu(hp1).opsize := S_B;
  3005. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3006. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3007. end;
  3008. 256..65535:
  3009. if (taicpu(hp1).opsize <> S_W) then
  3010. begin
  3011. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3012. { Only print debug message if the TEST instruction
  3013. is a different size before and after }
  3014. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3015. taicpu(hp1).opsize := S_W;
  3016. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3017. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3018. end;
  3019. {$ifdef x86_64}
  3020. 65536..$7FFFFFFF:
  3021. if (taicpu(hp1).opsize <> S_L) then
  3022. begin
  3023. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3024. { Only print debug message if the TEST instruction
  3025. is a different size before and after }
  3026. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3027. taicpu(hp1).opsize := S_L;
  3028. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3029. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3030. end;
  3031. {$endif x86_64}
  3032. else
  3033. ;
  3034. end;
  3035. RemoveInstruction(hp2);
  3036. RemoveCurrentP(p, hp1);
  3037. Result:=true;
  3038. exit;
  3039. end;
  3040. end;
  3041. end
  3042. else if IsMOVZXAcceptable and
  3043. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3044. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3045. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3046. then
  3047. begin
  3048. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3049. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3050. case taicpu(p).opsize of
  3051. S_B:
  3052. if (taicpu(hp1).oper[0]^.val = $ff) then
  3053. begin
  3054. { Convert:
  3055. movb x, %regl movb x, %regl
  3056. andw ffh, %regw andl ffh, %regd
  3057. To:
  3058. movzbw x, %regd movzbl x, %regd
  3059. (Identical registers, just different sizes)
  3060. }
  3061. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3062. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3063. case taicpu(hp1).opsize of
  3064. S_W: NewSize := S_BW;
  3065. S_L: NewSize := S_BL;
  3066. {$ifdef x86_64}
  3067. S_Q: NewSize := S_BQ;
  3068. {$endif x86_64}
  3069. else
  3070. InternalError(2018011510);
  3071. end;
  3072. end
  3073. else
  3074. NewSize := S_NO;
  3075. S_W:
  3076. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3077. begin
  3078. { Convert:
  3079. movw x, %regw
  3080. andl ffffh, %regd
  3081. To:
  3082. movzwl x, %regd
  3083. (Identical registers, just different sizes)
  3084. }
  3085. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3086. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3087. case taicpu(hp1).opsize of
  3088. S_L: NewSize := S_WL;
  3089. {$ifdef x86_64}
  3090. S_Q: NewSize := S_WQ;
  3091. {$endif x86_64}
  3092. else
  3093. InternalError(2018011511);
  3094. end;
  3095. end
  3096. else
  3097. NewSize := S_NO;
  3098. else
  3099. NewSize := S_NO;
  3100. end;
  3101. if NewSize <> S_NO then
  3102. begin
  3103. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3104. { The actual optimization }
  3105. taicpu(p).opcode := A_MOVZX;
  3106. taicpu(p).changeopsize(NewSize);
  3107. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3108. { Safeguard if "and" is followed by a conditional command }
  3109. TransferUsedRegs(TmpUsedRegs);
  3110. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3111. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3112. begin
  3113. { At this point, the "and" command is effectively equivalent to
  3114. "test %reg,%reg". This will be handled separately by the
  3115. Peephole Optimizer. [Kit] }
  3116. DebugMsg(SPeepholeOptimization + PreMessage +
  3117. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3118. end
  3119. else
  3120. begin
  3121. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3122. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3123. RemoveInstruction(hp1);
  3124. end;
  3125. Result := True;
  3126. Exit;
  3127. end;
  3128. end;
  3129. end;
  3130. if (taicpu(hp1).opcode = A_OR) and
  3131. (taicpu(p).oper[1]^.typ = top_reg) and
  3132. MatchOperand(taicpu(p).oper[0]^, 0) and
  3133. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3134. begin
  3135. { mov 0, %reg
  3136. or ###,%reg
  3137. Change to (only if the flags are not used):
  3138. mov ###,%reg
  3139. }
  3140. TransferUsedRegs(TmpUsedRegs);
  3141. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3142. DoOptimisation := True;
  3143. { Even if the flags are used, we might be able to do the optimisation
  3144. if the conditions are predictable }
  3145. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3146. begin
  3147. { Only perform if ### = %reg (the same register) or equal to 0,
  3148. so %reg is guaranteed to still have a value of zero }
  3149. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3150. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3151. begin
  3152. hp2 := hp1;
  3153. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3154. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3155. GetNextInstruction(hp2, hp3) do
  3156. begin
  3157. { Don't continue modifying if the flags state is getting changed }
  3158. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3159. Break;
  3160. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3161. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3162. begin
  3163. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3164. begin
  3165. { Condition is always true }
  3166. case taicpu(hp3).opcode of
  3167. A_Jcc:
  3168. begin
  3169. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3170. { Check for jump shortcuts before we destroy the condition }
  3171. DoJumpOptimizations(hp3, TempBool);
  3172. MakeUnconditional(taicpu(hp3));
  3173. Result := True;
  3174. end;
  3175. A_CMOVcc:
  3176. begin
  3177. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3178. taicpu(hp3).opcode := A_MOV;
  3179. taicpu(hp3).condition := C_None;
  3180. Result := True;
  3181. end;
  3182. A_SETcc:
  3183. begin
  3184. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3185. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3186. taicpu(hp3).opcode := A_MOV;
  3187. taicpu(hp3).ops := 2;
  3188. taicpu(hp3).condition := C_None;
  3189. taicpu(hp3).opsize := S_B;
  3190. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3191. taicpu(hp3).loadconst(0, 1);
  3192. Result := True;
  3193. end;
  3194. else
  3195. InternalError(2021090701);
  3196. end;
  3197. end
  3198. 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
  3199. begin
  3200. { Condition is always false }
  3201. case taicpu(hp3).opcode of
  3202. A_Jcc:
  3203. begin
  3204. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3205. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3206. RemoveInstruction(hp3);
  3207. Result := True;
  3208. { Since hp3 was deleted, hp2 must not be updated }
  3209. Continue;
  3210. end;
  3211. A_CMOVcc:
  3212. begin
  3213. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3214. RemoveInstruction(hp3);
  3215. Result := True;
  3216. { Since hp3 was deleted, hp2 must not be updated }
  3217. Continue;
  3218. end;
  3219. A_SETcc:
  3220. begin
  3221. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3222. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3223. taicpu(hp3).opcode := A_MOV;
  3224. taicpu(hp3).ops := 2;
  3225. taicpu(hp3).condition := C_None;
  3226. taicpu(hp3).opsize := S_B;
  3227. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3228. taicpu(hp3).loadconst(0, 0);
  3229. Result := True;
  3230. end;
  3231. else
  3232. InternalError(2021090702);
  3233. end;
  3234. end
  3235. else
  3236. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3237. DoOptimisation := False;
  3238. end;
  3239. hp2 := hp3;
  3240. end;
  3241. { Flags are still in use - don't optimise }
  3242. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3243. DoOptimisation := False;
  3244. end
  3245. else
  3246. DoOptimisation := False;
  3247. end;
  3248. if DoOptimisation then
  3249. begin
  3250. {$ifdef x86_64}
  3251. { OR only supports 32-bit sign-extended constants for 64-bit
  3252. instructions, so compensate for this if the constant is
  3253. encoded as a value greater than or equal to 2^31 }
  3254. if (taicpu(hp1).opsize = S_Q) and
  3255. (taicpu(hp1).oper[0]^.typ = top_const) and
  3256. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3257. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3258. {$endif x86_64}
  3259. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3260. taicpu(hp1).opcode := A_MOV;
  3261. RemoveCurrentP(p, hp1);
  3262. Result := True;
  3263. Exit;
  3264. end;
  3265. end;
  3266. { Next instruction is also a MOV ? }
  3267. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3268. begin
  3269. if MatchOpType(taicpu(p), top_const, top_ref) and
  3270. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3271. TryConstMerge(p, hp1) then
  3272. begin
  3273. Result := True;
  3274. { In case we have four byte writes in a row, check for 2 more
  3275. right now so we don't have to wait for another iteration of
  3276. pass 1
  3277. }
  3278. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3279. case taicpu(p).opsize of
  3280. S_W:
  3281. begin
  3282. if GetNextInstruction(p, hp1) and
  3283. MatchInstruction(hp1, A_MOV, [S_B]) and
  3284. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3285. GetNextInstruction(hp1, hp2) and
  3286. MatchInstruction(hp2, A_MOV, [S_B]) and
  3287. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3288. { Try to merge the two bytes }
  3289. TryConstMerge(hp1, hp2) then
  3290. { Now try to merge the two words (hp2 will get deleted) }
  3291. TryConstMerge(p, hp1);
  3292. end;
  3293. S_L:
  3294. begin
  3295. { Though this only really benefits x86_64 and not i386, it
  3296. gets a potential optimisation done faster and hence
  3297. reduces the number of times OptPass1MOV is entered }
  3298. if GetNextInstruction(p, hp1) and
  3299. MatchInstruction(hp1, A_MOV, [S_W]) and
  3300. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3301. GetNextInstruction(hp1, hp2) and
  3302. MatchInstruction(hp2, A_MOV, [S_W]) and
  3303. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3304. { Try to merge the two words }
  3305. TryConstMerge(hp1, hp2) then
  3306. { This will always fail on i386, so don't bother
  3307. calling it unless we're doing x86_64 }
  3308. {$ifdef x86_64}
  3309. { Now try to merge the two longwords (hp2 will get deleted) }
  3310. TryConstMerge(p, hp1)
  3311. {$endif x86_64}
  3312. ;
  3313. end;
  3314. else
  3315. ;
  3316. end;
  3317. Exit;
  3318. end;
  3319. if (taicpu(p).oper[1]^.typ = top_reg) and
  3320. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3321. begin
  3322. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3323. TransferUsedRegs(TmpUsedRegs);
  3324. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3325. { we have
  3326. mov x, %treg
  3327. mov %treg, y
  3328. }
  3329. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3330. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3331. { we've got
  3332. mov x, %treg
  3333. mov %treg, y
  3334. with %treg is not used after }
  3335. case taicpu(p).oper[0]^.typ Of
  3336. { top_reg is covered by DeepMOVOpt }
  3337. top_const:
  3338. begin
  3339. { change
  3340. mov const, %treg
  3341. mov %treg, y
  3342. to
  3343. mov const, y
  3344. }
  3345. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3346. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3347. begin
  3348. if taicpu(hp1).oper[1]^.typ=top_reg then
  3349. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3350. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3351. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3352. RemoveInstruction(hp1);
  3353. Result:=true;
  3354. Exit;
  3355. end;
  3356. end;
  3357. top_ref:
  3358. case taicpu(hp1).oper[1]^.typ of
  3359. top_reg:
  3360. begin
  3361. { change
  3362. mov mem, %treg
  3363. mov %treg, %reg
  3364. to
  3365. mov mem, %reg"
  3366. }
  3367. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3368. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3369. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3370. RemoveInstruction(hp1);
  3371. Result:=true;
  3372. Exit;
  3373. end;
  3374. top_ref:
  3375. begin
  3376. {$ifdef x86_64}
  3377. { Look for the following to simplify:
  3378. mov x(mem1), %reg
  3379. mov %reg, y(mem2)
  3380. mov x+8(mem1), %reg
  3381. mov %reg, y+8(mem2)
  3382. Change to:
  3383. movdqu x(mem1), %xmmreg
  3384. movdqu %xmmreg, y(mem2)
  3385. ...but only as long as the memory blocks don't overlap
  3386. }
  3387. SourceRef := taicpu(p).oper[0]^.ref^;
  3388. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3389. if (taicpu(p).opsize = S_Q) and
  3390. GetNextInstruction(hp1, hp2) and
  3391. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3392. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3393. begin
  3394. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3395. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3396. Inc(SourceRef.offset, 8);
  3397. if UseAVX then
  3398. begin
  3399. MovAligned := A_VMOVDQA;
  3400. MovUnaligned := A_VMOVDQU;
  3401. end
  3402. else
  3403. begin
  3404. MovAligned := A_MOVDQA;
  3405. MovUnaligned := A_MOVDQU;
  3406. end;
  3407. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3408. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3409. begin
  3410. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3411. Inc(TargetRef.offset, 8);
  3412. if GetNextInstruction(hp2, hp3) and
  3413. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3414. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3415. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3416. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3417. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3418. begin
  3419. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3420. if NewMMReg <> NR_NO then
  3421. begin
  3422. { Remember that the offsets are 8 ahead }
  3423. if ((SourceRef.offset mod 16) = 8) and
  3424. (
  3425. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3426. (SourceRef.base = current_procinfo.framepointer) or
  3427. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3428. ) then
  3429. taicpu(p).opcode := MovAligned
  3430. else
  3431. taicpu(p).opcode := MovUnaligned;
  3432. taicpu(p).opsize := S_XMM;
  3433. taicpu(p).oper[1]^.reg := NewMMReg;
  3434. if ((TargetRef.offset mod 16) = 8) and
  3435. (
  3436. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3437. (TargetRef.base = current_procinfo.framepointer) or
  3438. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3439. ) then
  3440. taicpu(hp1).opcode := MovAligned
  3441. else
  3442. taicpu(hp1).opcode := MovUnaligned;
  3443. taicpu(hp1).opsize := S_XMM;
  3444. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3445. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3446. RemoveInstruction(hp2);
  3447. RemoveInstruction(hp3);
  3448. Result := True;
  3449. Exit;
  3450. end;
  3451. end;
  3452. end
  3453. else
  3454. begin
  3455. { See if the next references are 8 less rather than 8 greater }
  3456. Dec(SourceRef.offset, 16); { -8 the other way }
  3457. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3458. begin
  3459. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3460. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3461. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3462. GetNextInstruction(hp2, hp3) and
  3463. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3464. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3465. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3466. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3467. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3468. begin
  3469. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3470. if NewMMReg <> NR_NO then
  3471. begin
  3472. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3473. if ((SourceRef.offset mod 16) = 0) and
  3474. (
  3475. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3476. (SourceRef.base = current_procinfo.framepointer) or
  3477. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3478. ) then
  3479. taicpu(hp2).opcode := MovAligned
  3480. else
  3481. taicpu(hp2).opcode := MovUnaligned;
  3482. taicpu(hp2).opsize := S_XMM;
  3483. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3484. if ((TargetRef.offset mod 16) = 0) and
  3485. (
  3486. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3487. (TargetRef.base = current_procinfo.framepointer) or
  3488. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3489. ) then
  3490. taicpu(hp3).opcode := MovAligned
  3491. else
  3492. taicpu(hp3).opcode := MovUnaligned;
  3493. taicpu(hp3).opsize := S_XMM;
  3494. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3495. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3496. RemoveInstruction(hp1);
  3497. RemoveCurrentP(p, hp2);
  3498. Result := True;
  3499. Exit;
  3500. end;
  3501. end;
  3502. end;
  3503. end;
  3504. end;
  3505. {$endif x86_64}
  3506. end;
  3507. else
  3508. { The write target should be a reg or a ref }
  3509. InternalError(2021091601);
  3510. end;
  3511. else
  3512. ;
  3513. end
  3514. else
  3515. { %treg is used afterwards, but all eventualities
  3516. other than the first MOV instruction being a constant
  3517. are covered by DeepMOVOpt, so only check for that }
  3518. if (taicpu(p).oper[0]^.typ = top_const) and
  3519. (
  3520. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3521. not (cs_opt_size in current_settings.optimizerswitches) or
  3522. (taicpu(hp1).opsize = S_B)
  3523. ) and
  3524. (
  3525. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3526. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3527. ) then
  3528. begin
  3529. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3530. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3531. end;
  3532. end;
  3533. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3534. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3535. { mov reg1, mem1 or mov mem1, reg1
  3536. mov mem2, reg2 mov reg2, mem2}
  3537. begin
  3538. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3539. { mov reg1, mem1 or mov mem1, reg1
  3540. mov mem2, reg1 mov reg2, mem1}
  3541. begin
  3542. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3543. { Removes the second statement from
  3544. mov reg1, mem1/reg2
  3545. mov mem1/reg2, reg1 }
  3546. begin
  3547. if taicpu(p).oper[0]^.typ=top_reg then
  3548. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3549. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3550. RemoveInstruction(hp1);
  3551. Result:=true;
  3552. exit;
  3553. end
  3554. else
  3555. begin
  3556. TransferUsedRegs(TmpUsedRegs);
  3557. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3558. if (taicpu(p).oper[1]^.typ = top_ref) and
  3559. { mov reg1, mem1
  3560. mov mem2, reg1 }
  3561. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3562. GetNextInstruction(hp1, hp2) and
  3563. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3564. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3565. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3566. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3567. { change to
  3568. mov reg1, mem1 mov reg1, mem1
  3569. mov mem2, reg1 cmp reg1, mem2
  3570. cmp mem1, reg1
  3571. }
  3572. begin
  3573. RemoveInstruction(hp2);
  3574. taicpu(hp1).opcode := A_CMP;
  3575. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3576. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3577. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3578. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3579. end;
  3580. end;
  3581. end
  3582. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3583. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3584. begin
  3585. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3586. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3587. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3588. end
  3589. else
  3590. begin
  3591. TransferUsedRegs(TmpUsedRegs);
  3592. if GetNextInstruction(hp1, hp2) and
  3593. MatchOpType(taicpu(p),top_ref,top_reg) and
  3594. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3595. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3596. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3597. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3598. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3599. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3600. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3601. { mov mem1, %reg1
  3602. mov %reg1, mem2
  3603. mov mem2, reg2
  3604. to:
  3605. mov mem1, reg2
  3606. mov reg2, mem2}
  3607. begin
  3608. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3609. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3610. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3611. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3612. RemoveInstruction(hp2);
  3613. Result := True;
  3614. end
  3615. {$ifdef i386}
  3616. { this is enabled for i386 only, as the rules to create the reg sets below
  3617. are too complicated for x86-64, so this makes this code too error prone
  3618. on x86-64
  3619. }
  3620. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3621. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3622. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3623. { mov mem1, reg1 mov mem1, reg1
  3624. mov reg1, mem2 mov reg1, mem2
  3625. mov mem2, reg2 mov mem2, reg1
  3626. to: to:
  3627. mov mem1, reg1 mov mem1, reg1
  3628. mov mem1, reg2 mov reg1, mem2
  3629. mov reg1, mem2
  3630. or (if mem1 depends on reg1
  3631. and/or if mem2 depends on reg2)
  3632. to:
  3633. mov mem1, reg1
  3634. mov reg1, mem2
  3635. mov reg1, reg2
  3636. }
  3637. begin
  3638. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3639. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3640. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3641. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3642. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3643. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3644. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3645. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3646. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3647. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3648. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3649. end
  3650. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3651. begin
  3652. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3653. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3654. end
  3655. else
  3656. begin
  3657. RemoveInstruction(hp2);
  3658. end
  3659. {$endif i386}
  3660. ;
  3661. end;
  3662. end
  3663. { movl [mem1],reg1
  3664. movl [mem1],reg2
  3665. to
  3666. movl [mem1],reg1
  3667. movl reg1,reg2
  3668. }
  3669. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3670. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3671. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3672. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3673. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3674. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3675. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3676. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3677. begin
  3678. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3679. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3680. end;
  3681. { movl const1,[mem1]
  3682. movl [mem1],reg1
  3683. to
  3684. movl const1,reg1
  3685. movl reg1,[mem1]
  3686. }
  3687. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3688. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3689. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3690. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3691. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3692. begin
  3693. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3694. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3695. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3696. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3697. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3698. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3699. Result:=true;
  3700. exit;
  3701. end;
  3702. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3703. { Change:
  3704. movl %reg1,%reg2
  3705. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3706. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3707. To:
  3708. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3709. movl x(%reg1),%reg1
  3710. movl %reg1,%regX
  3711. }
  3712. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3713. begin
  3714. p_SourceReg := taicpu(p).oper[0]^.reg;
  3715. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3716. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3717. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3718. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3719. GetNextInstruction(hp1, hp2) and
  3720. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3721. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3722. begin
  3723. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3724. if RegInRef(p_TargetReg, SourceRef) and
  3725. { If %reg1 also appears in the second reference, then it will
  3726. not refer to the same memory block as the first reference }
  3727. not RegInRef(p_SourceReg, SourceRef) then
  3728. begin
  3729. { Check to see if the references match if %reg2 is changed to %reg1 }
  3730. if SourceRef.base = p_TargetReg then
  3731. SourceRef.base := p_SourceReg;
  3732. if SourceRef.index = p_TargetReg then
  3733. SourceRef.index := p_SourceReg;
  3734. { RefsEqual also checks to ensure both references are non-volatile }
  3735. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3736. begin
  3737. taicpu(hp2).loadreg(0, p_SourceReg);
  3738. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3739. Result := True;
  3740. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3741. begin
  3742. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3743. RemoveCurrentP(p, hp1);
  3744. Exit;
  3745. end
  3746. else
  3747. begin
  3748. { Check to see if %reg2 is no longer in use }
  3749. TransferUsedRegs(TmpUsedRegs);
  3750. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3751. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3752. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3753. begin
  3754. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3755. RemoveCurrentP(p, hp1);
  3756. Exit;
  3757. end;
  3758. end;
  3759. { If we reach this point, p and hp1 weren't actually modified,
  3760. so we can do a bit more work on this pass }
  3761. end;
  3762. end;
  3763. end;
  3764. end;
  3765. end;
  3766. {$ifdef x86_64}
  3767. { Change:
  3768. movl %reg1l,%reg2l
  3769. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3770. To:
  3771. movl %reg1l,%reg2l
  3772. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3773. If %reg1 = %reg3, convert to:
  3774. movl %reg1l,%reg2l
  3775. andl %reg1l,%reg1l
  3776. }
  3777. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3778. MatchOpType(taicpu(p), top_reg, top_reg) and
  3779. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3780. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3781. begin
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. taicpu(hp1).opsize := S_L;
  3785. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3786. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3787. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3788. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3789. begin
  3790. { %reg1 = %reg3 }
  3791. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3792. taicpu(hp1).opcode := A_AND;
  3793. end
  3794. else
  3795. begin
  3796. { %reg1 <> %reg3 }
  3797. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3798. end;
  3799. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3800. begin
  3801. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3802. RemoveCurrentP(p, hp1);
  3803. Result := True;
  3804. Exit;
  3805. end
  3806. else
  3807. begin
  3808. { Initial instruction wasn't actually changed }
  3809. Include(OptsToCheck, aoc_ForceNewIteration);
  3810. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3811. appears below since %reg1 has technically changed }
  3812. if taicpu(hp1).opcode = A_AND then
  3813. Exit;
  3814. end;
  3815. end;
  3816. {$endif x86_64}
  3817. { search further than the next instruction for a mov (as long as it's not a jump) }
  3818. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3819. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3820. (taicpu(p).oper[1]^.typ = top_reg) and
  3821. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3822. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3823. begin
  3824. { we work with hp2 here, so hp1 can be still used later on when
  3825. checking for GetNextInstruction_p }
  3826. hp3 := hp1;
  3827. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3828. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3829. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3830. TransferUsedRegs(TmpUsedRegs);
  3831. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3832. if NotFirstIteration then
  3833. JumpTracking := TLinkedList.Create
  3834. else
  3835. JumpTracking := nil;
  3836. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3837. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3838. (hp2.typ=ait_instruction) do
  3839. begin
  3840. case taicpu(hp2).opcode of
  3841. A_POP:
  3842. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3843. begin
  3844. if not CrossJump and
  3845. not RegUsedBetween(p_TargetReg, p, hp2) then
  3846. begin
  3847. { We can remove the original MOV since the register
  3848. wasn't used between it and its popping from the stack }
  3849. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3850. RemoveCurrentp(p, hp1);
  3851. Result := True;
  3852. JumpTracking.Free;
  3853. Exit;
  3854. end;
  3855. { Can't go any further }
  3856. Break;
  3857. end;
  3858. A_MOV:
  3859. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3860. ((taicpu(p).oper[0]^.typ=top_const) or
  3861. ((taicpu(p).oper[0]^.typ=top_reg) and
  3862. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3863. )
  3864. ) then
  3865. begin
  3866. { we have
  3867. mov x, %treg
  3868. mov %treg, y
  3869. }
  3870. { We don't need to call UpdateUsedRegs for every instruction between
  3871. p and hp2 because the register we're concerned about will not
  3872. become deallocated (otherwise GetNextInstructionUsingReg would
  3873. have stopped at an earlier instruction). [Kit] }
  3874. TempRegUsed :=
  3875. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3876. RegReadByInstruction(p_TargetReg, hp3) or
  3877. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3878. case taicpu(p).oper[0]^.typ Of
  3879. top_reg:
  3880. begin
  3881. { change
  3882. mov %reg, %treg
  3883. mov %treg, y
  3884. to
  3885. mov %reg, y
  3886. }
  3887. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3888. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3889. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3890. begin
  3891. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3892. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3893. if TempRegUsed then
  3894. begin
  3895. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3896. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3897. { Set the start of the next GetNextInstructionUsingRegCond search
  3898. to start at the entry right before hp2 (which is about to be removed) }
  3899. hp3 := tai(hp2.Previous);
  3900. RemoveInstruction(hp2);
  3901. Include(OptsToCheck, aoc_ForceNewIteration);
  3902. { See if there's more we can optimise }
  3903. Continue;
  3904. end
  3905. else
  3906. begin
  3907. RemoveInstruction(hp2);
  3908. { We can remove the original MOV too }
  3909. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3910. RemoveCurrentP(p, hp1);
  3911. Result:=true;
  3912. JumpTracking.Free;
  3913. Exit;
  3914. end;
  3915. end
  3916. else
  3917. begin
  3918. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3919. taicpu(hp2).loadReg(0, p_SourceReg);
  3920. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3921. { Check to see if the register also appears in the reference }
  3922. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3923. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3924. { Don't remove the first instruction if the temporary register is in use }
  3925. if not TempRegUsed and
  3926. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3927. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3928. begin
  3929. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3930. RemoveCurrentP(p, hp1);
  3931. Result:=true;
  3932. JumpTracking.Free;
  3933. Exit;
  3934. end;
  3935. { No need to set Result to True here. If there's another instruction later
  3936. on that can be optimised, it will be detected when the main Pass 1 loop
  3937. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3938. end;
  3939. end;
  3940. top_const:
  3941. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3942. begin
  3943. { change
  3944. mov const, %treg
  3945. mov %treg, y
  3946. to
  3947. mov const, y
  3948. }
  3949. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3950. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3951. begin
  3952. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3953. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3954. if TempRegUsed then
  3955. begin
  3956. { Don't remove the first instruction if the temporary register is in use }
  3957. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3958. { No need to set Result to True. If there's another instruction later on
  3959. that can be optimised, it will be detected when the main Pass 1 loop
  3960. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3961. end
  3962. else
  3963. begin
  3964. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3965. RemoveCurrentP(p, hp1);
  3966. Result:=true;
  3967. Exit;
  3968. end;
  3969. end;
  3970. end;
  3971. else
  3972. Internalerror(2019103001);
  3973. end;
  3974. end
  3975. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3976. begin
  3977. if not CrossJump and
  3978. not RegUsedBetween(p_TargetReg, p, hp2) and
  3979. not RegReadByInstruction(p_TargetReg, hp2) then
  3980. begin
  3981. { Register is not used before it is overwritten }
  3982. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3983. RemoveCurrentp(p, hp1);
  3984. Result := True;
  3985. Exit;
  3986. end;
  3987. if (taicpu(p).oper[0]^.typ = top_const) and
  3988. (taicpu(hp2).oper[0]^.typ = top_const) then
  3989. begin
  3990. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3991. begin
  3992. { Same value - register hasn't changed }
  3993. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3994. RemoveInstruction(hp2);
  3995. Include(OptsToCheck, aoc_ForceNewIteration);
  3996. { See if there's more we can optimise }
  3997. Continue;
  3998. end;
  3999. end;
  4000. {$ifdef x86_64}
  4001. end
  4002. { Change:
  4003. movl %reg1l,%reg2l
  4004. ...
  4005. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4006. To:
  4007. movl %reg1l,%reg2l
  4008. ...
  4009. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4010. If %reg1 = %reg3, convert to:
  4011. movl %reg1l,%reg2l
  4012. ...
  4013. andl %reg1l,%reg1l
  4014. }
  4015. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4016. (taicpu(p).oper[0]^.typ = top_reg) and
  4017. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4018. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4019. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4020. begin
  4021. TempRegUsed :=
  4022. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4023. RegReadByInstruction(p_TargetReg, hp3) or
  4024. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4025. taicpu(hp2).opsize := S_L;
  4026. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4027. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4028. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4029. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4030. begin
  4031. { %reg1 = %reg3 }
  4032. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4033. taicpu(hp2).opcode := A_AND;
  4034. end
  4035. else
  4036. begin
  4037. { %reg1 <> %reg3 }
  4038. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4039. end;
  4040. if not TempRegUsed then
  4041. begin
  4042. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4043. RemoveCurrentP(p, hp1);
  4044. Result := True;
  4045. Exit;
  4046. end
  4047. else
  4048. begin
  4049. { Initial instruction wasn't actually changed }
  4050. Include(OptsToCheck, aoc_ForceNewIteration);
  4051. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4052. appears below since %reg1 has technically changed }
  4053. if taicpu(hp2).opcode = A_AND then
  4054. Break;
  4055. end;
  4056. {$endif x86_64}
  4057. end;
  4058. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4059. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4060. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4061. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4062. begin
  4063. {
  4064. Change from:
  4065. mov ###, %reg
  4066. ...
  4067. movs/z %reg,%reg (Same register, just different sizes)
  4068. To:
  4069. movs/z ###, %reg (Longer version)
  4070. ...
  4071. (remove)
  4072. }
  4073. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4074. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4075. { Keep the first instruction as mov if ### is a constant }
  4076. if taicpu(p).oper[0]^.typ = top_const then
  4077. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4078. else
  4079. begin
  4080. taicpu(p).opcode := taicpu(hp2).opcode;
  4081. taicpu(p).opsize := taicpu(hp2).opsize;
  4082. end;
  4083. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4084. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4085. RemoveInstruction(hp2);
  4086. Result := True;
  4087. JumpTracking.Free;
  4088. Exit;
  4089. end;
  4090. else
  4091. { Move down to the if-block below };
  4092. end;
  4093. { Also catches MOV/S/Z instructions that aren't modified }
  4094. if taicpu(p).oper[0]^.typ = top_reg then
  4095. begin
  4096. p_SourceReg := taicpu(p).oper[0]^.reg;
  4097. if
  4098. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4099. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4100. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4101. begin
  4102. Result := True;
  4103. { Just in case something didn't get modified (e.g. an
  4104. implicit register). Also, if it does read from this
  4105. register, then there's no longer an advantage to
  4106. changing the register on subsequent instructions.}
  4107. if not RegReadByInstruction(p_TargetReg, hp2) then
  4108. begin
  4109. { If a conditional jump was crossed, do not delete
  4110. the original MOV no matter what }
  4111. if not CrossJump and
  4112. { RegEndOfLife returns True if the register is
  4113. deallocated before the next instruction or has
  4114. been loaded with a new value }
  4115. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4116. begin
  4117. { We can remove the original MOV }
  4118. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4119. RemoveCurrentp(p, hp1);
  4120. JumpTracking.Free;
  4121. Result := True;
  4122. Exit;
  4123. end;
  4124. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4125. begin
  4126. { See if there's more we can optimise }
  4127. hp3 := hp2;
  4128. Continue;
  4129. end;
  4130. end;
  4131. end;
  4132. end;
  4133. { Break out of the while loop under normal circumstances }
  4134. Break;
  4135. end;
  4136. JumpTracking.Free;
  4137. end;
  4138. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4139. (taicpu(p).oper[1]^.typ = top_reg) and
  4140. (taicpu(p).opsize = S_L) and
  4141. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4142. (hp2.typ = ait_instruction) and
  4143. (taicpu(hp2).opcode = A_AND) and
  4144. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4145. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4146. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4147. ) then
  4148. begin
  4149. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4150. begin
  4151. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4152. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4153. begin
  4154. { Optimize out:
  4155. mov x, %reg
  4156. and ffffffffh, %reg
  4157. }
  4158. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4159. RemoveInstruction(hp2);
  4160. Result:=true;
  4161. exit;
  4162. end;
  4163. end;
  4164. end;
  4165. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4166. x >= RetOffset) as it doesn't do anything (it writes either to a
  4167. parameter or to the temporary storage room for the function
  4168. result)
  4169. }
  4170. if IsExitCode(hp1) and
  4171. (taicpu(p).oper[1]^.typ = top_ref) and
  4172. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4173. (
  4174. (
  4175. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4176. not (
  4177. assigned(current_procinfo.procdef.funcretsym) and
  4178. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4179. )
  4180. ) or
  4181. { Also discard writes to the stack that are below the base pointer,
  4182. as this is temporary storage rather than a function result on the
  4183. stack, say. }
  4184. (
  4185. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4186. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4187. )
  4188. ) then
  4189. begin
  4190. RemoveCurrentp(p, hp1);
  4191. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4192. RemoveLastDeallocForFuncRes(p);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4197. begin
  4198. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4199. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4200. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4201. begin
  4202. { change
  4203. mov reg1, mem1
  4204. test/cmp x, mem1
  4205. to
  4206. mov reg1, mem1
  4207. test/cmp x, reg1
  4208. }
  4209. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4210. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4211. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4212. Result := True;
  4213. Exit;
  4214. end;
  4215. if DoMovCmpMemOpt(p, hp1) then
  4216. begin
  4217. Result := True;
  4218. Exit;
  4219. end;
  4220. end;
  4221. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4222. { If the flags register is in use, don't change the instruction to an
  4223. ADD otherwise this will scramble the flags. [Kit] }
  4224. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4225. begin
  4226. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4227. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4228. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4229. ) or
  4230. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4231. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4232. )
  4233. ) then
  4234. { mov reg1,ref
  4235. lea reg2,[reg1,reg2]
  4236. to
  4237. add reg2,ref}
  4238. begin
  4239. TransferUsedRegs(TmpUsedRegs);
  4240. { reg1 may not be used afterwards }
  4241. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4242. begin
  4243. Taicpu(hp1).opcode:=A_ADD;
  4244. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4245. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4246. RemoveCurrentp(p, hp1);
  4247. result:=true;
  4248. exit;
  4249. end;
  4250. end;
  4251. { If the LEA instruction can be converted into an arithmetic instruction,
  4252. it may be possible to then fold it in the next optimisation, otherwise
  4253. there's nothing more that can be optimised here. }
  4254. if not ConvertLEA(taicpu(hp1)) then
  4255. Exit;
  4256. end;
  4257. if (taicpu(p).oper[1]^.typ = top_reg) and
  4258. (hp1.typ = ait_instruction) and
  4259. GetNextInstruction(hp1, hp2) and
  4260. MatchInstruction(hp2,A_MOV,[]) and
  4261. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4262. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4263. (
  4264. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4265. {$ifdef x86_64}
  4266. or
  4267. (
  4268. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4269. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4270. )
  4271. {$endif x86_64}
  4272. ) then
  4273. begin
  4274. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4275. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4276. { change movsX/movzX reg/ref, reg2
  4277. add/sub/or/... reg3/$const, reg2
  4278. mov reg2 reg/ref
  4279. dealloc reg2
  4280. to
  4281. add/sub/or/... reg3/$const, reg/ref }
  4282. begin
  4283. TransferUsedRegs(TmpUsedRegs);
  4284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4285. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4286. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4287. begin
  4288. { by example:
  4289. movswl %si,%eax movswl %si,%eax p
  4290. decl %eax addl %edx,%eax hp1
  4291. movw %ax,%si movw %ax,%si hp2
  4292. ->
  4293. movswl %si,%eax movswl %si,%eax p
  4294. decw %eax addw %edx,%eax hp1
  4295. movw %ax,%si movw %ax,%si hp2
  4296. }
  4297. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4298. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4299. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4300. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4301. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4302. {
  4303. ->
  4304. movswl %si,%eax movswl %si,%eax p
  4305. decw %si addw %dx,%si hp1
  4306. movw %ax,%si movw %ax,%si hp2
  4307. }
  4308. case taicpu(hp1).ops of
  4309. 1:
  4310. begin
  4311. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4312. if taicpu(hp1).oper[0]^.typ=top_reg then
  4313. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4314. end;
  4315. 2:
  4316. begin
  4317. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4318. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4319. (taicpu(hp1).opcode<>A_SHL) and
  4320. (taicpu(hp1).opcode<>A_SHR) and
  4321. (taicpu(hp1).opcode<>A_SAR) then
  4322. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4323. end;
  4324. else
  4325. internalerror(2008042701);
  4326. end;
  4327. {
  4328. ->
  4329. decw %si addw %dx,%si p
  4330. }
  4331. RemoveInstruction(hp2);
  4332. RemoveCurrentP(p, hp1);
  4333. Result:=True;
  4334. Exit;
  4335. end;
  4336. end;
  4337. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4338. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4339. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4340. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4341. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4342. )
  4343. {$ifdef i386}
  4344. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4345. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4346. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4347. {$endif i386}
  4348. then
  4349. { change movsX/movzX reg/ref, reg2
  4350. add/sub/or/... regX/$const, reg2
  4351. mov reg2, reg3
  4352. dealloc reg2
  4353. to
  4354. movsX/movzX reg/ref, reg3
  4355. add/sub/or/... reg3/$const, reg3
  4356. }
  4357. begin
  4358. TransferUsedRegs(TmpUsedRegs);
  4359. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4360. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4361. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4362. begin
  4363. { by example:
  4364. movswl %si,%eax movswl %si,%eax p
  4365. decl %eax addl %edx,%eax hp1
  4366. movw %ax,%si movw %ax,%si hp2
  4367. ->
  4368. movswl %si,%eax movswl %si,%eax p
  4369. decw %eax addw %edx,%eax hp1
  4370. movw %ax,%si movw %ax,%si hp2
  4371. }
  4372. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4373. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4374. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4375. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4376. { limit size of constants as well to avoid assembler errors, but
  4377. check opsize to avoid overflow when left shifting the 1 }
  4378. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4379. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4380. {$ifdef x86_64}
  4381. { Be careful of, for example:
  4382. movl %reg1,%reg2
  4383. addl %reg3,%reg2
  4384. movq %reg2,%reg4
  4385. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4386. }
  4387. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4388. begin
  4389. taicpu(hp2).changeopsize(S_L);
  4390. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4391. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4392. end;
  4393. {$endif x86_64}
  4394. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4395. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4396. if taicpu(p).oper[0]^.typ=top_reg then
  4397. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4398. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4399. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4400. {
  4401. ->
  4402. movswl %si,%eax movswl %si,%eax p
  4403. decw %si addw %dx,%si hp1
  4404. movw %ax,%si movw %ax,%si hp2
  4405. }
  4406. case taicpu(hp1).ops of
  4407. 1:
  4408. begin
  4409. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4410. if taicpu(hp1).oper[0]^.typ=top_reg then
  4411. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4412. end;
  4413. 2:
  4414. begin
  4415. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4416. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4417. (taicpu(hp1).opcode<>A_SHL) and
  4418. (taicpu(hp1).opcode<>A_SHR) and
  4419. (taicpu(hp1).opcode<>A_SAR) then
  4420. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4421. end;
  4422. else
  4423. internalerror(2018111801);
  4424. end;
  4425. {
  4426. ->
  4427. decw %si addw %dx,%si p
  4428. }
  4429. RemoveInstruction(hp2);
  4430. end;
  4431. end;
  4432. end;
  4433. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4434. GetNextInstruction(hp1, hp2) and
  4435. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4436. MatchOperand(Taicpu(p).oper[0]^,0) and
  4437. (Taicpu(p).oper[1]^.typ = top_reg) and
  4438. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4439. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4440. { mov reg1,0
  4441. bts reg1,operand1 --> mov reg1,operand2
  4442. or reg1,operand2 bts reg1,operand1}
  4443. begin
  4444. Taicpu(hp2).opcode:=A_MOV;
  4445. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4446. asml.remove(hp1);
  4447. insertllitem(hp2,hp2.next,hp1);
  4448. RemoveCurrentp(p, hp1);
  4449. Result:=true;
  4450. exit;
  4451. end;
  4452. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4453. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4454. GetNextInstruction(hp1, hp2) and
  4455. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4456. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4457. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4458. { change
  4459. mov reg1,reg2
  4460. sub reg3,reg2
  4461. cmp reg3,reg1
  4462. into
  4463. mov reg1,reg2
  4464. sub reg3,reg2
  4465. }
  4466. begin
  4467. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4468. RemoveInstruction(hp2);
  4469. Result:=true;
  4470. exit;
  4471. end;
  4472. {
  4473. mov ref,reg0
  4474. <op> reg0,reg1
  4475. dealloc reg0
  4476. to
  4477. <op> ref,reg1
  4478. }
  4479. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4480. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4481. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4482. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4483. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4484. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4485. begin
  4486. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4487. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4488. RemoveCurrentp(p, hp1);
  4489. Result:=true;
  4490. exit;
  4491. end;
  4492. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4493. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4494. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4495. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4496. begin
  4497. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4498. {$ifdef x86_64}
  4499. { Convert:
  4500. movq x(ref),%reg64
  4501. shrq y,%reg64
  4502. To:
  4503. movl x+4(ref),%reg32
  4504. shrl y-32,%reg32 (Remove if y = 32)
  4505. }
  4506. if (taicpu(p).opsize = S_Q) and
  4507. (taicpu(hp1).opcode = A_SHR) and
  4508. (taicpu(hp1).oper[0]^.val >= 32) then
  4509. begin
  4510. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4511. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4512. { Convert to 32-bit }
  4513. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4514. taicpu(p).opsize := S_L;
  4515. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4516. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4517. if (taicpu(hp1).oper[0]^.val = 32) then
  4518. begin
  4519. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4520. RemoveInstruction(hp1);
  4521. end
  4522. else
  4523. begin
  4524. { This will potentially open up more arithmetic operations since
  4525. the peephole optimizer now has a big hint that only the lower
  4526. 32 bits are currently in use (and opcodes are smaller in size) }
  4527. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4528. taicpu(hp1).opsize := S_L;
  4529. Dec(taicpu(hp1).oper[0]^.val, 32);
  4530. DebugMsg(SPeepholeOptimization + PreMessage +
  4531. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4532. end;
  4533. Result := True;
  4534. Exit;
  4535. end;
  4536. {$endif x86_64}
  4537. { Convert:
  4538. movl x(ref),%reg
  4539. shrl $24,%reg
  4540. To:
  4541. movzbl x+3(ref),%reg
  4542. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4543. Also accept sar instead of shr, but convert to movsx instead of movzx
  4544. }
  4545. if taicpu(hp1).opcode = A_SHR then
  4546. MovUnaligned := A_MOVZX
  4547. else
  4548. MovUnaligned := A_MOVSX;
  4549. NewSize := S_NO;
  4550. NewOffset := 0;
  4551. case taicpu(p).opsize of
  4552. S_B:
  4553. { No valid combinations };
  4554. S_W:
  4555. if (taicpu(hp1).oper[0]^.val = 8) then
  4556. begin
  4557. NewSize := S_BW;
  4558. NewOffset := 1;
  4559. end;
  4560. S_L:
  4561. case taicpu(hp1).oper[0]^.val of
  4562. 16:
  4563. begin
  4564. NewSize := S_WL;
  4565. NewOffset := 2;
  4566. end;
  4567. 24:
  4568. begin
  4569. NewSize := S_BL;
  4570. NewOffset := 3;
  4571. end;
  4572. else
  4573. ;
  4574. end;
  4575. {$ifdef x86_64}
  4576. S_Q:
  4577. case taicpu(hp1).oper[0]^.val of
  4578. 32:
  4579. begin
  4580. if taicpu(hp1).opcode = A_SAR then
  4581. begin
  4582. { 32-bit to 64-bit is a distinct instruction }
  4583. MovUnaligned := A_MOVSXD;
  4584. NewSize := S_LQ;
  4585. NewOffset := 4;
  4586. end
  4587. else
  4588. { Should have been handled by MovShr2Mov above }
  4589. InternalError(2022081811);
  4590. end;
  4591. 48:
  4592. begin
  4593. NewSize := S_WQ;
  4594. NewOffset := 6;
  4595. end;
  4596. 56:
  4597. begin
  4598. NewSize := S_BQ;
  4599. NewOffset := 7;
  4600. end;
  4601. else
  4602. ;
  4603. end;
  4604. {$endif x86_64}
  4605. else
  4606. InternalError(2022081810);
  4607. end;
  4608. if (NewSize <> S_NO) and
  4609. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4610. begin
  4611. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4612. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4613. debug_op2str(MovUnaligned);
  4614. {$ifdef x86_64}
  4615. if MovUnaligned <> A_MOVSXD then
  4616. { Don't add size suffix for MOVSXD }
  4617. {$endif x86_64}
  4618. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4619. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4620. taicpu(p).opcode := MovUnaligned;
  4621. taicpu(p).opsize := NewSize;
  4622. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4623. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4624. RemoveInstruction(hp1);
  4625. Result := True;
  4626. Exit;
  4627. end;
  4628. end;
  4629. { Backward optimisation shared with OptPass2MOV }
  4630. if FuncMov2Func(p, hp1) then
  4631. begin
  4632. Result := True;
  4633. Exit;
  4634. end;
  4635. end;
  4636. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4637. var
  4638. hp1 : tai;
  4639. begin
  4640. Result:=false;
  4641. if taicpu(p).ops <> 2 then
  4642. exit;
  4643. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4644. GetNextInstruction(p,hp1) then
  4645. begin
  4646. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4647. (taicpu(hp1).ops = 2) then
  4648. begin
  4649. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4650. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4651. { movXX reg1, mem1 or movXX mem1, reg1
  4652. movXX mem2, reg2 movXX reg2, mem2}
  4653. begin
  4654. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4655. { movXX reg1, mem1 or movXX mem1, reg1
  4656. movXX mem2, reg1 movXX reg2, mem1}
  4657. begin
  4658. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4659. begin
  4660. { Removes the second statement from
  4661. movXX reg1, mem1/reg2
  4662. movXX mem1/reg2, reg1
  4663. }
  4664. if taicpu(p).oper[0]^.typ=top_reg then
  4665. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4666. { Removes the second statement from
  4667. movXX mem1/reg1, reg2
  4668. movXX reg2, mem1/reg1
  4669. }
  4670. if (taicpu(p).oper[1]^.typ=top_reg) and
  4671. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4672. begin
  4673. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4674. RemoveInstruction(hp1);
  4675. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4676. Result:=true;
  4677. exit;
  4678. end
  4679. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4680. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4681. begin
  4682. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4683. RemoveInstruction(hp1);
  4684. Result:=true;
  4685. exit;
  4686. end;
  4687. end
  4688. end;
  4689. end;
  4690. end;
  4691. end;
  4692. end;
  4693. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4694. var
  4695. hp1 : tai;
  4696. begin
  4697. result:=false;
  4698. { replace
  4699. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4700. MovX %mreg2,%mreg1
  4701. dealloc %mreg2
  4702. by
  4703. <Op>X %mreg2,%mreg1
  4704. ?
  4705. }
  4706. if GetNextInstruction(p,hp1) and
  4707. { we mix single and double opperations here because we assume that the compiler
  4708. generates vmovapd only after double operations and vmovaps only after single operations }
  4709. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4710. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4711. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4712. (taicpu(p).oper[0]^.typ=top_reg) then
  4713. begin
  4714. TransferUsedRegs(TmpUsedRegs);
  4715. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4716. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4717. begin
  4718. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4719. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4720. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4721. RemoveInstruction(hp1);
  4722. result:=true;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4727. var
  4728. hp1, p_label, p_dist, hp1_dist: tai;
  4729. JumpLabel, JumpLabel_dist: TAsmLabel;
  4730. FirstValue, SecondValue: TCGInt;
  4731. TempBool: Boolean;
  4732. begin
  4733. Result := False;
  4734. if (taicpu(p).oper[0]^.typ = top_const) and
  4735. (taicpu(p).oper[0]^.val <> -1) then
  4736. begin
  4737. { Convert unsigned maximum constants to -1 to aid optimisation }
  4738. case taicpu(p).opsize of
  4739. S_B:
  4740. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4741. begin
  4742. taicpu(p).oper[0]^.val := -1;
  4743. Result := True;
  4744. Exit;
  4745. end;
  4746. S_W:
  4747. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4748. begin
  4749. taicpu(p).oper[0]^.val := -1;
  4750. Result := True;
  4751. Exit;
  4752. end;
  4753. S_L:
  4754. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4755. begin
  4756. taicpu(p).oper[0]^.val := -1;
  4757. Result := True;
  4758. Exit;
  4759. end;
  4760. {$ifdef x86_64}
  4761. S_Q:
  4762. { Storing anything greater than $7FFFFFFF is not possible so do
  4763. nothing };
  4764. {$endif x86_64}
  4765. else
  4766. InternalError(2021121001);
  4767. end;
  4768. end;
  4769. if GetNextInstruction(p, hp1) and
  4770. TrySwapMovCmp(p, hp1) then
  4771. begin
  4772. Result := True;
  4773. Exit;
  4774. end;
  4775. if MatchInstruction(hp1, A_Jcc, []) then
  4776. begin
  4777. TempBool := True;
  4778. if DoJumpOptimizations(hp1, TempBool) or
  4779. not TempBool then
  4780. begin
  4781. Result := True;
  4782. if Assigned(hp1) then
  4783. begin
  4784. if (hp1.typ in [ait_align]) then
  4785. SkipAligns(hp1, hp1);
  4786. { CollapseZeroDistJump will be set to the label after the
  4787. jump if it optimises, whether or not it's live or dead }
  4788. if (hp1.typ in [ait_label]) and
  4789. not (tai_label(hp1).labsym.is_used) then
  4790. GetNextInstruction(hp1, hp1);
  4791. end;
  4792. TransferUsedRegs(TmpUsedRegs);
  4793. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4794. if not Assigned(hp1) or
  4795. (
  4796. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4797. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4798. ) then
  4799. begin
  4800. { No more conditional jumps; conditional statement is no longer required }
  4801. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4802. RemoveCurrentP(p);
  4803. end;
  4804. Exit;
  4805. end;
  4806. end;
  4807. { Search for:
  4808. test $x,(reg/ref)
  4809. jne @lbl1
  4810. test $y,(reg/ref) (same register or reference)
  4811. jne @lbl1
  4812. Change to:
  4813. test $(x or y),(reg/ref)
  4814. jne @lbl1
  4815. (Note, this doesn't work with je instead of jne)
  4816. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4817. Also search for:
  4818. test $x,(reg/ref)
  4819. je @lbl1
  4820. test $y,(reg/ref)
  4821. je/jne @lbl2
  4822. If (x or y) = x, then the second jump is deterministic
  4823. }
  4824. if (
  4825. (
  4826. (taicpu(p).oper[0]^.typ = top_const) or
  4827. (
  4828. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4829. (taicpu(p).oper[0]^.typ = top_reg) and
  4830. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4831. )
  4832. ) and
  4833. MatchInstruction(hp1, A_JCC, [])
  4834. ) then
  4835. begin
  4836. if (taicpu(p).oper[0]^.typ = top_reg) and
  4837. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4838. FirstValue := -1
  4839. else
  4840. FirstValue := taicpu(p).oper[0]^.val;
  4841. { If we have several test/jne's in a row, it might be the case that
  4842. the second label doesn't go to the same location, but the one
  4843. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4844. so accommodate for this with a while loop.
  4845. }
  4846. hp1_dist := hp1;
  4847. if GetNextInstruction(hp1, p_dist) and
  4848. (p_dist.typ = ait_instruction) and
  4849. (
  4850. (
  4851. (taicpu(p_dist).opcode = A_TEST) and
  4852. (
  4853. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4854. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4855. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4856. )
  4857. ) or
  4858. (
  4859. { cmp 0,%reg = test %reg,%reg }
  4860. (taicpu(p_dist).opcode = A_CMP) and
  4861. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4862. )
  4863. ) and
  4864. { Make sure the destination operands are actually the same }
  4865. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4866. GetNextInstruction(p_dist, hp1_dist) and
  4867. MatchInstruction(hp1_dist, A_JCC, []) then
  4868. begin
  4869. if
  4870. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4871. (
  4872. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4873. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4874. ) then
  4875. SecondValue := -1
  4876. else
  4877. SecondValue := taicpu(p_dist).oper[0]^.val;
  4878. { If both of the TEST constants are identical, delete the second
  4879. TEST that is unnecessary. }
  4880. if (FirstValue = SecondValue) then
  4881. begin
  4882. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4883. RemoveInstruction(p_dist);
  4884. { Don't let the flags register become deallocated and reallocated between the jumps }
  4885. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4886. Result := True;
  4887. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4888. begin
  4889. { Since the second jump's condition is a subset of the first, we
  4890. know it will never branch because the first jump dominates it.
  4891. Get it out of the way now rather than wait for the jump
  4892. optimisations for a speed boost. }
  4893. if IsJumpToLabel(taicpu(hp1_dist)) then
  4894. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4895. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4896. RemoveInstruction(hp1_dist);
  4897. end
  4898. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4899. begin
  4900. { If the inverse of the first condition is a subset of the second,
  4901. the second one will definitely branch if the first one doesn't }
  4902. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4903. MakeUnconditional(taicpu(hp1_dist));
  4904. RemoveDeadCodeAfterJump(hp1_dist);
  4905. end;
  4906. Exit;
  4907. end;
  4908. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4909. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4910. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4911. then the second jump will never branch, so it can also be
  4912. removed regardless of where it goes }
  4913. (
  4914. (FirstValue = -1) or
  4915. (SecondValue = -1) or
  4916. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4917. ) then
  4918. begin
  4919. { Same jump location... can be a register since nothing's changed }
  4920. { If any of the entries are equivalent to test %reg,%reg, then the
  4921. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4922. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4923. if IsJumpToLabel(taicpu(hp1_dist)) then
  4924. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4925. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4926. RemoveInstruction(hp1_dist);
  4927. { Only remove the second test if no jumps or other conditional instructions follow }
  4928. TransferUsedRegs(TmpUsedRegs);
  4929. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4930. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4931. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4932. RemoveInstruction(p_dist);
  4933. Result := True;
  4934. Exit;
  4935. end;
  4936. end;
  4937. end;
  4938. { Search for:
  4939. test %reg,%reg
  4940. j(c1) @lbl1
  4941. ...
  4942. @lbl:
  4943. test %reg,%reg (same register)
  4944. j(c2) @lbl2
  4945. If c2 is a subset of c1, change to:
  4946. test %reg,%reg
  4947. j(c1) @lbl2
  4948. (@lbl1 may become a dead label as a result)
  4949. }
  4950. if (taicpu(p).oper[1]^.typ = top_reg) and
  4951. (taicpu(p).oper[0]^.typ = top_reg) and
  4952. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4953. MatchInstruction(hp1, A_JCC, []) and
  4954. IsJumpToLabel(taicpu(hp1)) then
  4955. begin
  4956. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4957. p_label := nil;
  4958. if Assigned(JumpLabel) then
  4959. p_label := getlabelwithsym(JumpLabel);
  4960. if Assigned(p_label) and
  4961. GetNextInstruction(p_label, p_dist) and
  4962. MatchInstruction(p_dist, A_TEST, []) and
  4963. { It's fine if the second test uses smaller sub-registers }
  4964. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4965. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4966. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4967. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4968. GetNextInstruction(p_dist, hp1_dist) and
  4969. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4970. begin
  4971. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4972. if JumpLabel = JumpLabel_dist then
  4973. { This is an infinite loop }
  4974. Exit;
  4975. { Best optimisation when the first condition is a subset (or equal) of the second }
  4976. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4977. begin
  4978. { Any registers used here will already be allocated }
  4979. if Assigned(JumpLabel) then
  4980. JumpLabel.DecRefs;
  4981. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4982. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4983. Result := True;
  4984. Exit;
  4985. end;
  4986. end;
  4987. end;
  4988. end;
  4989. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4990. var
  4991. hp1, hp2: tai;
  4992. ActiveReg: TRegister;
  4993. OldOffset: asizeint;
  4994. ThisConst: TCGInt;
  4995. function RegDeallocated: Boolean;
  4996. begin
  4997. TransferUsedRegs(TmpUsedRegs);
  4998. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4999. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5000. end;
  5001. begin
  5002. result:=false;
  5003. hp1 := nil;
  5004. { replace
  5005. addX const,%reg1
  5006. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5007. dealloc %reg1
  5008. by
  5009. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5010. }
  5011. if MatchOpType(taicpu(p),top_const,top_reg) then
  5012. begin
  5013. ActiveReg := taicpu(p).oper[1]^.reg;
  5014. { Ensures the entire register was updated }
  5015. if (taicpu(p).opsize >= S_L) and
  5016. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5017. MatchInstruction(hp1,A_LEA,[]) and
  5018. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5019. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5020. (
  5021. { Cover the case where the register in the reference is also the destination register }
  5022. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5023. (
  5024. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5025. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5026. RegDeallocated
  5027. )
  5028. ) then
  5029. begin
  5030. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5031. {$push}
  5032. {$R-}{$Q-}
  5033. { Explicitly disable overflow checking for these offset calculation
  5034. as those do not matter for the final result }
  5035. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5036. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5037. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5038. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5039. {$pop}
  5040. {$ifdef x86_64}
  5041. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5042. begin
  5043. { Overflow; abort }
  5044. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5045. end
  5046. else
  5047. {$endif x86_64}
  5048. begin
  5049. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5050. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5051. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5052. RemoveCurrentP(p, hp1)
  5053. else
  5054. RemoveCurrentP(p);
  5055. result:=true;
  5056. Exit;
  5057. end;
  5058. end;
  5059. if (
  5060. { Save calling GetNextInstructionUsingReg again }
  5061. Assigned(hp1) or
  5062. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5063. ) and
  5064. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5065. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5066. begin
  5067. if taicpu(hp1).oper[0]^.typ = top_const then
  5068. begin
  5069. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5070. if taicpu(hp1).opcode = A_ADD then
  5071. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5072. else
  5073. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5074. Result := True;
  5075. { Handle any overflows }
  5076. case taicpu(p).opsize of
  5077. S_B:
  5078. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5079. S_W:
  5080. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5081. S_L:
  5082. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5083. {$ifdef x86_64}
  5084. S_Q:
  5085. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5086. { Overflow; abort }
  5087. Result := False
  5088. else
  5089. taicpu(p).oper[0]^.val := ThisConst;
  5090. {$endif x86_64}
  5091. else
  5092. InternalError(2021102610);
  5093. end;
  5094. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5095. if Result then
  5096. begin
  5097. if (taicpu(p).oper[0]^.val < 0) and
  5098. (
  5099. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5100. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5101. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5102. ) then
  5103. begin
  5104. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5105. taicpu(p).opcode := A_SUB;
  5106. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5107. end
  5108. else
  5109. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5110. RemoveInstruction(hp1);
  5111. end;
  5112. end
  5113. else
  5114. begin
  5115. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5116. TransferUsedRegs(TmpUsedRegs);
  5117. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5118. hp2 := p;
  5119. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5120. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5121. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5122. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5123. begin
  5124. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5125. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5126. Asml.Remove(p);
  5127. Asml.InsertAfter(p, hp1);
  5128. p := hp1;
  5129. Result := True;
  5130. Exit;
  5131. end;
  5132. end;
  5133. end;
  5134. if DoArithCombineOpt(p) then
  5135. Result:=true;
  5136. end;
  5137. end;
  5138. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5139. var
  5140. hp1, hp2: tai;
  5141. ref: Integer;
  5142. saveref: treference;
  5143. offsetcalc: Int64;
  5144. TempReg: TRegister;
  5145. Multiple: TCGInt;
  5146. Adjacent, IntermediateRegDiscarded: Boolean;
  5147. begin
  5148. Result:=false;
  5149. { play save and throw an error if LEA uses a seg register prefix,
  5150. this is most likely an error somewhere else }
  5151. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5152. internalerror(2022022001);
  5153. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5154. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5155. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5156. (
  5157. { do not mess with leas accessing the stack pointer
  5158. unless it's a null operation }
  5159. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5160. (
  5161. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5162. (taicpu(p).oper[0]^.ref^.offset = 0)
  5163. )
  5164. ) and
  5165. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5166. begin
  5167. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5168. begin
  5169. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5170. begin
  5171. taicpu(p).opcode := A_MOV;
  5172. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5173. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5174. end
  5175. else
  5176. begin
  5177. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5178. RemoveCurrentP(p);
  5179. end;
  5180. Result:=true;
  5181. exit;
  5182. end
  5183. else if (
  5184. { continue to use lea to adjust the stack pointer,
  5185. it is the recommended way, but only if not optimizing for size }
  5186. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5187. (cs_opt_size in current_settings.optimizerswitches)
  5188. ) and
  5189. { If the flags register is in use, don't change the instruction
  5190. to an ADD otherwise this will scramble the flags. [Kit] }
  5191. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5192. ConvertLEA(taicpu(p)) then
  5193. begin
  5194. Result:=true;
  5195. exit;
  5196. end;
  5197. end;
  5198. { Don't optimise if the stack or frame pointer is the destination register }
  5199. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5200. Exit;
  5201. if GetNextInstruction(p,hp1) and
  5202. (hp1.typ=ait_instruction) then
  5203. begin
  5204. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5205. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5206. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5207. begin
  5208. TransferUsedRegs(TmpUsedRegs);
  5209. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5210. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5211. begin
  5212. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5213. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5214. RemoveInstruction(hp1);
  5215. result:=true;
  5216. exit;
  5217. end;
  5218. end;
  5219. { changes
  5220. lea <ref1>, reg1
  5221. <op> ...,<ref. with reg1>,...
  5222. to
  5223. <op> ...,<ref1>,... }
  5224. { find a reference which uses reg1 }
  5225. 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
  5226. ref:=0
  5227. 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
  5228. ref:=1
  5229. else
  5230. ref:=-1;
  5231. if (ref<>-1) and
  5232. { reg1 must be either the base or the index }
  5233. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5234. begin
  5235. { reg1 can be removed from the reference }
  5236. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5237. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5238. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5239. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5240. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5241. else
  5242. Internalerror(2019111201);
  5243. { check if the can insert all data of the lea into the second instruction }
  5244. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5245. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5246. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5247. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5248. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5249. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5250. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5251. {$ifdef x86_64}
  5252. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5253. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5254. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5255. )
  5256. {$endif x86_64}
  5257. then
  5258. begin
  5259. { reg1 might not used by the second instruction after it is remove from the reference }
  5260. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5261. begin
  5262. TransferUsedRegs(TmpUsedRegs);
  5263. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5264. { reg1 is not updated so it might not be used afterwards }
  5265. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5266. begin
  5267. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5268. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5269. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5270. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5271. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5272. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5273. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5274. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5275. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5276. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5277. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5278. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5279. RemoveCurrentP(p, hp1);
  5280. result:=true;
  5281. exit;
  5282. end
  5283. end;
  5284. end;
  5285. { recover }
  5286. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5287. end;
  5288. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5289. if Adjacent or
  5290. { Check further ahead (up to 2 instructions ahead for -O2) }
  5291. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5292. begin
  5293. { Check common LEA/LEA conditions }
  5294. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5295. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5296. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5297. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5298. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5299. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5300. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5301. (
  5302. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5303. calling it (since it calls GetNextInstruction) }
  5304. Adjacent or
  5305. (
  5306. (
  5307. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5308. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5309. ) and (
  5310. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5311. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5312. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5313. )
  5314. )
  5315. ) then
  5316. begin
  5317. TransferUsedRegs(TmpUsedRegs);
  5318. hp2 := p;
  5319. repeat
  5320. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5321. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5322. IntermediateRegDiscarded :=
  5323. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5324. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5325. { changes
  5326. lea offset1(regX,scale), reg1
  5327. lea offset2(reg1,reg1), reg2
  5328. to
  5329. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5330. and
  5331. lea offset1(regX,scale1), reg1
  5332. lea offset2(reg1,scale2), reg2
  5333. to
  5334. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5335. and
  5336. lea offset1(regX,scale1), reg1
  5337. lea offset2(reg3,reg1,scale2), reg2
  5338. to
  5339. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5340. ... so long as the final scale does not exceed 8
  5341. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5342. }
  5343. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5344. (
  5345. { Don't optimise if size is a concern and the intermediate register remains in use }
  5346. IntermediateRegDiscarded or
  5347. not (cs_opt_size in current_settings.optimizerswitches)
  5348. ) and
  5349. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5350. (
  5351. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5352. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5353. ) and (
  5354. (
  5355. { lea (reg1,scale2), reg2 variant }
  5356. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5357. (
  5358. Adjacent or
  5359. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5360. ) and
  5361. (
  5362. (
  5363. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5364. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5365. ) or (
  5366. { lea (regX,regX), reg1 variant }
  5367. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5368. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5369. )
  5370. )
  5371. ) or (
  5372. { lea (reg1,reg1), reg1 variant }
  5373. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5374. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5375. )
  5376. ) then
  5377. begin
  5378. { Make everything homogeneous to make calculations easier }
  5379. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5380. begin
  5381. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5382. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5383. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5384. else
  5385. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5386. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5387. end;
  5388. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5389. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5390. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5391. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5392. begin
  5393. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5394. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5395. begin
  5396. { Put the register to change in the index register }
  5397. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5398. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5399. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5400. end;
  5401. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5402. begin
  5403. { Just to prevent miscalculations }
  5404. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5405. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5406. else
  5407. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5408. end
  5409. else
  5410. begin
  5411. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5412. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5413. end;
  5414. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5415. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5416. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5417. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5418. if IntermediateRegDiscarded then
  5419. begin
  5420. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5421. RemoveCurrentP(p);
  5422. end
  5423. else
  5424. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5425. result:=true;
  5426. exit;
  5427. end;
  5428. end;
  5429. { changes
  5430. lea offset1(regX), reg1
  5431. lea offset2(reg1), reg2
  5432. to
  5433. lea offset1+offset2(regX), reg2 }
  5434. if (
  5435. { Don't optimise if size is a concern and the intermediate register remains in use }
  5436. IntermediateRegDiscarded or
  5437. not (cs_opt_size in current_settings.optimizerswitches)
  5438. ) and
  5439. (
  5440. (
  5441. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5442. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5443. ) or (
  5444. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5445. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5446. (
  5447. (
  5448. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5449. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5450. ) or (
  5451. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5452. (
  5453. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5454. (
  5455. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5456. (
  5457. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5458. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5459. )
  5460. )
  5461. )
  5462. )
  5463. )
  5464. )
  5465. ) then
  5466. begin
  5467. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5468. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5469. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5470. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5471. begin
  5472. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5473. begin
  5474. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5475. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5476. { if the register is used as index and base, we have to increase for base as well
  5477. and adapt base }
  5478. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5479. begin
  5480. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5481. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5482. end;
  5483. end
  5484. else
  5485. begin
  5486. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5487. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5488. end;
  5489. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5490. begin
  5491. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5492. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5493. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5494. end;
  5495. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5496. if IntermediateRegDiscarded then
  5497. begin
  5498. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5499. RemoveCurrentP(p);
  5500. end
  5501. else
  5502. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5503. result:=true;
  5504. exit;
  5505. end;
  5506. end;
  5507. end;
  5508. { Change:
  5509. leal/q $x(%reg1),%reg2
  5510. ...
  5511. shll/q $y,%reg2
  5512. To:
  5513. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5514. }
  5515. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5516. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5517. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5518. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5519. (taicpu(hp1).oper[0]^.val <= 3) then
  5520. begin
  5521. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5524. if
  5525. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5526. (this works even if scalefactor is zero) }
  5527. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5528. { Ensure offset doesn't go out of bounds }
  5529. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5530. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5531. (
  5532. (
  5533. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5534. (
  5535. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5536. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5537. (
  5538. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5539. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5540. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5541. )
  5542. )
  5543. ) or (
  5544. (
  5545. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5546. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5547. ) and
  5548. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5549. )
  5550. ) then
  5551. begin
  5552. repeat
  5553. with taicpu(p).oper[0]^.ref^ do
  5554. begin
  5555. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5556. if index = base then
  5557. begin
  5558. if Multiple > 4 then
  5559. { Optimisation will no longer work because resultant
  5560. scale factor will exceed 8 }
  5561. Break;
  5562. base := NR_NO;
  5563. scalefactor := 2;
  5564. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5565. end
  5566. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5567. begin
  5568. { Scale factor only works on the index register }
  5569. index := base;
  5570. base := NR_NO;
  5571. end;
  5572. { For safety }
  5573. if scalefactor <= 1 then
  5574. begin
  5575. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5576. scalefactor := Multiple;
  5577. end
  5578. else
  5579. begin
  5580. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5581. scalefactor := scalefactor * Multiple;
  5582. end;
  5583. offset := offset * Multiple;
  5584. end;
  5585. RemoveInstruction(hp1);
  5586. Result := True;
  5587. Exit;
  5588. { This repeat..until loop exists for the benefit of Break }
  5589. until True;
  5590. end;
  5591. end;
  5592. end;
  5593. end;
  5594. end;
  5595. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5596. var
  5597. hp1 : tai;
  5598. SubInstr: Boolean;
  5599. ThisConst: TCGInt;
  5600. const
  5601. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5602. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5603. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5604. begin
  5605. Result := False;
  5606. if taicpu(p).oper[0]^.typ <> top_const then
  5607. { Should have been confirmed before calling }
  5608. InternalError(2021102601);
  5609. SubInstr := (taicpu(p).opcode = A_SUB);
  5610. if GetLastInstruction(p, hp1) and
  5611. (hp1.typ = ait_instruction) and
  5612. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5613. begin
  5614. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5615. { Bad size }
  5616. InternalError(2022042001);
  5617. case taicpu(hp1).opcode Of
  5618. A_INC:
  5619. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5620. begin
  5621. if SubInstr then
  5622. ThisConst := taicpu(p).oper[0]^.val - 1
  5623. else
  5624. ThisConst := taicpu(p).oper[0]^.val + 1;
  5625. end
  5626. else
  5627. Exit;
  5628. A_DEC:
  5629. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5630. begin
  5631. if SubInstr then
  5632. ThisConst := taicpu(p).oper[0]^.val + 1
  5633. else
  5634. ThisConst := taicpu(p).oper[0]^.val - 1;
  5635. end
  5636. else
  5637. Exit;
  5638. A_SUB:
  5639. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5640. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5641. begin
  5642. if SubInstr then
  5643. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5644. else
  5645. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5646. end
  5647. else
  5648. Exit;
  5649. A_ADD:
  5650. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5651. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5652. begin
  5653. if SubInstr then
  5654. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5655. else
  5656. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5657. end
  5658. else
  5659. Exit;
  5660. else
  5661. Exit;
  5662. end;
  5663. { Check that the values are in range }
  5664. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5665. { Overflow; abort }
  5666. Exit;
  5667. if (ThisConst = 0) then
  5668. begin
  5669. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5670. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5671. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5672. RemoveInstruction(hp1);
  5673. hp1 := tai(p.next);
  5674. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5675. if not GetLastInstruction(hp1, p) then
  5676. p := hp1;
  5677. end
  5678. else
  5679. begin
  5680. if taicpu(hp1).opercnt=1 then
  5681. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5682. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5683. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5684. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5685. else
  5686. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5687. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5688. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5689. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5690. RemoveInstruction(hp1);
  5691. taicpu(p).loadconst(0, ThisConst);
  5692. end;
  5693. Result := True;
  5694. end;
  5695. end;
  5696. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5697. var
  5698. hp2: tai;
  5699. begin
  5700. Result := False;
  5701. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5702. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5703. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5704. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5705. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5706. (
  5707. (
  5708. (taicpu(hp1).opcode = A_TEST)
  5709. ) or (
  5710. (taicpu(hp1).opcode = A_CMP) and
  5711. { A sanity check more than anything }
  5712. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5713. )
  5714. ) then
  5715. begin
  5716. { change
  5717. mov mem, %reg
  5718. ...
  5719. cmp/test x, %reg / test %reg,%reg
  5720. (reg deallocated)
  5721. to
  5722. cmp/test x, mem / cmp 0, mem
  5723. }
  5724. TransferUsedRegs(TmpUsedRegs);
  5725. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5726. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5727. begin
  5728. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5729. if (taicpu(hp1).opcode = A_TEST) and
  5730. (
  5731. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5732. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5733. ) then
  5734. begin
  5735. taicpu(hp1).opcode := A_CMP;
  5736. taicpu(hp1).loadconst(0, 0);
  5737. end;
  5738. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5739. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5740. RemoveCurrentP(p);
  5741. if (p <> hp1) then
  5742. begin
  5743. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5744. hp2 := p;
  5745. repeat
  5746. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5747. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5748. end;
  5749. { Make sure the flags are allocated across the CMP instruction }
  5750. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5751. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5752. Result := True;
  5753. Exit;
  5754. end;
  5755. end;
  5756. end;
  5757. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5758. var
  5759. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5760. ThisReg, SecondReg: TRegister;
  5761. JumpLoc: TAsmLabel;
  5762. NewSize: TOpSize;
  5763. begin
  5764. Result := False;
  5765. {
  5766. Convert:
  5767. j<c> .L1
  5768. .L2:
  5769. mov 1,reg
  5770. jmp .L3 (or ret, although it might not be a RET yet)
  5771. .L1:
  5772. mov 0,reg
  5773. jmp .L3 (or ret)
  5774. ( As long as .L3 <> .L1 or .L2)
  5775. To:
  5776. mov 0,reg
  5777. set<not(c)> reg
  5778. jmp .L3 (or ret)
  5779. .L2:
  5780. mov 1,reg
  5781. jmp .L3 (or ret)
  5782. .L1:
  5783. mov 0,reg
  5784. jmp .L3 (or ret)
  5785. }
  5786. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5787. Exit;
  5788. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5789. if GetNextInstruction(hp_label, hp2) and
  5790. MatchInstruction(hp2,A_MOV,[]) and
  5791. (taicpu(hp2).oper[0]^.typ = top_const) and
  5792. (
  5793. (
  5794. (taicpu(hp2).oper[1]^.typ = top_reg)
  5795. {$ifdef i386}
  5796. { Under i386, ESI, EDI, EBP and ESP
  5797. don't have an 8-bit representation }
  5798. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5799. {$endif i386}
  5800. ) or (
  5801. {$ifdef i386}
  5802. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5803. {$endif i386}
  5804. (taicpu(hp2).opsize = S_B)
  5805. )
  5806. ) and
  5807. GetNextInstruction(hp2, hp3) and
  5808. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5809. (
  5810. (taicpu(hp3).opcode=A_RET) or
  5811. (
  5812. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5813. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5814. )
  5815. ) and
  5816. GetNextInstruction(hp3, hp4) and
  5817. SkipAligns(hp4, hp4) and
  5818. (hp4.typ=ait_label) and
  5819. (tai_label(hp4).labsym=JumpLoc) and
  5820. (
  5821. not (cs_opt_size in current_settings.optimizerswitches) or
  5822. { If the initial jump is the label's only reference, then it will
  5823. become a dead label if the other conditions are met and hence
  5824. remove at least 2 instructions, including a jump }
  5825. (JumpLoc.getrefs = 1)
  5826. ) and
  5827. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5828. that will be optimised out }
  5829. GetNextInstruction(hp4, hp5) and
  5830. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5831. (taicpu(hp5).oper[0]^.typ = top_const) and
  5832. (
  5833. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5834. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5835. ) and
  5836. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5837. GetNextInstruction(hp5,hp6) and
  5838. (
  5839. (hp6.typ<>ait_label) or
  5840. SkipLabels(hp6, hp6)
  5841. ) and
  5842. (hp6.typ=ait_instruction) then
  5843. begin
  5844. { First, let's look at the two jumps that are hp3 and hp6 }
  5845. if not
  5846. (
  5847. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5848. (
  5849. (taicpu(hp6).opcode=A_RET) or
  5850. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5851. )
  5852. ) then
  5853. { If condition is False, then the JMP/RET instructions matched conventionally }
  5854. begin
  5855. { See if one of the jumps can be instantly converted into a RET }
  5856. if (taicpu(hp3).opcode=A_JMP) then
  5857. begin
  5858. { Reuse hp5 }
  5859. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5860. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5861. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5862. Exit;
  5863. if MatchInstruction(hp5, A_RET, []) then
  5864. begin
  5865. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5866. ConvertJumpToRET(hp3, hp5);
  5867. Result := True;
  5868. end
  5869. else
  5870. Exit;
  5871. end;
  5872. if (taicpu(hp6).opcode=A_JMP) then
  5873. begin
  5874. { Reuse hp5 }
  5875. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5876. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5877. Exit;
  5878. if MatchInstruction(hp5, A_RET, []) then
  5879. begin
  5880. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5881. ConvertJumpToRET(hp6, hp5);
  5882. Result := True;
  5883. end
  5884. else
  5885. Exit;
  5886. end;
  5887. if not
  5888. (
  5889. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5890. (
  5891. (taicpu(hp6).opcode=A_RET) or
  5892. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5893. )
  5894. ) then
  5895. { Still doesn't match }
  5896. Exit;
  5897. end;
  5898. if (taicpu(hp2).oper[0]^.val = 1) then
  5899. begin
  5900. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5901. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5902. end
  5903. else
  5904. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5905. if taicpu(hp2).opsize=S_B then
  5906. begin
  5907. if taicpu(hp2).oper[1]^.typ = top_reg then
  5908. begin
  5909. SecondReg := taicpu(hp2).oper[1]^.reg;
  5910. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5911. end
  5912. else
  5913. begin
  5914. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5915. SecondReg := NR_NO;
  5916. end;
  5917. hp_pos := p;
  5918. hp_allocstart := hp4;
  5919. end
  5920. else
  5921. begin
  5922. { Will be a register because the size can't be S_B otherwise }
  5923. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5924. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5925. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5926. if (cs_opt_size in current_settings.optimizerswitches) then
  5927. begin
  5928. { Favour using MOVZX when optimising for size }
  5929. case taicpu(hp2).opsize of
  5930. S_W:
  5931. NewSize := S_BW;
  5932. S_L:
  5933. NewSize := S_BL;
  5934. {$ifdef x86_64}
  5935. S_Q:
  5936. begin
  5937. NewSize := S_BL;
  5938. { Will implicitly zero-extend to 64-bit }
  5939. setsubreg(SecondReg, R_SUBD);
  5940. end;
  5941. {$endif x86_64}
  5942. else
  5943. InternalError(2022101301);
  5944. end;
  5945. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5946. { Inserting it right before p will guarantee that the flags are also tracked }
  5947. Asml.InsertBefore(hp5, p);
  5948. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5949. hp_pos := hp5;
  5950. hp_allocstart := hp4;
  5951. end
  5952. else
  5953. begin
  5954. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5955. { Inserting it right before p will guarantee that the flags are also tracked }
  5956. Asml.InsertBefore(hp5, p);
  5957. hp_pos := p;
  5958. hp_allocstart := hp5;
  5959. end;
  5960. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5961. end;
  5962. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5963. taicpu(hp4).condition := taicpu(p).condition;
  5964. asml.InsertBefore(hp4, hp_pos);
  5965. if taicpu(hp3).is_jmp then
  5966. begin
  5967. JumpLoc.decrefs;
  5968. MakeUnconditional(taicpu(p));
  5969. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5970. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5971. end
  5972. else
  5973. ConvertJumpToRET(p, hp3);
  5974. if SecondReg <> NR_NO then
  5975. { Ensure the destination register is allocated over this region }
  5976. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5977. if (JumpLoc.getrefs = 0) then
  5978. RemoveDeadCodeAfterJump(hp3);
  5979. Result:=true;
  5980. exit;
  5981. end;
  5982. end;
  5983. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5984. var
  5985. hp1, hp2: tai;
  5986. ActiveReg: TRegister;
  5987. OldOffset: asizeint;
  5988. ThisConst: TCGInt;
  5989. function RegDeallocated: Boolean;
  5990. begin
  5991. TransferUsedRegs(TmpUsedRegs);
  5992. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5993. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5994. end;
  5995. begin
  5996. Result:=false;
  5997. hp1 := nil;
  5998. { replace
  5999. subX const,%reg1
  6000. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6001. dealloc %reg1
  6002. by
  6003. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6004. }
  6005. if MatchOpType(taicpu(p),top_const,top_reg) then
  6006. begin
  6007. ActiveReg := taicpu(p).oper[1]^.reg;
  6008. { Ensures the entire register was updated }
  6009. if (taicpu(p).opsize >= S_L) and
  6010. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6011. MatchInstruction(hp1,A_LEA,[]) and
  6012. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6013. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6014. (
  6015. { Cover the case where the register in the reference is also the destination register }
  6016. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6017. (
  6018. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6019. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6020. RegDeallocated
  6021. )
  6022. ) then
  6023. begin
  6024. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6025. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6026. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6027. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6028. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6029. {$ifdef x86_64}
  6030. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6031. begin
  6032. { Overflow; abort }
  6033. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6034. end
  6035. else
  6036. {$endif x86_64}
  6037. begin
  6038. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6039. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6040. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6041. RemoveCurrentP(p, hp1)
  6042. else
  6043. RemoveCurrentP(p);
  6044. result:=true;
  6045. Exit;
  6046. end;
  6047. end;
  6048. if (
  6049. { Save calling GetNextInstructionUsingReg again }
  6050. Assigned(hp1) or
  6051. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6052. ) and
  6053. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6054. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6055. begin
  6056. if taicpu(hp1).oper[0]^.typ = top_const then
  6057. begin
  6058. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6059. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6060. Result := True;
  6061. { Handle any overflows }
  6062. case taicpu(p).opsize of
  6063. S_B:
  6064. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6065. S_W:
  6066. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6067. S_L:
  6068. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6069. {$ifdef x86_64}
  6070. S_Q:
  6071. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6072. { Overflow; abort }
  6073. Result := False
  6074. else
  6075. taicpu(p).oper[0]^.val := ThisConst;
  6076. {$endif x86_64}
  6077. else
  6078. InternalError(2021102611);
  6079. end;
  6080. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6081. if Result then
  6082. begin
  6083. if (taicpu(p).oper[0]^.val < 0) and
  6084. (
  6085. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6086. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6087. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6088. ) then
  6089. begin
  6090. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6091. taicpu(p).opcode := A_SUB;
  6092. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6093. end
  6094. else
  6095. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6096. RemoveInstruction(hp1);
  6097. end;
  6098. end
  6099. else
  6100. begin
  6101. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6102. TransferUsedRegs(TmpUsedRegs);
  6103. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6104. hp2 := p;
  6105. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6106. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6107. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6108. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6109. begin
  6110. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6111. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6112. Asml.Remove(p);
  6113. Asml.InsertAfter(p, hp1);
  6114. p := hp1;
  6115. Result := True;
  6116. Exit;
  6117. end;
  6118. end;
  6119. end;
  6120. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6121. { * change "sub/add const1, reg" or "dec reg" followed by
  6122. "sub const2, reg" to one "sub ..., reg" }
  6123. {$ifdef i386}
  6124. if (taicpu(p).oper[0]^.val = 2) and
  6125. (ActiveReg = NR_ESP) and
  6126. { Don't do the sub/push optimization if the sub }
  6127. { comes from setting up the stack frame (JM) }
  6128. (not(GetLastInstruction(p,hp1)) or
  6129. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6130. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6131. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6132. begin
  6133. hp1 := tai(p.next);
  6134. while Assigned(hp1) and
  6135. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6136. not RegReadByInstruction(NR_ESP,hp1) and
  6137. not RegModifiedByInstruction(NR_ESP,hp1) do
  6138. hp1 := tai(hp1.next);
  6139. if Assigned(hp1) and
  6140. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6141. begin
  6142. taicpu(hp1).changeopsize(S_L);
  6143. if taicpu(hp1).oper[0]^.typ=top_reg then
  6144. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6145. hp1 := tai(p.next);
  6146. RemoveCurrentp(p, hp1);
  6147. Result:=true;
  6148. exit;
  6149. end;
  6150. end;
  6151. {$endif i386}
  6152. if DoArithCombineOpt(p) then
  6153. Result:=true;
  6154. end;
  6155. end;
  6156. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6157. var
  6158. TmpBool1,TmpBool2 : Boolean;
  6159. tmpref : treference;
  6160. hp1,hp2: tai;
  6161. mask, shiftval: tcgint;
  6162. begin
  6163. Result:=false;
  6164. { All these optimisations work on "shl/sal const,%reg" }
  6165. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6166. Exit;
  6167. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6168. (taicpu(p).oper[0]^.val <= 3) then
  6169. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6170. begin
  6171. { should we check the next instruction? }
  6172. TmpBool1 := True;
  6173. { have we found an add/sub which could be
  6174. integrated in the lea? }
  6175. TmpBool2 := False;
  6176. reference_reset(tmpref,2,[]);
  6177. TmpRef.index := taicpu(p).oper[1]^.reg;
  6178. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6179. while TmpBool1 and
  6180. GetNextInstruction(p, hp1) and
  6181. (tai(hp1).typ = ait_instruction) and
  6182. ((((taicpu(hp1).opcode = A_ADD) or
  6183. (taicpu(hp1).opcode = A_SUB)) and
  6184. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6185. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6186. (((taicpu(hp1).opcode = A_INC) or
  6187. (taicpu(hp1).opcode = A_DEC)) and
  6188. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6189. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6190. ((taicpu(hp1).opcode = A_LEA) and
  6191. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6192. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6193. (not GetNextInstruction(hp1,hp2) or
  6194. not instrReadsFlags(hp2)) Do
  6195. begin
  6196. TmpBool1 := False;
  6197. if taicpu(hp1).opcode=A_LEA then
  6198. begin
  6199. if (TmpRef.base = NR_NO) and
  6200. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6201. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6202. { Segment register isn't a concern here }
  6203. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6204. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6205. begin
  6206. TmpBool1 := True;
  6207. TmpBool2 := True;
  6208. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6209. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6210. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6211. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6212. RemoveInstruction(hp1);
  6213. end
  6214. end
  6215. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6216. begin
  6217. TmpBool1 := True;
  6218. TmpBool2 := True;
  6219. case taicpu(hp1).opcode of
  6220. A_ADD:
  6221. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6222. A_SUB:
  6223. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6224. else
  6225. internalerror(2019050536);
  6226. end;
  6227. RemoveInstruction(hp1);
  6228. end
  6229. else
  6230. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6231. (((taicpu(hp1).opcode = A_ADD) and
  6232. (TmpRef.base = NR_NO)) or
  6233. (taicpu(hp1).opcode = A_INC) or
  6234. (taicpu(hp1).opcode = A_DEC)) then
  6235. begin
  6236. TmpBool1 := True;
  6237. TmpBool2 := True;
  6238. case taicpu(hp1).opcode of
  6239. A_ADD:
  6240. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6241. A_INC:
  6242. inc(TmpRef.offset);
  6243. A_DEC:
  6244. dec(TmpRef.offset);
  6245. else
  6246. internalerror(2019050535);
  6247. end;
  6248. RemoveInstruction(hp1);
  6249. end;
  6250. end;
  6251. if TmpBool2
  6252. {$ifndef x86_64}
  6253. or
  6254. ((current_settings.optimizecputype < cpu_Pentium2) and
  6255. (taicpu(p).oper[0]^.val <= 3) and
  6256. not(cs_opt_size in current_settings.optimizerswitches))
  6257. {$endif x86_64}
  6258. then
  6259. begin
  6260. if not(TmpBool2) and
  6261. (taicpu(p).oper[0]^.val=1) then
  6262. begin
  6263. taicpu(p).opcode := A_ADD;
  6264. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6265. end
  6266. else
  6267. begin
  6268. taicpu(p).opcode := A_LEA;
  6269. taicpu(p).loadref(0, TmpRef);
  6270. end;
  6271. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6272. Result := True;
  6273. end;
  6274. end
  6275. {$ifndef x86_64}
  6276. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6277. begin
  6278. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6279. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6280. (unlike shl, which is only Tairable in the U pipe) }
  6281. if taicpu(p).oper[0]^.val=1 then
  6282. begin
  6283. taicpu(p).opcode := A_ADD;
  6284. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6285. Result := True;
  6286. end
  6287. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6288. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6289. else if (taicpu(p).opsize = S_L) and
  6290. (taicpu(p).oper[0]^.val<= 3) then
  6291. begin
  6292. reference_reset(tmpref,2,[]);
  6293. TmpRef.index := taicpu(p).oper[1]^.reg;
  6294. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6295. taicpu(p).opcode := A_LEA;
  6296. taicpu(p).loadref(0, TmpRef);
  6297. Result := True;
  6298. end;
  6299. end
  6300. {$endif x86_64}
  6301. else if
  6302. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6303. (
  6304. (
  6305. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6306. SetAndTest(hp1, hp2)
  6307. {$ifdef x86_64}
  6308. ) or
  6309. (
  6310. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6311. GetNextInstruction(hp1, hp2) and
  6312. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6313. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6314. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6315. {$endif x86_64}
  6316. )
  6317. ) and
  6318. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6319. begin
  6320. { Change:
  6321. shl x, %reg1
  6322. mov -(1<<x), %reg2
  6323. and %reg2, %reg1
  6324. Or:
  6325. shl x, %reg1
  6326. and -(1<<x), %reg1
  6327. To just:
  6328. shl x, %reg1
  6329. Since the and operation only zeroes bits that are already zero from the shl operation
  6330. }
  6331. case taicpu(p).oper[0]^.val of
  6332. 8:
  6333. mask:=$FFFFFFFFFFFFFF00;
  6334. 16:
  6335. mask:=$FFFFFFFFFFFF0000;
  6336. 32:
  6337. mask:=$FFFFFFFF00000000;
  6338. 63:
  6339. { Constant pre-calculated to prevent overflow errors with Int64 }
  6340. mask:=$8000000000000000;
  6341. else
  6342. begin
  6343. if taicpu(p).oper[0]^.val >= 64 then
  6344. { Shouldn't happen realistically, since the register
  6345. is guaranteed to be set to zero at this point }
  6346. mask := 0
  6347. else
  6348. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6349. end;
  6350. end;
  6351. if taicpu(hp1).oper[0]^.val = mask then
  6352. begin
  6353. { Everything checks out, perform the optimisation, as long as
  6354. the FLAGS register isn't being used}
  6355. TransferUsedRegs(TmpUsedRegs);
  6356. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6357. {$ifdef x86_64}
  6358. if (hp1 <> hp2) then
  6359. begin
  6360. { "shl/mov/and" version }
  6361. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6362. { Don't do the optimisation if the FLAGS register is in use }
  6363. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6364. begin
  6365. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6366. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6367. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6368. begin
  6369. RemoveInstruction(hp1);
  6370. Result := True;
  6371. end;
  6372. { Only set Result to True if the 'mov' instruction was removed }
  6373. RemoveInstruction(hp2);
  6374. end;
  6375. end
  6376. else
  6377. {$endif x86_64}
  6378. begin
  6379. { "shl/and" version }
  6380. { Don't do the optimisation if the FLAGS register is in use }
  6381. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6382. begin
  6383. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6384. RemoveInstruction(hp1);
  6385. Result := True;
  6386. end;
  6387. end;
  6388. Exit;
  6389. end
  6390. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6391. begin
  6392. { Even if the mask doesn't allow for its removal, we might be
  6393. able to optimise the mask for the "shl/and" version, which
  6394. may permit other peephole optimisations }
  6395. {$ifdef DEBUG_AOPTCPU}
  6396. mask := taicpu(hp1).oper[0]^.val and mask;
  6397. if taicpu(hp1).oper[0]^.val <> mask then
  6398. begin
  6399. DebugMsg(
  6400. SPeepholeOptimization +
  6401. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6402. ' to $' + debug_tostr(mask) +
  6403. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6404. taicpu(hp1).oper[0]^.val := mask;
  6405. end;
  6406. {$else DEBUG_AOPTCPU}
  6407. { If debugging is off, just set the operand even if it's the same }
  6408. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6409. {$endif DEBUG_AOPTCPU}
  6410. end;
  6411. end;
  6412. {
  6413. change
  6414. shl/sal const,reg
  6415. <op> ...(...,reg,1),...
  6416. into
  6417. <op> ...(...,reg,1 shl const),...
  6418. if const in 1..3
  6419. }
  6420. if MatchOpType(taicpu(p), top_const, top_reg) and
  6421. (taicpu(p).oper[0]^.val in [1..3]) and
  6422. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6423. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6424. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6425. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6426. MatchOpType(taicpu(hp1),top_ref))
  6427. ) and
  6428. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6429. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6430. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6431. begin
  6432. TransferUsedRegs(TmpUsedRegs);
  6433. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6434. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6435. begin
  6436. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6437. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6438. RemoveCurrentP(p);
  6439. Result:=true;
  6440. exit;
  6441. end;
  6442. end;
  6443. if MatchOpType(taicpu(p), top_const, top_reg) and
  6444. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6445. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6446. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6447. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6448. begin
  6449. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6450. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6451. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6452. {$ifdef x86_64}
  6453. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6454. {$endif x86_64}
  6455. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6456. begin
  6457. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6458. taicpu(hp1).opcode:=A_MOV;
  6459. taicpu(hp1).oper[0]^.val:=0;
  6460. end
  6461. else
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6464. taicpu(hp1).oper[0]^.val:=shiftval;
  6465. end;
  6466. RemoveCurrentP(p);
  6467. Result:=true;
  6468. exit;
  6469. end;
  6470. end;
  6471. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6472. begin
  6473. case shr_size of
  6474. S_B:
  6475. { No valid combinations }
  6476. Result := False;
  6477. S_W:
  6478. Result := (Shift >= 8) and (movz_size = S_BW);
  6479. S_L:
  6480. Result :=
  6481. (Shift >= 24) { Any opsize is valid for this shift } or
  6482. ((Shift >= 16) and (movz_size = S_WL));
  6483. {$ifdef x86_64}
  6484. S_Q:
  6485. Result :=
  6486. (Shift >= 56) { Any opsize is valid for this shift } or
  6487. ((Shift >= 48) and (movz_size = S_WL));
  6488. {$endif x86_64}
  6489. else
  6490. InternalError(2022081510);
  6491. end;
  6492. end;
  6493. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6494. var
  6495. hp1, hp2: tai;
  6496. Shift: TCGInt;
  6497. LimitSize: Topsize;
  6498. DoNotMerge: Boolean;
  6499. begin
  6500. Result := False;
  6501. { All these optimisations work on "shr const,%reg" }
  6502. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6503. Exit;
  6504. DoNotMerge := False;
  6505. Shift := taicpu(p).oper[0]^.val;
  6506. LimitSize := taicpu(p).opsize;
  6507. hp1 := p;
  6508. repeat
  6509. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6510. Exit;
  6511. case taicpu(hp1).opcode of
  6512. A_TEST, A_CMP, A_Jcc:
  6513. { Skip over conditional jumps and relevant comparisons }
  6514. Continue;
  6515. A_MOVZX:
  6516. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6517. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6518. begin
  6519. { Since the original register is being read as is, subsequent
  6520. SHRs must not be merged at this point }
  6521. DoNotMerge := True;
  6522. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6523. begin
  6524. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6525. begin
  6526. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6527. taicpu(hp1).opcode := A_MOV;
  6528. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6529. case taicpu(hp1).opsize of
  6530. S_BW:
  6531. taicpu(hp1).opsize := S_W;
  6532. S_BL, S_WL:
  6533. taicpu(hp1).opsize := S_L;
  6534. else
  6535. InternalError(2022081503);
  6536. end;
  6537. { p itself hasn't changed, so no need to set Result to True }
  6538. Include(OptsToCheck, aoc_ForceNewIteration);
  6539. { See if there's anything afterwards that can be
  6540. optimised, since the input register hasn't changed }
  6541. Continue;
  6542. end;
  6543. { NOTE: If the MOVZX instruction reads and writes the same
  6544. register, defer this to the post-peephole optimisation stage }
  6545. Exit;
  6546. end;
  6547. end;
  6548. A_SHL, A_SAL, A_SHR:
  6549. if (taicpu(hp1).opsize <= LimitSize) and
  6550. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6551. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6552. begin
  6553. { Make sure the sizes don't exceed the register size limit
  6554. (measured by the shift value falling below the limit) }
  6555. if taicpu(hp1).opsize < LimitSize then
  6556. LimitSize := taicpu(hp1).opsize;
  6557. if taicpu(hp1).opcode = A_SHR then
  6558. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6559. else
  6560. begin
  6561. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6562. DoNotMerge := True;
  6563. end;
  6564. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6565. Exit;
  6566. { Since we've established that the combined shift is within
  6567. limits, we can actually combine the adjacent SHR
  6568. instructions even if they're different sizes }
  6569. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6570. begin
  6571. hp2 := tai(hp1.Previous);
  6572. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6573. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6574. RemoveInstruction(hp1);
  6575. hp1 := hp2;
  6576. { Though p has changed, only the constant has, and its
  6577. effects can still be detected on the next iteration of
  6578. the repeat..until loop }
  6579. Include(OptsToCheck, aoc_ForceNewIteration);
  6580. end;
  6581. { Move onto the next instruction }
  6582. Continue;
  6583. end;
  6584. else
  6585. ;
  6586. end;
  6587. Break;
  6588. until False;
  6589. end;
  6590. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6591. var
  6592. CurrentRef: TReference;
  6593. FullReg: TRegister;
  6594. hp1, hp2: tai;
  6595. begin
  6596. Result := False;
  6597. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6598. Exit;
  6599. { We assume you've checked if the operand is actually a reference by
  6600. this point. If it isn't, you'll most likely get an access violation }
  6601. CurrentRef := first_mov.oper[1]^.ref^;
  6602. { Memory must be aligned }
  6603. if (CurrentRef.offset mod 4) <> 0 then
  6604. Exit;
  6605. Inc(CurrentRef.offset);
  6606. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6607. if MatchOperand(second_mov.oper[0]^, 0) and
  6608. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6609. GetNextInstruction(second_mov, hp1) and
  6610. (hp1.typ = ait_instruction) and
  6611. (taicpu(hp1).opcode = A_MOV) and
  6612. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6613. (taicpu(hp1).oper[0]^.val = 0) then
  6614. begin
  6615. Inc(CurrentRef.offset);
  6616. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6617. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6618. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6619. begin
  6620. case taicpu(hp1).opsize of
  6621. S_B:
  6622. if GetNextInstruction(hp1, hp2) and
  6623. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6624. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6625. (taicpu(hp2).oper[0]^.val = 0) then
  6626. begin
  6627. Inc(CurrentRef.offset);
  6628. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6629. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6630. (taicpu(hp2).opsize = S_B) then
  6631. begin
  6632. RemoveInstruction(hp1);
  6633. RemoveInstruction(hp2);
  6634. first_mov.opsize := S_L;
  6635. if first_mov.oper[0]^.typ = top_reg then
  6636. begin
  6637. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6638. { Reuse second_mov as a MOVZX instruction }
  6639. second_mov.opcode := A_MOVZX;
  6640. second_mov.opsize := S_BL;
  6641. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6642. second_mov.loadreg(1, FullReg);
  6643. first_mov.oper[0]^.reg := FullReg;
  6644. asml.Remove(second_mov);
  6645. asml.InsertBefore(second_mov, first_mov);
  6646. end
  6647. else
  6648. { It's a value }
  6649. begin
  6650. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6651. RemoveInstruction(second_mov);
  6652. end;
  6653. Result := True;
  6654. Exit;
  6655. end;
  6656. end;
  6657. S_W:
  6658. begin
  6659. RemoveInstruction(hp1);
  6660. first_mov.opsize := S_L;
  6661. if first_mov.oper[0]^.typ = top_reg then
  6662. begin
  6663. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6664. { Reuse second_mov as a MOVZX instruction }
  6665. second_mov.opcode := A_MOVZX;
  6666. second_mov.opsize := S_BL;
  6667. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6668. second_mov.loadreg(1, FullReg);
  6669. first_mov.oper[0]^.reg := FullReg;
  6670. asml.Remove(second_mov);
  6671. asml.InsertBefore(second_mov, first_mov);
  6672. end
  6673. else
  6674. { It's a value }
  6675. begin
  6676. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6677. RemoveInstruction(second_mov);
  6678. end;
  6679. Result := True;
  6680. Exit;
  6681. end;
  6682. else
  6683. ;
  6684. end;
  6685. end;
  6686. end;
  6687. end;
  6688. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6689. { returns true if a "continue" should be done after this optimization }
  6690. var
  6691. hp1, hp2, hp3: tai;
  6692. begin
  6693. Result := false;
  6694. hp3 := nil;
  6695. if MatchOpType(taicpu(p),top_ref) and
  6696. GetNextInstruction(p, hp1) and
  6697. (hp1.typ = ait_instruction) and
  6698. (((taicpu(hp1).opcode = A_FLD) and
  6699. (taicpu(p).opcode = A_FSTP)) or
  6700. ((taicpu(p).opcode = A_FISTP) and
  6701. (taicpu(hp1).opcode = A_FILD))) and
  6702. MatchOpType(taicpu(hp1),top_ref) and
  6703. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6704. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6705. begin
  6706. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6707. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6708. GetNextInstruction(hp1, hp2) and
  6709. (((hp2.typ = ait_instruction) and
  6710. IsExitCode(hp2) and
  6711. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6712. not(assigned(current_procinfo.procdef.funcretsym) and
  6713. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6714. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6715. { fstp <temp>
  6716. fld <temp>
  6717. <dealloc> <temp>
  6718. }
  6719. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6720. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6721. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6722. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6723. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6724. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6725. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6726. )
  6727. )
  6728. ) then
  6729. begin
  6730. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6731. RemoveInstruction(hp1);
  6732. RemoveCurrentP(p, hp2);
  6733. { first case: exit code }
  6734. if hp2.typ = ait_instruction then
  6735. RemoveLastDeallocForFuncRes(p);
  6736. Result := true;
  6737. end
  6738. else
  6739. { we can do this only in fast math mode as fstp is rounding ...
  6740. ... still disabled as it breaks the compiler and/or rtl }
  6741. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6742. { ... or if another fstp equal to the first one follows }
  6743. GetNextInstruction(hp1,hp2) and
  6744. (hp2.typ = ait_instruction) and
  6745. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6746. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6747. begin
  6748. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6749. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6750. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6751. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6752. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6753. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6754. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6755. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6756. ) then
  6757. begin
  6758. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6759. RemoveCurrentP(p,hp2);
  6760. RemoveInstruction(hp1);
  6761. Result := true;
  6762. end
  6763. else if { fst can't store an extended/comp value }
  6764. (taicpu(p).opsize <> S_FX) and
  6765. (taicpu(p).opsize <> S_IQ) then
  6766. begin
  6767. if (taicpu(p).opcode = A_FSTP) then
  6768. taicpu(p).opcode := A_FST
  6769. else
  6770. taicpu(p).opcode := A_FIST;
  6771. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6772. RemoveInstruction(hp1);
  6773. Result := true;
  6774. end;
  6775. end;
  6776. end;
  6777. end;
  6778. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6779. var
  6780. hp1, hp2, hp3: tai;
  6781. begin
  6782. result:=false;
  6783. if MatchOpType(taicpu(p),top_reg) and
  6784. GetNextInstruction(p, hp1) and
  6785. (hp1.typ = Ait_Instruction) and
  6786. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6787. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6788. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6789. { change to
  6790. fld reg fxxx reg,st
  6791. fxxxp st, st1 (hp1)
  6792. Remark: non commutative operations must be reversed!
  6793. }
  6794. begin
  6795. case taicpu(hp1).opcode Of
  6796. A_FMULP,A_FADDP,
  6797. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6798. begin
  6799. case taicpu(hp1).opcode Of
  6800. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6801. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6802. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6803. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6804. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6805. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6806. else
  6807. internalerror(2019050534);
  6808. end;
  6809. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6810. taicpu(hp1).oper[1]^.reg := NR_ST;
  6811. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6812. RemoveCurrentP(p, hp1);
  6813. Result:=true;
  6814. exit;
  6815. end;
  6816. else
  6817. ;
  6818. end;
  6819. end
  6820. else
  6821. if MatchOpType(taicpu(p),top_ref) and
  6822. GetNextInstruction(p, hp2) and
  6823. (hp2.typ = Ait_Instruction) and
  6824. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6825. (taicpu(p).opsize in [S_FS, S_FL]) and
  6826. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6827. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6828. if GetLastInstruction(p, hp1) and
  6829. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6830. MatchOpType(taicpu(hp1),top_ref) and
  6831. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6832. if ((taicpu(hp2).opcode = A_FMULP) or
  6833. (taicpu(hp2).opcode = A_FADDP)) then
  6834. { change to
  6835. fld/fst mem1 (hp1) fld/fst mem1
  6836. fld mem1 (p) fadd/
  6837. faddp/ fmul st, st
  6838. fmulp st, st1 (hp2) }
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6841. RemoveCurrentP(p, hp1);
  6842. if (taicpu(hp2).opcode = A_FADDP) then
  6843. taicpu(hp2).opcode := A_FADD
  6844. else
  6845. taicpu(hp2).opcode := A_FMUL;
  6846. taicpu(hp2).oper[1]^.reg := NR_ST;
  6847. end
  6848. else
  6849. { change to
  6850. fld/fst mem1 (hp1) fld/fst mem1
  6851. fld mem1 (p) fld st
  6852. }
  6853. begin
  6854. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6855. taicpu(p).changeopsize(S_FL);
  6856. taicpu(p).loadreg(0,NR_ST);
  6857. end
  6858. else
  6859. begin
  6860. case taicpu(hp2).opcode Of
  6861. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6862. { change to
  6863. fld/fst mem1 (hp1) fld/fst mem1
  6864. fld mem2 (p) fxxx mem2
  6865. fxxxp st, st1 (hp2) }
  6866. begin
  6867. case taicpu(hp2).opcode Of
  6868. A_FADDP: taicpu(p).opcode := A_FADD;
  6869. A_FMULP: taicpu(p).opcode := A_FMUL;
  6870. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6871. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6872. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6873. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6874. else
  6875. internalerror(2019050533);
  6876. end;
  6877. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6878. RemoveInstruction(hp2);
  6879. end
  6880. else
  6881. ;
  6882. end
  6883. end
  6884. end;
  6885. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6886. begin
  6887. Result := condition_in(cond1, cond2) or
  6888. { Not strictly subsets due to the actual flags checked, but because we're
  6889. comparing integers, E is a subset of AE and GE and their aliases }
  6890. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6891. end;
  6892. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6893. var
  6894. v: TCGInt;
  6895. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6896. FirstMatch, TempBool: Boolean;
  6897. NewReg: TRegister;
  6898. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6899. begin
  6900. Result:=false;
  6901. { All these optimisations need a next instruction }
  6902. if not GetNextInstruction(p, hp1) then
  6903. Exit;
  6904. { Search for:
  6905. cmp ###,###
  6906. j(c1) @lbl1
  6907. ...
  6908. @lbl:
  6909. cmp ###,### (same comparison as above)
  6910. j(c2) @lbl2
  6911. If c1 is a subset of c2, change to:
  6912. cmp ###,###
  6913. j(c1) @lbl2
  6914. (@lbl1 may become a dead label as a result)
  6915. }
  6916. { Also handle cases where there are multiple jumps in a row }
  6917. p_jump := hp1;
  6918. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6919. begin
  6920. if IsJumpToLabel(taicpu(p_jump)) then
  6921. begin
  6922. { Do jump optimisations first in case the condition becomes
  6923. unnecessary }
  6924. TempBool := True;
  6925. if DoJumpOptimizations(p_jump, TempBool) or
  6926. not TempBool then
  6927. begin
  6928. if Assigned(p_jump) then
  6929. begin
  6930. hp1 := p_jump;
  6931. if (p_jump.typ in [ait_align]) then
  6932. SkipAligns(p_jump, p_jump);
  6933. { CollapseZeroDistJump will be set to the label after the
  6934. jump if it optimises, whether or not it's live or dead }
  6935. if (p_jump.typ in [ait_label]) and
  6936. not (tai_label(p_jump).labsym.is_used) then
  6937. GetNextInstruction(p_jump, p_jump);
  6938. end;
  6939. TransferUsedRegs(TmpUsedRegs);
  6940. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6941. if not Assigned(p_jump) or
  6942. (
  6943. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6944. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6945. ) then
  6946. begin
  6947. { No more conditional jumps; conditional statement is no longer required }
  6948. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6949. RemoveCurrentP(p);
  6950. Result := True;
  6951. Exit;
  6952. end;
  6953. hp1 := p_jump;
  6954. Include(OptsToCheck, aoc_ForceNewIteration);
  6955. Continue;
  6956. end;
  6957. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6958. if GetNextInstruction(p_jump, hp2) and
  6959. (
  6960. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6961. not TempBool
  6962. ) then
  6963. begin
  6964. hp1 := p_jump;
  6965. Include(OptsToCheck, aoc_ForceNewIteration);
  6966. Continue;
  6967. end;
  6968. p_label := nil;
  6969. if Assigned(JumpLabel) then
  6970. p_label := getlabelwithsym(JumpLabel);
  6971. if Assigned(p_label) and
  6972. GetNextInstruction(p_label, p_dist) and
  6973. MatchInstruction(p_dist, A_CMP, []) and
  6974. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6975. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6976. GetNextInstruction(p_dist, hp1_dist) and
  6977. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6978. begin
  6979. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6980. if JumpLabel = JumpLabel_dist then
  6981. { This is an infinite loop }
  6982. Exit;
  6983. { Best optimisation when the first condition is a subset (or equal) of the second }
  6984. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6985. begin
  6986. { Any registers used here will already be allocated }
  6987. if Assigned(JumpLabel) then
  6988. JumpLabel.DecRefs;
  6989. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6990. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6991. Result := True;
  6992. { Don't exit yet. Since p and p_jump haven't actually been
  6993. removed, we can check for more on this iteration }
  6994. end
  6995. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6996. GetNextInstruction(hp1_dist, hp1_label) and
  6997. SkipAligns(hp1_label, hp1_label) and
  6998. (hp1_label.typ = ait_label) then
  6999. begin
  7000. JumpLabel_far := tai_label(hp1_label).labsym;
  7001. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7002. { This is an infinite loop }
  7003. Exit;
  7004. if Assigned(JumpLabel_far) then
  7005. begin
  7006. { In this situation, if the first jump branches, the second one will never,
  7007. branch so change the destination label to after the second jump }
  7008. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7009. if Assigned(JumpLabel) then
  7010. JumpLabel.DecRefs;
  7011. JumpLabel_far.IncRefs;
  7012. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7013. Result := True;
  7014. { Don't exit yet. Since p and p_jump haven't actually been
  7015. removed, we can check for more on this iteration }
  7016. Continue;
  7017. end;
  7018. end;
  7019. end;
  7020. end;
  7021. { Search for:
  7022. cmp ###,###
  7023. j(c1) @lbl1
  7024. cmp ###,### (same as first)
  7025. Remove second cmp
  7026. }
  7027. if GetNextInstruction(p_jump, hp2) and
  7028. (
  7029. (
  7030. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7031. (
  7032. (
  7033. MatchOpType(taicpu(p), top_const, top_reg) and
  7034. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7035. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7036. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7037. ) or (
  7038. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7039. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7040. )
  7041. )
  7042. ) or (
  7043. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7044. MatchOperand(taicpu(p).oper[0]^, 0) and
  7045. (taicpu(p).oper[1]^.typ = top_reg) and
  7046. MatchInstruction(hp2, A_TEST, []) and
  7047. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7048. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7049. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7050. )
  7051. ) then
  7052. begin
  7053. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7054. RemoveInstruction(hp2);
  7055. Result := True;
  7056. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7057. end;
  7058. GetNextInstruction(p_jump, p_jump);
  7059. end;
  7060. if (
  7061. { Don't call GetNextInstruction again if we already have it }
  7062. (hp1 = p_jump) or
  7063. GetNextInstruction(p, hp1)
  7064. ) and
  7065. MatchInstruction(hp1, A_Jcc, []) and
  7066. IsJumpToLabel(taicpu(hp1)) and
  7067. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7068. GetNextInstruction(hp1, hp2) then
  7069. begin
  7070. {
  7071. cmp x, y (or "cmp y, x")
  7072. je @lbl
  7073. mov x, y
  7074. @lbl:
  7075. (x and y can be constants, registers or references)
  7076. Change to:
  7077. mov x, y (x and y will always be equal in the end)
  7078. @lbl: (may beceome a dead label)
  7079. Also:
  7080. cmp x, y (or "cmp y, x")
  7081. jne @lbl
  7082. mov x, y
  7083. @lbl:
  7084. (x and y can be constants, registers or references)
  7085. Change to:
  7086. Absolutely nothing! (Except @lbl if it's still live)
  7087. }
  7088. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7089. (
  7090. (
  7091. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7092. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7093. ) or (
  7094. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7095. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7096. )
  7097. ) and
  7098. GetNextInstruction(hp2, hp1_label) and
  7099. SkipAligns(hp1_label, hp1_label) and
  7100. (hp1_label.typ = ait_label) and
  7101. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7102. begin
  7103. tai_label(hp1_label).labsym.DecRefs;
  7104. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7105. begin
  7106. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7107. RemoveInstruction(hp2);
  7108. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7109. end
  7110. else
  7111. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7112. RemoveInstruction(hp1);
  7113. RemoveCurrentp(p, hp2);
  7114. Result := True;
  7115. Exit;
  7116. end;
  7117. {
  7118. Try to optimise the following:
  7119. cmp $x,### ($x and $y can be registers or constants)
  7120. je @lbl1 (only reference)
  7121. cmp $y,### (### are identical)
  7122. @Lbl:
  7123. sete %reg1
  7124. Change to:
  7125. cmp $x,###
  7126. sete %reg2 (allocate new %reg2)
  7127. cmp $y,###
  7128. sete %reg1
  7129. orb %reg2,%reg1
  7130. (dealloc %reg2)
  7131. This adds an instruction (so don't perform under -Os), but it removes
  7132. a conditional branch.
  7133. }
  7134. if not (cs_opt_size in current_settings.optimizerswitches) and
  7135. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7136. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7137. { The first operand of CMP instructions can only be a register or
  7138. immediate anyway, so no need to check }
  7139. GetNextInstruction(hp2, p_label) and
  7140. (p_label.typ = ait_label) and
  7141. (tai_label(p_label).labsym.getrefs = 1) and
  7142. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7143. GetNextInstruction(p_label, p_dist) and
  7144. MatchInstruction(p_dist, A_SETcc, []) and
  7145. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7146. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7147. begin
  7148. TransferUsedRegs(TmpUsedRegs);
  7149. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7150. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7151. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7152. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7153. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7154. { Get the instruction after the SETcc instruction so we can
  7155. allocate a new register over the entire range }
  7156. GetNextInstruction(p_dist, hp1_dist) then
  7157. begin
  7158. { Register can appear in p if it's not used afterwards, so only
  7159. allocate between hp1 and hp1_dist }
  7160. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7161. if NewReg <> NR_NO then
  7162. begin
  7163. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7164. { Change the jump instruction into a SETcc instruction }
  7165. taicpu(hp1).opcode := A_SETcc;
  7166. taicpu(hp1).opsize := S_B;
  7167. taicpu(hp1).loadreg(0, NewReg);
  7168. { This is now a dead label }
  7169. tai_label(p_label).labsym.decrefs;
  7170. { Prefer adding before the next instruction so the FLAGS
  7171. register is deallicated first }
  7172. AsmL.InsertBefore(
  7173. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7174. hp1_dist
  7175. );
  7176. Result := True;
  7177. { Don't exit yet, as p wasn't changed and hp1, while
  7178. modified, is still intact and might be optimised by the
  7179. SETcc optimisation below }
  7180. end;
  7181. end;
  7182. end;
  7183. end;
  7184. if taicpu(p).oper[0]^.typ = top_const then
  7185. begin
  7186. if (taicpu(p).oper[0]^.val = 0) and
  7187. (taicpu(p).oper[1]^.typ = top_reg) and
  7188. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7189. begin
  7190. hp2 := p;
  7191. FirstMatch := True;
  7192. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7193. anything meaningful once it's converted to "test %reg,%reg";
  7194. additionally, some jumps will always (or never) branch, so
  7195. evaluate every jump immediately following the
  7196. comparison, optimising the conditions if possible.
  7197. Similarly with SETcc... those that are always set to 0 or 1
  7198. are changed to MOV instructions }
  7199. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7200. (
  7201. GetNextInstruction(hp2, hp1) and
  7202. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7203. ) do
  7204. begin
  7205. FirstMatch := False;
  7206. case taicpu(hp1).condition of
  7207. C_B, C_C, C_NAE, C_O:
  7208. { For B/NAE:
  7209. Will never branch since an unsigned integer can never be below zero
  7210. For C/O:
  7211. Result cannot overflow because 0 is being subtracted
  7212. }
  7213. begin
  7214. if taicpu(hp1).opcode = A_Jcc then
  7215. begin
  7216. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7217. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7218. RemoveInstruction(hp1);
  7219. { Since hp1 was deleted, hp2 must not be updated }
  7220. Continue;
  7221. end
  7222. else
  7223. begin
  7224. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7225. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7226. taicpu(hp1).opcode := A_MOV;
  7227. taicpu(hp1).ops := 2;
  7228. taicpu(hp1).condition := C_None;
  7229. taicpu(hp1).opsize := S_B;
  7230. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7231. taicpu(hp1).loadconst(0, 0);
  7232. end;
  7233. end;
  7234. C_BE, C_NA:
  7235. begin
  7236. { Will only branch if equal to zero }
  7237. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7238. taicpu(hp1).condition := C_E;
  7239. end;
  7240. C_A, C_NBE:
  7241. begin
  7242. { Will only branch if not equal to zero }
  7243. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7244. taicpu(hp1).condition := C_NE;
  7245. end;
  7246. C_AE, C_NB, C_NC, C_NO:
  7247. begin
  7248. { Will always branch }
  7249. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7250. if taicpu(hp1).opcode = A_Jcc then
  7251. begin
  7252. MakeUnconditional(taicpu(hp1));
  7253. { Any jumps/set that follow will now be dead code }
  7254. RemoveDeadCodeAfterJump(taicpu(hp1));
  7255. Break;
  7256. end
  7257. else
  7258. begin
  7259. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7260. taicpu(hp1).opcode := A_MOV;
  7261. taicpu(hp1).ops := 2;
  7262. taicpu(hp1).condition := C_None;
  7263. taicpu(hp1).opsize := S_B;
  7264. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7265. taicpu(hp1).loadconst(0, 1);
  7266. end;
  7267. end;
  7268. C_None:
  7269. InternalError(2020012201);
  7270. C_P, C_PE, C_NP, C_PO:
  7271. { We can't handle parity checks and they should never be generated
  7272. after a general-purpose CMP (it's used in some floating-point
  7273. comparisons that don't use CMP) }
  7274. InternalError(2020012202);
  7275. else
  7276. { Zero/Equality, Sign, their complements and all of the
  7277. signed comparisons do not need to be converted };
  7278. end;
  7279. hp2 := hp1;
  7280. end;
  7281. { Convert the instruction to a TEST }
  7282. taicpu(p).opcode := A_TEST;
  7283. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7284. Result := True;
  7285. Exit;
  7286. end
  7287. else if (taicpu(p).oper[0]^.val = 1) and
  7288. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7289. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7290. begin
  7291. { Convert; To:
  7292. cmp $1,r/m cmp $0,r/m
  7293. jl @lbl jle @lbl
  7294. (Also do inverted conditions)
  7295. }
  7296. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7297. taicpu(p).oper[0]^.val := 0;
  7298. if taicpu(hp1).condition in [C_L, C_NGE] then
  7299. taicpu(hp1).condition := C_LE
  7300. else
  7301. taicpu(hp1).condition := C_NLE;
  7302. { If the instruction is now "cmp $0,%reg", convert it to a
  7303. TEST (and effectively do the work of the "cmp $0,%reg" in
  7304. the block above)
  7305. }
  7306. if (taicpu(p).oper[1]^.typ = top_reg) then
  7307. begin
  7308. taicpu(p).opcode := A_TEST;
  7309. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7310. end;
  7311. Result := True;
  7312. Exit;
  7313. end
  7314. else if (taicpu(p).oper[1]^.typ = top_reg)
  7315. {$ifdef x86_64}
  7316. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7317. {$endif x86_64}
  7318. then
  7319. begin
  7320. { cmp register,$8000 neg register
  7321. je target --> jo target
  7322. .... only if register is deallocated before jump.}
  7323. case Taicpu(p).opsize of
  7324. S_B: v:=$80;
  7325. S_W: v:=$8000;
  7326. S_L: v:=qword($80000000);
  7327. else
  7328. internalerror(2013112905);
  7329. end;
  7330. if (taicpu(p).oper[0]^.val=v) and
  7331. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7332. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7333. begin
  7334. TransferUsedRegs(TmpUsedRegs);
  7335. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7336. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7337. begin
  7338. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7339. Taicpu(p).opcode:=A_NEG;
  7340. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7341. Taicpu(p).clearop(1);
  7342. Taicpu(p).ops:=1;
  7343. if Taicpu(hp1).condition=C_E then
  7344. Taicpu(hp1).condition:=C_O
  7345. else
  7346. Taicpu(hp1).condition:=C_NO;
  7347. Result:=true;
  7348. exit;
  7349. end;
  7350. end;
  7351. end;
  7352. end;
  7353. if TrySwapMovCmp(p, hp1) then
  7354. begin
  7355. Result := True;
  7356. Exit;
  7357. end;
  7358. end;
  7359. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7360. var
  7361. hp1: tai;
  7362. begin
  7363. {
  7364. remove the second (v)pxor from
  7365. pxor reg,reg
  7366. ...
  7367. pxor reg,reg
  7368. }
  7369. Result:=false;
  7370. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7371. MatchOpType(taicpu(p),top_reg,top_reg) and
  7372. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7373. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7374. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7375. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7376. begin
  7377. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7378. RemoveInstruction(hp1);
  7379. Result:=true;
  7380. Exit;
  7381. end
  7382. {
  7383. replace
  7384. pxor reg1,reg1
  7385. movapd/s reg1,reg2
  7386. dealloc reg1
  7387. by
  7388. pxor reg2,reg2
  7389. }
  7390. else if GetNextInstruction(p,hp1) and
  7391. { we mix single and double opperations here because we assume that the compiler
  7392. generates vmovapd only after double operations and vmovaps only after single operations }
  7393. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7394. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7395. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7396. (taicpu(p).oper[0]^.typ=top_reg) then
  7397. begin
  7398. TransferUsedRegs(TmpUsedRegs);
  7399. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7400. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7401. begin
  7402. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7403. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7404. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7405. RemoveInstruction(hp1);
  7406. result:=true;
  7407. end;
  7408. end;
  7409. end;
  7410. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7411. var
  7412. hp1: tai;
  7413. begin
  7414. {
  7415. remove the second (v)pxor from
  7416. (v)pxor reg,reg
  7417. ...
  7418. (v)pxor reg,reg
  7419. }
  7420. Result:=false;
  7421. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7422. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7423. begin
  7424. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7425. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7426. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7427. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7428. begin
  7429. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7430. RemoveInstruction(hp1);
  7431. Result:=true;
  7432. Exit;
  7433. end;
  7434. {$ifdef x86_64}
  7435. {
  7436. replace
  7437. vpxor reg1,reg1,reg1
  7438. vmov reg,mem
  7439. by
  7440. movq $0,mem
  7441. }
  7442. if GetNextInstruction(p,hp1) and
  7443. MatchInstruction(hp1,A_VMOVSD,[]) and
  7444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7445. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7446. begin
  7447. TransferUsedRegs(TmpUsedRegs);
  7448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7450. begin
  7451. taicpu(hp1).loadconst(0,0);
  7452. taicpu(hp1).opcode:=A_MOV;
  7453. taicpu(hp1).opsize:=S_Q;
  7454. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7455. RemoveCurrentP(p);
  7456. result:=true;
  7457. Exit;
  7458. end;
  7459. end;
  7460. {$endif x86_64}
  7461. end
  7462. {
  7463. replace
  7464. vpxor reg1,reg1,reg2
  7465. by
  7466. vpxor reg2,reg2,reg2
  7467. to avoid unncessary data dependencies
  7468. }
  7469. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7470. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7471. begin
  7472. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7473. { avoid unncessary data dependency }
  7474. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7475. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7476. result:=true;
  7477. exit;
  7478. end;
  7479. Result:=OptPass1VOP(p);
  7480. end;
  7481. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7482. var
  7483. hp1 : tai;
  7484. begin
  7485. result:=false;
  7486. { replace
  7487. IMul const,%mreg1,%mreg2
  7488. Mov %reg2,%mreg3
  7489. dealloc %mreg3
  7490. by
  7491. Imul const,%mreg1,%mreg23
  7492. }
  7493. if (taicpu(p).ops=3) and
  7494. GetNextInstruction(p,hp1) and
  7495. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7496. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7497. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7498. begin
  7499. TransferUsedRegs(TmpUsedRegs);
  7500. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7501. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7502. begin
  7503. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7504. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7505. RemoveInstruction(hp1);
  7506. result:=true;
  7507. end;
  7508. end;
  7509. end;
  7510. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7511. var
  7512. hp1 : tai;
  7513. begin
  7514. result:=false;
  7515. { replace
  7516. IMul %reg0,%reg1,%reg2
  7517. Mov %reg2,%reg3
  7518. dealloc %reg2
  7519. by
  7520. Imul %reg0,%reg1,%reg3
  7521. }
  7522. if GetNextInstruction(p,hp1) and
  7523. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7524. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7525. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7526. begin
  7527. TransferUsedRegs(TmpUsedRegs);
  7528. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7529. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7530. begin
  7531. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7532. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7533. RemoveInstruction(hp1);
  7534. result:=true;
  7535. end;
  7536. end;
  7537. end;
  7538. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7539. var
  7540. hp1: tai;
  7541. begin
  7542. Result:=false;
  7543. { get rid of
  7544. (v)cvtss2sd reg0,<reg1,>reg2
  7545. (v)cvtss2sd reg2,<reg2,>reg0
  7546. }
  7547. if GetNextInstruction(p,hp1) and
  7548. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7549. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7550. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7551. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7552. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7553. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7554. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7555. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7556. )
  7557. ) then
  7558. begin
  7559. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7560. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7561. begin
  7562. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7563. RemoveCurrentP(p);
  7564. RemoveInstruction(hp1);
  7565. end
  7566. else
  7567. begin
  7568. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7569. if taicpu(hp1).opcode=A_CVTSD2SS then
  7570. begin
  7571. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7572. taicpu(p).opcode:=A_MOVAPS;
  7573. end
  7574. else
  7575. begin
  7576. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7577. taicpu(p).opcode:=A_VMOVAPS;
  7578. end;
  7579. taicpu(p).ops:=2;
  7580. RemoveInstruction(hp1);
  7581. end;
  7582. Result:=true;
  7583. Exit;
  7584. end;
  7585. end;
  7586. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7587. var
  7588. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7589. ThisReg: TRegister;
  7590. begin
  7591. Result := False;
  7592. if not GetNextInstruction(p,hp1) then
  7593. Exit;
  7594. {
  7595. convert
  7596. j<c> .L1
  7597. mov 1,reg
  7598. jmp .L2
  7599. .L1
  7600. mov 0,reg
  7601. .L2
  7602. into
  7603. mov 0,reg
  7604. set<not(c)> reg
  7605. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7606. would destroy the flag contents
  7607. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7608. executed at the same time as a previous comparison.
  7609. set<not(c)> reg
  7610. movzx reg, reg
  7611. }
  7612. if MatchInstruction(hp1,A_MOV,[]) and
  7613. (taicpu(hp1).oper[0]^.typ = top_const) and
  7614. (
  7615. (
  7616. (taicpu(hp1).oper[1]^.typ = top_reg)
  7617. {$ifdef i386}
  7618. { Under i386, ESI, EDI, EBP and ESP
  7619. don't have an 8-bit representation }
  7620. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7621. {$endif i386}
  7622. ) or (
  7623. {$ifdef i386}
  7624. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7625. {$endif i386}
  7626. (taicpu(hp1).opsize = S_B)
  7627. )
  7628. ) and
  7629. GetNextInstruction(hp1,hp2) and
  7630. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7631. GetNextInstruction(hp2,hp3) and
  7632. SkipAligns(hp3, hp3) and
  7633. (hp3.typ=ait_label) and
  7634. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7635. GetNextInstruction(hp3,hp4) and
  7636. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7637. (taicpu(hp4).oper[0]^.typ = top_const) and
  7638. (
  7639. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7640. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7641. ) and
  7642. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7643. GetNextInstruction(hp4,hp5) and
  7644. SkipAligns(hp5, hp5) and
  7645. (hp5.typ=ait_label) and
  7646. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7647. begin
  7648. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7649. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7650. tai_label(hp3).labsym.DecRefs;
  7651. { If this isn't the only reference to the middle label, we can
  7652. still make a saving - only that the first jump and everything
  7653. that follows will remain. }
  7654. if (tai_label(hp3).labsym.getrefs = 0) then
  7655. begin
  7656. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7657. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7658. else
  7659. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7660. { remove jump, first label and second MOV (also catching any aligns) }
  7661. repeat
  7662. if not GetNextInstruction(hp2, hp3) then
  7663. InternalError(2021040810);
  7664. RemoveInstruction(hp2);
  7665. hp2 := hp3;
  7666. until hp2 = hp5;
  7667. { Don't decrement reference count before the removal loop
  7668. above, otherwise GetNextInstruction won't stop on the
  7669. the label }
  7670. tai_label(hp5).labsym.DecRefs;
  7671. end
  7672. else
  7673. begin
  7674. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7675. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7676. else
  7677. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7678. end;
  7679. taicpu(p).opcode:=A_SETcc;
  7680. taicpu(p).opsize:=S_B;
  7681. taicpu(p).is_jmp:=False;
  7682. if taicpu(hp1).opsize=S_B then
  7683. begin
  7684. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7685. if taicpu(hp1).oper[1]^.typ = top_reg then
  7686. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7687. RemoveInstruction(hp1);
  7688. end
  7689. else
  7690. begin
  7691. { Will be a register because the size can't be S_B otherwise }
  7692. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7693. taicpu(p).loadreg(0, ThisReg);
  7694. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7695. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7696. begin
  7697. case taicpu(hp1).opsize of
  7698. S_W:
  7699. taicpu(hp1).opsize := S_BW;
  7700. S_L:
  7701. taicpu(hp1).opsize := S_BL;
  7702. {$ifdef x86_64}
  7703. S_Q:
  7704. begin
  7705. taicpu(hp1).opsize := S_BL;
  7706. { Change the destination register to 32-bit }
  7707. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7708. end;
  7709. {$endif x86_64}
  7710. else
  7711. InternalError(2021040820);
  7712. end;
  7713. taicpu(hp1).opcode := A_MOVZX;
  7714. taicpu(hp1).loadreg(0, ThisReg);
  7715. end
  7716. else
  7717. begin
  7718. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7719. { hp1 is already a MOV instruction with the correct register }
  7720. taicpu(hp1).loadconst(0, 0);
  7721. { Inserting it right before p will guarantee that the flags are also tracked }
  7722. asml.Remove(hp1);
  7723. asml.InsertBefore(hp1, p);
  7724. end;
  7725. end;
  7726. Result:=true;
  7727. exit;
  7728. end
  7729. else if (hp1.typ = ait_label) then
  7730. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7731. end;
  7732. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7733. var
  7734. hp1, hp2, hp3: tai;
  7735. SourceRef, TargetRef: TReference;
  7736. CurrentReg: TRegister;
  7737. begin
  7738. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7739. if not UseAVX then
  7740. InternalError(2021100501);
  7741. Result := False;
  7742. { Look for the following to simplify:
  7743. vmovdqa/u x(mem1), %xmmreg
  7744. vmovdqa/u %xmmreg, y(mem2)
  7745. vmovdqa/u x+16(mem1), %xmmreg
  7746. vmovdqa/u %xmmreg, y+16(mem2)
  7747. Change to:
  7748. vmovdqa/u x(mem1), %ymmreg
  7749. vmovdqa/u %ymmreg, y(mem2)
  7750. vpxor %ymmreg, %ymmreg, %ymmreg
  7751. ( The VPXOR instruction is to zero the upper half, thus removing the
  7752. need to call the potentially expensive VZEROUPPER instruction. Other
  7753. peephole optimisations can remove VPXOR if it's unnecessary )
  7754. }
  7755. TransferUsedRegs(TmpUsedRegs);
  7756. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7757. { NOTE: In the optimisations below, if the references dictate that an
  7758. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7759. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7760. if (taicpu(p).opsize = S_XMM) and
  7761. MatchOpType(taicpu(p), top_ref, top_reg) and
  7762. GetNextInstruction(p, hp1) and
  7763. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7764. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7765. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7766. begin
  7767. SourceRef := taicpu(p).oper[0]^.ref^;
  7768. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7769. if GetNextInstruction(hp1, hp2) and
  7770. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7771. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7772. begin
  7773. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7774. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7775. Inc(SourceRef.offset, 16);
  7776. { Reuse the register in the first block move }
  7777. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7778. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7779. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7780. begin
  7781. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7782. Inc(TargetRef.offset, 16);
  7783. if GetNextInstruction(hp2, hp3) and
  7784. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7785. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7786. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7787. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7788. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7789. begin
  7790. { Update the register tracking to the new size }
  7791. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7792. { Remember that the offsets are 16 ahead }
  7793. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7794. if not (
  7795. ((SourceRef.offset mod 32) = 16) and
  7796. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7797. ) then
  7798. taicpu(p).opcode := A_VMOVDQU;
  7799. taicpu(p).opsize := S_YMM;
  7800. taicpu(p).oper[1]^.reg := CurrentReg;
  7801. if not (
  7802. ((TargetRef.offset mod 32) = 16) and
  7803. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7804. ) then
  7805. taicpu(hp1).opcode := A_VMOVDQU;
  7806. taicpu(hp1).opsize := S_YMM;
  7807. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7808. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7809. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7810. if (pi_uses_ymm in current_procinfo.flags) then
  7811. RemoveInstruction(hp2)
  7812. else
  7813. begin
  7814. taicpu(hp2).opcode := A_VPXOR;
  7815. taicpu(hp2).opsize := S_YMM;
  7816. taicpu(hp2).loadreg(0, CurrentReg);
  7817. taicpu(hp2).loadreg(1, CurrentReg);
  7818. taicpu(hp2).loadreg(2, CurrentReg);
  7819. taicpu(hp2).ops := 3;
  7820. end;
  7821. RemoveInstruction(hp3);
  7822. Result := True;
  7823. Exit;
  7824. end;
  7825. end
  7826. else
  7827. begin
  7828. { See if the next references are 16 less rather than 16 greater }
  7829. Dec(SourceRef.offset, 32); { -16 the other way }
  7830. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7831. begin
  7832. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7833. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7834. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7835. GetNextInstruction(hp2, hp3) and
  7836. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7837. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7838. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7839. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7840. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7841. begin
  7842. { Update the register tracking to the new size }
  7843. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7844. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7845. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7846. if not(
  7847. ((SourceRef.offset mod 32) = 0) and
  7848. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7849. ) then
  7850. taicpu(hp2).opcode := A_VMOVDQU;
  7851. taicpu(hp2).opsize := S_YMM;
  7852. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7853. if not (
  7854. ((TargetRef.offset mod 32) = 0) and
  7855. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7856. ) then
  7857. taicpu(hp3).opcode := A_VMOVDQU;
  7858. taicpu(hp3).opsize := S_YMM;
  7859. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7860. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7861. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7862. if (pi_uses_ymm in current_procinfo.flags) then
  7863. RemoveInstruction(hp1)
  7864. else
  7865. begin
  7866. taicpu(hp1).opcode := A_VPXOR;
  7867. taicpu(hp1).opsize := S_YMM;
  7868. taicpu(hp1).loadreg(0, CurrentReg);
  7869. taicpu(hp1).loadreg(1, CurrentReg);
  7870. taicpu(hp1).loadreg(2, CurrentReg);
  7871. taicpu(hp1).ops := 3;
  7872. Asml.Remove(hp1);
  7873. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7874. end;
  7875. RemoveCurrentP(p, hp2);
  7876. Result := True;
  7877. Exit;
  7878. end;
  7879. end;
  7880. end;
  7881. end;
  7882. end;
  7883. end;
  7884. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7885. var
  7886. hp2, hp3, first_assignment: tai;
  7887. IncCount, OperIdx: Integer;
  7888. OrigLabel: TAsmLabel;
  7889. begin
  7890. Count := 0;
  7891. Result := False;
  7892. first_assignment := nil;
  7893. if (LoopCount >= 20) then
  7894. begin
  7895. { Guard against infinite loops }
  7896. Exit;
  7897. end;
  7898. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7899. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7900. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7901. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7902. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7903. Exit;
  7904. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7905. {
  7906. change
  7907. jmp .L1
  7908. ...
  7909. .L1:
  7910. mov ##, ## ( multiple movs possible )
  7911. jmp/ret
  7912. into
  7913. mov ##, ##
  7914. jmp/ret
  7915. }
  7916. if not Assigned(hp1) then
  7917. begin
  7918. hp1 := GetLabelWithSym(OrigLabel);
  7919. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7920. Exit;
  7921. end;
  7922. hp2 := hp1;
  7923. while Assigned(hp2) do
  7924. begin
  7925. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7926. SkipLabels(hp2,hp2);
  7927. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7928. Break;
  7929. case taicpu(hp2).opcode of
  7930. A_MOVSD:
  7931. begin
  7932. if taicpu(hp2).ops = 0 then
  7933. { Wrong MOVSD }
  7934. Break;
  7935. Inc(Count);
  7936. if Count >= 5 then
  7937. { Too many to be worthwhile }
  7938. Break;
  7939. GetNextInstruction(hp2, hp2);
  7940. Continue;
  7941. end;
  7942. A_MOV,
  7943. A_MOVD,
  7944. A_MOVQ,
  7945. A_MOVSX,
  7946. {$ifdef x86_64}
  7947. A_MOVSXD,
  7948. {$endif x86_64}
  7949. A_MOVZX,
  7950. A_MOVAPS,
  7951. A_MOVUPS,
  7952. A_MOVSS,
  7953. A_MOVAPD,
  7954. A_MOVUPD,
  7955. A_MOVDQA,
  7956. A_MOVDQU,
  7957. A_VMOVSS,
  7958. A_VMOVAPS,
  7959. A_VMOVUPS,
  7960. A_VMOVSD,
  7961. A_VMOVAPD,
  7962. A_VMOVUPD,
  7963. A_VMOVDQA,
  7964. A_VMOVDQU:
  7965. begin
  7966. Inc(Count);
  7967. if Count >= 5 then
  7968. { Too many to be worthwhile }
  7969. Break;
  7970. GetNextInstruction(hp2, hp2);
  7971. Continue;
  7972. end;
  7973. A_JMP:
  7974. begin
  7975. { Guard against infinite loops }
  7976. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7977. Exit;
  7978. { Analyse this jump first in case it also duplicates assignments }
  7979. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7980. begin
  7981. { Something did change! }
  7982. Result := True;
  7983. Inc(Count, IncCount);
  7984. if Count >= 5 then
  7985. begin
  7986. { Too many to be worthwhile }
  7987. Exit;
  7988. end;
  7989. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7990. Break;
  7991. end;
  7992. Result := True;
  7993. Break;
  7994. end;
  7995. A_RET:
  7996. begin
  7997. Result := True;
  7998. Break;
  7999. end;
  8000. else
  8001. Break;
  8002. end;
  8003. end;
  8004. if Result then
  8005. begin
  8006. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8007. if Count = 0 then
  8008. begin
  8009. Result := False;
  8010. Exit;
  8011. end;
  8012. hp3 := p;
  8013. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8014. while True do
  8015. begin
  8016. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8017. SkipLabels(hp1,hp1);
  8018. if (hp1.typ <> ait_instruction) then
  8019. InternalError(2021040720);
  8020. case taicpu(hp1).opcode of
  8021. A_JMP:
  8022. begin
  8023. { Change the original jump to the new destination }
  8024. OrigLabel.decrefs;
  8025. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8026. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8027. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8028. if not Assigned(first_assignment) then
  8029. InternalError(2021040810)
  8030. else
  8031. p := first_assignment;
  8032. Exit;
  8033. end;
  8034. A_RET:
  8035. begin
  8036. { Now change the jump into a RET instruction }
  8037. ConvertJumpToRET(p, hp1);
  8038. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8039. if not Assigned(first_assignment) then
  8040. InternalError(2021040811)
  8041. else
  8042. p := first_assignment;
  8043. Exit;
  8044. end;
  8045. else
  8046. begin
  8047. { Duplicate the MOV instruction }
  8048. hp3:=tai(hp1.getcopy);
  8049. if first_assignment = nil then
  8050. first_assignment := hp3;
  8051. asml.InsertBefore(hp3, p);
  8052. { Make sure the compiler knows about any final registers written here }
  8053. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8054. with taicpu(hp3).oper[OperIdx]^ do
  8055. begin
  8056. case typ of
  8057. top_ref:
  8058. begin
  8059. if (ref^.base <> NR_NO) and
  8060. (getsupreg(ref^.base) <> RS_ESP) and
  8061. (getsupreg(ref^.base) <> RS_EBP)
  8062. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8063. then
  8064. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8065. if (ref^.index <> NR_NO) and
  8066. (getsupreg(ref^.index) <> RS_ESP) and
  8067. (getsupreg(ref^.index) <> RS_EBP)
  8068. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8069. (ref^.index <> ref^.base) then
  8070. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8071. end;
  8072. top_reg:
  8073. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8074. else
  8075. ;
  8076. end;
  8077. end;
  8078. end;
  8079. end;
  8080. if not GetNextInstruction(hp1, hp1) then
  8081. { Should have dropped out earlier }
  8082. InternalError(2021040710);
  8083. end;
  8084. end;
  8085. end;
  8086. const
  8087. WriteOp: array[0..3] of set of TInsChange = (
  8088. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8089. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8090. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8091. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8092. RegWriteFlags: array[0..7] of set of TInsChange = (
  8093. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8094. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8095. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8096. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8097. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8098. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8099. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8100. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8101. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8102. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8103. var
  8104. hp2: tai;
  8105. X: Integer;
  8106. begin
  8107. { If we have something like:
  8108. op ###,###
  8109. mov ###,###
  8110. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8111. interfere in regards to what they write to.
  8112. NOTE: p must be a 2-operand instruction
  8113. }
  8114. Result := False;
  8115. if (hp1.typ <> ait_instruction) or
  8116. taicpu(hp1).is_jmp or
  8117. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8118. Exit;
  8119. { NOP is a pipeline fence, likely marking the beginning of the function
  8120. epilogue, so drop out. Similarly, drop out if POP or RET are
  8121. encountered }
  8122. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8123. Exit;
  8124. if (taicpu(hp1).opcode = A_MOVSD) and
  8125. (taicpu(hp1).ops = 0) then
  8126. { Wrong MOVSD }
  8127. Exit;
  8128. { Check for writes to specific registers first }
  8129. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8130. for X := 0 to 7 do
  8131. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8132. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8133. Exit;
  8134. for X := 0 to taicpu(hp1).ops - 1 do
  8135. begin
  8136. { Check to see if this operand writes to something }
  8137. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8138. { And matches something in the CMP/TEST instruction }
  8139. (
  8140. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8141. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8142. (
  8143. { If it's a register, make sure the register written to doesn't
  8144. appear in the cmp instruction as part of a reference }
  8145. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8146. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8147. )
  8148. ) then
  8149. Exit;
  8150. end;
  8151. { Check p to make sure it doesn't write to something that affects hp1 }
  8152. { Check for writes to specific registers first }
  8153. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8154. for X := 0 to 7 do
  8155. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8156. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8157. Exit;
  8158. for X := 0 to taicpu(p).ops - 1 do
  8159. begin
  8160. { Check to see if this operand writes to something }
  8161. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8162. { And matches something in hp1 }
  8163. (taicpu(p).oper[X]^.typ = top_reg) and
  8164. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8165. Exit;
  8166. end;
  8167. { The instruction can be safely moved }
  8168. asml.Remove(hp1);
  8169. { Try to insert after the last instructions where the FLAGS register is not
  8170. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8171. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8172. asml.InsertBefore(hp1, hp2)
  8173. { Failing that, try to insert after the last instructions where the
  8174. FLAGS register is not yet in use }
  8175. else if GetLastInstruction(p, hp2) and
  8176. (
  8177. (hp2.typ <> ait_instruction) or
  8178. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8179. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8180. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8181. ) then
  8182. asml.InsertAfter(hp1, hp2)
  8183. else
  8184. { Note, if p.Previous is nil (even if it should logically never be the
  8185. case), FindRegAllocBackward immediately exits with False and so we
  8186. safely land here (we can't just pass p because FindRegAllocBackward
  8187. immediately exits on an instruction). [Kit] }
  8188. asml.InsertBefore(hp1, p);
  8189. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8190. { We can't trust UsedRegs because we're looking backwards, although we
  8191. know the registers are allocated after p at the very least, so manually
  8192. create tai_regalloc objects if needed }
  8193. for X := 0 to taicpu(hp1).ops - 1 do
  8194. case taicpu(hp1).oper[X]^.typ of
  8195. top_reg:
  8196. begin
  8197. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8198. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8199. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8200. end;
  8201. top_ref:
  8202. begin
  8203. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8204. begin
  8205. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8206. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8207. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8208. end;
  8209. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8210. begin
  8211. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8212. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8213. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8214. end;
  8215. end;
  8216. else
  8217. ;
  8218. end;
  8219. Result := True;
  8220. end;
  8221. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8222. var
  8223. hp2: tai;
  8224. X: Integer;
  8225. begin
  8226. { If we have something like:
  8227. cmp ###,%reg1
  8228. mov 0,%reg2
  8229. And no modified registers are shared, move the instruction to before
  8230. the comparison as this means it can be optimised without worrying
  8231. about the FLAGS register. (CMP/MOV is generated by
  8232. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8233. As long as the second instruction doesn't use the flags or one of the
  8234. registers used by CMP or TEST (also check any references that use the
  8235. registers), then it can be moved prior to the comparison.
  8236. }
  8237. Result := False;
  8238. if not TrySwapMovOp(p, hp1) then
  8239. Exit;
  8240. if taicpu(hp1).opcode = A_LEA then
  8241. { The flags will be overwritten by the CMP/TEST instruction }
  8242. ConvertLEA(taicpu(hp1));
  8243. Result := True;
  8244. { Can we move it one further back? }
  8245. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8246. { Check to see if CMP/TEST is a comparison against zero }
  8247. (
  8248. (
  8249. (taicpu(p).opcode = A_CMP) and
  8250. MatchOperand(taicpu(p).oper[0]^, 0)
  8251. ) or
  8252. (
  8253. (taicpu(p).opcode = A_TEST) and
  8254. (
  8255. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8256. MatchOperand(taicpu(p).oper[0]^, -1)
  8257. )
  8258. )
  8259. ) and
  8260. { These instructions set the zero flag if the result is zero }
  8261. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8262. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8263. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8264. TrySwapMovOp(hp2, hp1);
  8265. end;
  8266. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8267. function IsXCHGAcceptable: Boolean; inline;
  8268. begin
  8269. { Always accept if optimising for size }
  8270. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8271. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8272. than 3, so it becomes a saving compared to three MOVs with two of
  8273. them able to execute simultaneously. [Kit] }
  8274. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8275. end;
  8276. var
  8277. NewRef: TReference;
  8278. hp1, hp2, hp3, hp4: Tai;
  8279. {$ifndef x86_64}
  8280. OperIdx: Integer;
  8281. {$endif x86_64}
  8282. NewInstr : Taicpu;
  8283. NewAligh : Tai_align;
  8284. DestLabel: TAsmLabel;
  8285. TempTracking: TAllUsedRegs;
  8286. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8287. var
  8288. NextInstr: tai;
  8289. begin
  8290. Result := False;
  8291. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8292. if not GetNextInstruction(InputInstr, NextInstr) or
  8293. (
  8294. { The FLAGS register isn't always tracked properly, so do not
  8295. perform this optimisation if a conditional statement follows }
  8296. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8297. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8298. ) then
  8299. begin
  8300. reference_reset(NewRef, 1, []);
  8301. NewRef.base := taicpu(p).oper[0]^.reg;
  8302. NewRef.scalefactor := 1;
  8303. if taicpu(InputInstr).opcode = A_ADD then
  8304. begin
  8305. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8306. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8307. end
  8308. else
  8309. begin
  8310. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8311. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8312. end;
  8313. taicpu(p).opcode := A_LEA;
  8314. taicpu(p).loadref(0, NewRef);
  8315. RemoveInstruction(InputInstr);
  8316. Result := True;
  8317. end;
  8318. end;
  8319. begin
  8320. Result:=false;
  8321. { This optimisation adds an instruction, so only do it for speed }
  8322. if not (cs_opt_size in current_settings.optimizerswitches) and
  8323. MatchOpType(taicpu(p), top_const, top_reg) and
  8324. (taicpu(p).oper[0]^.val = 0) then
  8325. begin
  8326. { To avoid compiler warning }
  8327. DestLabel := nil;
  8328. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8329. InternalError(2021040750);
  8330. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8331. Exit;
  8332. case hp1.typ of
  8333. ait_align,
  8334. ait_label:
  8335. begin
  8336. { Change:
  8337. mov $0,%reg mov $0,%reg
  8338. @Lbl1: @Lbl1:
  8339. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8340. je @Lbl2 jne @Lbl2
  8341. To: To:
  8342. mov $0,%reg mov $0,%reg
  8343. jmp @Lbl2 jmp @Lbl3
  8344. (align) (align)
  8345. @Lbl1: @Lbl1:
  8346. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8347. je @Lbl2 je @Lbl2
  8348. @Lbl3: <-- Only if label exists
  8349. (Not if it's optimised for size)
  8350. }
  8351. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8352. Exit;
  8353. if (hp2.typ = ait_instruction) and
  8354. (
  8355. { Register sizes must exactly match }
  8356. (
  8357. (taicpu(hp2).opcode = A_CMP) and
  8358. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8359. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8360. ) or (
  8361. (taicpu(hp2).opcode = A_TEST) and
  8362. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8363. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8364. )
  8365. ) and GetNextInstruction(hp2, hp3) and
  8366. (hp3.typ = ait_instruction) and
  8367. (taicpu(hp3).opcode = A_JCC) and
  8368. (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
  8369. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8370. begin
  8371. { Check condition of jump }
  8372. { Always true? }
  8373. if condition_in(C_E, taicpu(hp3).condition) then
  8374. begin
  8375. { Copy label symbol and obtain matching label entry for the
  8376. conditional jump, as this will be our destination}
  8377. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8378. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8379. Result := True;
  8380. end
  8381. { Always false? }
  8382. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8383. begin
  8384. { This is only worth it if there's a jump to take }
  8385. case hp2.typ of
  8386. ait_instruction:
  8387. begin
  8388. if taicpu(hp2).opcode = A_JMP then
  8389. begin
  8390. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8391. { An unconditional jump follows the conditional jump which will always be false,
  8392. so use this jump's destination for the new jump }
  8393. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8394. Result := True;
  8395. end
  8396. else if taicpu(hp2).opcode = A_JCC then
  8397. begin
  8398. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8399. if condition_in(C_E, taicpu(hp2).condition) then
  8400. begin
  8401. { A second conditional jump follows the conditional jump which will always be false,
  8402. while the second jump is always True, so use this jump's destination for the new jump }
  8403. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8404. Result := True;
  8405. end;
  8406. { Don't risk it if the jump isn't always true (Result remains False) }
  8407. end;
  8408. end;
  8409. else
  8410. { If anything else don't optimise };
  8411. end;
  8412. end;
  8413. if Result then
  8414. begin
  8415. { Just so we have something to insert as a paremeter}
  8416. reference_reset(NewRef, 1, []);
  8417. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8418. { Now actually load the correct parameter (this also
  8419. increases the reference count) }
  8420. NewInstr.loadsymbol(0, DestLabel, 0);
  8421. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8422. begin
  8423. { Get instruction before original label (may not be p under -O3) }
  8424. if not GetLastInstruction(hp1, hp2) then
  8425. { Shouldn't fail here }
  8426. InternalError(2021040701);
  8427. { Before the aligns too }
  8428. while (hp2.typ = ait_align) do
  8429. if not GetLastInstruction(hp2, hp2) then
  8430. { Shouldn't fail here }
  8431. InternalError(2021040702);
  8432. end
  8433. else
  8434. hp2 := p;
  8435. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8436. AsmL.InsertAfter(NewInstr, hp2);
  8437. { Add new alignment field }
  8438. (* AsmL.InsertAfter(
  8439. cai_align.create_max(
  8440. current_settings.alignment.jumpalign,
  8441. current_settings.alignment.jumpalignskipmax
  8442. ),
  8443. NewInstr
  8444. ); *)
  8445. end;
  8446. Exit;
  8447. end;
  8448. end;
  8449. else
  8450. ;
  8451. end;
  8452. end;
  8453. if not GetNextInstruction(p, hp1) then
  8454. Exit;
  8455. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8456. and DoMovCmpMemOpt(p, hp1) then
  8457. begin
  8458. Result := True;
  8459. Exit;
  8460. end
  8461. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8462. begin
  8463. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8464. further, but we can't just put this jump optimisation in pass 1
  8465. because it tends to perform worse when conditional jumps are
  8466. nearby (e.g. when converting CMOV instructions). [Kit] }
  8467. CopyUsedRegs(TempTracking);
  8468. UpdateUsedRegs(tai(p.Next));
  8469. if OptPass2JMP(hp1) then
  8470. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8471. Result := OptPass1MOV(p);
  8472. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8473. returned True and the instruction is still a MOV, thus checking
  8474. the optimisations below }
  8475. { If OptPass2JMP returned False, no optimisations were done to
  8476. the jump and there are no further optimisations that can be done
  8477. to the MOV instruction on this pass }
  8478. { Restore register state }
  8479. RestoreUsedRegs(TempTracking);
  8480. ReleaseUsedRegs(TempTracking);
  8481. end
  8482. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8483. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8484. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8485. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8486. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8487. begin
  8488. { Change:
  8489. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8490. addl/q $x,%reg2 subl/q $x,%reg2
  8491. To:
  8492. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8493. }
  8494. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8495. { be lazy, checking separately for sub would be slightly better }
  8496. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8497. begin
  8498. TransferUsedRegs(TmpUsedRegs);
  8499. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8500. if TryMovArith2Lea(hp1) then
  8501. begin
  8502. Result := True;
  8503. Exit;
  8504. end
  8505. end
  8506. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8507. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8508. { Same as above, but also adds or subtracts to %reg2 in between.
  8509. It's still valid as long as the flags aren't in use }
  8510. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8511. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8512. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8513. { be lazy, checking separately for sub would be slightly better }
  8514. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8515. begin
  8516. TransferUsedRegs(TmpUsedRegs);
  8517. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8518. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8519. if TryMovArith2Lea(hp2) then
  8520. begin
  8521. Result := True;
  8522. Exit;
  8523. end;
  8524. end;
  8525. end
  8526. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8527. {$ifdef x86_64}
  8528. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8529. {$else x86_64}
  8530. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8531. {$endif x86_64}
  8532. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8533. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8534. { mov reg1, reg2 mov reg1, reg2
  8535. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8536. begin
  8537. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8538. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8539. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8540. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8541. TransferUsedRegs(TmpUsedRegs);
  8542. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8543. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8544. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8545. then
  8546. begin
  8547. RemoveCurrentP(p, hp1);
  8548. Result:=true;
  8549. end;
  8550. exit;
  8551. end
  8552. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8553. IsXCHGAcceptable and
  8554. { XCHG doesn't support 8-byte registers }
  8555. (taicpu(p).opsize <> S_B) and
  8556. MatchInstruction(hp1, A_MOV, []) and
  8557. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8558. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8559. GetNextInstruction(hp1, hp2) and
  8560. MatchInstruction(hp2, A_MOV, []) and
  8561. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8562. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8563. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8564. begin
  8565. { mov %reg1,%reg2
  8566. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8567. mov %reg2,%reg3
  8568. (%reg2 not used afterwards)
  8569. Note that xchg takes 3 cycles to execute, and generally mov's take
  8570. only one cycle apiece, but the first two mov's can be executed in
  8571. parallel, only taking 2 cycles overall. Older processors should
  8572. therefore only optimise for size. [Kit]
  8573. }
  8574. TransferUsedRegs(TmpUsedRegs);
  8575. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8576. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8577. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8578. begin
  8579. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8580. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8581. taicpu(hp1).opcode := A_XCHG;
  8582. RemoveCurrentP(p, hp1);
  8583. RemoveInstruction(hp2);
  8584. Result := True;
  8585. Exit;
  8586. end;
  8587. end
  8588. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8589. MatchInstruction(hp1, A_SAR, []) then
  8590. begin
  8591. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8592. begin
  8593. { the use of %edx also covers the opsize being S_L }
  8594. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8595. begin
  8596. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8597. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8598. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8599. begin
  8600. { Change:
  8601. movl %eax,%edx
  8602. sarl $31,%edx
  8603. To:
  8604. cltd
  8605. }
  8606. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8607. RemoveInstruction(hp1);
  8608. taicpu(p).opcode := A_CDQ;
  8609. taicpu(p).opsize := S_NO;
  8610. taicpu(p).clearop(1);
  8611. taicpu(p).clearop(0);
  8612. taicpu(p).ops:=0;
  8613. Result := True;
  8614. end
  8615. else if (cs_opt_size in current_settings.optimizerswitches) and
  8616. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8617. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8618. begin
  8619. { Change:
  8620. movl %edx,%eax
  8621. sarl $31,%edx
  8622. To:
  8623. movl %edx,%eax
  8624. cltd
  8625. Note that this creates a dependency between the two instructions,
  8626. so only perform if optimising for size.
  8627. }
  8628. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8629. taicpu(hp1).opcode := A_CDQ;
  8630. taicpu(hp1).opsize := S_NO;
  8631. taicpu(hp1).clearop(1);
  8632. taicpu(hp1).clearop(0);
  8633. taicpu(hp1).ops:=0;
  8634. end;
  8635. {$ifndef x86_64}
  8636. end
  8637. { Don't bother if CMOV is supported, because a more optimal
  8638. sequence would have been generated for the Abs() intrinsic }
  8639. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8640. { the use of %eax also covers the opsize being S_L }
  8641. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8642. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8643. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8644. GetNextInstruction(hp1, hp2) and
  8645. MatchInstruction(hp2, A_XOR, [S_L]) and
  8646. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8647. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8648. GetNextInstruction(hp2, hp3) and
  8649. MatchInstruction(hp3, A_SUB, [S_L]) and
  8650. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8651. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8652. begin
  8653. { Change:
  8654. movl %eax,%edx
  8655. sarl $31,%eax
  8656. xorl %eax,%edx
  8657. subl %eax,%edx
  8658. (Instruction that uses %edx)
  8659. (%eax deallocated)
  8660. (%edx deallocated)
  8661. To:
  8662. cltd
  8663. xorl %edx,%eax <-- Note the registers have swapped
  8664. subl %edx,%eax
  8665. (Instruction that uses %eax) <-- %eax rather than %edx
  8666. }
  8667. TransferUsedRegs(TmpUsedRegs);
  8668. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8669. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8670. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8671. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8672. begin
  8673. if GetNextInstruction(hp3, hp4) and
  8674. not RegModifiedByInstruction(NR_EDX, hp4) and
  8675. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8676. begin
  8677. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8678. taicpu(p).opcode := A_CDQ;
  8679. taicpu(p).clearop(1);
  8680. taicpu(p).clearop(0);
  8681. taicpu(p).ops:=0;
  8682. RemoveInstruction(hp1);
  8683. taicpu(hp2).loadreg(0, NR_EDX);
  8684. taicpu(hp2).loadreg(1, NR_EAX);
  8685. taicpu(hp3).loadreg(0, NR_EDX);
  8686. taicpu(hp3).loadreg(1, NR_EAX);
  8687. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8688. { Convert references in the following instruction (hp4) from %edx to %eax }
  8689. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8690. with taicpu(hp4).oper[OperIdx]^ do
  8691. case typ of
  8692. top_reg:
  8693. if getsupreg(reg) = RS_EDX then
  8694. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8695. top_ref:
  8696. begin
  8697. if getsupreg(reg) = RS_EDX then
  8698. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8699. if getsupreg(reg) = RS_EDX then
  8700. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8701. end;
  8702. else
  8703. ;
  8704. end;
  8705. end;
  8706. end;
  8707. {$else x86_64}
  8708. end;
  8709. end
  8710. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8711. { the use of %rdx also covers the opsize being S_Q }
  8712. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8713. begin
  8714. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8715. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8716. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8717. begin
  8718. { Change:
  8719. movq %rax,%rdx
  8720. sarq $63,%rdx
  8721. To:
  8722. cqto
  8723. }
  8724. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8725. RemoveInstruction(hp1);
  8726. taicpu(p).opcode := A_CQO;
  8727. taicpu(p).opsize := S_NO;
  8728. taicpu(p).clearop(1);
  8729. taicpu(p).clearop(0);
  8730. taicpu(p).ops:=0;
  8731. Result := True;
  8732. end
  8733. else if (cs_opt_size in current_settings.optimizerswitches) and
  8734. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8735. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8736. begin
  8737. { Change:
  8738. movq %rdx,%rax
  8739. sarq $63,%rdx
  8740. To:
  8741. movq %rdx,%rax
  8742. cqto
  8743. Note that this creates a dependency between the two instructions,
  8744. so only perform if optimising for size.
  8745. }
  8746. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8747. taicpu(hp1).opcode := A_CQO;
  8748. taicpu(hp1).opsize := S_NO;
  8749. taicpu(hp1).clearop(1);
  8750. taicpu(hp1).clearop(0);
  8751. taicpu(hp1).ops:=0;
  8752. {$endif x86_64}
  8753. end;
  8754. end;
  8755. end
  8756. else if MatchInstruction(hp1, A_MOV, []) and
  8757. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8758. { Though "GetNextInstruction" could be factored out, along with
  8759. the instructions that depend on hp2, it is an expensive call that
  8760. should be delayed for as long as possible, hence we do cheaper
  8761. checks first that are likely to be False. [Kit] }
  8762. begin
  8763. if (
  8764. (
  8765. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8766. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8767. (
  8768. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8769. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8770. )
  8771. ) or
  8772. (
  8773. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8774. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8775. (
  8776. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8777. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8778. )
  8779. )
  8780. ) and
  8781. GetNextInstruction(hp1, hp2) and
  8782. MatchInstruction(hp2, A_SAR, []) and
  8783. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8784. begin
  8785. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8786. begin
  8787. { Change:
  8788. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8789. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8790. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8791. To:
  8792. movl r/m,%eax <- Note the change in register
  8793. cltd
  8794. }
  8795. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8796. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8797. taicpu(p).loadreg(1, NR_EAX);
  8798. taicpu(hp1).opcode := A_CDQ;
  8799. taicpu(hp1).clearop(1);
  8800. taicpu(hp1).clearop(0);
  8801. taicpu(hp1).ops:=0;
  8802. RemoveInstruction(hp2);
  8803. (*
  8804. {$ifdef x86_64}
  8805. end
  8806. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8807. { This code sequence does not get generated - however it might become useful
  8808. if and when 128-bit signed integer types make an appearance, so the code
  8809. is kept here for when it is eventually needed. [Kit] }
  8810. (
  8811. (
  8812. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8813. (
  8814. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8815. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8816. )
  8817. ) or
  8818. (
  8819. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8820. (
  8821. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8822. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8823. )
  8824. )
  8825. ) and
  8826. GetNextInstruction(hp1, hp2) and
  8827. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8828. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8829. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8830. begin
  8831. { Change:
  8832. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8833. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8834. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8835. To:
  8836. movq r/m,%rax <- Note the change in register
  8837. cqto
  8838. }
  8839. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8840. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8841. taicpu(p).loadreg(1, NR_RAX);
  8842. taicpu(hp1).opcode := A_CQO;
  8843. taicpu(hp1).clearop(1);
  8844. taicpu(hp1).clearop(0);
  8845. taicpu(hp1).ops:=0;
  8846. RemoveInstruction(hp2);
  8847. {$endif x86_64}
  8848. *)
  8849. end;
  8850. end;
  8851. {$ifdef x86_64}
  8852. end
  8853. else if (taicpu(p).opsize = S_L) and
  8854. (taicpu(p).oper[1]^.typ = top_reg) and
  8855. (
  8856. MatchInstruction(hp1, A_MOV,[]) and
  8857. (taicpu(hp1).opsize = S_L) and
  8858. (taicpu(hp1).oper[1]^.typ = top_reg)
  8859. ) and (
  8860. GetNextInstruction(hp1, hp2) and
  8861. (tai(hp2).typ=ait_instruction) and
  8862. (taicpu(hp2).opsize = S_Q) and
  8863. (
  8864. (
  8865. MatchInstruction(hp2, A_ADD,[]) and
  8866. (taicpu(hp2).opsize = S_Q) and
  8867. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8868. (
  8869. (
  8870. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8871. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8872. ) or (
  8873. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8874. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8875. )
  8876. )
  8877. ) or (
  8878. MatchInstruction(hp2, A_LEA,[]) and
  8879. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8880. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8881. (
  8882. (
  8883. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8884. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8885. ) or (
  8886. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8887. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8888. )
  8889. ) and (
  8890. (
  8891. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8892. ) or (
  8893. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8894. )
  8895. )
  8896. )
  8897. )
  8898. ) and (
  8899. GetNextInstruction(hp2, hp3) and
  8900. MatchInstruction(hp3, A_SHR,[]) and
  8901. (taicpu(hp3).opsize = S_Q) and
  8902. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8903. (taicpu(hp3).oper[0]^.val = 1) and
  8904. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8905. ) then
  8906. begin
  8907. { Change movl x, reg1d movl x, reg1d
  8908. movl y, reg2d movl y, reg2d
  8909. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8910. shrq $1, reg1q shrq $1, reg1q
  8911. ( reg1d and reg2d can be switched around in the first two instructions )
  8912. To movl x, reg1d
  8913. addl y, reg1d
  8914. rcrl $1, reg1d
  8915. This corresponds to the common expression (x + y) shr 1, where
  8916. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8917. smaller code, but won't account for x + y causing an overflow). [Kit]
  8918. }
  8919. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8920. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8921. { Change first MOV command to have the same register as the final output }
  8922. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8923. else
  8924. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8925. { Change second MOV command to an ADD command. This is easier than
  8926. converting the existing command because it means we don't have to
  8927. touch 'y', which might be a complicated reference, and also the
  8928. fact that the third command might either be ADD or LEA. [Kit] }
  8929. taicpu(hp1).opcode := A_ADD;
  8930. { Delete old ADD/LEA instruction }
  8931. RemoveInstruction(hp2);
  8932. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8933. taicpu(hp3).opcode := A_RCR;
  8934. taicpu(hp3).changeopsize(S_L);
  8935. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8936. {$endif x86_64}
  8937. end;
  8938. if FuncMov2Func(p, hp1) then
  8939. begin
  8940. Result := True;
  8941. Exit;
  8942. end;
  8943. end;
  8944. {$push}
  8945. {$q-}{$r-}
  8946. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8947. var
  8948. ThisReg: TRegister;
  8949. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8950. TargetSubReg: TSubRegister;
  8951. hp1, hp2: tai;
  8952. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8953. { Store list of found instructions so we don't have to call
  8954. GetNextInstructionUsingReg multiple times }
  8955. InstrList: array of taicpu;
  8956. InstrMax, Index: Integer;
  8957. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8958. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8959. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8960. WorkingValue: TCgInt;
  8961. PreMessage: string;
  8962. { Data flow analysis }
  8963. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8964. BitwiseOnly, OrXorUsed,
  8965. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8966. function CheckOverflowConditions: Boolean;
  8967. begin
  8968. Result := True;
  8969. if (TestValSignedMax > SignedUpperLimit) then
  8970. UpperSignedOverflow := True;
  8971. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8972. LowerSignedOverflow := True;
  8973. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8974. LowerUnsignedOverflow := True;
  8975. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8976. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8977. begin
  8978. { Absolute overflow }
  8979. Result := False;
  8980. Exit;
  8981. end;
  8982. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8983. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8984. ShiftDownOverflow := True;
  8985. if (TestValMin < 0) or (TestValMax < 0) then
  8986. begin
  8987. LowerUnsignedOverflow := True;
  8988. UpperUnsignedOverflow := True;
  8989. end;
  8990. end;
  8991. function AdjustInitialLoadAndSize: Boolean;
  8992. begin
  8993. Result := False;
  8994. if not p_removed then
  8995. begin
  8996. if TargetSize = MinSize then
  8997. begin
  8998. { Convert the input MOVZX to a MOV }
  8999. if (taicpu(p).oper[0]^.typ = top_reg) and
  9000. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9001. begin
  9002. { Or remove it completely! }
  9003. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9004. RemoveCurrentP(p);
  9005. p_removed := True;
  9006. end
  9007. else
  9008. begin
  9009. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9010. taicpu(p).opcode := A_MOV;
  9011. taicpu(p).oper[1]^.reg := ThisReg;
  9012. taicpu(p).opsize := TargetSize;
  9013. end;
  9014. Result := True;
  9015. end
  9016. else if TargetSize <> MaxSize then
  9017. begin
  9018. case MaxSize of
  9019. S_L:
  9020. if TargetSize = S_W then
  9021. begin
  9022. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9023. taicpu(p).opsize := S_BW;
  9024. taicpu(p).oper[1]^.reg := ThisReg;
  9025. Result := True;
  9026. end
  9027. else
  9028. InternalError(2020112341);
  9029. S_W:
  9030. if TargetSize = S_L then
  9031. begin
  9032. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9033. taicpu(p).opsize := S_BL;
  9034. taicpu(p).oper[1]^.reg := ThisReg;
  9035. Result := True;
  9036. end
  9037. else
  9038. InternalError(2020112342);
  9039. else
  9040. ;
  9041. end;
  9042. end
  9043. else if not hp1_removed and not RegInUse then
  9044. begin
  9045. { If we have something like:
  9046. movzbl (oper),%regd
  9047. add x, %regd
  9048. movzbl %regb, %regd
  9049. We can reduce the register size to the input of the final
  9050. movzbl instruction. Overflows won't have any effect.
  9051. }
  9052. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9053. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9054. begin
  9055. TargetSize := S_B;
  9056. setsubreg(ThisReg, R_SUBL);
  9057. Result := True;
  9058. end
  9059. else if (taicpu(p).opsize = S_WL) and
  9060. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9061. begin
  9062. TargetSize := S_W;
  9063. setsubreg(ThisReg, R_SUBW);
  9064. Result := True;
  9065. end;
  9066. if Result then
  9067. begin
  9068. { Convert the input MOVZX to a MOV }
  9069. if (taicpu(p).oper[0]^.typ = top_reg) and
  9070. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9071. begin
  9072. { Or remove it completely! }
  9073. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9074. RemoveCurrentP(p);
  9075. p_removed := True;
  9076. end
  9077. else
  9078. begin
  9079. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9080. taicpu(p).opcode := A_MOV;
  9081. taicpu(p).oper[1]^.reg := ThisReg;
  9082. taicpu(p).opsize := TargetSize;
  9083. end;
  9084. end;
  9085. end;
  9086. end;
  9087. end;
  9088. procedure AdjustFinalLoad;
  9089. begin
  9090. if not LowerUnsignedOverflow then
  9091. begin
  9092. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9093. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9094. begin
  9095. { Convert the output MOVZX to a MOV }
  9096. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9097. begin
  9098. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9099. if (MinSize = S_B) or
  9100. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9101. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9102. begin
  9103. { Remove it completely! }
  9104. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9105. { Be careful; if p = hp1 and p was also removed, p
  9106. will become a dangling pointer }
  9107. if p = hp1 then
  9108. begin
  9109. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9110. p_removed := True;
  9111. end
  9112. else
  9113. RemoveInstruction(hp1);
  9114. hp1_removed := True;
  9115. end;
  9116. end
  9117. else
  9118. begin
  9119. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9120. taicpu(hp1).opcode := A_MOV;
  9121. taicpu(hp1).oper[0]^.reg := ThisReg;
  9122. taicpu(hp1).opsize := TargetSize;
  9123. end;
  9124. end
  9125. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9126. begin
  9127. { Need to change the size of the output }
  9128. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9129. taicpu(hp1).oper[0]^.reg := ThisReg;
  9130. taicpu(hp1).opsize := S_BL;
  9131. end;
  9132. end;
  9133. end;
  9134. function CompressInstructions: Boolean;
  9135. var
  9136. LocalIndex: Integer;
  9137. begin
  9138. Result := False;
  9139. { The objective here is to try to find a combination that
  9140. removes one of the MOV/Z instructions. }
  9141. if (
  9142. (taicpu(p).oper[0]^.typ <> top_reg) or
  9143. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9144. ) and
  9145. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9146. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9147. begin
  9148. { Make a preference to remove the second MOVZX instruction }
  9149. case taicpu(hp1).opsize of
  9150. S_BL, S_WL:
  9151. begin
  9152. TargetSize := S_L;
  9153. TargetSubReg := R_SUBD;
  9154. end;
  9155. S_BW:
  9156. begin
  9157. TargetSize := S_W;
  9158. TargetSubReg := R_SUBW;
  9159. end;
  9160. else
  9161. InternalError(2020112302);
  9162. end;
  9163. end
  9164. else
  9165. begin
  9166. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9167. begin
  9168. { Exceeded lower bound but not upper bound }
  9169. TargetSize := MaxSize;
  9170. end
  9171. else if not LowerUnsignedOverflow then
  9172. begin
  9173. { Size didn't exceed lower bound }
  9174. TargetSize := MinSize;
  9175. end
  9176. else
  9177. Exit;
  9178. end;
  9179. case TargetSize of
  9180. S_B:
  9181. TargetSubReg := R_SUBL;
  9182. S_W:
  9183. TargetSubReg := R_SUBW;
  9184. S_L:
  9185. TargetSubReg := R_SUBD;
  9186. else
  9187. InternalError(2020112350);
  9188. end;
  9189. { Update the register to its new size }
  9190. setsubreg(ThisReg, TargetSubReg);
  9191. RegInUse := False;
  9192. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9193. begin
  9194. { Check to see if the active register is used afterwards;
  9195. if not, we can change it and make a saving. }
  9196. TransferUsedRegs(TmpUsedRegs);
  9197. { The target register may be marked as in use to cross
  9198. a jump to a distant label, so exclude it }
  9199. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9200. hp2 := p;
  9201. repeat
  9202. { Explicitly check for the excluded register (don't include the first
  9203. instruction as it may be reading from here }
  9204. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9205. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9206. begin
  9207. RegInUse := True;
  9208. Break;
  9209. end;
  9210. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9211. if not GetNextInstruction(hp2, hp2) then
  9212. InternalError(2020112340);
  9213. until (hp2 = hp1);
  9214. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9215. { We might still be able to get away with this }
  9216. RegInUse := not
  9217. (
  9218. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9219. (hp2.typ = ait_instruction) and
  9220. (
  9221. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9222. instruction that doesn't actually contain ThisReg }
  9223. (cs_opt_level3 in current_settings.optimizerswitches) or
  9224. RegInInstruction(ThisReg, hp2)
  9225. ) and
  9226. RegLoadedWithNewValue(ThisReg, hp2)
  9227. );
  9228. if not RegInUse then
  9229. begin
  9230. { Force the register size to the same as this instruction so it can be removed}
  9231. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9232. begin
  9233. TargetSize := S_L;
  9234. TargetSubReg := R_SUBD;
  9235. end
  9236. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9237. begin
  9238. TargetSize := S_W;
  9239. TargetSubReg := R_SUBW;
  9240. end;
  9241. ThisReg := taicpu(hp1).oper[1]^.reg;
  9242. setsubreg(ThisReg, TargetSubReg);
  9243. RegChanged := True;
  9244. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9245. TransferUsedRegs(TmpUsedRegs);
  9246. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9247. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9248. if p = hp1 then
  9249. begin
  9250. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9251. p_removed := True;
  9252. end
  9253. else
  9254. RemoveInstruction(hp1);
  9255. hp1_removed := True;
  9256. { Instruction will become "mov %reg,%reg" }
  9257. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9258. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9259. begin
  9260. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9261. RemoveCurrentP(p);
  9262. p_removed := True;
  9263. end
  9264. else
  9265. taicpu(p).oper[1]^.reg := ThisReg;
  9266. Result := True;
  9267. end
  9268. else
  9269. begin
  9270. if TargetSize <> MaxSize then
  9271. begin
  9272. { Since the register is in use, we have to force it to
  9273. MaxSize otherwise part of it may become undefined later on }
  9274. TargetSize := MaxSize;
  9275. case TargetSize of
  9276. S_B:
  9277. TargetSubReg := R_SUBL;
  9278. S_W:
  9279. TargetSubReg := R_SUBW;
  9280. S_L:
  9281. TargetSubReg := R_SUBD;
  9282. else
  9283. InternalError(2020112351);
  9284. end;
  9285. setsubreg(ThisReg, TargetSubReg);
  9286. end;
  9287. AdjustFinalLoad;
  9288. end;
  9289. end
  9290. else
  9291. AdjustFinalLoad;
  9292. Result := AdjustInitialLoadAndSize or Result;
  9293. { Now go through every instruction we found and change the
  9294. size. If TargetSize = MaxSize, then almost no changes are
  9295. needed and Result can remain False if it hasn't been set
  9296. yet.
  9297. If RegChanged is True, then the register requires changing
  9298. and so the point about TargetSize = MaxSize doesn't apply. }
  9299. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9300. begin
  9301. for LocalIndex := 0 to InstrMax do
  9302. begin
  9303. { If p_removed is true, then the original MOV/Z was removed
  9304. and removing the AND instruction may not be safe if it
  9305. appears first }
  9306. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9307. InternalError(2020112310);
  9308. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9309. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9310. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9311. InstrList[LocalIndex].opsize := TargetSize;
  9312. end;
  9313. Result := True;
  9314. end;
  9315. end;
  9316. begin
  9317. Result := False;
  9318. p_removed := False;
  9319. hp1_removed := False;
  9320. ThisReg := taicpu(p).oper[1]^.reg;
  9321. { Check for:
  9322. movs/z ###,%ecx (or %cx or %rcx)
  9323. ...
  9324. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9325. (dealloc %ecx)
  9326. Change to:
  9327. mov ###,%cl (if ### = %cl, then remove completely)
  9328. ...
  9329. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9330. }
  9331. if (getsupreg(ThisReg) = RS_ECX) and
  9332. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9333. (hp1.typ = ait_instruction) and
  9334. (
  9335. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9336. instruction that doesn't actually contain ECX }
  9337. (cs_opt_level3 in current_settings.optimizerswitches) or
  9338. RegInInstruction(NR_ECX, hp1) or
  9339. (
  9340. { It's common for the shift/rotate's read/write register to be
  9341. initialised in between, so under -O2 and under, search ahead
  9342. one more instruction
  9343. }
  9344. GetNextInstruction(hp1, hp1) and
  9345. (hp1.typ = ait_instruction) and
  9346. RegInInstruction(NR_ECX, hp1)
  9347. )
  9348. ) and
  9349. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9350. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9351. begin
  9352. TransferUsedRegs(TmpUsedRegs);
  9353. hp2 := p;
  9354. repeat
  9355. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9356. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9357. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9358. begin
  9359. case taicpu(p).opsize of
  9360. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9361. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9362. begin
  9363. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9364. RemoveCurrentP(p);
  9365. end
  9366. else
  9367. begin
  9368. taicpu(p).opcode := A_MOV;
  9369. taicpu(p).opsize := S_B;
  9370. taicpu(p).oper[1]^.reg := NR_CL;
  9371. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9372. end;
  9373. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9374. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9375. begin
  9376. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9377. RemoveCurrentP(p);
  9378. end
  9379. else
  9380. begin
  9381. taicpu(p).opcode := A_MOV;
  9382. taicpu(p).opsize := S_W;
  9383. taicpu(p).oper[1]^.reg := NR_CX;
  9384. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9385. end;
  9386. {$ifdef x86_64}
  9387. S_LQ:
  9388. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9389. begin
  9390. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9391. RemoveCurrentP(p);
  9392. end
  9393. else
  9394. begin
  9395. taicpu(p).opcode := A_MOV;
  9396. taicpu(p).opsize := S_L;
  9397. taicpu(p).oper[1]^.reg := NR_ECX;
  9398. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9399. end;
  9400. {$endif x86_64}
  9401. else
  9402. InternalError(2021120401);
  9403. end;
  9404. Result := True;
  9405. Exit;
  9406. end;
  9407. end;
  9408. { This is anything but quick! }
  9409. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9410. Exit;
  9411. SetLength(InstrList, 0);
  9412. InstrMax := -1;
  9413. case taicpu(p).opsize of
  9414. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9415. begin
  9416. {$if defined(i386) or defined(i8086)}
  9417. { If the target size is 8-bit, make sure we can actually encode it }
  9418. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9419. Exit;
  9420. {$endif i386 or i8086}
  9421. LowerLimit := $FF;
  9422. SignedLowerLimit := $7F;
  9423. SignedLowerLimitBottom := -128;
  9424. MinSize := S_B;
  9425. if taicpu(p).opsize = S_BW then
  9426. begin
  9427. MaxSize := S_W;
  9428. UpperLimit := $FFFF;
  9429. SignedUpperLimit := $7FFF;
  9430. SignedUpperLimitBottom := -32768;
  9431. end
  9432. else
  9433. begin
  9434. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9435. MaxSize := S_L;
  9436. UpperLimit := $FFFFFFFF;
  9437. SignedUpperLimit := $7FFFFFFF;
  9438. SignedUpperLimitBottom := -2147483648;
  9439. end;
  9440. end;
  9441. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9442. begin
  9443. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9444. LowerLimit := $FFFF;
  9445. SignedLowerLimit := $7FFF;
  9446. SignedLowerLimitBottom := -32768;
  9447. UpperLimit := $FFFFFFFF;
  9448. SignedUpperLimit := $7FFFFFFF;
  9449. SignedUpperLimitBottom := -2147483648;
  9450. MinSize := S_W;
  9451. MaxSize := S_L;
  9452. end;
  9453. {$ifdef x86_64}
  9454. S_LQ:
  9455. begin
  9456. { Both the lower and upper limits are set to 32-bit. If a limit
  9457. is breached, then optimisation is impossible }
  9458. LowerLimit := $FFFFFFFF;
  9459. SignedLowerLimit := $7FFFFFFF;
  9460. SignedLowerLimitBottom := -2147483648;
  9461. UpperLimit := $FFFFFFFF;
  9462. SignedUpperLimit := $7FFFFFFF;
  9463. SignedUpperLimitBottom := -2147483648;
  9464. MinSize := S_L;
  9465. MaxSize := S_L;
  9466. end;
  9467. {$endif x86_64}
  9468. else
  9469. InternalError(2020112301);
  9470. end;
  9471. TestValMin := 0;
  9472. TestValMax := LowerLimit;
  9473. TestValSignedMax := SignedLowerLimit;
  9474. TryShiftDownLimit := LowerLimit;
  9475. TryShiftDown := S_NO;
  9476. ShiftDownOverflow := False;
  9477. RegChanged := False;
  9478. BitwiseOnly := True;
  9479. OrXorUsed := False;
  9480. UpperSignedOverflow := False;
  9481. LowerSignedOverflow := False;
  9482. UpperUnsignedOverflow := False;
  9483. LowerUnsignedOverflow := False;
  9484. hp1 := p;
  9485. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9486. (hp1.typ = ait_instruction) and
  9487. (
  9488. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9489. instruction that doesn't actually contain ThisReg }
  9490. (cs_opt_level3 in current_settings.optimizerswitches) or
  9491. { This allows this Movx optimisation to work through the SETcc instructions
  9492. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9493. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9494. skip over these SETcc instructions). }
  9495. (taicpu(hp1).opcode = A_SETcc) or
  9496. RegInInstruction(ThisReg, hp1)
  9497. ) do
  9498. begin
  9499. case taicpu(hp1).opcode of
  9500. A_INC,A_DEC:
  9501. begin
  9502. { Has to be an exact match on the register }
  9503. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9504. Break;
  9505. if taicpu(hp1).opcode = A_INC then
  9506. begin
  9507. Inc(TestValMin);
  9508. Inc(TestValMax);
  9509. Inc(TestValSignedMax);
  9510. end
  9511. else
  9512. begin
  9513. Dec(TestValMin);
  9514. Dec(TestValMax);
  9515. Dec(TestValSignedMax);
  9516. end;
  9517. end;
  9518. A_TEST, A_CMP:
  9519. begin
  9520. if (
  9521. { Too high a risk of non-linear behaviour that breaks DFA
  9522. here, unless it's cmp $0,%reg, which is equivalent to
  9523. test %reg,%reg }
  9524. OrXorUsed and
  9525. (taicpu(hp1).opcode = A_CMP) and
  9526. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9527. ) or
  9528. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9529. { Has to be an exact match on the register }
  9530. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9531. (
  9532. { Permit "test %reg,%reg" }
  9533. (taicpu(hp1).opcode = A_TEST) and
  9534. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9535. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9536. ) or
  9537. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9538. { Make sure the comparison value is not smaller than the
  9539. smallest allowed signed value for the minimum size (e.g.
  9540. -128 for 8-bit) }
  9541. not (
  9542. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9543. { Is it in the negative range? }
  9544. (
  9545. (taicpu(hp1).oper[0]^.val < 0) and
  9546. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9547. )
  9548. ) then
  9549. Break;
  9550. { Check to see if the active register is used afterwards }
  9551. TransferUsedRegs(TmpUsedRegs);
  9552. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9553. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9554. begin
  9555. { Make sure the comparison or any previous instructions
  9556. hasn't pushed the test values outside of the range of
  9557. MinSize }
  9558. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9559. begin
  9560. { Exceeded lower bound but not upper bound }
  9561. Exit;
  9562. end
  9563. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9564. begin
  9565. { Size didn't exceed lower bound }
  9566. TargetSize := MinSize;
  9567. end
  9568. else
  9569. Break;
  9570. case TargetSize of
  9571. S_B:
  9572. TargetSubReg := R_SUBL;
  9573. S_W:
  9574. TargetSubReg := R_SUBW;
  9575. S_L:
  9576. TargetSubReg := R_SUBD;
  9577. else
  9578. InternalError(2021051002);
  9579. end;
  9580. if TargetSize <> MaxSize then
  9581. begin
  9582. { Update the register to its new size }
  9583. setsubreg(ThisReg, TargetSubReg);
  9584. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9585. taicpu(hp1).oper[1]^.reg := ThisReg;
  9586. taicpu(hp1).opsize := TargetSize;
  9587. { Convert the input MOVZX to a MOV if necessary }
  9588. AdjustInitialLoadAndSize;
  9589. if (InstrMax >= 0) then
  9590. begin
  9591. for Index := 0 to InstrMax do
  9592. begin
  9593. { If p_removed is true, then the original MOV/Z was removed
  9594. and removing the AND instruction may not be safe if it
  9595. appears first }
  9596. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9597. InternalError(2020112311);
  9598. if InstrList[Index].oper[0]^.typ = top_reg then
  9599. InstrList[Index].oper[0]^.reg := ThisReg;
  9600. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9601. InstrList[Index].opsize := MinSize;
  9602. end;
  9603. end;
  9604. Result := True;
  9605. end;
  9606. Exit;
  9607. end;
  9608. end;
  9609. A_SETcc:
  9610. begin
  9611. { This allows this Movx optimisation to work through the SETcc instructions
  9612. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9613. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9614. skip over these SETcc instructions). }
  9615. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9616. { Of course, break out if the current register is used }
  9617. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9618. Break
  9619. else
  9620. { We must use Continue so the instruction doesn't get added
  9621. to InstrList }
  9622. Continue;
  9623. end;
  9624. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9625. begin
  9626. if
  9627. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9628. { Has to be an exact match on the register }
  9629. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9630. (
  9631. (
  9632. (taicpu(hp1).oper[0]^.typ = top_const) and
  9633. (
  9634. (
  9635. (taicpu(hp1).opcode = A_SHL) and
  9636. (
  9637. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9638. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9639. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9640. )
  9641. ) or (
  9642. (taicpu(hp1).opcode <> A_SHL) and
  9643. (
  9644. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9645. { Is it in the negative range? }
  9646. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9647. )
  9648. )
  9649. )
  9650. ) or (
  9651. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9652. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9653. )
  9654. ) then
  9655. Break;
  9656. { Only process OR and XOR if there are only bitwise operations,
  9657. since otherwise they can too easily fool the data flow
  9658. analysis (they can cause non-linear behaviour) }
  9659. case taicpu(hp1).opcode of
  9660. A_ADD:
  9661. begin
  9662. if OrXorUsed then
  9663. { Too high a risk of non-linear behaviour that breaks DFA here }
  9664. Break
  9665. else
  9666. BitwiseOnly := False;
  9667. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9668. begin
  9669. TestValMin := TestValMin * 2;
  9670. TestValMax := TestValMax * 2;
  9671. TestValSignedMax := TestValSignedMax * 2;
  9672. end
  9673. else
  9674. begin
  9675. WorkingValue := taicpu(hp1).oper[0]^.val;
  9676. TestValMin := TestValMin + WorkingValue;
  9677. TestValMax := TestValMax + WorkingValue;
  9678. TestValSignedMax := TestValSignedMax + WorkingValue;
  9679. end;
  9680. end;
  9681. A_SUB:
  9682. begin
  9683. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9684. begin
  9685. TestValMin := 0;
  9686. TestValMax := 0;
  9687. TestValSignedMax := 0;
  9688. end
  9689. else
  9690. begin
  9691. if OrXorUsed then
  9692. { Too high a risk of non-linear behaviour that breaks DFA here }
  9693. Break
  9694. else
  9695. BitwiseOnly := False;
  9696. WorkingValue := taicpu(hp1).oper[0]^.val;
  9697. TestValMin := TestValMin - WorkingValue;
  9698. TestValMax := TestValMax - WorkingValue;
  9699. TestValSignedMax := TestValSignedMax - WorkingValue;
  9700. end;
  9701. end;
  9702. A_AND:
  9703. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9704. begin
  9705. { we might be able to go smaller if AND appears first }
  9706. if InstrMax = -1 then
  9707. case MinSize of
  9708. S_B:
  9709. ;
  9710. S_W:
  9711. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9712. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9713. begin
  9714. TryShiftDown := S_B;
  9715. TryShiftDownLimit := $FF;
  9716. end;
  9717. S_L:
  9718. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9719. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9720. begin
  9721. TryShiftDown := S_B;
  9722. TryShiftDownLimit := $FF;
  9723. end
  9724. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9725. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9726. begin
  9727. TryShiftDown := S_W;
  9728. TryShiftDownLimit := $FFFF;
  9729. end;
  9730. else
  9731. InternalError(2020112320);
  9732. end;
  9733. WorkingValue := taicpu(hp1).oper[0]^.val;
  9734. TestValMin := TestValMin and WorkingValue;
  9735. TestValMax := TestValMax and WorkingValue;
  9736. TestValSignedMax := TestValSignedMax and WorkingValue;
  9737. end;
  9738. A_OR:
  9739. begin
  9740. if not BitwiseOnly then
  9741. Break;
  9742. OrXorUsed := True;
  9743. WorkingValue := taicpu(hp1).oper[0]^.val;
  9744. TestValMin := TestValMin or WorkingValue;
  9745. TestValMax := TestValMax or WorkingValue;
  9746. TestValSignedMax := TestValSignedMax or WorkingValue;
  9747. end;
  9748. A_XOR:
  9749. begin
  9750. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9751. begin
  9752. TestValMin := 0;
  9753. TestValMax := 0;
  9754. TestValSignedMax := 0;
  9755. end
  9756. else
  9757. begin
  9758. if not BitwiseOnly then
  9759. Break;
  9760. OrXorUsed := True;
  9761. WorkingValue := taicpu(hp1).oper[0]^.val;
  9762. TestValMin := TestValMin xor WorkingValue;
  9763. TestValMax := TestValMax xor WorkingValue;
  9764. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9765. end;
  9766. end;
  9767. A_SHL:
  9768. begin
  9769. BitwiseOnly := False;
  9770. WorkingValue := taicpu(hp1).oper[0]^.val;
  9771. TestValMin := TestValMin shl WorkingValue;
  9772. TestValMax := TestValMax shl WorkingValue;
  9773. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9774. end;
  9775. A_SHR,
  9776. { The first instruction was MOVZX, so the value won't be negative }
  9777. A_SAR:
  9778. begin
  9779. if InstrMax <> -1 then
  9780. BitwiseOnly := False
  9781. else
  9782. { we might be able to go smaller if SHR appears first }
  9783. case MinSize of
  9784. S_B:
  9785. ;
  9786. S_W:
  9787. if (taicpu(hp1).oper[0]^.val >= 8) then
  9788. begin
  9789. TryShiftDown := S_B;
  9790. TryShiftDownLimit := $FF;
  9791. TryShiftDownSignedLimit := $7F;
  9792. TryShiftDownSignedLimitLower := -128;
  9793. end;
  9794. S_L:
  9795. if (taicpu(hp1).oper[0]^.val >= 24) then
  9796. begin
  9797. TryShiftDown := S_B;
  9798. TryShiftDownLimit := $FF;
  9799. TryShiftDownSignedLimit := $7F;
  9800. TryShiftDownSignedLimitLower := -128;
  9801. end
  9802. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9803. begin
  9804. TryShiftDown := S_W;
  9805. TryShiftDownLimit := $FFFF;
  9806. TryShiftDownSignedLimit := $7FFF;
  9807. TryShiftDownSignedLimitLower := -32768;
  9808. end;
  9809. else
  9810. InternalError(2020112321);
  9811. end;
  9812. WorkingValue := taicpu(hp1).oper[0]^.val;
  9813. if taicpu(hp1).opcode = A_SAR then
  9814. begin
  9815. TestValMin := SarInt64(TestValMin, WorkingValue);
  9816. TestValMax := SarInt64(TestValMax, WorkingValue);
  9817. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9818. end
  9819. else
  9820. begin
  9821. TestValMin := TestValMin shr WorkingValue;
  9822. TestValMax := TestValMax shr WorkingValue;
  9823. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9824. end;
  9825. end;
  9826. else
  9827. InternalError(2020112303);
  9828. end;
  9829. end;
  9830. (*
  9831. A_IMUL:
  9832. case taicpu(hp1).ops of
  9833. 2:
  9834. begin
  9835. if not MatchOpType(hp1, top_reg, top_reg) or
  9836. { Has to be an exact match on the register }
  9837. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9838. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9839. Break;
  9840. TestValMin := TestValMin * TestValMin;
  9841. TestValMax := TestValMax * TestValMax;
  9842. TestValSignedMax := TestValSignedMax * TestValMax;
  9843. end;
  9844. 3:
  9845. begin
  9846. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9847. { Has to be an exact match on the register }
  9848. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9849. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9850. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9851. { Is it in the negative range? }
  9852. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9853. Break;
  9854. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9855. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9856. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9857. end;
  9858. else
  9859. Break;
  9860. end;
  9861. A_IDIV:
  9862. case taicpu(hp1).ops of
  9863. 3:
  9864. begin
  9865. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9866. { Has to be an exact match on the register }
  9867. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9868. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9869. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9870. { Is it in the negative range? }
  9871. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9872. Break;
  9873. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9874. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9875. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9876. end;
  9877. else
  9878. Break;
  9879. end;
  9880. *)
  9881. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9882. begin
  9883. { If there are no instructions in between, then we might be able to make a saving }
  9884. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9885. Break;
  9886. { We have something like:
  9887. movzbw %dl,%dx
  9888. ...
  9889. movswl %dx,%edx
  9890. Change the latter to a zero-extension then enter the
  9891. A_MOVZX case branch.
  9892. }
  9893. {$ifdef x86_64}
  9894. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9895. begin
  9896. { this becomes a zero extension from 32-bit to 64-bit, but
  9897. the upper 32 bits are already zero, so just delete the
  9898. instruction }
  9899. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9900. RemoveInstruction(hp1);
  9901. Result := True;
  9902. Exit;
  9903. end
  9904. else
  9905. {$endif x86_64}
  9906. begin
  9907. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9908. taicpu(hp1).opcode := A_MOVZX;
  9909. {$ifdef x86_64}
  9910. case taicpu(hp1).opsize of
  9911. S_BQ:
  9912. begin
  9913. taicpu(hp1).opsize := S_BL;
  9914. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9915. end;
  9916. S_WQ:
  9917. begin
  9918. taicpu(hp1).opsize := S_WL;
  9919. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9920. end;
  9921. S_LQ:
  9922. begin
  9923. taicpu(hp1).opcode := A_MOV;
  9924. taicpu(hp1).opsize := S_L;
  9925. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9926. { In this instance, we need to break out because the
  9927. instruction is no longer MOVZX or MOVSXD }
  9928. Result := True;
  9929. Exit;
  9930. end;
  9931. else
  9932. ;
  9933. end;
  9934. {$endif x86_64}
  9935. Result := CompressInstructions;
  9936. Exit;
  9937. end;
  9938. end;
  9939. A_MOVZX:
  9940. begin
  9941. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9942. Break;
  9943. if (InstrMax = -1) then
  9944. begin
  9945. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9946. begin
  9947. { Optimise around i40003 }
  9948. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9949. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9950. {$ifndef x86_64}
  9951. and (
  9952. (taicpu(p).oper[0]^.typ <> top_reg) or
  9953. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9954. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9955. )
  9956. {$endif not x86_64}
  9957. then
  9958. begin
  9959. if (taicpu(p).oper[0]^.typ = top_reg) then
  9960. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9961. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9962. taicpu(p).opsize := S_BL;
  9963. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9964. RemoveInstruction(hp1);
  9965. Result := True;
  9966. Exit;
  9967. end;
  9968. end
  9969. else
  9970. begin
  9971. { Will return false if the second parameter isn't ThisReg
  9972. (can happen on -O2 and under) }
  9973. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9974. begin
  9975. { The two MOVZX instructions are adjacent, so remove the first one }
  9976. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9977. RemoveCurrentP(p);
  9978. Result := True;
  9979. Exit;
  9980. end;
  9981. Break;
  9982. end;
  9983. end;
  9984. Result := CompressInstructions;
  9985. Exit;
  9986. end;
  9987. else
  9988. { This includes ADC, SBB and IDIV }
  9989. Break;
  9990. end;
  9991. if not CheckOverflowConditions then
  9992. Break;
  9993. { Contains highest index (so instruction count - 1) }
  9994. Inc(InstrMax);
  9995. if InstrMax > High(InstrList) then
  9996. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9997. InstrList[InstrMax] := taicpu(hp1);
  9998. end;
  9999. end;
  10000. {$pop}
  10001. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10002. var
  10003. hp1 : tai;
  10004. begin
  10005. Result:=false;
  10006. if (taicpu(p).ops >= 2) and
  10007. ((taicpu(p).oper[0]^.typ = top_const) or
  10008. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10009. (taicpu(p).oper[1]^.typ = top_reg) and
  10010. ((taicpu(p).ops = 2) or
  10011. ((taicpu(p).oper[2]^.typ = top_reg) and
  10012. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10013. GetLastInstruction(p,hp1) and
  10014. MatchInstruction(hp1,A_MOV,[]) and
  10015. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10016. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10017. begin
  10018. TransferUsedRegs(TmpUsedRegs);
  10019. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10020. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10021. { change
  10022. mov reg1,reg2
  10023. imul y,reg2 to imul y,reg1,reg2 }
  10024. begin
  10025. taicpu(p).ops := 3;
  10026. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10027. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10028. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10029. RemoveInstruction(hp1);
  10030. result:=true;
  10031. end;
  10032. end;
  10033. end;
  10034. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10035. var
  10036. ThisLabel: TAsmLabel;
  10037. begin
  10038. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10039. ThisLabel.decrefs;
  10040. taicpu(p).condition := C_None;
  10041. taicpu(p).opcode := A_RET;
  10042. taicpu(p).is_jmp := false;
  10043. taicpu(p).ops := taicpu(ret_p).ops;
  10044. case taicpu(ret_p).ops of
  10045. 0:
  10046. taicpu(p).clearop(0);
  10047. 1:
  10048. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10049. else
  10050. internalerror(2016041301);
  10051. end;
  10052. { If the original label is now dead, it might turn out that the label
  10053. immediately follows p. As a result, everything beyond it, which will
  10054. be just some final register configuration and a RET instruction, is
  10055. now dead code. [Kit] }
  10056. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10057. running RemoveDeadCodeAfterJump for each RET instruction, because
  10058. this optimisation rarely happens and most RETs appear at the end of
  10059. routines where there is nothing that can be stripped. [Kit] }
  10060. if not ThisLabel.is_used then
  10061. RemoveDeadCodeAfterJump(p);
  10062. end;
  10063. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10064. var
  10065. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10066. Unconditional, PotentialModified: Boolean;
  10067. OperPtr: POper;
  10068. NewRef: TReference;
  10069. InstrList: array of taicpu;
  10070. InstrMax, Index: Integer;
  10071. const
  10072. {$ifdef DEBUG_AOPTCPU}
  10073. SNoFlags: shortstring = ' so the flags aren''t modified';
  10074. {$else DEBUG_AOPTCPU}
  10075. SNoFlags = '';
  10076. {$endif DEBUG_AOPTCPU}
  10077. begin
  10078. Result:=false;
  10079. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10080. begin
  10081. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10082. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10083. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10084. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10085. GetNextInstruction(hp1, hp2) and
  10086. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10087. { Change from: To:
  10088. set(C) %reg j(~C) label
  10089. test %reg,%reg/cmp $0,%reg
  10090. je label
  10091. set(C) %reg j(C) label
  10092. test %reg,%reg/cmp $0,%reg
  10093. jne label
  10094. (Also do something similar with sete/setne instead of je/jne)
  10095. }
  10096. begin
  10097. { Before we do anything else, we need to check the instructions
  10098. in between SETcc and TEST to make sure they don't modify the
  10099. FLAGS register - if -O2 or under, there won't be any
  10100. instructions between SET and TEST }
  10101. TransferUsedRegs(TmpUsedRegs);
  10102. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10103. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10104. begin
  10105. next := p;
  10106. SetLength(InstrList, 0);
  10107. InstrMax := -1;
  10108. PotentialModified := False;
  10109. { Make a note of every instruction that modifies the FLAGS
  10110. register }
  10111. while GetNextInstruction(next, next) and (next <> hp1) do
  10112. begin
  10113. if next.typ <> ait_instruction then
  10114. { GetNextInstructionUsingReg should have returned False }
  10115. InternalError(2021051701);
  10116. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10117. begin
  10118. case taicpu(next).opcode of
  10119. A_SETcc,
  10120. A_CMOVcc,
  10121. A_Jcc:
  10122. begin
  10123. if PotentialModified then
  10124. { Not safe because the flags were modified earlier }
  10125. Exit
  10126. else
  10127. { Condition is the same as the initial SETcc, so this is safe
  10128. (don't add to instruction list though) }
  10129. Continue;
  10130. end;
  10131. A_ADD:
  10132. begin
  10133. if (taicpu(next).opsize = S_B) or
  10134. { LEA doesn't support 8-bit operands }
  10135. (taicpu(next).oper[1]^.typ <> top_reg) or
  10136. { Must write to a register }
  10137. (taicpu(next).oper[0]^.typ = top_ref) then
  10138. { Require a constant or a register }
  10139. Exit;
  10140. PotentialModified := True;
  10141. end;
  10142. A_SUB:
  10143. begin
  10144. if (taicpu(next).opsize = S_B) or
  10145. { LEA doesn't support 8-bit operands }
  10146. (taicpu(next).oper[1]^.typ <> top_reg) or
  10147. { Must write to a register }
  10148. (taicpu(next).oper[0]^.typ <> top_const) or
  10149. (taicpu(next).oper[0]^.val = $80000000) then
  10150. { Can't subtract a register with LEA - also
  10151. check that the value isn't -2^31, as this
  10152. can't be negated }
  10153. Exit;
  10154. PotentialModified := True;
  10155. end;
  10156. A_SAL,
  10157. A_SHL:
  10158. begin
  10159. if (taicpu(next).opsize = S_B) or
  10160. { LEA doesn't support 8-bit operands }
  10161. (taicpu(next).oper[1]^.typ <> top_reg) or
  10162. { Must write to a register }
  10163. (taicpu(next).oper[0]^.typ <> top_const) or
  10164. (taicpu(next).oper[0]^.val < 0) or
  10165. (taicpu(next).oper[0]^.val > 3) then
  10166. Exit;
  10167. PotentialModified := True;
  10168. end;
  10169. A_IMUL:
  10170. begin
  10171. if (taicpu(next).ops <> 3) or
  10172. (taicpu(next).oper[1]^.typ <> top_reg) or
  10173. { Must write to a register }
  10174. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10175. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10176. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10177. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10178. Exit
  10179. else
  10180. PotentialModified := True;
  10181. end;
  10182. else
  10183. { Don't know how to change this, so abort }
  10184. Exit;
  10185. end;
  10186. { Contains highest index (so instruction count - 1) }
  10187. Inc(InstrMax);
  10188. if InstrMax > High(InstrList) then
  10189. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10190. InstrList[InstrMax] := taicpu(next);
  10191. end;
  10192. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10193. end;
  10194. if not Assigned(next) or (next <> hp1) then
  10195. { It should be equal to hp1 }
  10196. InternalError(2021051702);
  10197. { Cycle through each instruction and check to see if we can
  10198. change them to versions that don't modify the flags }
  10199. if (InstrMax >= 0) then
  10200. begin
  10201. for Index := 0 to InstrMax do
  10202. case InstrList[Index].opcode of
  10203. A_ADD:
  10204. begin
  10205. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10206. InstrList[Index].opcode := A_LEA;
  10207. reference_reset(NewRef, 1, []);
  10208. NewRef.base := InstrList[Index].oper[1]^.reg;
  10209. if InstrList[Index].oper[0]^.typ = top_reg then
  10210. begin
  10211. NewRef.index := InstrList[Index].oper[0]^.reg;
  10212. NewRef.scalefactor := 1;
  10213. end
  10214. else
  10215. NewRef.offset := InstrList[Index].oper[0]^.val;
  10216. InstrList[Index].loadref(0, NewRef);
  10217. end;
  10218. A_SUB:
  10219. begin
  10220. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10221. InstrList[Index].opcode := A_LEA;
  10222. reference_reset(NewRef, 1, []);
  10223. NewRef.base := InstrList[Index].oper[1]^.reg;
  10224. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10225. InstrList[Index].loadref(0, NewRef);
  10226. end;
  10227. A_SHL,
  10228. A_SAL:
  10229. begin
  10230. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10231. InstrList[Index].opcode := A_LEA;
  10232. reference_reset(NewRef, 1, []);
  10233. NewRef.index := InstrList[Index].oper[1]^.reg;
  10234. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10235. InstrList[Index].loadref(0, NewRef);
  10236. end;
  10237. A_IMUL:
  10238. begin
  10239. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10240. InstrList[Index].opcode := A_LEA;
  10241. reference_reset(NewRef, 1, []);
  10242. NewRef.index := InstrList[Index].oper[1]^.reg;
  10243. case InstrList[Index].oper[0]^.val of
  10244. 2, 4, 8:
  10245. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10246. else {3, 5 and 9}
  10247. begin
  10248. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10249. NewRef.base := InstrList[Index].oper[1]^.reg;
  10250. end;
  10251. end;
  10252. InstrList[Index].loadref(0, NewRef);
  10253. end;
  10254. else
  10255. InternalError(2021051710);
  10256. end;
  10257. end;
  10258. { Mark the FLAGS register as used across this whole block }
  10259. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10260. end;
  10261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10262. JumpC := taicpu(hp2).condition;
  10263. Unconditional := False;
  10264. if conditions_equal(JumpC, C_E) then
  10265. SetC := inverse_cond(taicpu(p).condition)
  10266. else if conditions_equal(JumpC, C_NE) then
  10267. SetC := taicpu(p).condition
  10268. else
  10269. { We've got something weird here (and inefficent) }
  10270. begin
  10271. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10272. SetC := C_NONE;
  10273. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10274. if condition_in(C_AE, JumpC) then
  10275. Unconditional := True
  10276. else
  10277. { Not sure what to do with this jump - drop out }
  10278. Exit;
  10279. end;
  10280. RemoveInstruction(hp1);
  10281. if Unconditional then
  10282. MakeUnconditional(taicpu(hp2))
  10283. else
  10284. begin
  10285. if SetC = C_NONE then
  10286. InternalError(2018061402);
  10287. taicpu(hp2).SetCondition(SetC);
  10288. end;
  10289. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10290. TmpUsedRegs }
  10291. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10292. begin
  10293. RemoveCurrentp(p, hp2);
  10294. if taicpu(hp2).opcode = A_SETcc then
  10295. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10296. else
  10297. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10298. end
  10299. else
  10300. if taicpu(hp2).opcode = A_SETcc then
  10301. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10302. else
  10303. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10304. Result := True;
  10305. end
  10306. else if
  10307. { Make sure the instructions are adjacent }
  10308. (
  10309. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10310. GetNextInstruction(p, hp1)
  10311. ) and
  10312. MatchInstruction(hp1, A_MOV, [S_B]) and
  10313. { Writing to memory is allowed }
  10314. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10315. begin
  10316. {
  10317. Watch out for sequences such as:
  10318. set(c)b %regb
  10319. movb %regb,(ref)
  10320. movb $0,1(ref)
  10321. movb $0,2(ref)
  10322. movb $0,3(ref)
  10323. Much more efficient to turn it into:
  10324. movl $0,%regl
  10325. set(c)b %regb
  10326. movl %regl,(ref)
  10327. Or:
  10328. set(c)b %regb
  10329. movzbl %regb,%regl
  10330. movl %regl,(ref)
  10331. }
  10332. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10333. GetNextInstruction(hp1, hp2) and
  10334. MatchInstruction(hp2, A_MOV, [S_B]) and
  10335. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10336. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10337. begin
  10338. { Don't do anything else except set Result to True }
  10339. end
  10340. else
  10341. begin
  10342. if taicpu(p).oper[0]^.typ = top_reg then
  10343. begin
  10344. TransferUsedRegs(TmpUsedRegs);
  10345. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10346. end;
  10347. { If it's not a register, it's a memory address }
  10348. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10349. begin
  10350. { Even if the register is still in use, we can minimise the
  10351. pipeline stall by changing the MOV into another SETcc. }
  10352. taicpu(hp1).opcode := A_SETcc;
  10353. taicpu(hp1).condition := taicpu(p).condition;
  10354. if taicpu(hp1).oper[1]^.typ = top_ref then
  10355. begin
  10356. { Swapping the operand pointers like this is probably a
  10357. bit naughty, but it is far faster than using loadoper
  10358. to transfer the reference from oper[1] to oper[0] if
  10359. you take into account the extra procedure calls and
  10360. the memory allocation and deallocation required }
  10361. OperPtr := taicpu(hp1).oper[1];
  10362. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10363. taicpu(hp1).oper[0] := OperPtr;
  10364. end
  10365. else
  10366. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10367. taicpu(hp1).clearop(1);
  10368. taicpu(hp1).ops := 1;
  10369. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10370. end
  10371. else
  10372. begin
  10373. if taicpu(hp1).oper[1]^.typ = top_reg then
  10374. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10375. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10376. RemoveInstruction(hp1);
  10377. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10378. end
  10379. end;
  10380. Result := True;
  10381. end;
  10382. end;
  10383. end;
  10384. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10385. var
  10386. hp1: tai;
  10387. Count: Integer;
  10388. OrigLabel: TAsmLabel;
  10389. begin
  10390. result := False;
  10391. { Sometimes, the optimisations below can permit this }
  10392. RemoveDeadCodeAfterJump(p);
  10393. 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
  10394. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10395. begin
  10396. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10397. { Also a side-effect of optimisations }
  10398. if CollapseZeroDistJump(p, OrigLabel) then
  10399. begin
  10400. Result := True;
  10401. Exit;
  10402. end;
  10403. hp1 := GetLabelWithSym(OrigLabel);
  10404. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10405. begin
  10406. if taicpu(hp1).opcode = A_RET then
  10407. begin
  10408. {
  10409. change
  10410. jmp .L1
  10411. ...
  10412. .L1:
  10413. ret
  10414. into
  10415. ret
  10416. }
  10417. begin
  10418. ConvertJumpToRET(p, hp1);
  10419. result:=true;
  10420. end;
  10421. end
  10422. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10423. not (cs_opt_size in current_settings.optimizerswitches) and
  10424. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10425. begin
  10426. Result := True;
  10427. Exit;
  10428. end;
  10429. end;
  10430. end;
  10431. end;
  10432. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10433. begin
  10434. Result := assigned(p) and
  10435. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10436. (taicpu(p).oper[1]^.typ = top_reg) and
  10437. (
  10438. (taicpu(p).oper[0]^.typ = top_reg) or
  10439. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10440. it is not expected that this can cause a seg. violation }
  10441. (
  10442. (taicpu(p).oper[0]^.typ = top_ref) and
  10443. { TODO: Can we detect which references become constants at this
  10444. stage so we don't have to do a blanket ban? }
  10445. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10446. (
  10447. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10448. (
  10449. { If the reference also appears in the condition, then we know it's safe, otherwise
  10450. any kind of access violation would have occurred already }
  10451. Assigned(cond_p) and
  10452. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10453. (cond_p.typ = ait_instruction) and
  10454. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10455. { Just consider 2-operand comparison instructions for now to be safe }
  10456. (taicpu(cond_p).ops = 2) and
  10457. (
  10458. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10459. (
  10460. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10461. { Don't risk identical registers but different offsets, as we may have constructs
  10462. such as buffer streams with things like length fields that indicate whether
  10463. any more data follows. And there are probably some contrived examples where
  10464. writing to offsets behind the one being read also lead to access violations }
  10465. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10466. (
  10467. { Check that we're not modifying a register that appears in the reference }
  10468. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10469. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10470. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10471. )
  10472. )
  10473. )
  10474. )
  10475. )
  10476. )
  10477. );
  10478. end;
  10479. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10480. begin
  10481. { Update integer registers, ignoring deallocations }
  10482. repeat
  10483. while assigned(p) and
  10484. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10485. (p.typ = ait_label) or
  10486. ((p.typ = ait_marker) and
  10487. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10488. p := tai(p.next);
  10489. while assigned(p) and
  10490. (p.typ=ait_RegAlloc) Do
  10491. begin
  10492. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10493. begin
  10494. case tai_regalloc(p).ratype of
  10495. ra_alloc :
  10496. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10497. else
  10498. ;
  10499. end;
  10500. end;
  10501. p := tai(p.next);
  10502. end;
  10503. until not(assigned(p)) or
  10504. (not(p.typ in SkipInstr) and
  10505. not((p.typ = ait_label) and
  10506. labelCanBeSkipped(tai_label(p))));
  10507. end;
  10508. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10509. var
  10510. hp1,hp2: tai;
  10511. carryadd_opcode : TAsmOp;
  10512. symbol: TAsmSymbol;
  10513. increg, tmpreg: TRegister;
  10514. {$ifndef i8086}
  10515. { Code and variables specific to CMOV optimisations }
  10516. hp3,hp4,hp5,
  10517. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10518. l, c, w, x : Longint;
  10519. condition, second_condition : TAsmCond;
  10520. FoundMatchingJump, RegMatch: Boolean;
  10521. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10522. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10523. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10524. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10525. new register to store the constant }
  10526. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10527. var
  10528. RegSize: TSubRegister;
  10529. CurrentVal: TCGInt;
  10530. NewReg: TRegister;
  10531. X: ShortInt;
  10532. begin
  10533. Result := False;
  10534. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10535. Exit;
  10536. if StoredCount >= MAX_CMOV_REGISTERS then
  10537. { Arrays are full }
  10538. Exit;
  10539. { Remember that CMOV can't encode 8-bit registers }
  10540. case taicpu(p).opsize of
  10541. S_W:
  10542. RegSize := R_SUBW;
  10543. S_L:
  10544. RegSize := R_SUBD;
  10545. S_Q:
  10546. RegSize := R_SUBQ;
  10547. else
  10548. InternalError(2021100401);
  10549. end;
  10550. { See if the value has already been reserved for another CMOV instruction }
  10551. CurrentVal := taicpu(p).oper[0]^.val;
  10552. for X := 0 to StoredCount - 1 do
  10553. if ConstVals[X] = CurrentVal then
  10554. begin
  10555. ConstRegs[StoredCount] := ConstRegs[X];
  10556. ConstVals[StoredCount] := CurrentVal;
  10557. Result := True;
  10558. Inc(StoredCount);
  10559. { Don't increase CMOVCount this time, since we're re-using a register }
  10560. Exit;
  10561. end;
  10562. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10563. if NewReg = NR_NO then
  10564. { No free registers }
  10565. Exit;
  10566. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10567. up vying for the same register }
  10568. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10569. ConstRegs[StoredCount] := NewReg;
  10570. ConstVals[StoredCount] := CurrentVal;
  10571. Inc(StoredCount);
  10572. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10573. MOV required adds complexity and will cause diminishing returns
  10574. sooner than normal. This is more of an approximate weighting than
  10575. anything else. }
  10576. Inc(CMOVCount);
  10577. Result := True;
  10578. end;
  10579. {$endif i8086}
  10580. begin
  10581. result:=false;
  10582. if GetNextInstruction(p,hp1) then
  10583. begin
  10584. if (hp1.typ=ait_label) then
  10585. begin
  10586. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10587. Exit;
  10588. end
  10589. else if (hp1.typ<>ait_instruction) then
  10590. Exit;
  10591. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10592. if (
  10593. (
  10594. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10595. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10596. (Taicpu(hp1).oper[0]^.val=1)
  10597. ) or
  10598. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10599. ) and
  10600. GetNextInstruction(hp1,hp2) and
  10601. SkipAligns(hp2, hp2) and
  10602. (hp2.typ = ait_label) and
  10603. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10604. { jb @@1 cmc
  10605. inc/dec operand --> adc/sbb operand,0
  10606. @@1:
  10607. ... and ...
  10608. jnb @@1
  10609. inc/dec operand --> adc/sbb operand,0
  10610. @@1: }
  10611. begin
  10612. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10613. begin
  10614. case taicpu(hp1).opcode of
  10615. A_INC,
  10616. A_ADD:
  10617. carryadd_opcode:=A_ADC;
  10618. A_DEC,
  10619. A_SUB:
  10620. carryadd_opcode:=A_SBB;
  10621. else
  10622. InternalError(2021011001);
  10623. end;
  10624. Taicpu(p).clearop(0);
  10625. Taicpu(p).ops:=0;
  10626. Taicpu(p).is_jmp:=false;
  10627. Taicpu(p).opcode:=A_CMC;
  10628. Taicpu(p).condition:=C_NONE;
  10629. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10630. Taicpu(hp1).ops:=2;
  10631. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10632. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10633. else
  10634. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10635. Taicpu(hp1).loadconst(0,0);
  10636. Taicpu(hp1).opcode:=carryadd_opcode;
  10637. result:=true;
  10638. exit;
  10639. end
  10640. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10641. begin
  10642. case taicpu(hp1).opcode of
  10643. A_INC,
  10644. A_ADD:
  10645. carryadd_opcode:=A_ADC;
  10646. A_DEC,
  10647. A_SUB:
  10648. carryadd_opcode:=A_SBB;
  10649. else
  10650. InternalError(2021011002);
  10651. end;
  10652. Taicpu(hp1).ops:=2;
  10653. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10654. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10655. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10656. else
  10657. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10658. Taicpu(hp1).loadconst(0,0);
  10659. Taicpu(hp1).opcode:=carryadd_opcode;
  10660. RemoveCurrentP(p, hp1);
  10661. result:=true;
  10662. exit;
  10663. end
  10664. {
  10665. jcc @@1 setcc tmpreg
  10666. inc/dec/add/sub operand -> (movzx tmpreg)
  10667. @@1: add/sub tmpreg,operand
  10668. While this increases code size slightly, it makes the code much faster if the
  10669. jump is unpredictable
  10670. }
  10671. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10672. begin
  10673. { search for an available register which is volatile }
  10674. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10675. if increg <> NR_NO then
  10676. begin
  10677. { We don't need to check if tmpreg is in hp1 or not, because
  10678. it will be marked as in use at p (if not, this is
  10679. indictive of a compiler bug). }
  10680. TAsmLabel(symbol).decrefs;
  10681. Taicpu(p).clearop(0);
  10682. Taicpu(p).ops:=1;
  10683. Taicpu(p).is_jmp:=false;
  10684. Taicpu(p).opcode:=A_SETcc;
  10685. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10686. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10687. Taicpu(p).loadreg(0,increg);
  10688. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10689. begin
  10690. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10691. R_SUBW:
  10692. begin
  10693. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10694. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10695. end;
  10696. R_SUBD:
  10697. begin
  10698. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10699. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10700. end;
  10701. {$ifdef x86_64}
  10702. R_SUBQ:
  10703. begin
  10704. { MOVZX doesn't have a 64-bit variant, because
  10705. the 32-bit version implicitly zeroes the
  10706. upper 32-bits of the destination register }
  10707. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10708. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10709. setsubreg(tmpreg, R_SUBQ);
  10710. end;
  10711. {$endif x86_64}
  10712. else
  10713. Internalerror(2020030601);
  10714. end;
  10715. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10716. asml.InsertAfter(hp2,p);
  10717. end
  10718. else
  10719. tmpreg := increg;
  10720. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10721. begin
  10722. Taicpu(hp1).ops:=2;
  10723. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10724. end;
  10725. Taicpu(hp1).loadreg(0,tmpreg);
  10726. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10727. Result := True;
  10728. { p is no longer a Jcc instruction, so exit }
  10729. Exit;
  10730. end;
  10731. end;
  10732. end;
  10733. { Detect the following:
  10734. jmp<cond> @Lbl1
  10735. jmp @Lbl2
  10736. ...
  10737. @Lbl1:
  10738. ret
  10739. Change to:
  10740. jmp<inv_cond> @Lbl2
  10741. ret
  10742. }
  10743. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10744. begin
  10745. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10746. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10747. MatchInstruction(hp2,A_RET,[S_NO]) then
  10748. begin
  10749. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10750. { Change label address to that of the unconditional jump }
  10751. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10752. TAsmLabel(symbol).DecRefs;
  10753. taicpu(hp1).opcode := A_RET;
  10754. taicpu(hp1).is_jmp := false;
  10755. taicpu(hp1).ops := taicpu(hp2).ops;
  10756. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10757. case taicpu(hp2).ops of
  10758. 0:
  10759. taicpu(hp1).clearop(0);
  10760. 1:
  10761. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10762. else
  10763. internalerror(2016041302);
  10764. end;
  10765. end;
  10766. {$ifndef i8086}
  10767. end
  10768. {
  10769. convert
  10770. j<c> .L1
  10771. mov 1,reg
  10772. jmp .L2
  10773. .L1
  10774. mov 0,reg
  10775. .L2
  10776. into
  10777. mov 0,reg
  10778. set<not(c)> reg
  10779. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10780. would destroy the flag contents
  10781. }
  10782. else if MatchInstruction(hp1,A_MOV,[]) and
  10783. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10784. {$ifdef i386}
  10785. (
  10786. { Under i386, ESI, EDI, EBP and ESP
  10787. don't have an 8-bit representation }
  10788. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10789. ) and
  10790. {$endif i386}
  10791. (taicpu(hp1).oper[0]^.val=1) and
  10792. GetNextInstruction(hp1,hp2) and
  10793. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10794. GetNextInstruction(hp2,hp3) and
  10795. { skip align }
  10796. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10797. (hp3.typ=ait_label) and
  10798. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10799. (tai_label(hp3).labsym.getrefs=1) and
  10800. GetNextInstruction(hp3,hp4) and
  10801. MatchInstruction(hp4,A_MOV,[]) and
  10802. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10803. (taicpu(hp4).oper[0]^.val=0) and
  10804. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10805. GetNextInstruction(hp4,hp5) and
  10806. (hp5.typ=ait_label) and
  10807. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10808. (tai_label(hp5).labsym.getrefs=1) then
  10809. begin
  10810. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10811. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10812. { remove last label }
  10813. RemoveInstruction(hp5);
  10814. { remove second label }
  10815. RemoveInstruction(hp3);
  10816. { if align is present remove it }
  10817. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10818. RemoveInstruction(hp3);
  10819. { remove jmp }
  10820. RemoveInstruction(hp2);
  10821. if taicpu(hp1).opsize=S_B then
  10822. RemoveInstruction(hp1)
  10823. else
  10824. taicpu(hp1).loadconst(0,0);
  10825. taicpu(hp4).opcode:=A_SETcc;
  10826. taicpu(hp4).opsize:=S_B;
  10827. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10828. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10829. taicpu(hp4).opercnt:=1;
  10830. taicpu(hp4).ops:=1;
  10831. taicpu(hp4).freeop(1);
  10832. RemoveCurrentP(p);
  10833. Result:=true;
  10834. exit;
  10835. end
  10836. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10837. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10838. begin
  10839. { check for
  10840. jCC xxx
  10841. <several movs>
  10842. xxx:
  10843. Also spot:
  10844. Jcc xxx
  10845. <several movs>
  10846. jmp xxx
  10847. Change to:
  10848. <several cmovs with inverted condition>
  10849. jmp xxx (only for the 2nd case)
  10850. }
  10851. hp2 := p;
  10852. hp_lblxxx := hp1;
  10853. hp_flagalloc := nil;
  10854. hp_stop := nil;
  10855. FoundMatchingJump := False;
  10856. { Remember the first instruction in the first block of MOVs }
  10857. hpmov1 := hp1;
  10858. TransferUsedRegs(TmpUsedRegs);
  10859. while assigned(hp_lblxxx) and
  10860. { stop on labels }
  10861. (hp_lblxxx.typ <> ait_label) do
  10862. begin
  10863. { Keep track of all integer registers that are used }
  10864. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10865. if hp_lblxxx.typ = ait_instruction then
  10866. begin
  10867. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10868. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10869. begin
  10870. hp_stop := hp_lblxxx;
  10871. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10872. begin
  10873. { We found Jcc xxx; <several movs>; Jmp xxx }
  10874. FoundMatchingJump := True;
  10875. Break;
  10876. end;
  10877. { If it's not the jump we're looking for, it's
  10878. possibly the "if..else" variant }
  10879. end
  10880. { Check to see if we have a valid MOV instruction instead }
  10881. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10882. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10883. Break
  10884. else
  10885. { This will be a valid MOV }
  10886. hp_stop := hp_lblxxx;
  10887. end;
  10888. hp2 := hp_lblxxx;
  10889. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10890. end;
  10891. { Just make sure the last MOV is included if there's no jump }
  10892. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10893. hp_stop := hp_lblxxx;
  10894. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10895. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10896. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10897. jmp yyy; xxx:; movs; yyy:" variation }
  10898. if assigned(hp_lblxxx) and
  10899. (
  10900. { If we found JMP xxx, we don't actually need a label
  10901. (hp_lblxxx is the JMP instruction instead) }
  10902. FoundMatchingJump or
  10903. { Make sure we actually have the right label }
  10904. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10905. ) then
  10906. begin
  10907. { Use TmpUsedRegs to track registers that we reserve }
  10908. { When allocating temporary registers, try to look one
  10909. instruction back, as defining them before a CMP or TEST
  10910. instruction will be faster, and also avoid picking a
  10911. register that was only just deallocated }
  10912. if GetLastInstruction(p, hp_prev) and
  10913. MatchInstruction(hp_prev, [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
  10914. begin
  10915. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10916. for l := 0 to 1 do
  10917. with taicpu(hp_prev).oper[l]^ do
  10918. case typ of
  10919. top_reg:
  10920. if getregtype(reg) = R_INTREGISTER then
  10921. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10922. top_ref:
  10923. begin
  10924. if
  10925. {$ifdef x86_64}
  10926. (ref^.base <> NR_RIP) and
  10927. {$endif x86_64}
  10928. (ref^.base <> NR_NO) then
  10929. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10930. if (ref^.index <> NR_NO) then
  10931. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10932. end
  10933. else
  10934. ;
  10935. end;
  10936. { When inserting instructions before hp_prev, try to insert
  10937. them before the allocation of the FLAGS register }
  10938. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10939. { If not found, set it equal to hp_prev so it's something sensible }
  10940. hp_flagalloc := hp_prev;
  10941. hp_prev2 := nil;
  10942. { When dealing with a comparison against zero, take
  10943. note of the instruction before it to see if we can
  10944. move instructions further back in order to benefit
  10945. PostPeepholeOptTestOr.
  10946. }
  10947. if (
  10948. (
  10949. (taicpu(hp_prev).opcode = A_CMP) and
  10950. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10951. ) or
  10952. (
  10953. (taicpu(hp_prev).opcode = A_TEST) and
  10954. (
  10955. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10956. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10957. )
  10958. )
  10959. ) and
  10960. GetLastInstruction(hp_prev, hp_prev2) then
  10961. begin
  10962. if (hp_prev2.typ = ait_instruction) and
  10963. { These instructions set the zero flag if the result is zero }
  10964. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10965. begin
  10966. { Also mark all the registers in this previous instruction
  10967. as 'in use', even if they've just been deallocated }
  10968. for l := 0 to 1 do
  10969. with taicpu(hp_prev2).oper[l]^ do
  10970. case typ of
  10971. top_reg:
  10972. if getregtype(reg) = R_INTREGISTER then
  10973. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10974. top_ref:
  10975. begin
  10976. if
  10977. {$ifdef x86_64}
  10978. (ref^.base <> NR_RIP) and
  10979. {$endif x86_64}
  10980. (ref^.base <> NR_NO) then
  10981. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10982. if (ref^.index <> NR_NO) then
  10983. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10984. end
  10985. else
  10986. ;
  10987. end;
  10988. end
  10989. else
  10990. { Unsuitable instruction }
  10991. hp_prev2 := nil;
  10992. end;
  10993. end
  10994. else
  10995. begin
  10996. hp_prev := p;
  10997. { When inserting instructions before hp_prev, try to insert
  10998. them before the allocation of the FLAGS register }
  10999. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11000. { If not found, set it equal to p so it's something sensible }
  11001. hp_flagalloc := p;
  11002. hp_prev2 := nil;
  11003. end;
  11004. l := 0;
  11005. c := 0;
  11006. { Initialise RegWrites, ConstRegs and ConstVals }
  11007. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11008. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11009. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11010. while assigned(hp1) and
  11011. { Stop on the label we found }
  11012. (hp1 <> hp_lblxxx) do
  11013. begin
  11014. case hp1.typ of
  11015. ait_instruction:
  11016. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11017. begin
  11018. if CanBeCMOV(hp1, hp_prev) then
  11019. Inc(l)
  11020. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11021. { CMOV with constants grows the code size }
  11022. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11023. begin
  11024. { Register was reserved by TryCMOVConst and
  11025. stored on ConstRegs[c] }
  11026. end
  11027. else
  11028. Break;
  11029. end
  11030. else
  11031. Break;
  11032. else
  11033. ;
  11034. end;
  11035. GetNextInstruction(hp1,hp1);
  11036. end;
  11037. if (hp1 = hp_lblxxx) then
  11038. begin
  11039. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11040. begin
  11041. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11042. TmpUsedRegs[R_INTREGISTER].Clear;
  11043. x := 0;
  11044. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11045. condition := inverse_cond(taicpu(p).condition);
  11046. UpdateUsedRegs(tai(p.next));
  11047. hp1 := hpmov1;
  11048. repeat
  11049. if not Assigned(hp1) then
  11050. InternalError(2018062900);
  11051. if (hp1.typ = ait_instruction) then
  11052. begin
  11053. { Extra safeguard }
  11054. if (taicpu(hp1).opcode <> A_MOV) then
  11055. InternalError(2018062901);
  11056. if taicpu(hp1).oper[0]^.typ = top_const then
  11057. begin
  11058. if x >= MAX_CMOV_REGISTERS then
  11059. InternalError(2021100410);
  11060. { If it's in TmpUsedRegs, then this register
  11061. is being used more than once and hence has
  11062. already had its value defined (it gets
  11063. added to UsedRegs through AllocRegBetween
  11064. below) }
  11065. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11066. begin
  11067. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11068. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11069. asml.InsertBefore(hp_new, hp_flagalloc);
  11070. if Assigned(hp_prev2) then
  11071. TrySwapMovOp(hp_prev2, hp_new);
  11072. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11073. end
  11074. else
  11075. { We just need an instruction between hp_prev and hp1
  11076. where we know the register is marked as in use }
  11077. hp_new := hpmov1;
  11078. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11079. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11080. Inc(x);
  11081. end;
  11082. taicpu(hp1).opcode := A_CMOVcc;
  11083. taicpu(hp1).condition := condition;
  11084. end;
  11085. UpdateUsedRegs(tai(hp1.next));
  11086. GetNextInstruction(hp1, hp1);
  11087. until (hp1 = hp_lblxxx);
  11088. hp2 := hp_lblxxx;
  11089. repeat
  11090. if not Assigned(hp2) then
  11091. InternalError(2018062910);
  11092. case hp2.typ of
  11093. ait_label:
  11094. { What we expected - break out of the loop (it won't be a dead label at the top of
  11095. a cluster because that was optimised at an earlier stage) }
  11096. Break;
  11097. ait_align:
  11098. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11099. begin
  11100. hp2 := tai(hp2.Next);
  11101. Continue;
  11102. end;
  11103. ait_instruction:
  11104. begin
  11105. if taicpu(hp2).opcode<>A_JMP then
  11106. InternalError(2018062912);
  11107. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11108. Break;
  11109. end
  11110. else
  11111. begin
  11112. { Might be a comment or temporary allocation entry }
  11113. if not (hp2.typ in SkipInstr) then
  11114. InternalError(2018062911);
  11115. hp2 := tai(hp2.Next);
  11116. Continue;
  11117. end;
  11118. end;
  11119. until False;
  11120. { Now we can safely decrement the reference count }
  11121. tasmlabel(symbol).decrefs;
  11122. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11123. { Remove the original jump }
  11124. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11125. if hp2.typ=ait_instruction then
  11126. begin
  11127. p := hp2;
  11128. Result := True;
  11129. end
  11130. else
  11131. begin
  11132. UpdateUsedRegs(tai(hp2.next));
  11133. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11134. { Remove the label if this is its final reference }
  11135. if (tasmlabel(symbol).getrefs=0) then
  11136. begin
  11137. { Make sure the aligns get stripped too }
  11138. hp1 := tai(hp_lblxxx.Previous);
  11139. while Assigned(hp1) and (hp1.typ = ait_align) do
  11140. begin
  11141. hp_lblxxx := hp1;
  11142. hp1 := tai(hp_lblxxx.Previous);
  11143. end;
  11144. StripLabelFast(hp_lblxxx);
  11145. end;
  11146. end;
  11147. Exit;
  11148. end;
  11149. end
  11150. else if assigned(hp_lblxxx) and
  11151. { check further for
  11152. jCC xxx
  11153. <several movs 1>
  11154. jmp yyy
  11155. xxx:
  11156. <several movs 2>
  11157. yyy:
  11158. }
  11159. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11160. { hp1 should be pointing to jmp yyy }
  11161. MatchInstruction(hp1, A_JMP, []) and
  11162. { real label and jump, no further references to the
  11163. label are allowed }
  11164. (TAsmLabel(symbol).getrefs=1) and
  11165. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11166. begin
  11167. hp_jump := hp1;
  11168. { Don't set c to zero }
  11169. l := 0;
  11170. w := 0;
  11171. GetNextInstruction(hp_lblxxx, hpmov2);
  11172. hp2 := hp_lblxxx;
  11173. hp_lblyyy := hpmov2;
  11174. while assigned(hp_lblyyy) and
  11175. { stop on labels }
  11176. (hp_lblyyy.typ <> ait_label) do
  11177. begin
  11178. { Keep track of all integer registers that are used }
  11179. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11180. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11181. Break;
  11182. hp2 := hp_lblyyy;
  11183. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11184. end;
  11185. { Analyse the second batch of MOVs to see if the setup is valid }
  11186. hp1 := hpmov2;
  11187. while assigned(hp1) and
  11188. (hp1 <> hp_lblyyy) do
  11189. begin
  11190. case hp1.typ of
  11191. ait_instruction:
  11192. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11193. begin
  11194. if CanBeCMOV(hp1, hp_prev) then
  11195. Inc(l)
  11196. else if not (cs_opt_size in current_settings.optimizerswitches)
  11197. { CMOV with constants grows the code size }
  11198. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11199. begin
  11200. { Register was reserved by TryCMOVConst and
  11201. stored on ConstRegs[c] }
  11202. end
  11203. else
  11204. Break;
  11205. end
  11206. else
  11207. Break;
  11208. else
  11209. ;
  11210. end;
  11211. GetNextInstruction(hp1,hp1);
  11212. end;
  11213. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11214. TmpUsedRegs[R_INTREGISTER].Clear;
  11215. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11216. (hp1 = hp_lblyyy) and
  11217. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11218. begin
  11219. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11220. second_condition := taicpu(p).condition;
  11221. condition := inverse_cond(taicpu(p).condition);
  11222. UpdateUsedRegs(tai(p.next));
  11223. { Scan through the first set of MOVs to update UsedRegs,
  11224. but don't process them yet }
  11225. hp1 := hpmov1;
  11226. repeat
  11227. if not Assigned(hp1) then
  11228. InternalError(2018062901);
  11229. UpdateUsedRegs(tai(hp1.next));
  11230. GetNextInstruction(hp1, hp1);
  11231. until (hp1 = hp_lblxxx);
  11232. UpdateUsedRegs(tai(hp_lblxxx.next));
  11233. { Process the second set of MOVs first,
  11234. because if a destination register is
  11235. shared between the first and second MOV
  11236. sets, it is more efficient to turn the
  11237. first one into a MOV instruction and place
  11238. it before the CMP if possible, but we
  11239. won't know which registers are shared
  11240. until we've processed at least one list,
  11241. so we might as well make it the second
  11242. one since that won't be modified again. }
  11243. hp1 := hpmov2;
  11244. repeat
  11245. if not Assigned(hp1) then
  11246. InternalError(2018062902);
  11247. if (hp1.typ = ait_instruction) then
  11248. begin
  11249. { Extra safeguard }
  11250. if (taicpu(hp1).opcode <> A_MOV) then
  11251. InternalError(2018062903);
  11252. if taicpu(hp1).oper[0]^.typ = top_const then
  11253. begin
  11254. RegMatch := False;
  11255. for x := 0 to c - 1 do
  11256. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11257. begin
  11258. RegMatch := True;
  11259. { If it's in TmpUsedRegs, then this register
  11260. is being used more than once and hence has
  11261. already had its value defined (it gets
  11262. added to UsedRegs through AllocRegBetween
  11263. below) }
  11264. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11265. begin
  11266. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11267. asml.InsertBefore(hp_new, hp_flagalloc);
  11268. if Assigned(hp_prev2) then
  11269. TrySwapMovOp(hp_prev2, hp_new);
  11270. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11271. end
  11272. else
  11273. { We just need an instruction between hp_prev and hp1
  11274. where we know the register is marked as in use }
  11275. hp_new := hpmov2;
  11276. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11277. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11278. Break;
  11279. end;
  11280. if not RegMatch then
  11281. InternalError(2021100411);
  11282. end;
  11283. taicpu(hp1).opcode := A_CMOVcc;
  11284. taicpu(hp1).condition := second_condition;
  11285. { Store these writes to search for
  11286. duplicates later on }
  11287. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11288. Inc(w);
  11289. end;
  11290. UpdateUsedRegs(tai(hp1.next));
  11291. GetNextInstruction(hp1, hp1);
  11292. until (hp1 = hp_lblyyy);
  11293. { Now do the first set of MOVs }
  11294. hp1 := hpmov1;
  11295. repeat
  11296. if not Assigned(hp1) then
  11297. InternalError(2018062904);
  11298. if (hp1.typ = ait_instruction) then
  11299. begin
  11300. RegMatch := False;
  11301. { Extra safeguard }
  11302. if (taicpu(hp1).opcode <> A_MOV) then
  11303. InternalError(2018062905);
  11304. { Search through the RegWrites list to see
  11305. if there are any opposing CMOV pairs that
  11306. write to the same register }
  11307. for x := 0 to w - 1 do
  11308. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11309. begin
  11310. { We have a match. Keep this as a MOV }
  11311. { Move ahead in preparation }
  11312. GetNextInstruction(hp1, hp1);
  11313. RegMatch := True;
  11314. Break;
  11315. end;
  11316. if RegMatch then
  11317. Continue;
  11318. if taicpu(hp1).oper[0]^.typ = top_const then
  11319. begin
  11320. RegMatch := False;
  11321. for x := 0 to c - 1 do
  11322. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11323. begin
  11324. RegMatch := True;
  11325. { If it's in TmpUsedRegs, then this register
  11326. is being used more than once and hence has
  11327. already had its value defined (it gets
  11328. added to UsedRegs through AllocRegBetween
  11329. below) }
  11330. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11331. begin
  11332. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11333. asml.InsertBefore(hp_new, hp_flagalloc);
  11334. if Assigned(hp_prev2) then
  11335. TrySwapMovOp(hp_prev2, hp_new);
  11336. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11337. end
  11338. else
  11339. { We just need an instruction between hp_prev and hp1
  11340. where we know the register is marked as in use }
  11341. hp_new := hpmov1;
  11342. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11343. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11344. Break;
  11345. end;
  11346. if not RegMatch then
  11347. InternalError(2021100412);
  11348. end;
  11349. taicpu(hp1).opcode := A_CMOVcc;
  11350. taicpu(hp1).condition := condition;
  11351. end;
  11352. GetNextInstruction(hp1, hp1);
  11353. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11354. UpdateUsedRegs(tai(hp_jump.next));
  11355. UpdateUsedRegs(tai(hp_lblyyy.next));
  11356. { Get first instruction after label }
  11357. hp1 := p;
  11358. GetNextInstruction(hp_lblyyy, p);
  11359. { Don't dereference yet, as doing so will cause
  11360. GetNextInstruction to skip the label and
  11361. optional align marker. [Kit] }
  11362. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11363. { remove Jcc }
  11364. RemoveInstruction(hp1);
  11365. { Now we can safely decrement it }
  11366. tasmlabel(symbol).decrefs;
  11367. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11368. { Make sure the aligns get stripped too }
  11369. hp1 := tai(hp_lblxxx.Previous);
  11370. while Assigned(hp1) and (hp1.typ = ait_align) do
  11371. begin
  11372. hp_lblxxx := hp1;
  11373. hp1 := tai(hp_lblxxx.Previous);
  11374. end;
  11375. StripLabelFast(hp_lblxxx);
  11376. { remove jmp }
  11377. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11378. RemoveInstruction(hp_jump);
  11379. { As before, now we can safely decrement it }
  11380. TAsmLabel(symbol).decrefs;
  11381. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11382. if TAsmLabel(symbol).getrefs = 0 then
  11383. begin
  11384. { Make sure the aligns get stripped too }
  11385. hp1 := tai(hp_lblyyy.Previous);
  11386. while Assigned(hp1) and (hp1.typ = ait_align) do
  11387. begin
  11388. hp_lblyyy := hp1;
  11389. hp1 := tai(hp_lblyyy.Previous);
  11390. end;
  11391. StripLabelFast(hp_lblyyy);
  11392. end;
  11393. if Assigned(p) then
  11394. result := True;
  11395. exit;
  11396. end;
  11397. end;
  11398. end;
  11399. {$endif i8086}
  11400. end;
  11401. end;
  11402. end;
  11403. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11404. var
  11405. hp1,hp2,hp3: tai;
  11406. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11407. NewSize: TOpSize;
  11408. NewRegSize: TSubRegister;
  11409. Limit: TCgInt;
  11410. SwapOper: POper;
  11411. begin
  11412. result:=false;
  11413. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11414. GetNextInstruction(p,hp1) and
  11415. (hp1.typ = ait_instruction);
  11416. if reg_and_hp1_is_instr and
  11417. (
  11418. (taicpu(hp1).opcode <> A_LEA) or
  11419. { If the LEA instruction can be converted into an arithmetic instruction,
  11420. it may be possible to then fold it. }
  11421. (
  11422. { If the flags register is in use, don't change the instruction
  11423. to an ADD otherwise this will scramble the flags. [Kit] }
  11424. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11425. ConvertLEA(taicpu(hp1))
  11426. )
  11427. ) and
  11428. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11429. GetNextInstruction(hp1,hp2) and
  11430. MatchInstruction(hp2,A_MOV,[]) and
  11431. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11432. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11433. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11434. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11435. {$ifdef i386}
  11436. { not all registers have byte size sub registers on i386 }
  11437. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11438. {$endif i386}
  11439. (((taicpu(hp1).ops=2) and
  11440. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11441. ((taicpu(hp1).ops=1) and
  11442. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11443. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11444. begin
  11445. { change movsX/movzX reg/ref, reg2
  11446. add/sub/or/... reg3/$const, reg2
  11447. mov reg2 reg/ref
  11448. to add/sub/or/... reg3/$const, reg/ref }
  11449. { by example:
  11450. movswl %si,%eax movswl %si,%eax p
  11451. decl %eax addl %edx,%eax hp1
  11452. movw %ax,%si movw %ax,%si hp2
  11453. ->
  11454. movswl %si,%eax movswl %si,%eax p
  11455. decw %eax addw %edx,%eax hp1
  11456. movw %ax,%si movw %ax,%si hp2
  11457. }
  11458. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11459. {
  11460. ->
  11461. movswl %si,%eax movswl %si,%eax p
  11462. decw %si addw %dx,%si hp1
  11463. movw %ax,%si movw %ax,%si hp2
  11464. }
  11465. case taicpu(hp1).ops of
  11466. 1:
  11467. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11468. 2:
  11469. begin
  11470. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11471. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11472. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11473. end;
  11474. else
  11475. internalerror(2008042702);
  11476. end;
  11477. {
  11478. ->
  11479. decw %si addw %dx,%si p
  11480. }
  11481. DebugMsg(SPeepholeOptimization + 'var3',p);
  11482. RemoveCurrentP(p, hp1);
  11483. RemoveInstruction(hp2);
  11484. Result := True;
  11485. Exit;
  11486. end;
  11487. if reg_and_hp1_is_instr and
  11488. (taicpu(hp1).opcode = A_MOV) and
  11489. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11490. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11491. {$ifdef x86_64}
  11492. { check for implicit extension to 64 bit }
  11493. or
  11494. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11495. (taicpu(hp1).opsize=S_Q) and
  11496. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11497. )
  11498. {$endif x86_64}
  11499. )
  11500. then
  11501. begin
  11502. { change
  11503. movx %reg1,%reg2
  11504. mov %reg2,%reg3
  11505. dealloc %reg2
  11506. into
  11507. movx %reg,%reg3
  11508. }
  11509. TransferUsedRegs(TmpUsedRegs);
  11510. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11511. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11512. begin
  11513. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11514. {$ifdef x86_64}
  11515. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11516. (taicpu(hp1).opsize=S_Q) then
  11517. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11518. else
  11519. {$endif x86_64}
  11520. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11521. RemoveInstruction(hp1);
  11522. Result := True;
  11523. Exit;
  11524. end;
  11525. end;
  11526. if reg_and_hp1_is_instr and
  11527. ((taicpu(hp1).opcode=A_MOV) or
  11528. (taicpu(hp1).opcode=A_ADD) or
  11529. (taicpu(hp1).opcode=A_SUB) or
  11530. (taicpu(hp1).opcode=A_CMP) or
  11531. (taicpu(hp1).opcode=A_OR) or
  11532. (taicpu(hp1).opcode=A_XOR) or
  11533. (taicpu(hp1).opcode=A_AND)
  11534. ) and
  11535. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11536. begin
  11537. AndTest := (taicpu(hp1).opcode=A_AND) and
  11538. GetNextInstruction(hp1, hp2) and
  11539. (hp2.typ = ait_instruction) and
  11540. (
  11541. (
  11542. (taicpu(hp2).opcode=A_TEST) and
  11543. (
  11544. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11545. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11546. (
  11547. { If the AND and TEST instructions share a constant, this is also valid }
  11548. (taicpu(hp1).oper[0]^.typ = top_const) and
  11549. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11550. )
  11551. ) and
  11552. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11553. ) or
  11554. (
  11555. (taicpu(hp2).opcode=A_CMP) and
  11556. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11557. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11558. )
  11559. );
  11560. { change
  11561. movx (oper),%reg2
  11562. and $x,%reg2
  11563. test %reg2,%reg2
  11564. dealloc %reg2
  11565. into
  11566. op %reg1,%reg3
  11567. if the second op accesses only the bits stored in reg1
  11568. }
  11569. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11570. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11571. (taicpu(hp1).oper[0]^.typ = top_const) and
  11572. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11573. AndTest then
  11574. begin
  11575. { Check if the AND constant is in range }
  11576. case taicpu(p).opsize of
  11577. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11578. begin
  11579. NewSize := S_B;
  11580. Limit := $FF;
  11581. end;
  11582. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11583. begin
  11584. NewSize := S_W;
  11585. Limit := $FFFF;
  11586. end;
  11587. {$ifdef x86_64}
  11588. S_LQ:
  11589. begin
  11590. NewSize := S_L;
  11591. Limit := $FFFFFFFF;
  11592. end;
  11593. {$endif x86_64}
  11594. else
  11595. InternalError(2021120303);
  11596. end;
  11597. if (
  11598. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11599. { Check for negative operands }
  11600. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11601. ) and
  11602. GetNextInstruction(hp2,hp3) and
  11603. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11604. (taicpu(hp3).condition in [C_E,C_NE]) then
  11605. begin
  11606. TransferUsedRegs(TmpUsedRegs);
  11607. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11608. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11609. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11610. begin
  11611. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11612. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11613. taicpu(hp1).opcode := A_TEST;
  11614. taicpu(hp1).opsize := NewSize;
  11615. RemoveInstruction(hp2);
  11616. RemoveCurrentP(p, hp1);
  11617. Result:=true;
  11618. exit;
  11619. end;
  11620. end;
  11621. end;
  11622. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11623. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11624. (taicpu(hp1).opsize=S_B)) or
  11625. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11626. (taicpu(hp1).opsize=S_W))
  11627. {$ifdef x86_64}
  11628. or ((taicpu(p).opsize=S_LQ) and
  11629. (taicpu(hp1).opsize=S_L))
  11630. {$endif x86_64}
  11631. ) and
  11632. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11633. begin
  11634. { change
  11635. movx %reg1,%reg2
  11636. op %reg2,%reg3
  11637. dealloc %reg2
  11638. into
  11639. op %reg1,%reg3
  11640. if the second op accesses only the bits stored in reg1
  11641. }
  11642. TransferUsedRegs(TmpUsedRegs);
  11643. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11644. if AndTest then
  11645. begin
  11646. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11647. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11648. end
  11649. else
  11650. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11651. if not RegUsed then
  11652. begin
  11653. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11654. if taicpu(p).oper[0]^.typ=top_reg then
  11655. begin
  11656. case taicpu(hp1).opsize of
  11657. S_B:
  11658. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11659. S_W:
  11660. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11661. S_L:
  11662. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11663. else
  11664. Internalerror(2020102301);
  11665. end;
  11666. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11667. end
  11668. else
  11669. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11670. RemoveCurrentP(p);
  11671. if AndTest then
  11672. RemoveInstruction(hp2);
  11673. result:=true;
  11674. exit;
  11675. end;
  11676. end
  11677. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11678. (
  11679. { Bitwise operations only }
  11680. (taicpu(hp1).opcode=A_AND) or
  11681. (taicpu(hp1).opcode=A_TEST) or
  11682. (
  11683. (taicpu(hp1).oper[0]^.typ = top_const) and
  11684. (
  11685. (taicpu(hp1).opcode=A_OR) or
  11686. (taicpu(hp1).opcode=A_XOR)
  11687. )
  11688. )
  11689. ) and
  11690. (
  11691. (taicpu(hp1).oper[0]^.typ = top_const) or
  11692. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11693. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11694. ) then
  11695. begin
  11696. { change
  11697. movx %reg2,%reg2
  11698. op const,%reg2
  11699. into
  11700. op const,%reg2 (smaller version)
  11701. movx %reg2,%reg2
  11702. also change
  11703. movx %reg1,%reg2
  11704. and/test (oper),%reg2
  11705. dealloc %reg2
  11706. into
  11707. and/test (oper),%reg1
  11708. }
  11709. case taicpu(p).opsize of
  11710. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11711. begin
  11712. NewSize := S_B;
  11713. NewRegSize := R_SUBL;
  11714. Limit := $FF;
  11715. end;
  11716. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11717. begin
  11718. NewSize := S_W;
  11719. NewRegSize := R_SUBW;
  11720. Limit := $FFFF;
  11721. end;
  11722. {$ifdef x86_64}
  11723. S_LQ:
  11724. begin
  11725. NewSize := S_L;
  11726. NewRegSize := R_SUBD;
  11727. Limit := $FFFFFFFF;
  11728. end;
  11729. {$endif x86_64}
  11730. else
  11731. Internalerror(2021120302);
  11732. end;
  11733. TransferUsedRegs(TmpUsedRegs);
  11734. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11735. if AndTest then
  11736. begin
  11737. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11738. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11739. end
  11740. else
  11741. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11742. if
  11743. (
  11744. (taicpu(p).opcode = A_MOVZX) and
  11745. (
  11746. (taicpu(hp1).opcode=A_AND) or
  11747. (taicpu(hp1).opcode=A_TEST)
  11748. ) and
  11749. not (
  11750. { If both are references, then the final instruction will have
  11751. both operands as references, which is not allowed }
  11752. (taicpu(p).oper[0]^.typ = top_ref) and
  11753. (taicpu(hp1).oper[0]^.typ = top_ref)
  11754. ) and
  11755. not RegUsed
  11756. ) or
  11757. (
  11758. (
  11759. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11760. not RegUsed
  11761. ) and
  11762. (taicpu(p).oper[0]^.typ = top_reg) and
  11763. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11764. (taicpu(hp1).oper[0]^.typ = top_const) and
  11765. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11766. ) then
  11767. begin
  11768. {$if defined(i386) or defined(i8086)}
  11769. { If the target size is 8-bit, make sure we can actually encode it }
  11770. 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
  11771. Exit;
  11772. {$endif i386 or i8086}
  11773. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11774. taicpu(hp1).opsize := NewSize;
  11775. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11776. if AndTest then
  11777. begin
  11778. RemoveInstruction(hp2);
  11779. if not RegUsed then
  11780. begin
  11781. taicpu(hp1).opcode := A_TEST;
  11782. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11783. begin
  11784. { Make sure the reference is the second operand }
  11785. SwapOper := taicpu(hp1).oper[0];
  11786. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11787. taicpu(hp1).oper[1] := SwapOper;
  11788. end;
  11789. end;
  11790. end;
  11791. case taicpu(hp1).oper[0]^.typ of
  11792. top_reg:
  11793. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11794. top_const:
  11795. { For the AND/TEST case }
  11796. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11797. else
  11798. ;
  11799. end;
  11800. if RegUsed then
  11801. begin
  11802. AsmL.Remove(p);
  11803. AsmL.InsertAfter(p, hp1);
  11804. p := hp1;
  11805. end
  11806. else
  11807. RemoveCurrentP(p, hp1);
  11808. result:=true;
  11809. exit;
  11810. end;
  11811. end;
  11812. end;
  11813. if reg_and_hp1_is_instr and
  11814. (taicpu(p).oper[0]^.typ = top_reg) and
  11815. (
  11816. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11817. ) and
  11818. (taicpu(hp1).oper[0]^.typ = top_const) and
  11819. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11820. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11821. { Minimum shift value allowed is the bit difference between the sizes }
  11822. (taicpu(hp1).oper[0]^.val >=
  11823. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11824. 8 * (
  11825. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11826. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11827. )
  11828. ) then
  11829. begin
  11830. { For:
  11831. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11832. shl/sal ##, %reg1
  11833. Remove the movsx/movzx instruction if the shift overwrites the
  11834. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11835. }
  11836. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11837. RemoveCurrentP(p, hp1);
  11838. Result := True;
  11839. Exit;
  11840. end
  11841. else if reg_and_hp1_is_instr and
  11842. (taicpu(p).oper[0]^.typ = top_reg) and
  11843. (
  11844. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11845. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11846. ) and
  11847. (taicpu(hp1).oper[0]^.typ = top_const) and
  11848. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11849. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11850. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11851. (taicpu(hp1).oper[0]^.val <
  11852. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11853. 8 * (
  11854. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11855. )
  11856. ) then
  11857. begin
  11858. { For:
  11859. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11860. sar ##, %reg1 shr ##, %reg1
  11861. Move the shift to before the movx instruction if the shift value
  11862. is not too large.
  11863. }
  11864. asml.Remove(hp1);
  11865. asml.InsertBefore(hp1, p);
  11866. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11867. case taicpu(p).opsize of
  11868. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11869. taicpu(hp1).opsize := S_B;
  11870. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11871. taicpu(hp1).opsize := S_W;
  11872. {$ifdef x86_64}
  11873. S_LQ:
  11874. taicpu(hp1).opsize := S_L;
  11875. {$endif}
  11876. else
  11877. InternalError(2020112401);
  11878. end;
  11879. if (taicpu(hp1).opcode = A_SHR) then
  11880. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11881. else
  11882. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11883. Result := True;
  11884. end;
  11885. if reg_and_hp1_is_instr and
  11886. (taicpu(p).oper[0]^.typ = top_reg) and
  11887. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11888. (
  11889. (taicpu(hp1).opcode = taicpu(p).opcode)
  11890. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11891. {$ifdef x86_64}
  11892. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11893. {$endif x86_64}
  11894. ) then
  11895. begin
  11896. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11897. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11898. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11899. begin
  11900. {
  11901. For example:
  11902. movzbw %al,%ax
  11903. movzwl %ax,%eax
  11904. Compress into:
  11905. movzbl %al,%eax
  11906. }
  11907. RegUsed := False;
  11908. case taicpu(p).opsize of
  11909. S_BW:
  11910. case taicpu(hp1).opsize of
  11911. S_WL:
  11912. begin
  11913. taicpu(p).opsize := S_BL;
  11914. RegUsed := True;
  11915. end;
  11916. {$ifdef x86_64}
  11917. S_WQ:
  11918. begin
  11919. if taicpu(p).opcode = A_MOVZX then
  11920. begin
  11921. taicpu(p).opsize := S_BL;
  11922. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11923. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11924. end
  11925. else
  11926. taicpu(p).opsize := S_BQ;
  11927. RegUsed := True;
  11928. end;
  11929. {$endif x86_64}
  11930. else
  11931. ;
  11932. end;
  11933. {$ifdef x86_64}
  11934. S_BL:
  11935. case taicpu(hp1).opsize of
  11936. S_LQ:
  11937. begin
  11938. if taicpu(p).opcode = A_MOVZX then
  11939. begin
  11940. taicpu(p).opsize := S_BL;
  11941. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11942. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11943. end
  11944. else
  11945. taicpu(p).opsize := S_BQ;
  11946. RegUsed := True;
  11947. end;
  11948. else
  11949. ;
  11950. end;
  11951. S_WL:
  11952. case taicpu(hp1).opsize of
  11953. S_LQ:
  11954. begin
  11955. if taicpu(p).opcode = A_MOVZX then
  11956. begin
  11957. taicpu(p).opsize := S_WL;
  11958. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11959. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11960. end
  11961. else
  11962. taicpu(p).opsize := S_WQ;
  11963. RegUsed := True;
  11964. end;
  11965. else
  11966. ;
  11967. end;
  11968. {$endif x86_64}
  11969. else
  11970. ;
  11971. end;
  11972. if RegUsed then
  11973. begin
  11974. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11975. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11976. RemoveInstruction(hp1);
  11977. Result := True;
  11978. Exit;
  11979. end;
  11980. end;
  11981. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11982. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11983. GetNextInstruction(hp1, hp2) and
  11984. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11985. (
  11986. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11987. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11988. {$ifdef x86_64}
  11989. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11990. {$endif x86_64}
  11991. ) and
  11992. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11993. (
  11994. (
  11995. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11996. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11997. ) or
  11998. (
  11999. { Only allow the operands in reverse order for TEST instructions }
  12000. (taicpu(hp2).opcode = A_TEST) and
  12001. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12002. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12003. )
  12004. ) then
  12005. begin
  12006. {
  12007. For example:
  12008. movzbl %al,%eax
  12009. movzbl (ref),%edx
  12010. andl %edx,%eax
  12011. (%edx deallocated)
  12012. Change to:
  12013. andb (ref),%al
  12014. movzbl %al,%eax
  12015. Rules are:
  12016. - First two instructions have the same opcode and opsize
  12017. - First instruction's operands are the same super-register
  12018. - Second instruction operates on a different register
  12019. - Third instruction is AND, OR, XOR or TEST
  12020. - Third instruction's operands are the destination registers of the first two instructions
  12021. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12022. - Second instruction's destination register is deallocated afterwards
  12023. }
  12024. TransferUsedRegs(TmpUsedRegs);
  12025. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12026. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12027. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12028. begin
  12029. case taicpu(p).opsize of
  12030. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12031. NewSize := S_B;
  12032. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12033. NewSize := S_W;
  12034. {$ifdef x86_64}
  12035. S_LQ:
  12036. NewSize := S_L;
  12037. {$endif x86_64}
  12038. else
  12039. InternalError(2021120301);
  12040. end;
  12041. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12042. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12043. taicpu(hp2).opsize := NewSize;
  12044. RemoveInstruction(hp1);
  12045. { With TEST, it's best to keep the MOVX instruction at the top }
  12046. if (taicpu(hp2).opcode <> A_TEST) then
  12047. begin
  12048. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12049. asml.Remove(p);
  12050. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12051. asml.InsertAfter(p, hp2);
  12052. p := hp2;
  12053. end
  12054. else
  12055. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12056. Result := True;
  12057. Exit;
  12058. end;
  12059. end;
  12060. end;
  12061. if taicpu(p).opcode=A_MOVZX then
  12062. begin
  12063. { removes superfluous And's after movzx's }
  12064. if reg_and_hp1_is_instr and
  12065. (taicpu(hp1).opcode = A_AND) and
  12066. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12067. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12068. {$ifdef x86_64}
  12069. { check for implicit extension to 64 bit }
  12070. or
  12071. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12072. (taicpu(hp1).opsize=S_Q) and
  12073. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12074. )
  12075. {$endif x86_64}
  12076. )
  12077. then
  12078. begin
  12079. case taicpu(p).opsize Of
  12080. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12081. if (taicpu(hp1).oper[0]^.val = $ff) then
  12082. begin
  12083. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12084. RemoveInstruction(hp1);
  12085. Result:=true;
  12086. exit;
  12087. end;
  12088. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12089. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12090. begin
  12091. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12092. RemoveInstruction(hp1);
  12093. Result:=true;
  12094. exit;
  12095. end;
  12096. {$ifdef x86_64}
  12097. S_LQ:
  12098. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12099. begin
  12100. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12101. RemoveInstruction(hp1);
  12102. Result:=true;
  12103. exit;
  12104. end;
  12105. {$endif x86_64}
  12106. else
  12107. ;
  12108. end;
  12109. { we cannot get rid of the and, but can we get rid of the movz ?}
  12110. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12111. begin
  12112. case taicpu(p).opsize Of
  12113. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12114. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12115. begin
  12116. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12117. RemoveCurrentP(p,hp1);
  12118. Result:=true;
  12119. exit;
  12120. end;
  12121. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12122. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12123. begin
  12124. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12125. RemoveCurrentP(p,hp1);
  12126. Result:=true;
  12127. exit;
  12128. end;
  12129. {$ifdef x86_64}
  12130. S_LQ:
  12131. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12132. begin
  12133. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12134. RemoveCurrentP(p,hp1);
  12135. Result:=true;
  12136. exit;
  12137. end;
  12138. {$endif x86_64}
  12139. else
  12140. ;
  12141. end;
  12142. end;
  12143. end;
  12144. { changes some movzx constructs to faster synonyms (all examples
  12145. are given with eax/ax, but are also valid for other registers)}
  12146. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12147. begin
  12148. case taicpu(p).opsize of
  12149. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12150. (the machine code is equivalent to movzbl %al,%eax), but the
  12151. code generator still generates that assembler instruction and
  12152. it is silently converted. This should probably be checked.
  12153. [Kit] }
  12154. S_BW:
  12155. begin
  12156. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12157. (
  12158. not IsMOVZXAcceptable
  12159. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12160. or (
  12161. (cs_opt_size in current_settings.optimizerswitches) and
  12162. (taicpu(p).oper[1]^.reg = NR_AX)
  12163. )
  12164. ) then
  12165. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12166. begin
  12167. DebugMsg(SPeepholeOptimization + 'var7',p);
  12168. taicpu(p).opcode := A_AND;
  12169. taicpu(p).changeopsize(S_W);
  12170. taicpu(p).loadConst(0,$ff);
  12171. Result := True;
  12172. end
  12173. else if not IsMOVZXAcceptable and
  12174. GetNextInstruction(p, hp1) and
  12175. (tai(hp1).typ = ait_instruction) and
  12176. (taicpu(hp1).opcode = A_AND) and
  12177. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12178. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12179. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12180. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12181. begin
  12182. DebugMsg(SPeepholeOptimization + 'var8',p);
  12183. taicpu(p).opcode := A_MOV;
  12184. taicpu(p).changeopsize(S_W);
  12185. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12186. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12187. Result := True;
  12188. end;
  12189. end;
  12190. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12191. S_BL:
  12192. if not IsMOVZXAcceptable then
  12193. begin
  12194. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12195. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12196. begin
  12197. DebugMsg(SPeepholeOptimization + 'var9',p);
  12198. taicpu(p).opcode := A_AND;
  12199. taicpu(p).changeopsize(S_L);
  12200. taicpu(p).loadConst(0,$ff);
  12201. Result := True;
  12202. end
  12203. else if GetNextInstruction(p, hp1) and
  12204. (tai(hp1).typ = ait_instruction) and
  12205. (taicpu(hp1).opcode = A_AND) and
  12206. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12207. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12208. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12209. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12210. begin
  12211. DebugMsg(SPeepholeOptimization + 'var10',p);
  12212. taicpu(p).opcode := A_MOV;
  12213. taicpu(p).changeopsize(S_L);
  12214. { do not use R_SUBWHOLE
  12215. as movl %rdx,%eax
  12216. is invalid in assembler PM }
  12217. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12218. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12219. Result := True;
  12220. end;
  12221. end;
  12222. {$endif i8086}
  12223. S_WL:
  12224. if not IsMOVZXAcceptable then
  12225. begin
  12226. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12227. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12228. begin
  12229. DebugMsg(SPeepholeOptimization + 'var11',p);
  12230. taicpu(p).opcode := A_AND;
  12231. taicpu(p).changeopsize(S_L);
  12232. taicpu(p).loadConst(0,$ffff);
  12233. Result := True;
  12234. end
  12235. else if GetNextInstruction(p, hp1) and
  12236. (tai(hp1).typ = ait_instruction) and
  12237. (taicpu(hp1).opcode = A_AND) and
  12238. (taicpu(hp1).oper[0]^.typ = top_const) and
  12239. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12240. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12241. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12242. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12243. begin
  12244. DebugMsg(SPeepholeOptimization + 'var12',p);
  12245. taicpu(p).opcode := A_MOV;
  12246. taicpu(p).changeopsize(S_L);
  12247. { do not use R_SUBWHOLE
  12248. as movl %rdx,%eax
  12249. is invalid in assembler PM }
  12250. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12251. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12252. Result := True;
  12253. end;
  12254. end;
  12255. else
  12256. InternalError(2017050705);
  12257. end;
  12258. end
  12259. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12260. begin
  12261. if GetNextInstruction(p, hp1) and
  12262. (tai(hp1).typ = ait_instruction) and
  12263. (taicpu(hp1).opcode = A_AND) and
  12264. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12265. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12266. begin
  12267. //taicpu(p).opcode := A_MOV;
  12268. case taicpu(p).opsize Of
  12269. S_BL:
  12270. begin
  12271. DebugMsg(SPeepholeOptimization + 'var13',p);
  12272. taicpu(hp1).changeopsize(S_L);
  12273. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12274. end;
  12275. S_WL:
  12276. begin
  12277. DebugMsg(SPeepholeOptimization + 'var14',p);
  12278. taicpu(hp1).changeopsize(S_L);
  12279. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12280. end;
  12281. S_BW:
  12282. begin
  12283. DebugMsg(SPeepholeOptimization + 'var15',p);
  12284. taicpu(hp1).changeopsize(S_W);
  12285. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12286. end;
  12287. else
  12288. Internalerror(2017050704)
  12289. end;
  12290. Result := True;
  12291. end;
  12292. end;
  12293. end;
  12294. end;
  12295. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12296. var
  12297. hp1, hp2 : tai;
  12298. MaskLength : Cardinal;
  12299. MaskedBits : TCgInt;
  12300. ActiveReg : TRegister;
  12301. begin
  12302. Result:=false;
  12303. { There are no optimisations for reference targets }
  12304. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12305. Exit;
  12306. while GetNextInstruction(p, hp1) and
  12307. (hp1.typ = ait_instruction) do
  12308. begin
  12309. if (taicpu(p).oper[0]^.typ = top_const) then
  12310. begin
  12311. case taicpu(hp1).opcode of
  12312. A_AND:
  12313. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12314. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12315. { the second register must contain the first one, so compare their subreg types }
  12316. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12317. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12318. { change
  12319. and const1, reg
  12320. and const2, reg
  12321. to
  12322. and (const1 and const2), reg
  12323. }
  12324. begin
  12325. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12326. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12327. RemoveCurrentP(p, hp1);
  12328. Result:=true;
  12329. exit;
  12330. end;
  12331. A_CMP:
  12332. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12333. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12334. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12335. { Just check that the condition on the next instruction is compatible }
  12336. GetNextInstruction(hp1, hp2) and
  12337. (hp2.typ = ait_instruction) and
  12338. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12339. then
  12340. { change
  12341. and 2^n, reg
  12342. cmp 2^n, reg
  12343. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12344. to
  12345. and 2^n, reg
  12346. test reg, reg
  12347. j(~c) / set(~c) / cmov(~c)
  12348. }
  12349. begin
  12350. { Keep TEST instruction in, rather than remove it, because
  12351. it may trigger other optimisations such as MovAndTest2Test }
  12352. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12353. taicpu(hp1).opcode := A_TEST;
  12354. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12355. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12356. Result := True;
  12357. Exit;
  12358. end
  12359. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12360. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12361. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12362. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12363. { change
  12364. and $ff/$ff/$ffff, reg
  12365. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12366. dealloc reg
  12367. to
  12368. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12369. }
  12370. begin
  12371. TransferUsedRegs(TmpUsedRegs);
  12372. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12373. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12374. begin
  12375. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12376. case taicpu(p).oper[0]^.val of
  12377. $ff:
  12378. begin
  12379. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12380. taicpu(hp1).opsize:=S_B;
  12381. end;
  12382. $ffff:
  12383. begin
  12384. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12385. taicpu(hp1).opsize:=S_W;
  12386. end;
  12387. $ffffffff:
  12388. begin
  12389. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12390. taicpu(hp1).opsize:=S_L;
  12391. end;
  12392. else
  12393. Internalerror(2023030401);
  12394. end;
  12395. RemoveCurrentP(p);
  12396. Result := True;
  12397. Exit;
  12398. end;
  12399. end;
  12400. A_MOVZX:
  12401. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12402. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12403. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12404. (
  12405. (
  12406. (taicpu(p).opsize=S_W) and
  12407. (taicpu(hp1).opsize=S_BW)
  12408. ) or
  12409. (
  12410. (taicpu(p).opsize=S_L) and
  12411. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12412. )
  12413. {$ifdef x86_64}
  12414. or
  12415. (
  12416. (taicpu(p).opsize=S_Q) and
  12417. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12418. )
  12419. {$endif x86_64}
  12420. ) then
  12421. begin
  12422. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12423. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12424. ) or
  12425. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12426. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12427. then
  12428. begin
  12429. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12430. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12431. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12432. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12433. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12434. }
  12435. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12436. RemoveInstruction(hp1);
  12437. { See if there are other optimisations possible }
  12438. Continue;
  12439. end;
  12440. end;
  12441. A_SHL:
  12442. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12443. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12444. begin
  12445. {$ifopt R+}
  12446. {$define RANGE_WAS_ON}
  12447. {$R-}
  12448. {$endif}
  12449. { get length of potential and mask }
  12450. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12451. { really a mask? }
  12452. {$ifdef RANGE_WAS_ON}
  12453. {$R+}
  12454. {$endif}
  12455. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12456. { unmasked part shifted out? }
  12457. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12458. begin
  12459. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12460. RemoveCurrentP(p, hp1);
  12461. Result:=true;
  12462. exit;
  12463. end;
  12464. end;
  12465. A_SHR:
  12466. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12467. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12468. (taicpu(hp1).oper[0]^.val <= 63) then
  12469. begin
  12470. { Does SHR combined with the AND cover all the bits?
  12471. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12472. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12473. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12474. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12475. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12476. begin
  12477. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12478. RemoveCurrentP(p, hp1);
  12479. Result := True;
  12480. Exit;
  12481. end;
  12482. end;
  12483. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12484. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12485. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12486. begin
  12487. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12488. (
  12489. (
  12490. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12491. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12492. ) or (
  12493. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12494. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12495. {$ifdef x86_64}
  12496. ) or (
  12497. (taicpu(hp1).opsize = S_LQ) and
  12498. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12499. {$endif x86_64}
  12500. )
  12501. ) then
  12502. begin
  12503. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12504. begin
  12505. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12506. RemoveInstruction(hp1);
  12507. { See if there are other optimisations possible }
  12508. Continue;
  12509. end;
  12510. { The super-registers are the same though.
  12511. Note that this change by itself doesn't improve
  12512. code speed, but it opens up other optimisations. }
  12513. {$ifdef x86_64}
  12514. { Convert 64-bit register to 32-bit }
  12515. case taicpu(hp1).opsize of
  12516. S_BQ:
  12517. begin
  12518. taicpu(hp1).opsize := S_BL;
  12519. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12520. end;
  12521. S_WQ:
  12522. begin
  12523. taicpu(hp1).opsize := S_WL;
  12524. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12525. end
  12526. else
  12527. ;
  12528. end;
  12529. {$endif x86_64}
  12530. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12531. taicpu(hp1).opcode := A_MOVZX;
  12532. { See if there are other optimisations possible }
  12533. Continue;
  12534. end;
  12535. end;
  12536. else
  12537. ;
  12538. end;
  12539. end
  12540. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12541. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12542. begin
  12543. {$ifdef x86_64}
  12544. if (taicpu(p).opsize = S_Q) then
  12545. begin
  12546. { Never necessary }
  12547. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12548. RemoveCurrentP(p, hp1);
  12549. Result := True;
  12550. Exit;
  12551. end;
  12552. {$endif x86_64}
  12553. { Forward check to determine necessity of and %reg,%reg }
  12554. TransferUsedRegs(TmpUsedRegs);
  12555. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12556. { Saves on a bunch of dereferences }
  12557. ActiveReg := taicpu(p).oper[1]^.reg;
  12558. case taicpu(hp1).opcode of
  12559. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12560. if (
  12561. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12562. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12563. ) and
  12564. (
  12565. (taicpu(hp1).opcode <> A_MOV) or
  12566. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12567. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12568. ) and
  12569. not (
  12570. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12571. (taicpu(hp1).opcode = A_MOV) and
  12572. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12573. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12574. ) and
  12575. (
  12576. (
  12577. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12578. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12579. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12580. ) or
  12581. (
  12582. {$ifdef x86_64}
  12583. (
  12584. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12585. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12586. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12587. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12588. ) and
  12589. {$endif x86_64}
  12590. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12591. )
  12592. ) then
  12593. begin
  12594. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12595. RemoveCurrentP(p, hp1);
  12596. Result := True;
  12597. Exit;
  12598. end;
  12599. A_ADD,
  12600. A_AND,
  12601. A_BSF,
  12602. A_BSR,
  12603. A_BTC,
  12604. A_BTR,
  12605. A_BTS,
  12606. A_OR,
  12607. A_SUB,
  12608. A_XOR:
  12609. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12610. if (
  12611. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12612. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12613. ) and
  12614. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12615. begin
  12616. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12617. RemoveCurrentP(p, hp1);
  12618. Result := True;
  12619. Exit;
  12620. end;
  12621. A_CMP,
  12622. A_TEST:
  12623. if (
  12624. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12625. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12626. ) and
  12627. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12628. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12629. begin
  12630. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12631. RemoveCurrentP(p, hp1);
  12632. Result := True;
  12633. Exit;
  12634. end;
  12635. A_BSWAP,
  12636. A_NEG,
  12637. A_NOT:
  12638. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12639. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12640. begin
  12641. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12642. RemoveCurrentP(p, hp1);
  12643. Result := True;
  12644. Exit;
  12645. end;
  12646. else
  12647. ;
  12648. end;
  12649. end;
  12650. if (taicpu(hp1).is_jmp) and
  12651. (taicpu(hp1).opcode<>A_JMP) and
  12652. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12653. begin
  12654. { change
  12655. and x, reg
  12656. jxx
  12657. to
  12658. test x, reg
  12659. jxx
  12660. if reg is deallocated before the
  12661. jump, but only if it's a conditional jump (PFV)
  12662. }
  12663. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12664. taicpu(p).opcode := A_TEST;
  12665. Exit;
  12666. end;
  12667. Break;
  12668. end;
  12669. { Lone AND tests }
  12670. if (taicpu(p).oper[0]^.typ = top_const) then
  12671. begin
  12672. {
  12673. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12674. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12675. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12676. }
  12677. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12678. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12679. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12680. begin
  12681. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12682. if taicpu(p).opsize = S_L then
  12683. begin
  12684. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12685. Result := True;
  12686. end;
  12687. end;
  12688. end;
  12689. { Backward check to determine necessity of and %reg,%reg }
  12690. if (taicpu(p).oper[0]^.typ = top_reg) and
  12691. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12692. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12693. GetLastInstruction(p, hp2) and
  12694. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12695. { Check size of adjacent instruction to determine if the AND is
  12696. effectively a null operation }
  12697. (
  12698. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12699. { Note: Don't include S_Q }
  12700. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12701. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12702. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12703. ) then
  12704. begin
  12705. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12706. { If GetNextInstruction returned False, hp1 will be nil }
  12707. RemoveCurrentP(p, hp1);
  12708. Result := True;
  12709. Exit;
  12710. end;
  12711. end;
  12712. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12713. var
  12714. hp1, hp2: tai;
  12715. NewRef: TReference;
  12716. Distance: Cardinal;
  12717. TempTracking: TAllUsedRegs;
  12718. { This entire nested function is used in an if-statement below, but we
  12719. want to avoid all the used reg transfers and GetNextInstruction calls
  12720. until we really have to check }
  12721. function MemRegisterNotUsedLater: Boolean; inline;
  12722. var
  12723. hp2: tai;
  12724. begin
  12725. TransferUsedRegs(TmpUsedRegs);
  12726. hp2 := p;
  12727. repeat
  12728. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12729. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12730. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12731. end;
  12732. begin
  12733. Result := False;
  12734. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12735. (taicpu(p).oper[1]^.typ = top_reg) then
  12736. begin
  12737. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12738. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12739. (hp1.typ <> ait_instruction) or
  12740. not
  12741. (
  12742. (cs_opt_level3 in current_settings.optimizerswitches) or
  12743. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12744. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12745. ) then
  12746. Exit;
  12747. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12748. addq $x, %rax
  12749. movq %rax, %rdx
  12750. sarq $63, %rdx
  12751. (%rax still in use)
  12752. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12753. leaq $x(%rax),%rdx
  12754. addq $x, %rax
  12755. sarq $63, %rdx
  12756. ...which is okay since it breaks the dependency chain between
  12757. addq and movq, but if OptPass2MOV is called first:
  12758. addq $x, %rax
  12759. cqto
  12760. ...which is better in all ways, taking only 2 cycles to execute
  12761. and much smaller in code size.
  12762. }
  12763. { The extra register tracking is quite strenuous }
  12764. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12765. MatchInstruction(hp1, A_MOV, []) then
  12766. begin
  12767. { Update the register tracking to the MOV instruction }
  12768. CopyUsedRegs(TempTracking);
  12769. hp2 := p;
  12770. repeat
  12771. UpdateUsedRegs(tai(hp2.Next));
  12772. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12773. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12774. OptPass2ADD get called again }
  12775. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12776. begin
  12777. { Reset the tracking to the current instruction }
  12778. RestoreUsedRegs(TempTracking);
  12779. ReleaseUsedRegs(TempTracking);
  12780. Result := True;
  12781. Exit;
  12782. end;
  12783. { Reset the tracking to the current instruction }
  12784. RestoreUsedRegs(TempTracking);
  12785. ReleaseUsedRegs(TempTracking);
  12786. { If OptPass2MOV returned True, we don't need to set Result to
  12787. True if hp1 didn't change because the ADD instruction didn't
  12788. get modified and we'll be evaluating hp1 again when the
  12789. peephole optimizer reaches it }
  12790. end;
  12791. { Change:
  12792. add %reg2,%reg1
  12793. (%reg2 not modified in between)
  12794. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12795. To:
  12796. mov/s/z #(%reg1,%reg2),%reg1
  12797. }
  12798. if (taicpu(p).oper[0]^.typ = top_reg) and
  12799. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12800. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12801. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12802. (
  12803. (
  12804. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12805. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12806. { r/esp cannot be an index }
  12807. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12808. ) or (
  12809. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12810. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12811. )
  12812. ) and (
  12813. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12814. (
  12815. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12816. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12817. MemRegisterNotUsedLater
  12818. )
  12819. ) then
  12820. begin
  12821. if (
  12822. { Instructions are guaranteed to be adjacent on -O2 and under }
  12823. (cs_opt_level3 in current_settings.optimizerswitches) and
  12824. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12825. ) then
  12826. begin
  12827. { If the other register is used in between, move the MOV
  12828. instruction to right after the ADD instruction so a
  12829. saving can still be made }
  12830. Asml.Remove(hp1);
  12831. Asml.InsertAfter(hp1, p);
  12832. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12833. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12834. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12835. RemoveCurrentp(p, hp1);
  12836. end
  12837. else
  12838. begin
  12839. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12840. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12841. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12842. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12843. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12844. { hp1 may not be the immediate next instruction under -O3 }
  12845. RemoveCurrentp(p)
  12846. else
  12847. RemoveCurrentp(p, hp1);
  12848. end;
  12849. Result := True;
  12850. Exit;
  12851. end;
  12852. { Change:
  12853. addl/q $x,%reg1
  12854. movl/q %reg1,%reg2
  12855. To:
  12856. leal/q $x(%reg1),%reg2
  12857. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12858. Breaks the dependency chain.
  12859. }
  12860. if (taicpu(p).oper[0]^.typ = top_const) and
  12861. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12862. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12863. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12864. (
  12865. { Instructions are guaranteed to be adjacent on -O2 and under }
  12866. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12867. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12868. ) then
  12869. begin
  12870. TransferUsedRegs(TmpUsedRegs);
  12871. hp2 := p;
  12872. repeat
  12873. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12874. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12875. if (
  12876. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12877. not (cs_opt_size in current_settings.optimizerswitches) or
  12878. (
  12879. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12880. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12881. )
  12882. ) then
  12883. begin
  12884. { Change the MOV instruction to a LEA instruction, and update the
  12885. first operand }
  12886. reference_reset(NewRef, 1, []);
  12887. NewRef.base := taicpu(p).oper[1]^.reg;
  12888. NewRef.scalefactor := 1;
  12889. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12890. taicpu(hp1).opcode := A_LEA;
  12891. taicpu(hp1).loadref(0, NewRef);
  12892. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12893. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12894. begin
  12895. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12896. { Move what is now the LEA instruction to before the ADD instruction }
  12897. Asml.Remove(hp1);
  12898. Asml.InsertBefore(hp1, p);
  12899. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12900. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12901. p := hp1;
  12902. end
  12903. else
  12904. begin
  12905. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12906. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12907. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12908. { hp1 may not be the immediate next instruction under -O3 }
  12909. RemoveCurrentp(p)
  12910. else
  12911. RemoveCurrentp(p, hp1);
  12912. end;
  12913. Result := True;
  12914. end;
  12915. end;
  12916. end;
  12917. end;
  12918. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12919. var
  12920. SubReg: TSubRegister;
  12921. begin
  12922. Result:=false;
  12923. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12924. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12925. with taicpu(p).oper[0]^.ref^ do
  12926. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12927. begin
  12928. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12929. begin
  12930. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12931. taicpu(p).opcode := A_ADD;
  12932. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12933. Result := True;
  12934. end
  12935. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12936. begin
  12937. if (base <> NR_NO) then
  12938. begin
  12939. if (scalefactor <= 1) then
  12940. begin
  12941. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12942. taicpu(p).opcode := A_ADD;
  12943. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12944. Result := True;
  12945. end;
  12946. end
  12947. else
  12948. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12949. if (scalefactor in [2, 4, 8]) then
  12950. begin
  12951. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12952. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12953. taicpu(p).opcode := A_SHL;
  12954. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12955. Result := True;
  12956. end;
  12957. end;
  12958. end;
  12959. end;
  12960. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12961. var
  12962. hp1, hp2: tai;
  12963. NewRef: TReference;
  12964. Distance: Cardinal;
  12965. TempTracking: TAllUsedRegs;
  12966. begin
  12967. Result := False;
  12968. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12969. MatchOpType(taicpu(p),top_const,top_reg) then
  12970. begin
  12971. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12972. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12973. (hp1.typ <> ait_instruction) or
  12974. not
  12975. (
  12976. (cs_opt_level3 in current_settings.optimizerswitches) or
  12977. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12978. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12979. ) then
  12980. Exit;
  12981. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12982. subq $x, %rax
  12983. movq %rax, %rdx
  12984. sarq $63, %rdx
  12985. (%rax still in use)
  12986. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12987. leaq $-x(%rax),%rdx
  12988. movq $x, %rax
  12989. sarq $63, %rdx
  12990. ...which is okay since it breaks the dependency chain between
  12991. subq and movq, but if OptPass2MOV is called first:
  12992. subq $x, %rax
  12993. cqto
  12994. ...which is better in all ways, taking only 2 cycles to execute
  12995. and much smaller in code size.
  12996. }
  12997. { The extra register tracking is quite strenuous }
  12998. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12999. MatchInstruction(hp1, A_MOV, []) then
  13000. begin
  13001. { Update the register tracking to the MOV instruction }
  13002. CopyUsedRegs(TempTracking);
  13003. hp2 := p;
  13004. repeat
  13005. UpdateUsedRegs(tai(hp2.Next));
  13006. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13007. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13008. OptPass2SUB get called again }
  13009. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13010. begin
  13011. { Reset the tracking to the current instruction }
  13012. RestoreUsedRegs(TempTracking);
  13013. ReleaseUsedRegs(TempTracking);
  13014. Result := True;
  13015. Exit;
  13016. end;
  13017. { Reset the tracking to the current instruction }
  13018. RestoreUsedRegs(TempTracking);
  13019. ReleaseUsedRegs(TempTracking);
  13020. { If OptPass2MOV returned True, we don't need to set Result to
  13021. True if hp1 didn't change because the SUB instruction didn't
  13022. get modified and we'll be evaluating hp1 again when the
  13023. peephole optimizer reaches it }
  13024. end;
  13025. { Change:
  13026. subl/q $x,%reg1
  13027. movl/q %reg1,%reg2
  13028. To:
  13029. leal/q $-x(%reg1),%reg2
  13030. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13031. Breaks the dependency chain and potentially permits the removal of
  13032. a CMP instruction if one follows.
  13033. }
  13034. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13035. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13036. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13037. (
  13038. { Instructions are guaranteed to be adjacent on -O2 and under }
  13039. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13040. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13041. ) then
  13042. begin
  13043. TransferUsedRegs(TmpUsedRegs);
  13044. hp2 := p;
  13045. repeat
  13046. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13047. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13048. if (
  13049. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13050. not (cs_opt_size in current_settings.optimizerswitches) or
  13051. (
  13052. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13053. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13054. )
  13055. ) then
  13056. begin
  13057. { Change the MOV instruction to a LEA instruction, and update the
  13058. first operand }
  13059. reference_reset(NewRef, 1, []);
  13060. NewRef.base := taicpu(p).oper[1]^.reg;
  13061. NewRef.scalefactor := 1;
  13062. NewRef.offset := -taicpu(p).oper[0]^.val;
  13063. taicpu(hp1).opcode := A_LEA;
  13064. taicpu(hp1).loadref(0, NewRef);
  13065. TransferUsedRegs(TmpUsedRegs);
  13066. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13067. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13068. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13069. begin
  13070. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13071. { Move what is now the LEA instruction to before the SUB instruction }
  13072. Asml.Remove(hp1);
  13073. Asml.InsertBefore(hp1, p);
  13074. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13075. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13076. p := hp1;
  13077. end
  13078. else
  13079. begin
  13080. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13081. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13082. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13083. { hp1 may not be the immediate next instruction under -O3 }
  13084. RemoveCurrentp(p)
  13085. else
  13086. RemoveCurrentp(p, hp1);
  13087. end;
  13088. Result := True;
  13089. end;
  13090. end;
  13091. end;
  13092. end;
  13093. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13094. begin
  13095. { we can skip all instructions not messing with the stack pointer }
  13096. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13097. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13098. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13099. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13100. ({(taicpu(hp1).ops=0) or }
  13101. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13102. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13103. ) and }
  13104. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13105. )
  13106. ) do
  13107. GetNextInstruction(hp1,hp1);
  13108. Result:=assigned(hp1);
  13109. end;
  13110. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13111. var
  13112. hp1, hp2, hp3, hp4, hp5: tai;
  13113. begin
  13114. Result:=false;
  13115. hp5:=nil;
  13116. { replace
  13117. leal(q) x(<stackpointer>),<stackpointer>
  13118. call procname
  13119. leal(q) -x(<stackpointer>),<stackpointer>
  13120. ret
  13121. by
  13122. jmp procname
  13123. but do it only on level 4 because it destroys stack back traces
  13124. }
  13125. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13126. MatchOpType(taicpu(p),top_ref,top_reg) and
  13127. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13128. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13129. { the -8 or -24 are not required, but bail out early if possible,
  13130. higher values are unlikely }
  13131. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13132. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13133. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13134. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13135. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13136. GetNextInstruction(p, hp1) and
  13137. { Take a copy of hp1 }
  13138. SetAndTest(hp1, hp4) and
  13139. { trick to skip label }
  13140. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13141. SkipSimpleInstructions(hp1) and
  13142. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13143. GetNextInstruction(hp1, hp2) and
  13144. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13145. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13146. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13147. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13148. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13149. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13150. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13151. { Segment register will be NR_NO }
  13152. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13153. GetNextInstruction(hp2, hp3) and
  13154. { trick to skip label }
  13155. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13156. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13157. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13158. SetAndTest(hp3,hp5) and
  13159. GetNextInstruction(hp3,hp3) and
  13160. MatchInstruction(hp3,A_RET,[S_NO])
  13161. )
  13162. ) and
  13163. (taicpu(hp3).ops=0) then
  13164. begin
  13165. taicpu(hp1).opcode := A_JMP;
  13166. taicpu(hp1).is_jmp := true;
  13167. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13168. RemoveCurrentP(p, hp4);
  13169. RemoveInstruction(hp2);
  13170. RemoveInstruction(hp3);
  13171. if Assigned(hp5) then
  13172. begin
  13173. AsmL.Remove(hp5);
  13174. ASmL.InsertBefore(hp5,hp1)
  13175. end;
  13176. Result:=true;
  13177. end;
  13178. end;
  13179. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13180. {$ifdef x86_64}
  13181. var
  13182. hp1, hp2, hp3, hp4, hp5: tai;
  13183. {$endif x86_64}
  13184. begin
  13185. Result:=false;
  13186. {$ifdef x86_64}
  13187. hp5:=nil;
  13188. { replace
  13189. push %rax
  13190. call procname
  13191. pop %rcx
  13192. ret
  13193. by
  13194. jmp procname
  13195. but do it only on level 4 because it destroys stack back traces
  13196. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13197. for all supported calling conventions
  13198. }
  13199. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13200. MatchOpType(taicpu(p),top_reg) and
  13201. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13202. GetNextInstruction(p, hp1) and
  13203. { Take a copy of hp1 }
  13204. SetAndTest(hp1, hp4) and
  13205. { trick to skip label }
  13206. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13207. SkipSimpleInstructions(hp1) and
  13208. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13209. GetNextInstruction(hp1, hp2) and
  13210. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13211. MatchOpType(taicpu(hp2),top_reg) and
  13212. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13213. GetNextInstruction(hp2, hp3) and
  13214. { trick to skip label }
  13215. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13216. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13217. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13218. SetAndTest(hp3,hp5) and
  13219. GetNextInstruction(hp3,hp3) and
  13220. MatchInstruction(hp3,A_RET,[S_NO])
  13221. )
  13222. ) and
  13223. (taicpu(hp3).ops=0) then
  13224. begin
  13225. taicpu(hp1).opcode := A_JMP;
  13226. taicpu(hp1).is_jmp := true;
  13227. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13228. RemoveCurrentP(p, hp4);
  13229. RemoveInstruction(hp2);
  13230. RemoveInstruction(hp3);
  13231. if Assigned(hp5) then
  13232. begin
  13233. AsmL.Remove(hp5);
  13234. ASmL.InsertBefore(hp5,hp1)
  13235. end;
  13236. Result:=true;
  13237. end;
  13238. {$endif x86_64}
  13239. end;
  13240. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13241. var
  13242. Value, RegName: string;
  13243. begin
  13244. Result:=false;
  13245. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13246. begin
  13247. case taicpu(p).oper[0]^.val of
  13248. 0:
  13249. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13250. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13251. begin
  13252. { change "mov $0,%reg" into "xor %reg,%reg" }
  13253. taicpu(p).opcode := A_XOR;
  13254. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13255. Result := True;
  13256. {$ifdef x86_64}
  13257. end
  13258. else if (taicpu(p).opsize = S_Q) then
  13259. begin
  13260. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13261. { The actual optimization }
  13262. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13263. taicpu(p).changeopsize(S_L);
  13264. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13265. Result := True;
  13266. end;
  13267. $1..$FFFFFFFF:
  13268. begin
  13269. { Code size reduction by J. Gareth "Kit" Moreton }
  13270. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13271. case taicpu(p).opsize of
  13272. S_Q:
  13273. begin
  13274. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13275. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13276. { The actual optimization }
  13277. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13278. taicpu(p).changeopsize(S_L);
  13279. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13280. Result := True;
  13281. end;
  13282. else
  13283. { Do nothing };
  13284. end;
  13285. {$endif x86_64}
  13286. end;
  13287. -1:
  13288. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13289. if (cs_opt_size in current_settings.optimizerswitches) and
  13290. (taicpu(p).opsize <> S_B) and
  13291. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13292. begin
  13293. { change "mov $-1,%reg" into "or $-1,%reg" }
  13294. { NOTES:
  13295. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13296. - This operation creates a false dependency on the register, so only do it when optimising for size
  13297. - 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
  13298. }
  13299. taicpu(p).opcode := A_OR;
  13300. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13301. Result := True;
  13302. end;
  13303. else
  13304. { Do nothing };
  13305. end;
  13306. end;
  13307. end;
  13308. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13309. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13310. begin
  13311. Result := False;
  13312. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13313. Exit;
  13314. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13315. so don't bother optimising }
  13316. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13317. Exit;
  13318. if (taicpu(p).oper[0]^.typ <> top_const) or
  13319. { If the value can fit into an 8-bit signed integer, a smaller
  13320. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13321. falls within this range }
  13322. (
  13323. (taicpu(p).oper[0]^.val > -128) and
  13324. (taicpu(p).oper[0]^.val <= 127)
  13325. ) then
  13326. Exit;
  13327. { If we're optimising for size, this is acceptable }
  13328. if (cs_opt_size in current_settings.optimizerswitches) then
  13329. Exit(True);
  13330. if (taicpu(p).oper[1]^.typ = top_reg) and
  13331. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13332. Exit(True);
  13333. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13334. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13335. Exit(True);
  13336. end;
  13337. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13338. var
  13339. hp1: tai;
  13340. Value: TCGInt;
  13341. begin
  13342. Result := False;
  13343. if MatchOpType(taicpu(p), top_const, top_reg) then
  13344. begin
  13345. { Detect:
  13346. andw x, %ax (0 <= x < $8000)
  13347. ...
  13348. movzwl %ax,%eax
  13349. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13350. }
  13351. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13352. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13353. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13354. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13355. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13356. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13357. begin
  13358. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13359. taicpu(hp1).opcode := A_CWDE;
  13360. taicpu(hp1).clearop(0);
  13361. taicpu(hp1).clearop(1);
  13362. taicpu(hp1).ops := 0;
  13363. { A change was made, but not with p, so don't set Result, but
  13364. notify the compiler that a change was made }
  13365. Include(OptsToCheck, aoc_ForceNewIteration);
  13366. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13367. end;
  13368. end;
  13369. { If "not x" is a power of 2 (popcnt = 1), change:
  13370. and $x, %reg/ref
  13371. To:
  13372. btr lb(x), %reg/ref
  13373. }
  13374. if IsBTXAcceptable(p) and
  13375. (
  13376. { Make sure a TEST doesn't follow that plays with the register }
  13377. not GetNextInstruction(p, hp1) or
  13378. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13379. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13380. ) then
  13381. begin
  13382. {$push}{$R-}{$Q-}
  13383. { Value is a sign-extended 32-bit integer - just correct it
  13384. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13385. checks to see if this operand is an immediate. }
  13386. Value := not taicpu(p).oper[0]^.val;
  13387. {$pop}
  13388. {$ifdef x86_64}
  13389. if taicpu(p).opsize = S_L then
  13390. {$endif x86_64}
  13391. Value := Value and $FFFFFFFF;
  13392. if (PopCnt(QWord(Value)) = 1) then
  13393. begin
  13394. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13395. taicpu(p).opcode := A_BTR;
  13396. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13397. Result := True;
  13398. Exit;
  13399. end;
  13400. end;
  13401. end;
  13402. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13403. begin
  13404. Result := False;
  13405. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13406. Exit;
  13407. { Convert:
  13408. movswl %ax,%eax -> cwtl
  13409. movslq %eax,%rax -> cdqe
  13410. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13411. refer to the same opcode and depends only on the assembler's
  13412. current operand-size attribute. [Kit]
  13413. }
  13414. with taicpu(p) do
  13415. case opsize of
  13416. S_WL:
  13417. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13418. begin
  13419. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13420. opcode := A_CWDE;
  13421. clearop(0);
  13422. clearop(1);
  13423. ops := 0;
  13424. Result := True;
  13425. end;
  13426. {$ifdef x86_64}
  13427. S_LQ:
  13428. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13429. begin
  13430. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13431. opcode := A_CDQE;
  13432. clearop(0);
  13433. clearop(1);
  13434. ops := 0;
  13435. Result := True;
  13436. end;
  13437. {$endif x86_64}
  13438. else
  13439. ;
  13440. end;
  13441. end;
  13442. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13443. var
  13444. hp1, hp2: tai;
  13445. IdentityMask, Shift: TCGInt;
  13446. LimitSize: Topsize;
  13447. DoNotMerge: Boolean;
  13448. begin
  13449. Result := False;
  13450. { All these optimisations work on "shr const,%reg" }
  13451. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13452. Exit;
  13453. DoNotMerge := False;
  13454. Shift := taicpu(p).oper[0]^.val;
  13455. LimitSize := taicpu(p).opsize;
  13456. hp1 := p;
  13457. repeat
  13458. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13459. Break;
  13460. { Detect:
  13461. shr x, %reg
  13462. and y, %reg
  13463. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13464. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13465. }
  13466. case taicpu(hp1).opcode of
  13467. A_AND:
  13468. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13469. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13470. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13471. begin
  13472. { Make sure the FLAGS register isn't in use }
  13473. TransferUsedRegs(TmpUsedRegs);
  13474. hp2 := p;
  13475. repeat
  13476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13477. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13478. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13479. begin
  13480. { Generate the identity mask }
  13481. case taicpu(p).opsize of
  13482. S_B:
  13483. IdentityMask := $FF shr Shift;
  13484. S_W:
  13485. IdentityMask := $FFFF shr Shift;
  13486. S_L:
  13487. IdentityMask := $FFFFFFFF shr Shift;
  13488. {$ifdef x86_64}
  13489. S_Q:
  13490. { We need to force the operands to be unsigned 64-bit
  13491. integers otherwise the wrong value is generated }
  13492. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13493. {$endif x86_64}
  13494. else
  13495. InternalError(2022081501);
  13496. end;
  13497. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13498. begin
  13499. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13500. { All the possible 1 bits are covered, so we can remove the AND }
  13501. hp2 := tai(hp1.Previous);
  13502. RemoveInstruction(hp1);
  13503. { p wasn't actually changed, so don't set Result to True,
  13504. but a change was nonetheless made elsewhere }
  13505. Include(OptsToCheck, aoc_ForceNewIteration);
  13506. { Do another pass in case other AND or MOVZX instructions
  13507. follow }
  13508. hp1 := hp2;
  13509. Continue;
  13510. end;
  13511. end;
  13512. end;
  13513. A_TEST, A_CMP, A_Jcc:
  13514. { Skip over conditional jumps and relevant comparisons }
  13515. Continue;
  13516. A_MOVZX:
  13517. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13518. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13519. begin
  13520. { Since the original register is being read as is, subsequent
  13521. SHRs must not be merged at this point }
  13522. DoNotMerge := True;
  13523. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13524. begin
  13525. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13526. begin
  13527. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13528. { All the possible 1 bits are covered, so we can remove the AND }
  13529. hp2 := tai(hp1.Previous);
  13530. RemoveInstruction(hp1);
  13531. hp1 := hp2;
  13532. end
  13533. else { Different register target }
  13534. begin
  13535. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13536. taicpu(hp1).opcode := A_MOV;
  13537. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13538. case taicpu(hp1).opsize of
  13539. S_BW:
  13540. taicpu(hp1).opsize := S_W;
  13541. S_BL, S_WL:
  13542. taicpu(hp1).opsize := S_L;
  13543. else
  13544. InternalError(2022081503);
  13545. end;
  13546. end;
  13547. end
  13548. else if (Shift > 0) and
  13549. (taicpu(p).opsize = S_W) and
  13550. (taicpu(hp1).opsize = S_WL) and
  13551. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13552. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13553. begin
  13554. { Detect:
  13555. shr x, %ax (x > 0)
  13556. ...
  13557. movzwl %ax,%eax
  13558. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13559. }
  13560. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13561. taicpu(hp1).opcode := A_CWDE;
  13562. taicpu(hp1).clearop(0);
  13563. taicpu(hp1).clearop(1);
  13564. taicpu(hp1).ops := 0;
  13565. end;
  13566. { Move onto the next instruction }
  13567. Continue;
  13568. end;
  13569. A_SHL, A_SAL, A_SHR:
  13570. if (taicpu(hp1).opsize <= LimitSize) and
  13571. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13572. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13573. begin
  13574. { Make sure the sizes don't exceed the register size limit
  13575. (measured by the shift value falling below the limit) }
  13576. if taicpu(hp1).opsize < LimitSize then
  13577. LimitSize := taicpu(hp1).opsize;
  13578. if taicpu(hp1).opcode = A_SHR then
  13579. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13580. else
  13581. begin
  13582. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13583. DoNotMerge := True;
  13584. end;
  13585. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13586. Break;
  13587. { Since we've established that the combined shift is within
  13588. limits, we can actually combine the adjacent SHR
  13589. instructions even if they're different sizes }
  13590. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13591. begin
  13592. hp2 := tai(hp1.Previous);
  13593. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13594. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13595. RemoveInstruction(hp1);
  13596. hp1 := hp2;
  13597. end;
  13598. { Move onto the next instruction }
  13599. Continue;
  13600. end;
  13601. else
  13602. ;
  13603. end;
  13604. Break;
  13605. until False;
  13606. { Detect the following (looking backwards):
  13607. shr %cl,%reg
  13608. shr x, %reg
  13609. Swap the two SHR instructions to minimise a pipeline stall.
  13610. }
  13611. if GetLastInstruction(p, hp1) and
  13612. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13613. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13614. { First operand will be %cl }
  13615. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13616. { Just to be sure }
  13617. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13618. begin
  13619. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13620. { Moving the entries this way ensures the register tracking remains correct }
  13621. Asml.Remove(p);
  13622. Asml.InsertBefore(p, hp1);
  13623. p := hp1;
  13624. { Don't set Result to True because the current instruction is now
  13625. "shr %cl,%reg" and there's nothing more we can do with it }
  13626. end;
  13627. end;
  13628. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13629. var
  13630. hp1, hp2: tai;
  13631. Opposite, SecondOpposite: TAsmOp;
  13632. NewCond: TAsmCond;
  13633. begin
  13634. Result := False;
  13635. { Change:
  13636. add/sub 128,(dest)
  13637. To:
  13638. sub/add -128,(dest)
  13639. This generaally takes fewer bytes to encode because -128 can be stored
  13640. in a signed byte, whereas +128 cannot.
  13641. }
  13642. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13643. begin
  13644. if taicpu(p).opcode = A_ADD then
  13645. Opposite := A_SUB
  13646. else
  13647. Opposite := A_ADD;
  13648. { Be careful if the flags are in use, because the CF flag inverts
  13649. when changing from ADD to SUB and vice versa }
  13650. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13651. GetNextInstruction(p, hp1) then
  13652. begin
  13653. TransferUsedRegs(TmpUsedRegs);
  13654. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13655. hp2 := hp1;
  13656. { Scan ahead to check if everything's safe }
  13657. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13658. begin
  13659. if (hp1.typ <> ait_instruction) then
  13660. { Probably unsafe since the flags are still in use }
  13661. Exit;
  13662. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13663. { Stop searching at an unconditional jump }
  13664. Break;
  13665. if not
  13666. (
  13667. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13668. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13669. ) and
  13670. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13671. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13672. Exit;
  13673. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13674. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13675. { Move to the next instruction }
  13676. GetNextInstruction(hp1, hp1);
  13677. end;
  13678. while Assigned(hp2) and (hp2 <> hp1) do
  13679. begin
  13680. NewCond := C_None;
  13681. case taicpu(hp2).condition of
  13682. C_A, C_NBE:
  13683. NewCond := C_BE;
  13684. C_B, C_C, C_NAE:
  13685. NewCond := C_AE;
  13686. C_AE, C_NB, C_NC:
  13687. NewCond := C_B;
  13688. C_BE, C_NA:
  13689. NewCond := C_A;
  13690. else
  13691. { No change needed };
  13692. end;
  13693. if NewCond <> C_None then
  13694. begin
  13695. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13696. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13697. taicpu(hp2).condition := NewCond;
  13698. end
  13699. else
  13700. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13701. begin
  13702. { Because of the flipping of the carry bit, to ensure
  13703. the operation remains equivalent, ADC becomes SBB
  13704. and vice versa, and the constant is not-inverted.
  13705. If multiple ADCs or SBBs appear in a row, each one
  13706. changed causes the carry bit to invert, so they all
  13707. need to be flipped }
  13708. if taicpu(hp2).opcode = A_ADC then
  13709. SecondOpposite := A_SBB
  13710. else
  13711. SecondOpposite := A_ADC;
  13712. if taicpu(hp2).oper[0]^.typ <> top_const then
  13713. { Should have broken out of this optimisation already }
  13714. InternalError(2021112901);
  13715. 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]^) + ' -> ' +
  13716. 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);
  13717. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13718. taicpu(hp2).opcode := SecondOpposite;
  13719. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13720. end;
  13721. { Move to the next instruction }
  13722. GetNextInstruction(hp2, hp2);
  13723. end;
  13724. if (hp2 <> hp1) then
  13725. InternalError(2021111501);
  13726. end;
  13727. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13728. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13729. taicpu(p).opcode := Opposite;
  13730. taicpu(p).oper[0]^.val := -128;
  13731. { No further optimisations can be made on this instruction, so move
  13732. onto the next one to save time }
  13733. p := tai(p.Next);
  13734. UpdateUsedRegs(p);
  13735. Result := True;
  13736. Exit;
  13737. end;
  13738. { Detect:
  13739. add/sub %reg2,(dest)
  13740. add/sub x, (dest)
  13741. (dest can be a register or a reference)
  13742. Swap the instructions to minimise a pipeline stall. This reverses the
  13743. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13744. optimisations could be made.
  13745. }
  13746. if (taicpu(p).oper[0]^.typ = top_reg) and
  13747. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13748. (
  13749. (
  13750. (taicpu(p).oper[1]^.typ = top_reg) and
  13751. { We can try searching further ahead if we're writing to a register }
  13752. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13753. ) or
  13754. (
  13755. (taicpu(p).oper[1]^.typ = top_ref) and
  13756. GetNextInstruction(p, hp1)
  13757. )
  13758. ) and
  13759. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13760. (taicpu(hp1).oper[0]^.typ = top_const) and
  13761. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13762. begin
  13763. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13764. TransferUsedRegs(TmpUsedRegs);
  13765. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13766. hp2 := p;
  13767. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13768. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13769. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13770. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13771. begin
  13772. asml.remove(hp1);
  13773. asml.InsertBefore(hp1, p);
  13774. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13775. Result := True;
  13776. end;
  13777. end;
  13778. end;
  13779. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13780. var
  13781. hp1: tai;
  13782. begin
  13783. Result:=false;
  13784. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13785. while GetNextInstruction(p, hp1) and
  13786. TrySwapMovCmp(p, hp1) do
  13787. begin
  13788. if MatchInstruction(hp1, A_MOV, []) then
  13789. begin
  13790. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13791. begin
  13792. { A little hacky, but since CMP doesn't read the flags, only
  13793. modify them, it's safe if they get scrambled by MOV -> XOR }
  13794. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13795. Result := PostPeepholeOptMov(hp1);
  13796. {$ifdef x86_64}
  13797. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13798. { Used to shrink instruction size }
  13799. PostPeepholeOptXor(hp1);
  13800. {$endif x86_64}
  13801. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13802. end
  13803. else
  13804. begin
  13805. Result := PostPeepholeOptMov(hp1);
  13806. {$ifdef x86_64}
  13807. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13808. { Used to shrink instruction size }
  13809. PostPeepholeOptXor(hp1);
  13810. {$endif x86_64}
  13811. end;
  13812. end;
  13813. { Enabling this flag is actually a null operation, but it marks
  13814. the code as 'modified' during this pass }
  13815. Include(OptsToCheck, aoc_ForceNewIteration);
  13816. end;
  13817. { change "cmp $0, %reg" to "test %reg, %reg" }
  13818. if MatchOpType(taicpu(p),top_const,top_reg) and
  13819. (taicpu(p).oper[0]^.val = 0) then
  13820. begin
  13821. taicpu(p).opcode := A_TEST;
  13822. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13823. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13824. Result:=true;
  13825. end;
  13826. end;
  13827. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13828. var
  13829. IsTestConstX, IsValid : Boolean;
  13830. hp1,hp2 : tai;
  13831. begin
  13832. Result:=false;
  13833. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13834. if (taicpu(p).opcode = A_TEST) then
  13835. while GetNextInstruction(p, hp1) and
  13836. TrySwapMovCmp(p, hp1) do
  13837. begin
  13838. if MatchInstruction(hp1, A_MOV, []) then
  13839. begin
  13840. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13841. begin
  13842. { A little hacky, but since TEST doesn't read the flags, only
  13843. modify them, it's safe if they get scrambled by MOV -> XOR }
  13844. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13845. Result := PostPeepholeOptMov(hp1);
  13846. {$ifdef x86_64}
  13847. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13848. { Used to shrink instruction size }
  13849. PostPeepholeOptXor(hp1);
  13850. {$endif x86_64}
  13851. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13852. end
  13853. else
  13854. begin
  13855. Result := PostPeepholeOptMov(hp1);
  13856. {$ifdef x86_64}
  13857. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13858. { Used to shrink instruction size }
  13859. PostPeepholeOptXor(hp1);
  13860. {$endif x86_64}
  13861. end;
  13862. end;
  13863. { Enabling this flag is actually a null operation, but it marks
  13864. the code as 'modified' during this pass }
  13865. Include(OptsToCheck, aoc_ForceNewIteration);
  13866. end;
  13867. { If x is a power of 2 (popcnt = 1), change:
  13868. or $x, %reg/ref
  13869. To:
  13870. bts lb(x), %reg/ref
  13871. }
  13872. if (taicpu(p).opcode = A_OR) and
  13873. IsBTXAcceptable(p) and
  13874. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13875. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13876. (
  13877. { Don't optimise if a test instruction follows }
  13878. not GetNextInstruction(p, hp1) or
  13879. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13880. ) then
  13881. begin
  13882. 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);
  13883. taicpu(p).opcode := A_BTS;
  13884. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13885. Result := True;
  13886. Exit;
  13887. end;
  13888. { If x is a power of 2 (popcnt = 1), change:
  13889. test $x, %reg/ref
  13890. je / sete / cmove (or jne / setne)
  13891. To:
  13892. bt lb(x), %reg/ref
  13893. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13894. }
  13895. if (taicpu(p).opcode = A_TEST) and
  13896. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13897. (taicpu(p).oper[0]^.typ = top_const) and
  13898. (
  13899. (cs_opt_size in current_settings.optimizerswitches) or
  13900. (
  13901. (taicpu(p).oper[1]^.typ = top_reg) and
  13902. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13903. ) or
  13904. (
  13905. (taicpu(p).oper[1]^.typ <> top_reg) and
  13906. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13907. )
  13908. ) and
  13909. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13910. { For sizes less than S_L, the byte size is equal or larger with BT,
  13911. so don't bother optimising }
  13912. (taicpu(p).opsize >= S_L) then
  13913. begin
  13914. IsValid := True;
  13915. { Check the next set of instructions, watching the FLAGS register
  13916. and the conditions used }
  13917. TransferUsedRegs(TmpUsedRegs);
  13918. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13919. hp1 := p;
  13920. hp2 := nil;
  13921. while GetNextInstruction(hp1, hp1) do
  13922. begin
  13923. if not Assigned(hp2) then
  13924. { The first instruction after TEST }
  13925. hp2 := hp1;
  13926. if (hp1.typ <> ait_instruction) then
  13927. begin
  13928. { If the flags are no longer in use, everything is fine }
  13929. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13930. IsValid := False;
  13931. Break;
  13932. end;
  13933. case taicpu(hp1).condition of
  13934. C_None:
  13935. begin
  13936. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13937. { Something is not quite normal, so play safe and don't change }
  13938. IsValid := False;
  13939. Break;
  13940. end;
  13941. C_E, C_Z, C_NE, C_NZ:
  13942. { This is fine };
  13943. else
  13944. begin
  13945. { Unsupported condition }
  13946. IsValid := False;
  13947. Break;
  13948. end;
  13949. end;
  13950. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13951. end;
  13952. if IsValid then
  13953. begin
  13954. while hp2 <> hp1 do
  13955. begin
  13956. case taicpu(hp2).condition of
  13957. C_Z, C_E:
  13958. taicpu(hp2).condition := C_NC;
  13959. C_NZ, C_NE:
  13960. taicpu(hp2).condition := C_C;
  13961. else
  13962. { Should not get this by this point }
  13963. InternalError(2022110701);
  13964. end;
  13965. GetNextInstruction(hp2, hp2);
  13966. end;
  13967. 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);
  13968. taicpu(p).opcode := A_BT;
  13969. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13970. Result := True;
  13971. Exit;
  13972. end;
  13973. end;
  13974. { removes the line marked with (x) from the sequence
  13975. and/or/xor/add/sub/... $x, %y
  13976. test/or %y, %y | test $-1, %y (x)
  13977. j(n)z _Label
  13978. as the first instruction already adjusts the ZF
  13979. %y operand may also be a reference }
  13980. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13981. MatchOperand(taicpu(p).oper[0]^,-1);
  13982. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13983. GetLastInstruction(p, hp1) and
  13984. (tai(hp1).typ = ait_instruction) and
  13985. GetNextInstruction(p,hp2) and
  13986. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13987. case taicpu(hp1).opcode Of
  13988. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13989. { These two instructions set the zero flag if the result is zero }
  13990. A_POPCNT, A_LZCNT:
  13991. begin
  13992. if (
  13993. { With POPCNT, an input of zero will set the zero flag
  13994. because the population count of zero is zero }
  13995. (taicpu(hp1).opcode = A_POPCNT) and
  13996. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13997. (
  13998. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13999. { Faster than going through the second half of the 'or'
  14000. condition below }
  14001. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14002. )
  14003. ) or (
  14004. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14005. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14006. { and in case of carry for A(E)/B(E)/C/NC }
  14007. (
  14008. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14009. (
  14010. (taicpu(hp1).opcode <> A_ADD) and
  14011. (taicpu(hp1).opcode <> A_SUB) and
  14012. (taicpu(hp1).opcode <> A_LZCNT)
  14013. )
  14014. )
  14015. ) then
  14016. begin
  14017. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14018. RemoveCurrentP(p, hp2);
  14019. Result:=true;
  14020. Exit;
  14021. end;
  14022. end;
  14023. A_SHL, A_SAL, A_SHR, A_SAR:
  14024. begin
  14025. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14026. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14027. { therefore, it's only safe to do this optimization for }
  14028. { shifts by a (nonzero) constant }
  14029. (taicpu(hp1).oper[0]^.typ = top_const) and
  14030. (taicpu(hp1).oper[0]^.val <> 0) and
  14031. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14032. { and in case of carry for A(E)/B(E)/C/NC }
  14033. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14034. begin
  14035. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14036. RemoveCurrentP(p, hp2);
  14037. Result:=true;
  14038. Exit;
  14039. end;
  14040. end;
  14041. A_DEC, A_INC, A_NEG:
  14042. begin
  14043. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14044. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14045. { and in case of carry for A(E)/B(E)/C/NC }
  14046. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14047. begin
  14048. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14049. RemoveCurrentP(p, hp2);
  14050. Result:=true;
  14051. Exit;
  14052. end;
  14053. end;
  14054. A_ANDN, A_BZHI:
  14055. begin
  14056. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14057. { Only the zero and sign flags are consistent with what the result is }
  14058. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14059. begin
  14060. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14061. RemoveCurrentP(p, hp2);
  14062. Result:=true;
  14063. Exit;
  14064. end;
  14065. end;
  14066. A_BEXTR:
  14067. begin
  14068. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14069. { Only the zero flag is set }
  14070. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14071. begin
  14072. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14073. RemoveCurrentP(p, hp2);
  14074. Result:=true;
  14075. Exit;
  14076. end;
  14077. end;
  14078. else
  14079. ;
  14080. end; { case }
  14081. { change "test $-1,%reg" into "test %reg,%reg" }
  14082. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14083. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14084. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14085. if MatchInstruction(p, A_OR, []) and
  14086. { Can only match if they're both registers }
  14087. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14088. begin
  14089. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14090. taicpu(p).opcode := A_TEST;
  14091. { No need to set Result to True, as we've done all the optimisations we can }
  14092. end;
  14093. end;
  14094. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14095. var
  14096. hp1,hp3 : tai;
  14097. {$ifndef x86_64}
  14098. hp2 : taicpu;
  14099. {$endif x86_64}
  14100. begin
  14101. Result:=false;
  14102. hp3:=nil;
  14103. {$ifndef x86_64}
  14104. { don't do this on modern CPUs, this really hurts them due to
  14105. broken call/ret pairing }
  14106. if (current_settings.optimizecputype < cpu_Pentium2) and
  14107. not(cs_create_pic in current_settings.moduleswitches) and
  14108. GetNextInstruction(p, hp1) and
  14109. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14110. MatchOpType(taicpu(hp1),top_ref) and
  14111. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14112. begin
  14113. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14114. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14115. InsertLLItem(p.previous, p, hp2);
  14116. taicpu(p).opcode := A_JMP;
  14117. taicpu(p).is_jmp := true;
  14118. RemoveInstruction(hp1);
  14119. Result:=true;
  14120. end
  14121. else
  14122. {$endif x86_64}
  14123. { replace
  14124. call procname
  14125. ret
  14126. by
  14127. jmp procname
  14128. but do it only on level 4 because it destroys stack back traces
  14129. else if the subroutine is marked as no return, remove the ret
  14130. }
  14131. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14132. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14133. GetNextInstruction(p, hp1) and
  14134. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14135. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14136. SetAndTest(hp1,hp3) and
  14137. GetNextInstruction(hp1,hp1) and
  14138. MatchInstruction(hp1,A_RET,[S_NO])
  14139. )
  14140. ) and
  14141. (taicpu(hp1).ops=0) then
  14142. begin
  14143. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14144. { we might destroy stack alignment here if we do not do a call }
  14145. (target_info.stackalign<=sizeof(SizeUInt)) then
  14146. begin
  14147. taicpu(p).opcode := A_JMP;
  14148. taicpu(p).is_jmp := true;
  14149. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14150. end
  14151. else
  14152. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14153. RemoveInstruction(hp1);
  14154. if Assigned(hp3) then
  14155. begin
  14156. AsmL.Remove(hp3);
  14157. AsmL.InsertBefore(hp3,p)
  14158. end;
  14159. Result:=true;
  14160. end;
  14161. end;
  14162. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14163. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14164. begin
  14165. case OpSize of
  14166. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14167. Result := (Val <= $FF) and (Val >= -128);
  14168. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14169. Result := (Val <= $FFFF) and (Val >= -32768);
  14170. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14171. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14172. else
  14173. Result := True;
  14174. end;
  14175. end;
  14176. var
  14177. hp1, hp2 : tai;
  14178. SizeChange: Boolean;
  14179. PreMessage: string;
  14180. begin
  14181. Result := False;
  14182. if (taicpu(p).oper[0]^.typ = top_reg) and
  14183. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14184. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14185. begin
  14186. { Change (using movzbl %al,%eax as an example):
  14187. movzbl %al, %eax movzbl %al, %eax
  14188. cmpl x, %eax testl %eax,%eax
  14189. To:
  14190. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14191. movzbl %al, %eax movzbl %al, %eax
  14192. Smaller instruction and minimises pipeline stall as the CPU
  14193. doesn't have to wait for the register to get zero-extended. [Kit]
  14194. Also allow if the smaller of the two registers is being checked,
  14195. as this still removes the false dependency.
  14196. }
  14197. if
  14198. (
  14199. (
  14200. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14201. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14202. ) or (
  14203. { If MatchOperand returns True, they must both be registers }
  14204. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14205. )
  14206. ) and
  14207. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14208. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14209. begin
  14210. 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);
  14211. asml.Remove(hp1);
  14212. asml.InsertBefore(hp1, p);
  14213. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14214. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14215. begin
  14216. taicpu(hp1).opcode := A_TEST;
  14217. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14218. end;
  14219. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14220. case taicpu(p).opsize of
  14221. S_BW, S_BL:
  14222. begin
  14223. SizeChange := taicpu(hp1).opsize <> S_B;
  14224. taicpu(hp1).changeopsize(S_B);
  14225. end;
  14226. S_WL:
  14227. begin
  14228. SizeChange := taicpu(hp1).opsize <> S_W;
  14229. taicpu(hp1).changeopsize(S_W);
  14230. end
  14231. else
  14232. InternalError(2020112701);
  14233. end;
  14234. UpdateUsedRegs(tai(p.Next));
  14235. { Check if the register is used aferwards - if not, we can
  14236. remove the movzx instruction completely }
  14237. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14238. begin
  14239. { Hp1 is a better position than p for debugging purposes }
  14240. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14241. RemoveCurrentp(p, hp1);
  14242. Result := True;
  14243. end;
  14244. if SizeChange then
  14245. DebugMsg(SPeepholeOptimization + PreMessage +
  14246. 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)
  14247. else
  14248. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14249. Exit;
  14250. end;
  14251. { Change (using movzwl %ax,%eax as an example):
  14252. movzwl %ax, %eax
  14253. movb %al, (dest) (Register is smaller than read register in movz)
  14254. To:
  14255. movb %al, (dest) (Move one back to avoid a false dependency)
  14256. movzwl %ax, %eax
  14257. }
  14258. if (taicpu(hp1).opcode = A_MOV) and
  14259. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14260. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14261. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14262. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14263. begin
  14264. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14265. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14266. asml.Remove(hp1);
  14267. asml.InsertBefore(hp1, p);
  14268. if taicpu(hp1).oper[1]^.typ = top_reg then
  14269. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14270. { Check if the register is used aferwards - if not, we can
  14271. remove the movzx instruction completely }
  14272. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14273. begin
  14274. { Hp1 is a better position than p for debugging purposes }
  14275. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14276. RemoveCurrentp(p, hp1);
  14277. Result := True;
  14278. end;
  14279. Exit;
  14280. end;
  14281. end;
  14282. end;
  14283. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14284. var
  14285. hp1: tai;
  14286. {$ifdef x86_64}
  14287. PreMessage, RegName: string;
  14288. {$endif x86_64}
  14289. begin
  14290. Result := False;
  14291. { If x is a power of 2 (popcnt = 1), change:
  14292. xor $x, %reg/ref
  14293. To:
  14294. btc lb(x), %reg/ref
  14295. }
  14296. if IsBTXAcceptable(p) and
  14297. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14298. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14299. (
  14300. { Don't optimise if a test instruction follows }
  14301. not GetNextInstruction(p, hp1) or
  14302. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14303. ) then
  14304. begin
  14305. 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);
  14306. taicpu(p).opcode := A_BTC;
  14307. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14308. Result := True;
  14309. Exit;
  14310. end;
  14311. {$ifdef x86_64}
  14312. { Code size reduction by J. Gareth "Kit" Moreton }
  14313. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14314. as this removes the REX prefix }
  14315. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14316. Exit;
  14317. if taicpu(p).oper[0]^.typ <> top_reg then
  14318. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14319. InternalError(2018011500);
  14320. case taicpu(p).opsize of
  14321. S_Q:
  14322. begin
  14323. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14324. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14325. { The actual optimization }
  14326. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14327. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14328. taicpu(p).changeopsize(S_L);
  14329. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14330. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14331. end;
  14332. else
  14333. ;
  14334. end;
  14335. {$endif x86_64}
  14336. end;
  14337. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14338. var
  14339. XReg: TRegister;
  14340. begin
  14341. Result := False;
  14342. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14343. Smaller encoding and slightly faster on some platforms (also works for
  14344. ZMM-sized registers) }
  14345. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14346. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14347. begin
  14348. XReg := taicpu(p).oper[0]^.reg;
  14349. if (taicpu(p).oper[1]^.reg = XReg) then
  14350. begin
  14351. taicpu(p).changeopsize(S_XMM);
  14352. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14353. if (cs_opt_size in current_settings.optimizerswitches) then
  14354. begin
  14355. { Change input registers to %xmm0 to reduce size. Note that
  14356. there's a risk of a false dependency doing this, so only
  14357. optimise for size here }
  14358. XReg := NR_XMM0;
  14359. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14360. end
  14361. else
  14362. begin
  14363. setsubreg(XReg, R_SUBMMX);
  14364. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14365. end;
  14366. taicpu(p).oper[0]^.reg := XReg;
  14367. taicpu(p).oper[1]^.reg := XReg;
  14368. Result := True;
  14369. end;
  14370. end;
  14371. end;
  14372. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14373. var
  14374. OperIdx: Integer;
  14375. begin
  14376. for OperIdx := 0 to p.ops - 1 do
  14377. if p.oper[OperIdx]^.typ = top_ref then
  14378. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14379. end;
  14380. end.