aoptx86.pas 720 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1_V_MOVAP(var p : tai) : boolean;
  128. function OptPass1VOP(var p : tai) : boolean;
  129. function OptPass1MOV(var p : tai) : boolean;
  130. function OptPass1Movx(var p : tai) : boolean;
  131. function OptPass1MOVXX(var p : tai) : boolean;
  132. function OptPass1OP(var p : tai) : boolean;
  133. function OptPass1LEA(var p : tai) : boolean;
  134. function OptPass1Sub(var p : tai) : boolean;
  135. function OptPass1SHLSAL(var p : tai) : boolean;
  136. function OptPass1SHR(var p : tai) : boolean;
  137. function OptPass1FSTP(var p : tai) : boolean;
  138. function OptPass1FLD(var p : tai) : boolean;
  139. function OptPass1Cmp(var p : tai) : boolean;
  140. function OptPass1PXor(var p : tai) : boolean;
  141. function OptPass1VPXor(var p: tai): boolean;
  142. function OptPass1Imul(var p : tai) : boolean;
  143. function OptPass1Jcc(var p : tai) : boolean;
  144. function OptPass1SHXX(var p: tai): boolean;
  145. function OptPass1VMOVDQ(var p: tai): Boolean;
  146. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  147. function OptPass1STCCLC(var p: tai): Boolean;
  148. function OptPass2STCCLC(var p: tai): Boolean;
  149. function OptPass2Movx(var p : tai): Boolean;
  150. function OptPass2MOV(var p : tai) : boolean;
  151. function OptPass2Imul(var p : tai) : boolean;
  152. function OptPass2Jmp(var p : tai) : boolean;
  153. function OptPass2Jcc(var p : tai) : boolean;
  154. function OptPass2Lea(var p: tai): Boolean;
  155. function OptPass2SUB(var p: tai): Boolean;
  156. function OptPass2ADD(var p : tai): Boolean;
  157. function OptPass2SETcc(var p : tai) : boolean;
  158. function OptPass2Cmp(var p: tai): Boolean;
  159. function OptPass2Test(var p: tai): Boolean;
  160. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  161. function PostPeepholeOptMov(var p : tai) : Boolean;
  162. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  163. function PostPeepholeOptXor(var p : tai) : Boolean;
  164. function PostPeepholeOptAnd(var p : tai) : boolean;
  165. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  166. function PostPeepholeOptCmp(var p : tai) : Boolean;
  167. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  168. function PostPeepholeOptCall(var p : tai) : Boolean;
  169. function PostPeepholeOptLea(var p : tai) : Boolean;
  170. function PostPeepholeOptPush(var p: tai): Boolean;
  171. function PostPeepholeOptShr(var p : tai) : boolean;
  172. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  173. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  174. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  175. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  176. function TrySwapMovOp(var p, hp1: tai): Boolean;
  177. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  178. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  179. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  180. { Processor-dependent reference optimisation }
  181. class procedure OptimizeRefs(var p: taicpu); static;
  182. end;
  183. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  184. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  185. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  187. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  188. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  189. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  190. {$if max_operands>2}
  191. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  192. {$endif max_operands>2}
  193. function RefsEqual(const r1, r2: treference): boolean;
  194. { Note that Result is set to True if the references COULD overlap but the
  195. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  196. might still overlap because %reg2 could be equal to %reg1-4 }
  197. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  198. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  199. { returns true, if ref is a reference using only the registers passed as base and index
  200. and having an offset }
  201. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  202. implementation
  203. uses
  204. cutils,verbose,
  205. systems,
  206. globals,
  207. cpuinfo,
  208. procinfo,
  209. paramgr,
  210. aasmbase,
  211. aoptbase,aoptutils,
  212. symconst,symsym,
  213. cgx86,
  214. itcpugas;
  215. {$ifndef 8086}
  216. const
  217. MAX_CMOV_INSTRUCTIONS = 4;
  218. MAX_CMOV_REGISTERS = 8;
  219. type
  220. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  221. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  222. tsProcessed);
  223. { For OptPass2Jcc }
  224. TCMOVTracking = object
  225. private
  226. CMOVScore, ConstCount: LongInt;
  227. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  228. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  229. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  230. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  231. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  232. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  233. fOptimizer: TX86AsmOptimizer;
  234. fLabel: TAsmSymbol;
  235. fInsertionPoint,
  236. fCondition,
  237. fInitialJump,
  238. fFirstMovBlock,
  239. fFirstMovBlockStop,
  240. fSecondJump,
  241. fThirdJump,
  242. fSecondMovBlock,
  243. fSecondMovBlockStop,
  244. fMidLabel,
  245. fEndLabel,
  246. fAllocationRange: tai;
  247. fState: TCMovTrackingState;
  248. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  249. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  250. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  251. public
  252. RegisterTracking: TAllUsedRegs;
  253. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  254. destructor Done;
  255. procedure Process(out new_p: tai);
  256. property State: TCMovTrackingState read fState;
  257. end;
  258. PCMOVTracking = ^TCMOVTracking;
  259. {$endif 8086}
  260. {$ifdef DEBUG_AOPTCPU}
  261. const
  262. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  263. {$else DEBUG_AOPTCPU}
  264. { Empty strings help the optimizer to remove string concatenations that won't
  265. ever appear to the user on release builds. [Kit] }
  266. const
  267. SPeepholeOptimization = '';
  268. {$endif DEBUG_AOPTCPU}
  269. LIST_STEP_SIZE = 4;
  270. type
  271. TJumpTrackingItem = class(TLinkedListItem)
  272. private
  273. FSymbol: TAsmSymbol;
  274. FRefs: LongInt;
  275. public
  276. constructor Create(ASymbol: TAsmSymbol);
  277. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  278. property Symbol: TAsmSymbol read FSymbol;
  279. property Refs: LongInt read FRefs;
  280. end;
  281. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  282. begin
  283. inherited Create;
  284. FSymbol := ASymbol;
  285. FRefs := 0;
  286. end;
  287. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. begin
  289. Inc(FRefs);
  290. end;
  291. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  292. begin
  293. result :=
  294. (instr.typ = ait_instruction) and
  295. (taicpu(instr).opcode = op) and
  296. ((opsize = []) or (taicpu(instr).opsize in opsize));
  297. end;
  298. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  299. begin
  300. result :=
  301. (instr.typ = ait_instruction) and
  302. ((taicpu(instr).opcode = op1) or
  303. (taicpu(instr).opcode = op2)
  304. ) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. ((taicpu(instr).opcode = op1) or
  312. (taicpu(instr).opcode = op2) or
  313. (taicpu(instr).opcode = op3)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  318. const opsize : topsizes) : boolean;
  319. var
  320. op : TAsmOp;
  321. begin
  322. result:=false;
  323. if (instr.typ <> ait_instruction) or
  324. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  325. exit;
  326. for op in ops do
  327. begin
  328. if taicpu(instr).opcode = op then
  329. begin
  330. result:=true;
  331. exit;
  332. end;
  333. end;
  334. end;
  335. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  336. begin
  337. result := (oper.typ = top_reg) and (oper.reg = reg);
  338. end;
  339. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  340. begin
  341. result := (oper.typ = top_const) and (oper.val = a);
  342. end;
  343. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  344. begin
  345. result := oper1.typ = oper2.typ;
  346. if result then
  347. case oper1.typ of
  348. top_const:
  349. Result:=oper1.val = oper2.val;
  350. top_reg:
  351. Result:=oper1.reg = oper2.reg;
  352. top_ref:
  353. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  354. else
  355. internalerror(2013102801);
  356. end
  357. end;
  358. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  359. begin
  360. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  361. if result then
  362. case oper1.typ of
  363. top_const:
  364. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  365. top_reg:
  366. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  367. top_ref:
  368. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  369. else
  370. internalerror(2020052401);
  371. end
  372. end;
  373. function RefsEqual(const r1, r2: treference): boolean;
  374. begin
  375. RefsEqual :=
  376. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  377. (r1.relsymbol = r2.relsymbol) and
  378. (r1.segment = r2.segment) and (r1.base = r2.base) and
  379. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  380. (r1.offset = r2.offset) and
  381. (r1.volatility + r2.volatility = []);
  382. end;
  383. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  384. begin
  385. if (r1.symbol<>r2.symbol) then
  386. { If the index registers are different, there's a chance one could
  387. be set so it equals the other symbol }
  388. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  389. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  390. (r1.relsymbol = r2.relsymbol) and
  391. (r1.segment = r2.segment) and (r1.base = r2.base) and
  392. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  393. (r1.volatility + r2.volatility = []) then
  394. { In this case, it all depends on the offsets }
  395. Exit(abs(r1.offset - r2.offset) < Range);
  396. { There's a chance things MIGHT overlap, so take no chances }
  397. Result := True;
  398. end;
  399. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  400. begin
  401. Result:=(ref.offset=0) and
  402. (ref.scalefactor in [0,1]) and
  403. (ref.segment=NR_NO) and
  404. (ref.symbol=nil) and
  405. (ref.relsymbol=nil) and
  406. ((base=NR_INVALID) or
  407. (ref.base=base)) and
  408. ((index=NR_INVALID) or
  409. (ref.index=index)) and
  410. (ref.volatility=[]);
  411. end;
  412. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  413. begin
  414. Result:=(ref.scalefactor in [0,1]) and
  415. (ref.segment=NR_NO) and
  416. (ref.symbol=nil) and
  417. (ref.relsymbol=nil) and
  418. ((base=NR_INVALID) or
  419. (ref.base=base)) and
  420. ((index=NR_INVALID) or
  421. (ref.index=index)) and
  422. (ref.volatility=[]);
  423. end;
  424. function InstrReadsFlags(p: tai): boolean;
  425. begin
  426. InstrReadsFlags := true;
  427. case p.typ of
  428. ait_instruction:
  429. if InsProp[taicpu(p).opcode].Ch*
  430. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  431. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  432. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  433. exit;
  434. ait_label:
  435. exit;
  436. else
  437. ;
  438. end;
  439. InstrReadsFlags := false;
  440. end;
  441. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  442. begin
  443. Next:=Current;
  444. repeat
  445. Result:=GetNextInstruction(Next,Next);
  446. until not (Result) or
  447. not(cs_opt_level3 in current_settings.optimizerswitches) or
  448. (Next.typ<>ait_instruction) or
  449. RegInInstruction(reg,Next) or
  450. is_calljmp(taicpu(Next).opcode);
  451. end;
  452. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  453. var
  454. GetNextResult: Boolean;
  455. begin
  456. Result:=0;
  457. Next:=Current;
  458. repeat
  459. GetNextResult := GetNextInstruction(Next,Next);
  460. if GetNextResult then
  461. Inc(Result)
  462. else
  463. { Must return zero upon hitting the end of the linked list without a match }
  464. Result := 0;
  465. until not (GetNextResult) or
  466. not(cs_opt_level3 in current_settings.optimizerswitches) or
  467. (Next.typ<>ait_instruction) or
  468. RegInInstruction(reg,Next) or
  469. is_calljmp(taicpu(Next).opcode);
  470. end;
  471. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  472. procedure TrackJump(Symbol: TAsmSymbol);
  473. var
  474. Search: TJumpTrackingItem;
  475. begin
  476. { See if an entry already exists in our jump tracking list
  477. (faster to search backwards due to the higher chance of
  478. matching destinations) }
  479. Search := TJumpTrackingItem(JumpTracking.Last);
  480. while Assigned(Search) do
  481. begin
  482. if Search.Symbol = Symbol then
  483. begin
  484. { Found it - remove it so it can be pushed to the front }
  485. JumpTracking.Remove(Search);
  486. Break;
  487. end;
  488. Search := TJumpTrackingItem(Search.Previous);
  489. end;
  490. if not Assigned(Search) then
  491. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  492. JumpTracking.Concat(Search);
  493. Search.IncRefs;
  494. end;
  495. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  496. var
  497. Search: TJumpTrackingItem;
  498. begin
  499. Result := False;
  500. { See if this label appears in the tracking list }
  501. Search := TJumpTrackingItem(JumpTracking.Last);
  502. while Assigned(Search) do
  503. begin
  504. if Search.Symbol = Symbol then
  505. begin
  506. { Found it - let's see what we can discover }
  507. if Search.Symbol.getrefs = Search.Refs then
  508. begin
  509. { Success - all the references are accounted for }
  510. JumpTracking.Remove(Search);
  511. Search.Free;
  512. { It is logically impossible for CrossJump to be false here
  513. because we must have run into a conditional jump for
  514. this label at some point }
  515. if not CrossJump then
  516. InternalError(2022041710);
  517. if JumpTracking.First = nil then
  518. { Tracking list is now empty - no more cross jumps }
  519. CrossJump := False;
  520. Result := True;
  521. Exit;
  522. end;
  523. { If the references don't match, it's possible to enter
  524. this label through other means, so drop out }
  525. Exit;
  526. end;
  527. Search := TJumpTrackingItem(Search.Previous);
  528. end;
  529. end;
  530. var
  531. Next_Label: tai;
  532. begin
  533. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  534. Next := Current;
  535. repeat
  536. Result := GetNextInstruction(Next,Next);
  537. if not Result then
  538. Break;
  539. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  540. if is_calljmpuncondret(taicpu(Next).opcode) then
  541. begin
  542. if (taicpu(Next).opcode = A_JMP) and
  543. { Remove dead code now to save time }
  544. RemoveDeadCodeAfterJump(taicpu(Next)) then
  545. { A jump was removed, but not the current instruction, and
  546. Result doesn't necessarily translate into an optimisation
  547. routine's Result, so use the "Force New Iteration" flag so
  548. mark a new pass }
  549. Include(OptsToCheck, aoc_ForceNewIteration);
  550. if not Assigned(JumpTracking) then
  551. begin
  552. { Cross-label optimisations often causes other optimisations
  553. to perform worse because they're not given the chance to
  554. optimise locally. In this case, don't do the cross-label
  555. optimisations yet, but flag them as a potential possibility
  556. for the next iteration of Pass 1 }
  557. if not NotFirstIteration then
  558. Include(OptsToCheck, aoc_ForceNewIteration);
  559. end
  560. else if IsJumpToLabel(taicpu(Next)) and
  561. GetNextInstruction(Next, Next_Label) then
  562. begin
  563. { If we have JMP .lbl, and the label after it has all of its
  564. references tracked, then this is probably an if-else style of
  565. block and we can keep tracking. If the label for this jump
  566. then appears later and is fully tracked, then it's the end
  567. of the if-else blocks and the code paths converge (thus
  568. marking the end of the cross-jump) }
  569. if (Next_Label.typ = ait_label) then
  570. begin
  571. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  572. begin
  573. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  574. Next := Next_Label;
  575. { CrossJump gets set to false by LabelAccountedFor if the
  576. list is completely emptied (as it indicates that all
  577. code paths have converged). We could avoid this nuance
  578. by moving the TrackJump call to before the
  579. LabelAccountedFor call, but this is slower in situations
  580. where LabelAccountedFor would return False due to the
  581. creation of a new object that is not used and destroyed
  582. soon after. }
  583. CrossJump := True;
  584. Continue;
  585. end;
  586. end
  587. else if (Next_Label.typ <> ait_marker) then
  588. { We just did a RemoveDeadCodeAfterJump, so either we find
  589. a label, the end of the procedure or some kind of marker}
  590. InternalError(2022041720);
  591. end;
  592. Result := False;
  593. Exit;
  594. end
  595. else
  596. begin
  597. if not Assigned(JumpTracking) then
  598. begin
  599. { Cross-label optimisations often causes other optimisations
  600. to perform worse because they're not given the chance to
  601. optimise locally. In this case, don't do the cross-label
  602. optimisations yet, but flag them as a potential possibility
  603. for the next iteration of Pass 1 }
  604. if not NotFirstIteration then
  605. Include(OptsToCheck, aoc_ForceNewIteration);
  606. end
  607. else if IsJumpToLabel(taicpu(Next)) then
  608. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  609. else
  610. { Conditional jumps should always be a jump to label }
  611. InternalError(2022041701);
  612. CrossJump := True;
  613. Continue;
  614. end;
  615. if Next.typ = ait_label then
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if LabelAccountedFor(tai_label(Next).labsym) then
  628. Continue;
  629. { If we reach here, we're at a label that hasn't been seen before
  630. (or JumpTracking was nil) }
  631. Break;
  632. end;
  633. until not Result or
  634. not (cs_opt_level3 in current_settings.optimizerswitches) or
  635. not (Next.typ in [ait_label, ait_instruction]) or
  636. RegInInstruction(reg,Next);
  637. end;
  638. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  639. begin
  640. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  641. begin
  642. Result:=GetNextInstruction(Current,Next);
  643. exit;
  644. end;
  645. Next:=tai(Current.Next);
  646. Result:=false;
  647. while assigned(Next) do
  648. begin
  649. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  650. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  651. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  652. exit
  653. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  654. begin
  655. Result:=true;
  656. exit;
  657. end;
  658. Next:=tai(Next.Next);
  659. end;
  660. end;
  661. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  662. begin
  663. Result:=RegReadByInstruction(reg,hp);
  664. end;
  665. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  666. var
  667. p: taicpu;
  668. opcount: longint;
  669. begin
  670. RegReadByInstruction := false;
  671. if hp.typ <> ait_instruction then
  672. exit;
  673. p := taicpu(hp);
  674. case p.opcode of
  675. A_CALL:
  676. regreadbyinstruction := true;
  677. A_IMUL:
  678. case p.ops of
  679. 1:
  680. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  681. (
  682. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  683. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  684. );
  685. 2,3:
  686. regReadByInstruction :=
  687. reginop(reg,p.oper[0]^) or
  688. reginop(reg,p.oper[1]^);
  689. else
  690. InternalError(2019112801);
  691. end;
  692. A_MUL:
  693. begin
  694. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  695. (
  696. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  697. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  698. );
  699. end;
  700. A_IDIV,A_DIV:
  701. begin
  702. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  703. (
  704. (getregtype(reg)=R_INTREGISTER) and
  705. (
  706. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  707. )
  708. );
  709. end;
  710. else
  711. begin
  712. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  713. begin
  714. RegReadByInstruction := false;
  715. exit;
  716. end;
  717. for opcount := 0 to p.ops-1 do
  718. if (p.oper[opCount]^.typ = top_ref) and
  719. RegInRef(reg,p.oper[opcount]^.ref^) then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. { special handling for SSE MOVSD }
  725. if (p.opcode=A_MOVSD) and (p.ops>0) then
  726. begin
  727. if p.ops<>2 then
  728. internalerror(2017042702);
  729. regReadByInstruction := reginop(reg,p.oper[0]^) or
  730. (
  731. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  732. );
  733. exit;
  734. end;
  735. with insprop[p.opcode] do
  736. begin
  737. case getregtype(reg) of
  738. R_INTREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_EAX:
  742. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. RS_ECX:
  748. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  749. begin
  750. RegReadByInstruction := true;
  751. exit
  752. end;
  753. RS_EDX:
  754. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  755. begin
  756. RegReadByInstruction := true;
  757. exit
  758. end;
  759. RS_EBX:
  760. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ESP:
  766. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EBP:
  772. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_ESI:
  778. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_EDI:
  784. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. end;
  790. end;
  791. R_MMREGISTER:
  792. begin
  793. case getsupreg(reg) of
  794. RS_XMM0:
  795. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  796. begin
  797. RegReadByInstruction := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. else
  803. ;
  804. end;
  805. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  806. begin
  807. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  808. begin
  809. case p.condition of
  810. C_A,C_NBE, { CF=0 and ZF=0 }
  811. C_BE,C_NA: { CF=1 or ZF=1 }
  812. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  813. C_AE,C_NB,C_NC, { CF=0 }
  814. C_B,C_NAE,C_C: { CF=1 }
  815. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  816. C_NE,C_NZ, { ZF=0 }
  817. C_E,C_Z: { ZF=1 }
  818. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  819. C_G,C_NLE, { ZF=0 and SF=OF }
  820. C_LE,C_NG: { ZF=1 or SF<>OF }
  821. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  822. C_GE,C_NL, { SF=OF }
  823. C_L,C_NGE: { SF<>OF }
  824. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  825. C_NO, { OF=0 }
  826. C_O: { OF=1 }
  827. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  828. C_NP,C_PO, { PF=0 }
  829. C_P,C_PE: { PF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  831. C_NS, { SF=0 }
  832. C_S: { SF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  834. else
  835. internalerror(2017042701);
  836. end;
  837. if RegReadByInstruction then
  838. exit;
  839. end;
  840. case getsubreg(reg) of
  841. R_SUBW,R_SUBD,R_SUBQ:
  842. RegReadByInstruction :=
  843. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  844. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  845. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  846. R_SUBFLAGCARRY:
  847. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGPARITY:
  849. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGAUXILIARY:
  851. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGZERO:
  853. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGSIGN:
  855. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGOVERFLOW:
  857. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGINTERRUPT:
  859. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGDIRECTION:
  861. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. else
  863. internalerror(2017042601);
  864. end;
  865. exit;
  866. end;
  867. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  868. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  869. (p.oper[0]^.reg=p.oper[1]^.reg) then
  870. exit;
  871. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  872. begin
  873. RegReadByInstruction := true;
  874. exit
  875. end;
  876. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  877. begin
  878. RegReadByInstruction := true;
  879. exit
  880. end;
  881. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  882. begin
  883. RegReadByInstruction := true;
  884. exit
  885. end;
  886. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  887. begin
  888. RegReadByInstruction := true;
  889. exit
  890. end;
  891. end;
  892. end;
  893. end;
  894. end;
  895. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  896. begin
  897. result:=false;
  898. if p1.typ<>ait_instruction then
  899. exit;
  900. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  901. exit(true);
  902. if (getregtype(reg)=R_INTREGISTER) and
  903. { change information for xmm movsd are not correct }
  904. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  905. begin
  906. { Handle instructions that behave differently depending on the size and operand count }
  907. case taicpu(p1).opcode of
  908. A_MUL, A_DIV, A_IDIV:
  909. if taicpu(p1).opsize = S_B then
  910. Result := (getsupreg(Reg) = RS_EAX)
  911. else
  912. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  913. A_IMUL:
  914. if taicpu(p1).ops = 1 then
  915. begin
  916. if taicpu(p1).opsize = S_B then
  917. Result := (getsupreg(Reg) = RS_EAX)
  918. else
  919. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  920. end;
  921. { If ops are greater than 1, call inherited method }
  922. else
  923. case getsupreg(reg) of
  924. { RS_EAX = RS_RAX on x86-64 }
  925. RS_EAX:
  926. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_ECX:
  928. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_EDX:
  930. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EBX:
  932. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_ESP:
  934. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_EBP:
  936. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_ESI:
  938. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_EDI:
  940. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. else
  942. ;
  943. end;
  944. end;
  945. if result then
  946. exit;
  947. end
  948. else if getregtype(reg)=R_MMREGISTER then
  949. begin
  950. case getsupreg(reg) of
  951. RS_XMM0:
  952. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. else
  954. ;
  955. end;
  956. if result then
  957. exit;
  958. end
  959. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  960. begin
  961. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  962. exit(true);
  963. case getsubreg(reg) of
  964. R_SUBFLAGCARRY:
  965. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGPARITY:
  967. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGAUXILIARY:
  969. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGZERO:
  971. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGSIGN:
  973. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGOVERFLOW:
  975. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGINTERRUPT:
  977. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGDIRECTION:
  979. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBW,R_SUBD,R_SUBQ:
  981. { Everything except the direction bits }
  982. Result:=
  983. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  984. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  985. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  986. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  987. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  988. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  989. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. else
  991. ;
  992. end;
  993. if result then
  994. exit;
  995. end
  996. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  997. exit(true);
  998. Result:=inherited RegInInstruction(Reg, p1);
  999. end;
  1000. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1001. const
  1002. WriteOps: array[0..3] of set of TInsChange =
  1003. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1004. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1005. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1006. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1007. var
  1008. OperIdx: Integer;
  1009. begin
  1010. Result := False;
  1011. if p1.typ <> ait_instruction then
  1012. exit;
  1013. with insprop[taicpu(p1).opcode] do
  1014. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1015. begin
  1016. case getsubreg(reg) of
  1017. R_SUBW,R_SUBD,R_SUBQ:
  1018. Result :=
  1019. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1020. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1021. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1022. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1023. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1024. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGCARRY:
  1026. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGPARITY:
  1028. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGAUXILIARY:
  1030. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGZERO:
  1032. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGSIGN:
  1034. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGOVERFLOW:
  1036. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGINTERRUPT:
  1038. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGDIRECTION:
  1040. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. else
  1042. internalerror(2017042602);
  1043. end;
  1044. exit;
  1045. end;
  1046. case taicpu(p1).opcode of
  1047. A_CALL:
  1048. { We could potentially set Result to False if the register in
  1049. question is non-volatile for the subroutine's calling convention,
  1050. but this would require detecting the calling convention in use and
  1051. also assuming that the routine doesn't contain malformed assembly
  1052. language, for example... so it could only be done under -O4 as it
  1053. would be considered a side-effect. [Kit] }
  1054. Result := True;
  1055. A_MOVSD:
  1056. { special handling for SSE MOVSD }
  1057. if (taicpu(p1).ops>0) then
  1058. begin
  1059. if taicpu(p1).ops<>2 then
  1060. internalerror(2017042703);
  1061. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1062. end;
  1063. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1064. so fix it here (FK)
  1065. }
  1066. A_VMOVSS,
  1067. A_VMOVSD:
  1068. begin
  1069. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1070. exit;
  1071. end;
  1072. A_MUL, A_DIV, A_IDIV:
  1073. begin
  1074. if taicpu(p1).opsize = S_B then
  1075. Result := (getsupreg(Reg) = RS_EAX)
  1076. else
  1077. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1078. end;
  1079. A_IMUL:
  1080. begin
  1081. if taicpu(p1).ops = 1 then
  1082. begin
  1083. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1084. end
  1085. else
  1086. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1087. Exit;
  1088. end;
  1089. else
  1090. ;
  1091. end;
  1092. if Result then
  1093. exit;
  1094. with insprop[taicpu(p1).opcode] do
  1095. begin
  1096. if getregtype(reg)=R_INTREGISTER then
  1097. begin
  1098. case getsupreg(reg) of
  1099. RS_EAX:
  1100. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1101. begin
  1102. Result := True;
  1103. exit
  1104. end;
  1105. RS_ECX:
  1106. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1107. begin
  1108. Result := True;
  1109. exit
  1110. end;
  1111. RS_EDX:
  1112. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1113. begin
  1114. Result := True;
  1115. exit
  1116. end;
  1117. RS_EBX:
  1118. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ESP:
  1124. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EBP:
  1130. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_ESI:
  1136. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_EDI:
  1142. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. end;
  1148. end;
  1149. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1150. if (WriteOps[OperIdx]*Ch<>[]) and
  1151. { The register doesn't get modified inside a reference }
  1152. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1153. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1154. begin
  1155. Result := true;
  1156. exit
  1157. end;
  1158. end;
  1159. end;
  1160. {$ifdef DEBUG_AOPTCPU}
  1161. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1162. begin
  1163. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1164. end;
  1165. function debug_tostr(i: tcgint): string; inline;
  1166. begin
  1167. Result := tostr(i);
  1168. end;
  1169. function debug_hexstr(i: tcgint): string;
  1170. begin
  1171. Result := '0x';
  1172. case i of
  1173. 0..$FF:
  1174. Result := Result + hexstr(i, 2);
  1175. $100..$FFFF:
  1176. Result := Result + hexstr(i, 4);
  1177. $10000..$FFFFFF:
  1178. Result := Result + hexstr(i, 6);
  1179. $1000000..$FFFFFFFF:
  1180. Result := Result + hexstr(i, 8);
  1181. else
  1182. Result := Result + hexstr(i, 16);
  1183. end;
  1184. end;
  1185. function debug_regname(r: TRegister): string; inline;
  1186. begin
  1187. Result := '%' + std_regname(r);
  1188. end;
  1189. { Debug output function - creates a string representation of an operator }
  1190. function debug_operstr(oper: TOper): string;
  1191. begin
  1192. case oper.typ of
  1193. top_const:
  1194. Result := '$' + debug_tostr(oper.val);
  1195. top_reg:
  1196. Result := debug_regname(oper.reg);
  1197. top_ref:
  1198. begin
  1199. if oper.ref^.offset <> 0 then
  1200. Result := debug_tostr(oper.ref^.offset) + '('
  1201. else
  1202. Result := '(';
  1203. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1204. begin
  1205. Result := Result + debug_regname(oper.ref^.base);
  1206. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1207. Result := Result + ',' + debug_regname(oper.ref^.index);
  1208. end
  1209. else
  1210. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1211. Result := Result + debug_regname(oper.ref^.index);
  1212. if (oper.ref^.scalefactor > 1) then
  1213. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1214. else
  1215. Result := Result + ')';
  1216. end;
  1217. else
  1218. Result := '[UNKNOWN]';
  1219. end;
  1220. end;
  1221. function debug_op2str(opcode: tasmop): string; inline;
  1222. begin
  1223. Result := std_op2str[opcode];
  1224. end;
  1225. function debug_opsize2str(opsize: topsize): string; inline;
  1226. begin
  1227. Result := gas_opsize2str[opsize];
  1228. end;
  1229. {$else DEBUG_AOPTCPU}
  1230. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1231. begin
  1232. end;
  1233. function debug_tostr(i: tcgint): string; inline;
  1234. begin
  1235. Result := '';
  1236. end;
  1237. function debug_hexstr(i: tcgint): string; inline;
  1238. begin
  1239. Result := '';
  1240. end;
  1241. function debug_regname(r: TRegister): string; inline;
  1242. begin
  1243. Result := '';
  1244. end;
  1245. function debug_operstr(oper: TOper): string; inline;
  1246. begin
  1247. Result := '';
  1248. end;
  1249. function debug_op2str(opcode: tasmop): string; inline;
  1250. begin
  1251. Result := '';
  1252. end;
  1253. function debug_opsize2str(opsize: topsize): string; inline;
  1254. begin
  1255. Result := '';
  1256. end;
  1257. {$endif DEBUG_AOPTCPU}
  1258. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1259. begin
  1260. {$ifdef x86_64}
  1261. { Always fine on x86-64 }
  1262. Result := True;
  1263. {$else x86_64}
  1264. Result :=
  1265. {$ifdef i8086}
  1266. (current_settings.cputype >= cpu_386) and
  1267. {$endif i8086}
  1268. (
  1269. { Always accept if optimising for size }
  1270. (cs_opt_size in current_settings.optimizerswitches) or
  1271. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1272. (current_settings.optimizecputype >= cpu_Pentium2)
  1273. );
  1274. {$endif x86_64}
  1275. end;
  1276. { Attempts to allocate a volatile integer register for use between p and hp,
  1277. using AUsedRegs for the current register usage information. Returns NR_NO
  1278. if no free register could be found }
  1279. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1280. var
  1281. RegSet: TCPURegisterSet;
  1282. CurrentSuperReg: Integer;
  1283. CurrentReg: TRegister;
  1284. Currentp: tai;
  1285. Breakout: Boolean;
  1286. begin
  1287. Result := NR_NO;
  1288. RegSet :=
  1289. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1290. current_procinfo.saved_regs_int;
  1291. (*
  1292. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1293. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1294. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1295. *)
  1296. for CurrentSuperReg in RegSet do
  1297. begin
  1298. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1299. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1300. {$if defined(i386) or defined(i8086)}
  1301. { If the target size is 8-bit, make sure we can actually encode it }
  1302. and (
  1303. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1304. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1305. )
  1306. {$endif i386 or i8086}
  1307. then
  1308. begin
  1309. Currentp := p;
  1310. Breakout := False;
  1311. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1312. begin
  1313. case Currentp.typ of
  1314. ait_instruction:
  1315. begin
  1316. if RegInInstruction(CurrentReg, Currentp) then
  1317. begin
  1318. Breakout := True;
  1319. Break;
  1320. end;
  1321. { Cannot allocate across an unconditional jump }
  1322. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1323. Exit;
  1324. end;
  1325. ait_marker:
  1326. { Don't try anything more if a marker is hit }
  1327. Exit;
  1328. ait_regalloc:
  1329. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1330. begin
  1331. Breakout := True;
  1332. Break;
  1333. end;
  1334. else
  1335. ;
  1336. end;
  1337. end;
  1338. if Breakout then
  1339. { Try the next register }
  1340. Continue;
  1341. { We have a free register available }
  1342. Result := CurrentReg;
  1343. if not DontAlloc then
  1344. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1345. Exit;
  1346. end;
  1347. end;
  1348. end;
  1349. { Attempts to allocate a volatile MM register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_mm;
  1364. for CurrentSuperReg in RegSet do
  1365. begin
  1366. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1367. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1368. begin
  1369. Currentp := p;
  1370. Breakout := False;
  1371. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1372. begin
  1373. case Currentp.typ of
  1374. ait_instruction:
  1375. begin
  1376. if RegInInstruction(CurrentReg, Currentp) then
  1377. begin
  1378. Breakout := True;
  1379. Break;
  1380. end;
  1381. { Cannot allocate across an unconditional jump }
  1382. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1383. Exit;
  1384. end;
  1385. ait_marker:
  1386. { Don't try anything more if a marker is hit }
  1387. Exit;
  1388. ait_regalloc:
  1389. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. else
  1395. ;
  1396. end;
  1397. end;
  1398. if Breakout then
  1399. { Try the next register }
  1400. Continue;
  1401. { We have a free register available }
  1402. Result := CurrentReg;
  1403. if not DontAlloc then
  1404. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1405. Exit;
  1406. end;
  1407. end;
  1408. end;
  1409. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1410. begin
  1411. if not SuperRegistersEqual(reg1,reg2) then
  1412. exit(false);
  1413. if getregtype(reg1)<>R_INTREGISTER then
  1414. exit(true); {because SuperRegisterEqual is true}
  1415. case getsubreg(reg1) of
  1416. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1417. higher, it preserves the high bits, so the new value depends on
  1418. reg2's previous value. In other words, it is equivalent to doing:
  1419. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1420. R_SUBL:
  1421. exit(getsubreg(reg2)=R_SUBL);
  1422. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1423. higher, it actually does a:
  1424. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1425. R_SUBH:
  1426. exit(getsubreg(reg2)=R_SUBH);
  1427. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1428. bits of reg2:
  1429. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1430. R_SUBW:
  1431. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1432. { a write to R_SUBD always overwrites every other subregister,
  1433. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1434. R_SUBD,
  1435. R_SUBQ:
  1436. exit(true);
  1437. else
  1438. internalerror(2017042801);
  1439. end;
  1440. end;
  1441. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1442. begin
  1443. if not SuperRegistersEqual(reg1,reg2) then
  1444. exit(false);
  1445. if getregtype(reg1)<>R_INTREGISTER then
  1446. exit(true); {because SuperRegisterEqual is true}
  1447. case getsubreg(reg1) of
  1448. R_SUBL:
  1449. exit(getsubreg(reg2)<>R_SUBH);
  1450. R_SUBH:
  1451. exit(getsubreg(reg2)<>R_SUBL);
  1452. R_SUBW,
  1453. R_SUBD,
  1454. R_SUBQ:
  1455. exit(true);
  1456. else
  1457. internalerror(2017042802);
  1458. end;
  1459. end;
  1460. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1461. var
  1462. hp1 : tai;
  1463. l : TCGInt;
  1464. begin
  1465. result:=false;
  1466. if not(GetNextInstruction(p, hp1)) then
  1467. exit;
  1468. { changes the code sequence
  1469. shr/sar const1, x
  1470. shl const2, x
  1471. to
  1472. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1473. if (taicpu(p).oper[0]^.typ = top_const) and
  1474. MatchInstruction(hp1,A_SHL,[]) and
  1475. (taicpu(hp1).oper[0]^.typ = top_const) and
  1476. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1477. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1478. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1479. begin
  1480. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1481. not(cs_opt_size in current_settings.optimizerswitches) then
  1482. begin
  1483. { shr/sar const1, %reg
  1484. shl const2, %reg
  1485. with const1 > const2 }
  1486. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1487. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1488. taicpu(hp1).opcode := A_AND;
  1489. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1490. case taicpu(p).opsize Of
  1491. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1492. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1493. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1494. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1495. else
  1496. Internalerror(2017050703)
  1497. end;
  1498. end
  1499. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1500. not(cs_opt_size in current_settings.optimizerswitches) then
  1501. begin
  1502. { shr/sar const1, %reg
  1503. shl const2, %reg
  1504. with const1 < const2 }
  1505. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1506. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1507. taicpu(p).opcode := A_AND;
  1508. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1509. case taicpu(p).opsize Of
  1510. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1511. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1512. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1513. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1514. else
  1515. Internalerror(2017050702)
  1516. end;
  1517. end
  1518. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1519. begin
  1520. { shr/sar const1, %reg
  1521. shl const2, %reg
  1522. with const1 = const2 }
  1523. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1524. taicpu(p).opcode := A_AND;
  1525. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1526. case taicpu(p).opsize Of
  1527. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1528. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1529. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1530. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1531. else
  1532. Internalerror(2017050701)
  1533. end;
  1534. RemoveInstruction(hp1);
  1535. end;
  1536. end;
  1537. end;
  1538. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1539. var
  1540. opsize : topsize;
  1541. hp1, hp2 : tai;
  1542. tmpref : treference;
  1543. ShiftValue : Cardinal;
  1544. BaseValue : TCGInt;
  1545. begin
  1546. result:=false;
  1547. opsize:=taicpu(p).opsize;
  1548. { changes certain "imul const, %reg"'s to lea sequences }
  1549. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1550. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1551. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1552. if (taicpu(p).oper[0]^.val = 1) then
  1553. if (taicpu(p).ops = 2) then
  1554. { remove "imul $1, reg" }
  1555. begin
  1556. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1557. Result := RemoveCurrentP(p);
  1558. end
  1559. else
  1560. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1561. begin
  1562. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1563. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1564. asml.InsertAfter(hp1, p);
  1565. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1566. RemoveCurrentP(p, hp1);
  1567. Result := True;
  1568. end
  1569. else if ((taicpu(p).ops <= 2) or
  1570. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1571. not(cs_opt_size in current_settings.optimizerswitches) and
  1572. (not(GetNextInstruction(p, hp1)) or
  1573. not((tai(hp1).typ = ait_instruction) and
  1574. ((taicpu(hp1).opcode=A_Jcc) and
  1575. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1576. begin
  1577. {
  1578. imul X, reg1, reg2 to
  1579. lea (reg1,reg1,Y), reg2
  1580. shl ZZ,reg2
  1581. imul XX, reg1 to
  1582. lea (reg1,reg1,YY), reg1
  1583. shl ZZ,reg2
  1584. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1585. it does not exist as a separate optimization target in FPC though.
  1586. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1587. at most two zeros
  1588. }
  1589. reference_reset(tmpref,1,[]);
  1590. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1591. begin
  1592. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1593. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1594. TmpRef.base := taicpu(p).oper[1]^.reg;
  1595. TmpRef.index := taicpu(p).oper[1]^.reg;
  1596. if not(BaseValue in [3,5,9]) then
  1597. Internalerror(2018110101);
  1598. TmpRef.ScaleFactor := BaseValue-1;
  1599. if (taicpu(p).ops = 2) then
  1600. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1601. else
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1603. AsmL.InsertAfter(hp1,p);
  1604. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1605. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1606. RemoveCurrentP(p, hp1);
  1607. if ShiftValue>0 then
  1608. begin
  1609. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1610. AsmL.InsertAfter(hp2,hp1);
  1611. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1612. end;
  1613. Result := True;
  1614. end;
  1615. end;
  1616. end;
  1617. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1618. begin
  1619. Result := False;
  1620. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1621. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1622. begin
  1623. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1624. taicpu(p).opcode := A_MOV;
  1625. Result := True;
  1626. end;
  1627. end;
  1628. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1629. var
  1630. p: taicpu absolute hp; { Implicit typecast }
  1631. i: Integer;
  1632. begin
  1633. Result := False;
  1634. if not assigned(hp) or
  1635. (hp.typ <> ait_instruction) then
  1636. Exit;
  1637. Prefetch(insprop[p.opcode]);
  1638. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1639. with insprop[p.opcode] do
  1640. begin
  1641. case getsubreg(reg) of
  1642. R_SUBW,R_SUBD,R_SUBQ:
  1643. Result:=
  1644. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1645. uncommon flags are checked first }
  1646. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1647. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1648. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1652. R_SUBFLAGCARRY:
  1653. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGPARITY:
  1655. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGAUXILIARY:
  1657. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGZERO:
  1659. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGSIGN:
  1661. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGOVERFLOW:
  1663. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGINTERRUPT:
  1665. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGDIRECTION:
  1667. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1668. else
  1669. internalerror(2017050501);
  1670. end;
  1671. exit;
  1672. end;
  1673. { Handle special cases first }
  1674. case p.opcode of
  1675. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1676. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1677. begin
  1678. Result :=
  1679. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1680. (p.oper[1]^.typ = top_reg) and
  1681. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1682. (
  1683. (p.oper[0]^.typ = top_const) or
  1684. (
  1685. (p.oper[0]^.typ = top_reg) and
  1686. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1687. ) or (
  1688. (p.oper[0]^.typ = top_ref) and
  1689. not RegInRef(reg,p.oper[0]^.ref^)
  1690. )
  1691. );
  1692. end;
  1693. A_MUL, A_IMUL:
  1694. Result :=
  1695. (
  1696. (p.ops=3) and { IMUL only }
  1697. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1698. (
  1699. (
  1700. (p.oper[1]^.typ=top_reg) and
  1701. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1702. ) or (
  1703. (p.oper[1]^.typ=top_ref) and
  1704. not RegInRef(reg,p.oper[1]^.ref^)
  1705. )
  1706. )
  1707. ) or (
  1708. (
  1709. (p.ops=1) and
  1710. (
  1711. (
  1712. (
  1713. (p.oper[0]^.typ=top_reg) and
  1714. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1715. )
  1716. ) or (
  1717. (p.oper[0]^.typ=top_ref) and
  1718. not RegInRef(reg,p.oper[0]^.ref^)
  1719. )
  1720. ) and (
  1721. (
  1722. (p.opsize=S_B) and
  1723. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1724. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1725. ) or (
  1726. (p.opsize=S_W) and
  1727. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1728. ) or (
  1729. (p.opsize=S_L) and
  1730. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1731. {$ifdef x86_64}
  1732. ) or (
  1733. (p.opsize=S_Q) and
  1734. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1735. {$endif x86_64}
  1736. )
  1737. )
  1738. )
  1739. );
  1740. A_CBW:
  1741. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1742. {$ifndef x86_64}
  1743. A_LDS:
  1744. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1745. A_LES:
  1746. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. {$endif not x86_64}
  1748. A_LFS:
  1749. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LGS:
  1751. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LSS:
  1753. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1756. A_LODSB:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1758. A_LODSW:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1760. {$ifdef x86_64}
  1761. A_LODSQ:
  1762. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1763. {$endif x86_64}
  1764. A_LODSD:
  1765. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1766. A_FSTSW, A_FNSTSW:
  1767. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1768. else
  1769. begin
  1770. with insprop[p.opcode] do
  1771. begin
  1772. if (
  1773. { xor %reg,%reg etc. is classed as a new value }
  1774. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1775. MatchOpType(p, top_reg, top_reg) and
  1776. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1777. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1778. ) then
  1779. begin
  1780. Result := True;
  1781. Exit;
  1782. end;
  1783. { Make sure the entire register is overwritten }
  1784. if (getregtype(reg) = R_INTREGISTER) then
  1785. begin
  1786. if (p.ops > 0) then
  1787. begin
  1788. if RegInOp(reg, p.oper[0]^) then
  1789. begin
  1790. if (p.oper[0]^.typ = top_ref) then
  1791. begin
  1792. if RegInRef(reg, p.oper[0]^.ref^) then
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end
  1798. else if (p.oper[0]^.typ = top_reg) then
  1799. begin
  1800. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1801. begin
  1802. Result := False;
  1803. Exit;
  1804. end
  1805. else if ([Ch_WOp1]*Ch<>[]) then
  1806. begin
  1807. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1808. Result := True
  1809. else
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. if (p.ops > 1) then
  1818. begin
  1819. if RegInOp(reg, p.oper[1]^) then
  1820. begin
  1821. if (p.oper[1]^.typ = top_ref) then
  1822. begin
  1823. if RegInRef(reg, p.oper[1]^.ref^) then
  1824. begin
  1825. Result := False;
  1826. Exit;
  1827. end;
  1828. end
  1829. else if (p.oper[1]^.typ = top_reg) then
  1830. begin
  1831. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1832. begin
  1833. Result := False;
  1834. Exit;
  1835. end
  1836. else if ([Ch_WOp2]*Ch<>[]) then
  1837. begin
  1838. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1839. Result := True
  1840. else
  1841. begin
  1842. Result := False;
  1843. Exit;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. if (p.ops > 2) then
  1849. begin
  1850. if RegInOp(reg, p.oper[2]^) then
  1851. begin
  1852. if (p.oper[2]^.typ = top_ref) then
  1853. begin
  1854. if RegInRef(reg, p.oper[2]^.ref^) then
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end
  1860. else if (p.oper[2]^.typ = top_reg) then
  1861. begin
  1862. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1863. begin
  1864. Result := False;
  1865. Exit;
  1866. end
  1867. else if ([Ch_WOp3]*Ch<>[]) then
  1868. begin
  1869. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1870. Result := True
  1871. else
  1872. begin
  1873. Result := False;
  1874. Exit;
  1875. end;
  1876. end;
  1877. end;
  1878. end;
  1879. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1880. begin
  1881. if (p.oper[3]^.typ = top_ref) then
  1882. begin
  1883. if RegInRef(reg, p.oper[3]^.ref^) then
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end
  1889. else if (p.oper[3]^.typ = top_reg) then
  1890. begin
  1891. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end
  1896. else if ([Ch_WOp4]*Ch<>[]) then
  1897. begin
  1898. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1899. Result := True
  1900. else
  1901. begin
  1902. Result := False;
  1903. Exit;
  1904. end;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1912. case getsupreg(reg) of
  1913. RS_EAX:
  1914. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1915. begin
  1916. Result := True;
  1917. Exit;
  1918. end;
  1919. RS_ECX:
  1920. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1921. begin
  1922. Result := True;
  1923. Exit;
  1924. end;
  1925. RS_EDX:
  1926. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1927. begin
  1928. Result := True;
  1929. Exit;
  1930. end;
  1931. RS_EBX:
  1932. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1933. begin
  1934. Result := True;
  1935. Exit;
  1936. end;
  1937. RS_ESP:
  1938. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1939. begin
  1940. Result := True;
  1941. Exit;
  1942. end;
  1943. RS_EBP:
  1944. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1945. begin
  1946. Result := True;
  1947. Exit;
  1948. end;
  1949. RS_ESI:
  1950. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1951. begin
  1952. Result := True;
  1953. Exit;
  1954. end;
  1955. RS_EDI:
  1956. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1957. begin
  1958. Result := True;
  1959. Exit;
  1960. end;
  1961. else
  1962. ;
  1963. end;
  1964. end;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1970. var
  1971. hp2,hp3 : tai;
  1972. begin
  1973. { some x86-64 issue a NOP before the real exit code }
  1974. if MatchInstruction(p,A_NOP,[]) then
  1975. GetNextInstruction(p,p);
  1976. result:=assigned(p) and (p.typ=ait_instruction) and
  1977. ((taicpu(p).opcode = A_RET) or
  1978. ((taicpu(p).opcode=A_LEAVE) and
  1979. GetNextInstruction(p,hp2) and
  1980. MatchInstruction(hp2,A_RET,[S_NO])
  1981. ) or
  1982. (((taicpu(p).opcode=A_LEA) and
  1983. MatchOpType(taicpu(p),top_ref,top_reg) and
  1984. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1985. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1986. ) and
  1987. GetNextInstruction(p,hp2) and
  1988. MatchInstruction(hp2,A_RET,[S_NO])
  1989. ) or
  1990. ((((taicpu(p).opcode=A_MOV) and
  1991. MatchOpType(taicpu(p),top_reg,top_reg) and
  1992. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1993. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1994. ((taicpu(p).opcode=A_LEA) and
  1995. MatchOpType(taicpu(p),top_ref,top_reg) and
  1996. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1997. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1998. )
  1999. ) and
  2000. GetNextInstruction(p,hp2) and
  2001. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2002. MatchOpType(taicpu(hp2),top_reg) and
  2003. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2004. GetNextInstruction(hp2,hp3) and
  2005. MatchInstruction(hp3,A_RET,[S_NO])
  2006. )
  2007. );
  2008. end;
  2009. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2010. begin
  2011. isFoldableArithOp := False;
  2012. case hp1.opcode of
  2013. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2014. isFoldableArithOp :=
  2015. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2016. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2017. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2018. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[1]^.reg = reg);
  2020. A_INC,A_DEC,A_NEG,A_NOT:
  2021. isFoldableArithOp :=
  2022. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2023. (taicpu(hp1).oper[0]^.reg = reg);
  2024. else
  2025. ;
  2026. end;
  2027. end;
  2028. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2029. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2030. var
  2031. hp2: tai;
  2032. begin
  2033. hp2 := p;
  2034. repeat
  2035. hp2 := tai(hp2.previous);
  2036. if assigned(hp2) and
  2037. (hp2.typ = ait_regalloc) and
  2038. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2039. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2040. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2041. begin
  2042. RemoveInstruction(hp2);
  2043. break;
  2044. end;
  2045. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2046. end;
  2047. begin
  2048. case current_procinfo.procdef.returndef.typ of
  2049. arraydef,recorddef,pointerdef,
  2050. stringdef,enumdef,procdef,objectdef,errordef,
  2051. filedef,setdef,procvardef,
  2052. classrefdef,forwarddef:
  2053. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2054. orddef:
  2055. if current_procinfo.procdef.returndef.size <> 0 then
  2056. begin
  2057. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2058. { for int64/qword }
  2059. if current_procinfo.procdef.returndef.size = 8 then
  2060. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2061. end;
  2062. else
  2063. ;
  2064. end;
  2065. end;
  2066. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2067. var
  2068. hp1,hp2 : tai;
  2069. begin
  2070. result:=false;
  2071. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2072. begin
  2073. { vmova* reg1,reg1
  2074. =>
  2075. <nop> }
  2076. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2077. begin
  2078. RemoveCurrentP(p);
  2079. result:=true;
  2080. exit;
  2081. end;
  2082. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2083. (hp1.typ = ait_instruction) and
  2084. (
  2085. { Under -O2 and below, the instructions are always adjacent }
  2086. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2087. (taicpu(hp1).ops <= 1) or
  2088. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2089. { If reg1 = reg3, reg1 must not be modified in between }
  2090. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2091. ) then
  2092. begin
  2093. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2094. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2095. begin
  2096. { vmova* reg1,reg2
  2097. ...
  2098. vmova* reg2,reg3
  2099. dealloc reg2
  2100. =>
  2101. vmova* reg1,reg3 }
  2102. TransferUsedRegs(TmpUsedRegs);
  2103. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2104. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2105. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2106. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2107. begin
  2108. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2109. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2110. TransferUsedRegs(TmpUsedRegs);
  2111. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2112. RemoveInstruction(hp1);
  2113. result:=true;
  2114. exit;
  2115. end;
  2116. { special case:
  2117. vmova* reg1,<op>
  2118. ...
  2119. vmova* <op>,reg1
  2120. =>
  2121. vmova* reg1,<op> }
  2122. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2123. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2124. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2125. ) then
  2126. begin
  2127. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2128. RemoveInstruction(hp1);
  2129. result:=true;
  2130. exit;
  2131. end
  2132. end
  2133. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2134. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2135. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2136. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2137. ) and
  2138. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2139. begin
  2140. { vmova* reg1,reg2
  2141. ...
  2142. vmovs* reg2,<op>
  2143. dealloc reg2
  2144. =>
  2145. vmovs* reg1,<op> }
  2146. TransferUsedRegs(TmpUsedRegs);
  2147. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2148. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2151. taicpu(p).opcode:=taicpu(hp1).opcode;
  2152. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2153. TransferUsedRegs(TmpUsedRegs);
  2154. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2155. RemoveInstruction(hp1);
  2156. result:=true;
  2157. exit;
  2158. end
  2159. end;
  2160. if MatchInstruction(hp1,[A_VFMADDPD,
  2161. A_VFMADD132PD,
  2162. A_VFMADD132PS,
  2163. A_VFMADD132SD,
  2164. A_VFMADD132SS,
  2165. A_VFMADD213PD,
  2166. A_VFMADD213PS,
  2167. A_VFMADD213SD,
  2168. A_VFMADD213SS,
  2169. A_VFMADD231PD,
  2170. A_VFMADD231PS,
  2171. A_VFMADD231SD,
  2172. A_VFMADD231SS,
  2173. A_VFMADDSUB132PD,
  2174. A_VFMADDSUB132PS,
  2175. A_VFMADDSUB213PD,
  2176. A_VFMADDSUB213PS,
  2177. A_VFMADDSUB231PD,
  2178. A_VFMADDSUB231PS,
  2179. A_VFMSUB132PD,
  2180. A_VFMSUB132PS,
  2181. A_VFMSUB132SD,
  2182. A_VFMSUB132SS,
  2183. A_VFMSUB213PD,
  2184. A_VFMSUB213PS,
  2185. A_VFMSUB213SD,
  2186. A_VFMSUB213SS,
  2187. A_VFMSUB231PD,
  2188. A_VFMSUB231PS,
  2189. A_VFMSUB231SD,
  2190. A_VFMSUB231SS,
  2191. A_VFMSUBADD132PD,
  2192. A_VFMSUBADD132PS,
  2193. A_VFMSUBADD213PD,
  2194. A_VFMSUBADD213PS,
  2195. A_VFMSUBADD231PD,
  2196. A_VFMSUBADD231PS,
  2197. A_VFNMADD132PD,
  2198. A_VFNMADD132PS,
  2199. A_VFNMADD132SD,
  2200. A_VFNMADD132SS,
  2201. A_VFNMADD213PD,
  2202. A_VFNMADD213PS,
  2203. A_VFNMADD213SD,
  2204. A_VFNMADD213SS,
  2205. A_VFNMADD231PD,
  2206. A_VFNMADD231PS,
  2207. A_VFNMADD231SD,
  2208. A_VFNMADD231SS,
  2209. A_VFNMSUB132PD,
  2210. A_VFNMSUB132PS,
  2211. A_VFNMSUB132SD,
  2212. A_VFNMSUB132SS,
  2213. A_VFNMSUB213PD,
  2214. A_VFNMSUB213PS,
  2215. A_VFNMSUB213SD,
  2216. A_VFNMSUB213SS,
  2217. A_VFNMSUB231PD,
  2218. A_VFNMSUB231PS,
  2219. A_VFNMSUB231SD,
  2220. A_VFNMSUB231SS],[S_NO]) and
  2221. { we mix single and double opperations here because we assume that the compiler
  2222. generates vmovapd only after double operations and vmovaps only after single operations }
  2223. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2224. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2225. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2226. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2227. begin
  2228. TransferUsedRegs(TmpUsedRegs);
  2229. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2230. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2231. begin
  2232. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2233. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2234. RemoveCurrentP(p)
  2235. else
  2236. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2237. RemoveInstruction(hp2);
  2238. end;
  2239. end
  2240. else if (hp1.typ = ait_instruction) and
  2241. (((taicpu(p).opcode=A_MOVAPS) and
  2242. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2243. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2244. ((taicpu(p).opcode=A_MOVAPD) and
  2245. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2246. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2247. ) and
  2248. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2249. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2250. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2251. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2252. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2253. { change
  2254. movapX reg,reg2
  2255. addsX/subsX/... reg3, reg2
  2256. movapX reg2,reg
  2257. to
  2258. addsX/subsX/... reg3,reg
  2259. }
  2260. begin
  2261. TransferUsedRegs(TmpUsedRegs);
  2262. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2263. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2264. begin
  2265. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2266. debug_op2str(taicpu(p).opcode)+' '+
  2267. debug_op2str(taicpu(hp1).opcode)+' '+
  2268. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2269. { we cannot eliminate the first move if
  2270. the operations uses the same register for source and dest }
  2271. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2272. { Remember that hp1 is not necessarily the immediate
  2273. next instruction }
  2274. RemoveCurrentP(p);
  2275. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2276. RemoveInstruction(hp2);
  2277. result:=true;
  2278. end;
  2279. end
  2280. else if (hp1.typ = ait_instruction) and
  2281. (((taicpu(p).opcode=A_VMOVAPD) and
  2282. (taicpu(hp1).opcode=A_VCOMISD)) or
  2283. ((taicpu(p).opcode=A_VMOVAPS) and
  2284. ((taicpu(hp1).opcode=A_VCOMISS))
  2285. )
  2286. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2287. { change
  2288. movapX reg,reg1
  2289. vcomisX reg1,reg1
  2290. to
  2291. vcomisX reg,reg
  2292. }
  2293. begin
  2294. TransferUsedRegs(TmpUsedRegs);
  2295. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2296. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2297. begin
  2298. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2299. debug_op2str(taicpu(p).opcode)+' '+
  2300. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2301. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2302. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2303. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2304. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2305. RemoveCurrentP(p);
  2306. result:=true;
  2307. exit;
  2308. end;
  2309. end
  2310. end;
  2311. end;
  2312. end;
  2313. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2314. var
  2315. hp1 : tai;
  2316. begin
  2317. result:=false;
  2318. { replace
  2319. V<Op>X %mreg1,%mreg2,%mreg3
  2320. VMovX %mreg3,%mreg4
  2321. dealloc %mreg3
  2322. by
  2323. V<Op>X %mreg1,%mreg2,%mreg4
  2324. ?
  2325. }
  2326. if GetNextInstruction(p,hp1) and
  2327. { we mix single and double operations here because we assume that the compiler
  2328. generates vmovapd only after double operations and vmovaps only after single operations }
  2329. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2330. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2331. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2332. begin
  2333. TransferUsedRegs(TmpUsedRegs);
  2334. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2335. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2336. begin
  2337. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2338. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2339. RemoveInstruction(hp1);
  2340. result:=true;
  2341. end;
  2342. end;
  2343. end;
  2344. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2345. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2346. begin
  2347. Result := False;
  2348. { For safety reasons, only check for exact register matches }
  2349. { Check base register }
  2350. if (ref.base = AOldReg) then
  2351. begin
  2352. ref.base := ANewReg;
  2353. Result := True;
  2354. end;
  2355. { Check index register }
  2356. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2357. begin
  2358. ref.index := ANewReg;
  2359. Result := True;
  2360. end;
  2361. end;
  2362. { Replaces all references to AOldReg in an operand to ANewReg }
  2363. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2364. var
  2365. OldSupReg, NewSupReg: TSuperRegister;
  2366. OldSubReg, NewSubReg: TSubRegister;
  2367. OldRegType: TRegisterType;
  2368. ThisOper: POper;
  2369. begin
  2370. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2371. Result := False;
  2372. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2373. InternalError(2020011801);
  2374. OldSupReg := getsupreg(AOldReg);
  2375. OldSubReg := getsubreg(AOldReg);
  2376. OldRegType := getregtype(AOldReg);
  2377. NewSupReg := getsupreg(ANewReg);
  2378. NewSubReg := getsubreg(ANewReg);
  2379. if OldRegType <> getregtype(ANewReg) then
  2380. InternalError(2020011802);
  2381. if OldSubReg <> NewSubReg then
  2382. InternalError(2020011803);
  2383. case ThisOper^.typ of
  2384. top_reg:
  2385. if (
  2386. (ThisOper^.reg = AOldReg) or
  2387. (
  2388. (OldRegType = R_INTREGISTER) and
  2389. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2390. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2391. (
  2392. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2393. {$ifndef x86_64}
  2394. and (
  2395. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2396. don't have an 8-bit representation }
  2397. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2398. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2399. )
  2400. {$endif x86_64}
  2401. )
  2402. )
  2403. ) then
  2404. begin
  2405. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2406. Result := True;
  2407. end;
  2408. top_ref:
  2409. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2410. Result := True;
  2411. else
  2412. ;
  2413. end;
  2414. end;
  2415. { Replaces all references to AOldReg in an instruction to ANewReg }
  2416. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2417. const
  2418. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2419. var
  2420. OperIdx: Integer;
  2421. begin
  2422. Result := False;
  2423. for OperIdx := 0 to p.ops - 1 do
  2424. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2425. begin
  2426. { The shift and rotate instructions can only use CL }
  2427. if not (
  2428. (OperIdx = 0) and
  2429. { This second condition just helps to avoid unnecessarily
  2430. calling MatchInstruction for 10 different opcodes }
  2431. (p.oper[0]^.reg = NR_CL) and
  2432. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2433. ) then
  2434. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2435. end
  2436. else if p.oper[OperIdx]^.typ = top_ref then
  2437. { It's okay to replace registers in references that get written to }
  2438. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2439. end;
  2440. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2441. begin
  2442. Result :=
  2443. (ref^.index = NR_NO) and
  2444. (
  2445. {$ifdef x86_64}
  2446. (
  2447. (ref^.base = NR_RIP) and
  2448. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2449. ) or
  2450. {$endif x86_64}
  2451. (ref^.refaddr = addr_full) or
  2452. (ref^.base = NR_STACK_POINTER_REG) or
  2453. (ref^.base = current_procinfo.framepointer)
  2454. );
  2455. end;
  2456. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2457. var
  2458. l: asizeint;
  2459. begin
  2460. Result := False;
  2461. { Should have been checked previously }
  2462. if p.opcode <> A_LEA then
  2463. InternalError(2020072501);
  2464. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2465. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2466. not(cs_opt_size in current_settings.optimizerswitches) then
  2467. exit;
  2468. with p.oper[0]^.ref^ do
  2469. begin
  2470. if (base <> p.oper[1]^.reg) or
  2471. (index <> NR_NO) or
  2472. assigned(symbol) then
  2473. exit;
  2474. l:=offset;
  2475. if (l=1) and UseIncDec then
  2476. begin
  2477. p.opcode:=A_INC;
  2478. p.loadreg(0,p.oper[1]^.reg);
  2479. p.ops:=1;
  2480. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2481. end
  2482. else if (l=-1) and UseIncDec then
  2483. begin
  2484. p.opcode:=A_DEC;
  2485. p.loadreg(0,p.oper[1]^.reg);
  2486. p.ops:=1;
  2487. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2488. end
  2489. else
  2490. begin
  2491. if (l<0) and (l<>-2147483648) then
  2492. begin
  2493. p.opcode:=A_SUB;
  2494. p.loadConst(0,-l);
  2495. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2496. end
  2497. else
  2498. begin
  2499. p.opcode:=A_ADD;
  2500. p.loadConst(0,l);
  2501. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2502. end;
  2503. end;
  2504. end;
  2505. Result := True;
  2506. end;
  2507. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2508. var
  2509. CurrentReg, ReplaceReg: TRegister;
  2510. begin
  2511. Result := False;
  2512. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2513. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2514. case hp.opcode of
  2515. A_FSTSW, A_FNSTSW,
  2516. A_IN, A_INS, A_OUT, A_OUTS,
  2517. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2518. { These routines have explicit operands, but they are restricted in
  2519. what they can be (e.g. IN and OUT can only read from AL, AX or
  2520. EAX. }
  2521. Exit;
  2522. A_IMUL:
  2523. begin
  2524. { The 1-operand version writes to implicit registers
  2525. The 2-operand version reads from the first operator, and reads
  2526. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2527. the 3-operand version reads from a register that it doesn't write to
  2528. }
  2529. case hp.ops of
  2530. 1:
  2531. if (
  2532. (
  2533. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2534. ) or
  2535. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2536. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2537. begin
  2538. Result := True;
  2539. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2540. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2541. end;
  2542. 2:
  2543. { Only modify the first parameter }
  2544. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2545. begin
  2546. Result := True;
  2547. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2548. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2549. end;
  2550. 3:
  2551. { Only modify the second parameter }
  2552. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2553. begin
  2554. Result := True;
  2555. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2556. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2557. end;
  2558. else
  2559. InternalError(2020012901);
  2560. end;
  2561. end;
  2562. else
  2563. if (hp.ops > 0) and
  2564. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2565. begin
  2566. Result := True;
  2567. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2568. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2569. end;
  2570. end;
  2571. end;
  2572. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2573. var
  2574. hp2: tai;
  2575. p_SourceReg, p_TargetReg: TRegister;
  2576. begin
  2577. Result := False;
  2578. { Backward optimisation. If we have:
  2579. func. %reg1,%reg2
  2580. mov %reg2,%reg3
  2581. (dealloc %reg2)
  2582. Change to:
  2583. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2584. Perform similar optimisations with 1, 3 and 4-operand instructions
  2585. that only have one output.
  2586. }
  2587. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2588. begin
  2589. p_SourceReg := taicpu(p).oper[0]^.reg;
  2590. p_TargetReg := taicpu(p).oper[1]^.reg;
  2591. TransferUsedRegs(TmpUsedRegs);
  2592. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2593. GetLastInstruction(p, hp2) and
  2594. (hp2.typ = ait_instruction) and
  2595. { Have to make sure it's an instruction that only reads from
  2596. the first operands and only writes (not reads or modifies) to
  2597. the last one; in essence, a pure function such as BSR, POPCNT
  2598. or ANDN }
  2599. (
  2600. (
  2601. (taicpu(hp2).ops = 1) and
  2602. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2603. ) or
  2604. (
  2605. (taicpu(hp2).ops = 2) and
  2606. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2607. ) or
  2608. (
  2609. (taicpu(hp2).ops = 3) and
  2610. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2611. ) or
  2612. (
  2613. (taicpu(hp2).ops = 4) and
  2614. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2615. )
  2616. ) and
  2617. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2618. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2619. begin
  2620. case taicpu(hp2).opcode of
  2621. A_FSTSW, A_FNSTSW,
  2622. A_IN, A_INS, A_OUT, A_OUTS,
  2623. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2624. { These routines have explicit operands, but they are restricted in
  2625. what they can be (e.g. IN and OUT can only read from AL, AX or
  2626. EAX. }
  2627. ;
  2628. else
  2629. begin
  2630. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2631. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2632. if not RegInInstruction(p_TargetReg, hp2) then
  2633. begin
  2634. { Since we're allocating from an earlier point, we
  2635. need to remove the register from the tracking }
  2636. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2637. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2638. end;
  2639. RemoveCurrentp(p, hp1);
  2640. { If the Func was another MOV instruction, we might get
  2641. "mov %reg,%reg" that doesn't get removed in Pass 2
  2642. otherwise, so deal with it here (also do something
  2643. similar with lea (%reg),%reg}
  2644. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2645. begin
  2646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2647. if p = hp2 then
  2648. RemoveCurrentp(p)
  2649. else
  2650. RemoveInstruction(hp2);
  2651. end;
  2652. Result := True;
  2653. Exit;
  2654. end;
  2655. end;
  2656. end;
  2657. end;
  2658. end;
  2659. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2660. begin
  2661. Result := False;
  2662. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2663. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2664. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2665. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2666. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2667. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2668. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2670. begin
  2671. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2672. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2673. Result := True;
  2674. end;
  2675. end;
  2676. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2677. var
  2678. hp1, hp2, hp3, hp4: tai;
  2679. DoOptimisation, TempBool: Boolean;
  2680. {$ifdef x86_64}
  2681. NewConst: TCGInt;
  2682. {$endif x86_64}
  2683. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2684. begin
  2685. if taicpu(hp1).opcode = signed_movop then
  2686. begin
  2687. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2688. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2689. end
  2690. else
  2691. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2692. end;
  2693. function TryConstMerge(var p1, p2: tai): Boolean;
  2694. var
  2695. ThisRef: TReference;
  2696. begin
  2697. Result := False;
  2698. ThisRef := taicpu(p2).oper[1]^.ref^;
  2699. { Only permit writes to the stack, since we can guarantee alignment with that }
  2700. if (ThisRef.index = NR_NO) and
  2701. (
  2702. (ThisRef.base = NR_STACK_POINTER_REG) or
  2703. (ThisRef.base = current_procinfo.framepointer)
  2704. ) then
  2705. begin
  2706. case taicpu(p).opsize of
  2707. S_B:
  2708. begin
  2709. { Word writes must be on a 2-byte boundary }
  2710. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2711. begin
  2712. { Reduce offset of second reference to see if it is sequential with the first }
  2713. Dec(ThisRef.offset, 1);
  2714. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2715. begin
  2716. { Make sure the constants aren't represented as a
  2717. negative number, as these won't merge properly }
  2718. taicpu(p1).opsize := S_W;
  2719. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2720. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2721. RemoveInstruction(p2);
  2722. Result := True;
  2723. end;
  2724. end;
  2725. end;
  2726. S_W:
  2727. begin
  2728. { Longword writes must be on a 4-byte boundary }
  2729. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2730. begin
  2731. { Reduce offset of second reference to see if it is sequential with the first }
  2732. Dec(ThisRef.offset, 2);
  2733. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2734. begin
  2735. { Make sure the constants aren't represented as a
  2736. negative number, as these won't merge properly }
  2737. taicpu(p1).opsize := S_L;
  2738. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2739. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2740. RemoveInstruction(p2);
  2741. Result := True;
  2742. end;
  2743. end;
  2744. end;
  2745. {$ifdef x86_64}
  2746. S_L:
  2747. begin
  2748. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2749. see if the constants can be encoded this way. }
  2750. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2751. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2752. { Quadword writes must be on an 8-byte boundary }
  2753. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2754. begin
  2755. { Reduce offset of second reference to see if it is sequential with the first }
  2756. Dec(ThisRef.offset, 4);
  2757. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2758. begin
  2759. { Make sure the constants aren't represented as a
  2760. negative number, as these won't merge properly }
  2761. taicpu(p1).opsize := S_Q;
  2762. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2763. taicpu(p1).oper[0]^.val := NewConst;
  2764. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2765. RemoveInstruction(p2);
  2766. Result := True;
  2767. end;
  2768. end;
  2769. end;
  2770. {$endif x86_64}
  2771. else
  2772. ;
  2773. end;
  2774. end;
  2775. end;
  2776. var
  2777. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2778. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2779. NewSize: topsize; NewOffset: asizeint;
  2780. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2781. SourceRef, TargetRef: TReference;
  2782. MovAligned, MovUnaligned: TAsmOp;
  2783. ThisRef: TReference;
  2784. JumpTracking: TLinkedList;
  2785. begin
  2786. Result:=false;
  2787. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2788. { remove mov reg1,reg1? }
  2789. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2790. then
  2791. begin
  2792. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2793. { take care of the register (de)allocs following p }
  2794. RemoveCurrentP(p, hp1);
  2795. Result:=true;
  2796. exit;
  2797. end;
  2798. { All the next optimisations require a next instruction }
  2799. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2800. Exit;
  2801. { Prevent compiler warnings }
  2802. p_TargetReg := NR_NO;
  2803. if taicpu(p).oper[1]^.typ = top_reg then
  2804. begin
  2805. { Saves on a large number of dereferences }
  2806. p_TargetReg := taicpu(p).oper[1]^.reg;
  2807. { Look for:
  2808. mov %reg1,%reg2
  2809. ??? %reg2,r/m
  2810. Change to:
  2811. mov %reg1,%reg2
  2812. ??? %reg1,r/m
  2813. }
  2814. if taicpu(p).oper[0]^.typ = top_reg then
  2815. begin
  2816. if RegReadByInstruction(p_TargetReg, hp1) and
  2817. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2818. begin
  2819. { A change has occurred, just not in p }
  2820. Result := True;
  2821. TransferUsedRegs(TmpUsedRegs);
  2822. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2823. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2824. { Just in case something didn't get modified (e.g. an
  2825. implicit register) }
  2826. not RegReadByInstruction(p_TargetReg, hp1) then
  2827. begin
  2828. { We can remove the original MOV }
  2829. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2830. RemoveCurrentp(p, hp1);
  2831. { UsedRegs got updated by RemoveCurrentp }
  2832. Result := True;
  2833. Exit;
  2834. end;
  2835. { If we know a MOV instruction has become a null operation, we might as well
  2836. get rid of it now to save time. }
  2837. if (taicpu(hp1).opcode = A_MOV) and
  2838. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2839. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2840. { Just being a register is enough to confirm it's a null operation }
  2841. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2842. begin
  2843. Result := True;
  2844. { Speed-up to reduce a pipeline stall... if we had something like...
  2845. movl %eax,%edx
  2846. movw %dx,%ax
  2847. ... the second instruction would change to movw %ax,%ax, but
  2848. given that it is now %ax that's active rather than %eax,
  2849. penalties might occur due to a partial register write, so instead,
  2850. change it to a MOVZX instruction when optimising for speed.
  2851. }
  2852. if not (cs_opt_size in current_settings.optimizerswitches) and
  2853. IsMOVZXAcceptable and
  2854. (taicpu(hp1).opsize < taicpu(p).opsize)
  2855. {$ifdef x86_64}
  2856. { operations already implicitly set the upper 64 bits to zero }
  2857. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2858. {$endif x86_64}
  2859. then
  2860. begin
  2861. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2862. case taicpu(p).opsize of
  2863. S_W:
  2864. if taicpu(hp1).opsize = S_B then
  2865. taicpu(hp1).opsize := S_BL
  2866. else
  2867. InternalError(2020012911);
  2868. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2869. case taicpu(hp1).opsize of
  2870. S_B:
  2871. taicpu(hp1).opsize := S_BL;
  2872. S_W:
  2873. taicpu(hp1).opsize := S_WL;
  2874. else
  2875. InternalError(2020012912);
  2876. end;
  2877. else
  2878. InternalError(2020012910);
  2879. end;
  2880. taicpu(hp1).opcode := A_MOVZX;
  2881. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2882. end
  2883. else
  2884. begin
  2885. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2886. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2887. RemoveInstruction(hp1);
  2888. { The instruction after what was hp1 is now the immediate next instruction,
  2889. so we can continue to make optimisations if it's present }
  2890. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2891. Exit;
  2892. hp1 := hp2;
  2893. end;
  2894. end;
  2895. end;
  2896. end;
  2897. end;
  2898. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2899. overwrites the original destination register. e.g.
  2900. movl ###,%reg2d
  2901. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2902. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2903. }
  2904. if (taicpu(p).oper[1]^.typ = top_reg) and
  2905. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2906. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2907. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2908. begin
  2909. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2910. begin
  2911. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2912. case taicpu(p).oper[0]^.typ of
  2913. top_const:
  2914. { We have something like:
  2915. movb $x, %regb
  2916. movzbl %regb,%regd
  2917. Change to:
  2918. movl $x, %regd
  2919. }
  2920. begin
  2921. case taicpu(hp1).opsize of
  2922. S_BW:
  2923. begin
  2924. convert_mov_value(A_MOVSX, $FF);
  2925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2926. taicpu(p).opsize := S_W;
  2927. end;
  2928. S_BL:
  2929. begin
  2930. convert_mov_value(A_MOVSX, $FF);
  2931. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2932. taicpu(p).opsize := S_L;
  2933. end;
  2934. S_WL:
  2935. begin
  2936. convert_mov_value(A_MOVSX, $FFFF);
  2937. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2938. taicpu(p).opsize := S_L;
  2939. end;
  2940. {$ifdef x86_64}
  2941. S_BQ:
  2942. begin
  2943. convert_mov_value(A_MOVSX, $FF);
  2944. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2945. taicpu(p).opsize := S_Q;
  2946. end;
  2947. S_WQ:
  2948. begin
  2949. convert_mov_value(A_MOVSX, $FFFF);
  2950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2951. taicpu(p).opsize := S_Q;
  2952. end;
  2953. S_LQ:
  2954. begin
  2955. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2956. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2957. taicpu(p).opsize := S_Q;
  2958. end;
  2959. {$endif x86_64}
  2960. else
  2961. { If hp1 was a MOV instruction, it should have been
  2962. optimised already }
  2963. InternalError(2020021001);
  2964. end;
  2965. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2966. RemoveInstruction(hp1);
  2967. Result := True;
  2968. Exit;
  2969. end;
  2970. top_ref:
  2971. begin
  2972. { We have something like:
  2973. movb mem, %regb
  2974. movzbl %regb,%regd
  2975. Change to:
  2976. movzbl mem, %regd
  2977. }
  2978. ThisRef := taicpu(p).oper[0]^.ref^;
  2979. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2980. begin
  2981. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2982. taicpu(hp1).loadref(0, ThisRef);
  2983. { Make sure any registers in the references are properly tracked }
  2984. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2985. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2986. if (ThisRef.index <> NR_NO) then
  2987. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2988. RemoveCurrentP(p, hp1);
  2989. Result := True;
  2990. Exit;
  2991. end;
  2992. end;
  2993. else
  2994. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2995. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2996. Exit;
  2997. end;
  2998. end
  2999. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3000. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3001. optimised }
  3002. else
  3003. begin
  3004. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3005. RemoveCurrentP(p, hp1);
  3006. Result := True;
  3007. Exit;
  3008. end;
  3009. end;
  3010. if (taicpu(hp1).opcode = A_AND) and
  3011. (taicpu(p).oper[1]^.typ = top_reg) and
  3012. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3013. begin
  3014. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3015. begin
  3016. case taicpu(p).opsize of
  3017. S_L:
  3018. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3019. begin
  3020. { Optimize out:
  3021. mov x, %reg
  3022. and ffffffffh, %reg
  3023. }
  3024. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3025. RemoveInstruction(hp1);
  3026. Result:=true;
  3027. exit;
  3028. end;
  3029. S_Q: { TODO: Confirm if this is even possible }
  3030. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3031. begin
  3032. { Optimize out:
  3033. mov x, %reg
  3034. and ffffffffffffffffh, %reg
  3035. }
  3036. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3037. RemoveInstruction(hp1);
  3038. Result:=true;
  3039. exit;
  3040. end;
  3041. else
  3042. ;
  3043. end;
  3044. if (
  3045. (taicpu(p).oper[0]^.typ=top_reg) or
  3046. (
  3047. (taicpu(p).oper[0]^.typ=top_ref) and
  3048. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3049. )
  3050. ) and
  3051. GetNextInstruction(hp1,hp2) and
  3052. MatchInstruction(hp2,A_TEST,[]) and
  3053. (
  3054. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3055. (
  3056. { If the register being tested is smaller than the one
  3057. that received a bitwise AND, permit it if the constant
  3058. fits into the smaller size }
  3059. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3060. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3061. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3062. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3063. (
  3064. (
  3065. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3066. (taicpu(hp1).oper[0]^.val <= $FF)
  3067. ) or
  3068. (
  3069. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3070. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3071. {$ifdef x86_64}
  3072. ) or
  3073. (
  3074. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3075. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3076. {$endif x86_64}
  3077. )
  3078. )
  3079. )
  3080. ) and
  3081. (
  3082. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3083. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3084. ) and
  3085. GetNextInstruction(hp2,hp3) and
  3086. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3087. (taicpu(hp3).condition in [C_E,C_NE]) then
  3088. begin
  3089. TransferUsedRegs(TmpUsedRegs);
  3090. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3091. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3092. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3093. begin
  3094. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3095. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3096. taicpu(hp1).opcode:=A_TEST;
  3097. { Shrink the TEST instruction down to the smallest possible size }
  3098. case taicpu(hp1).oper[0]^.val of
  3099. 0..255:
  3100. if (taicpu(hp1).opsize <> S_B)
  3101. {$ifndef x86_64}
  3102. and (
  3103. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3104. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3105. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3106. )
  3107. {$endif x86_64}
  3108. then
  3109. begin
  3110. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3111. { Only print debug message if the TEST instruction
  3112. is a different size before and after }
  3113. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3114. taicpu(hp1).opsize := S_B;
  3115. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3117. end;
  3118. 256..65535:
  3119. if (taicpu(hp1).opsize <> S_W) then
  3120. begin
  3121. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3122. { Only print debug message if the TEST instruction
  3123. is a different size before and after }
  3124. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3125. taicpu(hp1).opsize := S_W;
  3126. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3127. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3128. end;
  3129. {$ifdef x86_64}
  3130. 65536..$7FFFFFFF:
  3131. if (taicpu(hp1).opsize <> S_L) then
  3132. begin
  3133. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3134. { Only print debug message if the TEST instruction
  3135. is a different size before and after }
  3136. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3137. taicpu(hp1).opsize := S_L;
  3138. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3139. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3140. end;
  3141. {$endif x86_64}
  3142. else
  3143. ;
  3144. end;
  3145. RemoveInstruction(hp2);
  3146. RemoveCurrentP(p, hp1);
  3147. Result:=true;
  3148. exit;
  3149. end;
  3150. end;
  3151. end
  3152. else if IsMOVZXAcceptable and
  3153. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3154. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3155. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3156. then
  3157. begin
  3158. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3159. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3160. case taicpu(p).opsize of
  3161. S_B:
  3162. if (taicpu(hp1).oper[0]^.val = $ff) then
  3163. begin
  3164. { Convert:
  3165. movb x, %regl movb x, %regl
  3166. andw ffh, %regw andl ffh, %regd
  3167. To:
  3168. movzbw x, %regd movzbl x, %regd
  3169. (Identical registers, just different sizes)
  3170. }
  3171. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3172. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3173. case taicpu(hp1).opsize of
  3174. S_W: NewSize := S_BW;
  3175. S_L: NewSize := S_BL;
  3176. {$ifdef x86_64}
  3177. S_Q: NewSize := S_BQ;
  3178. {$endif x86_64}
  3179. else
  3180. InternalError(2018011510);
  3181. end;
  3182. end
  3183. else
  3184. NewSize := S_NO;
  3185. S_W:
  3186. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3187. begin
  3188. { Convert:
  3189. movw x, %regw
  3190. andl ffffh, %regd
  3191. To:
  3192. movzwl x, %regd
  3193. (Identical registers, just different sizes)
  3194. }
  3195. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3196. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3197. case taicpu(hp1).opsize of
  3198. S_L: NewSize := S_WL;
  3199. {$ifdef x86_64}
  3200. S_Q: NewSize := S_WQ;
  3201. {$endif x86_64}
  3202. else
  3203. InternalError(2018011511);
  3204. end;
  3205. end
  3206. else
  3207. NewSize := S_NO;
  3208. else
  3209. NewSize := S_NO;
  3210. end;
  3211. if NewSize <> S_NO then
  3212. begin
  3213. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3214. { The actual optimization }
  3215. taicpu(p).opcode := A_MOVZX;
  3216. taicpu(p).changeopsize(NewSize);
  3217. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3218. { Safeguard if "and" is followed by a conditional command }
  3219. TransferUsedRegs(TmpUsedRegs);
  3220. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3221. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3222. begin
  3223. { At this point, the "and" command is effectively equivalent to
  3224. "test %reg,%reg". This will be handled separately by the
  3225. Peephole Optimizer. [Kit] }
  3226. DebugMsg(SPeepholeOptimization + PreMessage +
  3227. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3228. end
  3229. else
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3232. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3233. RemoveInstruction(hp1);
  3234. end;
  3235. Result := True;
  3236. Exit;
  3237. end;
  3238. end;
  3239. end;
  3240. if (taicpu(hp1).opcode = A_OR) and
  3241. (taicpu(p).oper[1]^.typ = top_reg) and
  3242. MatchOperand(taicpu(p).oper[0]^, 0) and
  3243. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3244. begin
  3245. { mov 0, %reg
  3246. or ###,%reg
  3247. Change to (only if the flags are not used):
  3248. mov ###,%reg
  3249. }
  3250. TransferUsedRegs(TmpUsedRegs);
  3251. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3252. DoOptimisation := True;
  3253. { Even if the flags are used, we might be able to do the optimisation
  3254. if the conditions are predictable }
  3255. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3256. begin
  3257. { Only perform if ### = %reg (the same register) or equal to 0,
  3258. so %reg is guaranteed to still have a value of zero }
  3259. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3260. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3261. begin
  3262. hp2 := hp1;
  3263. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3264. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3265. GetNextInstruction(hp2, hp3) do
  3266. begin
  3267. { Don't continue modifying if the flags state is getting changed }
  3268. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3269. Break;
  3270. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3271. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3272. begin
  3273. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3274. begin
  3275. { Condition is always true }
  3276. case taicpu(hp3).opcode of
  3277. A_Jcc:
  3278. begin
  3279. { Check for jump shortcuts before we destroy the condition }
  3280. hp4 := hp3;
  3281. DoJumpOptimizations(hp3, TempBool);
  3282. { Make sure hp3 hasn't changed }
  3283. if (hp4 = hp3) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3286. MakeUnconditional(taicpu(hp3));
  3287. end;
  3288. Result := True;
  3289. end;
  3290. A_CMOVcc:
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3293. taicpu(hp3).opcode := A_MOV;
  3294. taicpu(hp3).condition := C_None;
  3295. Result := True;
  3296. end;
  3297. A_SETcc:
  3298. begin
  3299. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3300. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3301. taicpu(hp3).opcode := A_MOV;
  3302. taicpu(hp3).ops := 2;
  3303. taicpu(hp3).condition := C_None;
  3304. taicpu(hp3).opsize := S_B;
  3305. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3306. taicpu(hp3).loadconst(0, 1);
  3307. Result := True;
  3308. end;
  3309. else
  3310. InternalError(2021090701);
  3311. end;
  3312. end
  3313. 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
  3314. begin
  3315. { Condition is always false }
  3316. case taicpu(hp3).opcode of
  3317. A_Jcc:
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3320. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3321. RemoveInstruction(hp3);
  3322. Result := True;
  3323. { Since hp3 was deleted, hp2 must not be updated }
  3324. Continue;
  3325. end;
  3326. A_CMOVcc:
  3327. begin
  3328. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3329. RemoveInstruction(hp3);
  3330. Result := True;
  3331. { Since hp3 was deleted, hp2 must not be updated }
  3332. Continue;
  3333. end;
  3334. A_SETcc:
  3335. begin
  3336. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3337. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3338. taicpu(hp3).opcode := A_MOV;
  3339. taicpu(hp3).ops := 2;
  3340. taicpu(hp3).condition := C_None;
  3341. taicpu(hp3).opsize := S_B;
  3342. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3343. taicpu(hp3).loadconst(0, 0);
  3344. Result := True;
  3345. end;
  3346. else
  3347. InternalError(2021090702);
  3348. end;
  3349. end
  3350. else
  3351. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3352. DoOptimisation := False;
  3353. end;
  3354. hp2 := hp3;
  3355. end;
  3356. { Flags are still in use - don't optimise }
  3357. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3358. DoOptimisation := False;
  3359. end
  3360. else
  3361. DoOptimisation := False;
  3362. end;
  3363. if DoOptimisation then
  3364. begin
  3365. {$ifdef x86_64}
  3366. { OR only supports 32-bit sign-extended constants for 64-bit
  3367. instructions, so compensate for this if the constant is
  3368. encoded as a value greater than or equal to 2^31 }
  3369. if (taicpu(hp1).opsize = S_Q) and
  3370. (taicpu(hp1).oper[0]^.typ = top_const) and
  3371. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3372. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3373. {$endif x86_64}
  3374. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3375. taicpu(hp1).opcode := A_MOV;
  3376. RemoveCurrentP(p, hp1);
  3377. Result := True;
  3378. Exit;
  3379. end;
  3380. end;
  3381. { Next instruction is also a MOV ? }
  3382. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3383. begin
  3384. if MatchOpType(taicpu(p), top_const, top_ref) and
  3385. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3386. TryConstMerge(p, hp1) then
  3387. begin
  3388. Result := True;
  3389. { In case we have four byte writes in a row, check for 2 more
  3390. right now so we don't have to wait for another iteration of
  3391. pass 1
  3392. }
  3393. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3394. case taicpu(p).opsize of
  3395. S_W:
  3396. begin
  3397. if GetNextInstruction(p, hp1) and
  3398. MatchInstruction(hp1, A_MOV, [S_B]) and
  3399. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3400. GetNextInstruction(hp1, hp2) and
  3401. MatchInstruction(hp2, A_MOV, [S_B]) and
  3402. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3403. { Try to merge the two bytes }
  3404. TryConstMerge(hp1, hp2) then
  3405. { Now try to merge the two words (hp2 will get deleted) }
  3406. TryConstMerge(p, hp1);
  3407. end;
  3408. S_L:
  3409. begin
  3410. { Though this only really benefits x86_64 and not i386, it
  3411. gets a potential optimisation done faster and hence
  3412. reduces the number of times OptPass1MOV is entered }
  3413. if GetNextInstruction(p, hp1) and
  3414. MatchInstruction(hp1, A_MOV, [S_W]) and
  3415. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3416. GetNextInstruction(hp1, hp2) and
  3417. MatchInstruction(hp2, A_MOV, [S_W]) and
  3418. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3419. { Try to merge the two words }
  3420. TryConstMerge(hp1, hp2) then
  3421. { This will always fail on i386, so don't bother
  3422. calling it unless we're doing x86_64 }
  3423. {$ifdef x86_64}
  3424. { Now try to merge the two longwords (hp2 will get deleted) }
  3425. TryConstMerge(p, hp1)
  3426. {$endif x86_64}
  3427. ;
  3428. end;
  3429. else
  3430. ;
  3431. end;
  3432. Exit;
  3433. end;
  3434. if (taicpu(p).oper[1]^.typ = top_reg) and
  3435. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3436. begin
  3437. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3438. TransferUsedRegs(TmpUsedRegs);
  3439. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3440. { we have
  3441. mov x, %treg
  3442. mov %treg, y
  3443. }
  3444. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3445. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3446. { we've got
  3447. mov x, %treg
  3448. mov %treg, y
  3449. with %treg is not used after }
  3450. case taicpu(p).oper[0]^.typ Of
  3451. { top_reg is covered by DeepMOVOpt }
  3452. top_const:
  3453. begin
  3454. { change
  3455. mov const, %treg
  3456. mov %treg, y
  3457. to
  3458. mov const, y
  3459. }
  3460. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3461. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3462. begin
  3463. if taicpu(hp1).oper[1]^.typ=top_reg then
  3464. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3465. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3466. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3467. RemoveInstruction(hp1);
  3468. Result:=true;
  3469. Exit;
  3470. end;
  3471. end;
  3472. top_ref:
  3473. case taicpu(hp1).oper[1]^.typ of
  3474. top_reg:
  3475. begin
  3476. { change
  3477. mov mem, %treg
  3478. mov %treg, %reg
  3479. to
  3480. mov mem, %reg"
  3481. }
  3482. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3483. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3484. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3485. RemoveInstruction(hp1);
  3486. Result:=true;
  3487. Exit;
  3488. end;
  3489. top_ref:
  3490. begin
  3491. {$ifdef x86_64}
  3492. { Look for the following to simplify:
  3493. mov x(mem1), %reg
  3494. mov %reg, y(mem2)
  3495. mov x+8(mem1), %reg
  3496. mov %reg, y+8(mem2)
  3497. Change to:
  3498. movdqu x(mem1), %xmmreg
  3499. movdqu %xmmreg, y(mem2)
  3500. ...but only as long as the memory blocks don't overlap
  3501. }
  3502. SourceRef := taicpu(p).oper[0]^.ref^;
  3503. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3504. if (taicpu(p).opsize = S_Q) and
  3505. GetNextInstruction(hp1, hp2) and
  3506. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3507. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3508. begin
  3509. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3510. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3511. Inc(SourceRef.offset, 8);
  3512. if UseAVX then
  3513. begin
  3514. MovAligned := A_VMOVDQA;
  3515. MovUnaligned := A_VMOVDQU;
  3516. end
  3517. else
  3518. begin
  3519. MovAligned := A_MOVDQA;
  3520. MovUnaligned := A_MOVDQU;
  3521. end;
  3522. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3523. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3524. begin
  3525. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3526. Inc(TargetRef.offset, 8);
  3527. if GetNextInstruction(hp2, hp3) and
  3528. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3529. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3530. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3531. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3532. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3533. begin
  3534. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3535. if NewMMReg <> NR_NO then
  3536. begin
  3537. { Remember that the offsets are 8 ahead }
  3538. if ((SourceRef.offset mod 16) = 8) and
  3539. (
  3540. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3541. (SourceRef.base = current_procinfo.framepointer) or
  3542. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3543. ) then
  3544. taicpu(p).opcode := MovAligned
  3545. else
  3546. taicpu(p).opcode := MovUnaligned;
  3547. taicpu(p).opsize := S_XMM;
  3548. taicpu(p).oper[1]^.reg := NewMMReg;
  3549. if ((TargetRef.offset mod 16) = 8) and
  3550. (
  3551. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3552. (TargetRef.base = current_procinfo.framepointer) or
  3553. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3554. ) then
  3555. taicpu(hp1).opcode := MovAligned
  3556. else
  3557. taicpu(hp1).opcode := MovUnaligned;
  3558. taicpu(hp1).opsize := S_XMM;
  3559. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3561. RemoveInstruction(hp2);
  3562. RemoveInstruction(hp3);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. end
  3568. else
  3569. begin
  3570. { See if the next references are 8 less rather than 8 greater }
  3571. Dec(SourceRef.offset, 16); { -8 the other way }
  3572. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3573. begin
  3574. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3575. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3576. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3577. GetNextInstruction(hp2, hp3) and
  3578. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3579. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3580. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3581. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3582. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3583. begin
  3584. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3585. if NewMMReg <> NR_NO then
  3586. begin
  3587. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3588. if ((SourceRef.offset mod 16) = 0) and
  3589. (
  3590. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3591. (SourceRef.base = current_procinfo.framepointer) or
  3592. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3593. ) then
  3594. taicpu(hp2).opcode := MovAligned
  3595. else
  3596. taicpu(hp2).opcode := MovUnaligned;
  3597. taicpu(hp2).opsize := S_XMM;
  3598. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3599. if ((TargetRef.offset mod 16) = 0) and
  3600. (
  3601. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3602. (TargetRef.base = current_procinfo.framepointer) or
  3603. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3604. ) then
  3605. taicpu(hp3).opcode := MovAligned
  3606. else
  3607. taicpu(hp3).opcode := MovUnaligned;
  3608. taicpu(hp3).opsize := S_XMM;
  3609. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3610. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3611. RemoveInstruction(hp1);
  3612. RemoveCurrentP(p, hp2);
  3613. Result := True;
  3614. Exit;
  3615. end;
  3616. end;
  3617. end;
  3618. end;
  3619. end;
  3620. {$endif x86_64}
  3621. end;
  3622. else
  3623. { The write target should be a reg or a ref }
  3624. InternalError(2021091601);
  3625. end;
  3626. else
  3627. ;
  3628. end
  3629. else
  3630. { %treg is used afterwards, but all eventualities
  3631. other than the first MOV instruction being a constant
  3632. are covered by DeepMOVOpt, so only check for that }
  3633. if (taicpu(p).oper[0]^.typ = top_const) and
  3634. (
  3635. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3636. not (cs_opt_size in current_settings.optimizerswitches) or
  3637. (taicpu(hp1).opsize = S_B)
  3638. ) and
  3639. (
  3640. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3641. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3642. ) then
  3643. begin
  3644. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3645. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3646. end;
  3647. end;
  3648. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3649. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3650. { mov reg1, mem1 or mov mem1, reg1
  3651. mov mem2, reg2 mov reg2, mem2}
  3652. begin
  3653. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3654. { mov reg1, mem1 or mov mem1, reg1
  3655. mov mem2, reg1 mov reg2, mem1}
  3656. begin
  3657. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3658. { Removes the second statement from
  3659. mov reg1, mem1/reg2
  3660. mov mem1/reg2, reg1 }
  3661. begin
  3662. if taicpu(p).oper[0]^.typ=top_reg then
  3663. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3664. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3665. RemoveInstruction(hp1);
  3666. Result:=true;
  3667. exit;
  3668. end
  3669. else
  3670. begin
  3671. TransferUsedRegs(TmpUsedRegs);
  3672. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3673. if (taicpu(p).oper[1]^.typ = top_ref) and
  3674. { mov reg1, mem1
  3675. mov mem2, reg1 }
  3676. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3679. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3680. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3681. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3682. { change to
  3683. mov reg1, mem1 mov reg1, mem1
  3684. mov mem2, reg1 cmp reg1, mem2
  3685. cmp mem1, reg1
  3686. }
  3687. begin
  3688. RemoveInstruction(hp2);
  3689. taicpu(hp1).opcode := A_CMP;
  3690. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3691. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3692. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3693. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3694. end;
  3695. end;
  3696. end
  3697. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3698. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3699. begin
  3700. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3701. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3702. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3703. end
  3704. else
  3705. begin
  3706. TransferUsedRegs(TmpUsedRegs);
  3707. if GetNextInstruction(hp1, hp2) and
  3708. MatchOpType(taicpu(p),top_ref,top_reg) and
  3709. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3710. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3711. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3712. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3713. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3714. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3715. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3716. { mov mem1, %reg1
  3717. mov %reg1, mem2
  3718. mov mem2, reg2
  3719. to:
  3720. mov mem1, reg2
  3721. mov reg2, mem2}
  3722. begin
  3723. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3724. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3725. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3726. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3727. RemoveInstruction(hp2);
  3728. Result := True;
  3729. end
  3730. {$ifdef i386}
  3731. { this is enabled for i386 only, as the rules to create the reg sets below
  3732. are too complicated for x86-64, so this makes this code too error prone
  3733. on x86-64
  3734. }
  3735. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3736. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3737. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3738. { mov mem1, reg1 mov mem1, reg1
  3739. mov reg1, mem2 mov reg1, mem2
  3740. mov mem2, reg2 mov mem2, reg1
  3741. to: to:
  3742. mov mem1, reg1 mov mem1, reg1
  3743. mov mem1, reg2 mov reg1, mem2
  3744. mov reg1, mem2
  3745. or (if mem1 depends on reg1
  3746. and/or if mem2 depends on reg2)
  3747. to:
  3748. mov mem1, reg1
  3749. mov reg1, mem2
  3750. mov reg1, reg2
  3751. }
  3752. begin
  3753. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3754. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3755. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3756. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3757. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3758. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3759. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3760. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3761. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3762. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3763. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3764. end
  3765. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3766. begin
  3767. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3768. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3769. end
  3770. else
  3771. begin
  3772. RemoveInstruction(hp2);
  3773. end
  3774. {$endif i386}
  3775. ;
  3776. end;
  3777. end
  3778. { movl [mem1],reg1
  3779. movl [mem1],reg2
  3780. to
  3781. movl [mem1],reg1
  3782. movl reg1,reg2
  3783. }
  3784. else if not CheckMovMov2MovMov2(p, hp1) and
  3785. { movl const1,[mem1]
  3786. movl [mem1],reg1
  3787. to
  3788. movl const1,reg1
  3789. movl reg1,[mem1]
  3790. }
  3791. MatchOpType(Taicpu(p),top_const,top_ref) and
  3792. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3793. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3794. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3795. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3796. begin
  3797. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3798. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3799. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3800. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3801. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3802. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3803. Result:=true;
  3804. exit;
  3805. end;
  3806. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3807. { Change:
  3808. movl %reg1,%reg2
  3809. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3810. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3811. To:
  3812. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3813. movl x(%reg1),%reg1
  3814. movl %reg1,%regX
  3815. }
  3816. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3817. begin
  3818. p_SourceReg := taicpu(p).oper[0]^.reg;
  3819. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3820. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3821. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3822. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3823. GetNextInstruction(hp1, hp2) and
  3824. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3825. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3826. begin
  3827. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3828. if RegInRef(p_TargetReg, SourceRef) and
  3829. { If %reg1 also appears in the second reference, then it will
  3830. not refer to the same memory block as the first reference }
  3831. not RegInRef(p_SourceReg, SourceRef) then
  3832. begin
  3833. { Check to see if the references match if %reg2 is changed to %reg1 }
  3834. if SourceRef.base = p_TargetReg then
  3835. SourceRef.base := p_SourceReg;
  3836. if SourceRef.index = p_TargetReg then
  3837. SourceRef.index := p_SourceReg;
  3838. { RefsEqual also checks to ensure both references are non-volatile }
  3839. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3840. begin
  3841. taicpu(hp2).loadreg(0, p_SourceReg);
  3842. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3843. Result := True;
  3844. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3845. begin
  3846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3847. RemoveCurrentP(p, hp1);
  3848. Exit;
  3849. end
  3850. else
  3851. begin
  3852. { Check to see if %reg2 is no longer in use }
  3853. TransferUsedRegs(TmpUsedRegs);
  3854. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3855. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3856. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3857. begin
  3858. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3859. RemoveCurrentP(p, hp1);
  3860. Exit;
  3861. end;
  3862. end;
  3863. { If we reach this point, p and hp1 weren't actually modified,
  3864. so we can do a bit more work on this pass }
  3865. end;
  3866. end;
  3867. end;
  3868. end;
  3869. end;
  3870. {$ifdef x86_64}
  3871. { Change:
  3872. movl %reg1l,%reg2l
  3873. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3874. To:
  3875. movl %reg1l,%reg2l
  3876. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3877. If %reg1 = %reg3, convert to:
  3878. movl %reg1l,%reg2l
  3879. andl %reg1l,%reg1l
  3880. }
  3881. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3882. MatchOpType(taicpu(p), top_reg, top_reg) and
  3883. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3884. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3888. taicpu(hp1).opsize := S_L;
  3889. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3890. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3891. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3892. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3893. begin
  3894. { %reg1 = %reg3 }
  3895. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3896. taicpu(hp1).opcode := A_AND;
  3897. end
  3898. else
  3899. begin
  3900. { %reg1 <> %reg3 }
  3901. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3902. end;
  3903. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3904. begin
  3905. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3906. RemoveCurrentP(p, hp1);
  3907. Result := True;
  3908. Exit;
  3909. end
  3910. else
  3911. begin
  3912. { Initial instruction wasn't actually changed }
  3913. Include(OptsToCheck, aoc_ForceNewIteration);
  3914. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3915. appears below since %reg1 has technically changed }
  3916. if taicpu(hp1).opcode = A_AND then
  3917. Exit;
  3918. end;
  3919. end;
  3920. {$endif x86_64}
  3921. { search further than the next instruction for a mov (as long as it's not a jump) }
  3922. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3923. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3924. (taicpu(p).oper[1]^.typ = top_reg) and
  3925. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3926. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3927. begin
  3928. { we work with hp2 here, so hp1 can be still used later on when
  3929. checking for GetNextInstruction_p }
  3930. hp3 := hp1;
  3931. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3932. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3933. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3934. TransferUsedRegs(TmpUsedRegs);
  3935. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3936. if NotFirstIteration then
  3937. JumpTracking := TLinkedList.Create
  3938. else
  3939. JumpTracking := nil;
  3940. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3941. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3942. (hp2.typ=ait_instruction) do
  3943. begin
  3944. case taicpu(hp2).opcode of
  3945. A_POP:
  3946. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3947. begin
  3948. if not CrossJump and
  3949. not RegUsedBetween(p_TargetReg, p, hp2) then
  3950. begin
  3951. { We can remove the original MOV since the register
  3952. wasn't used between it and its popping from the stack }
  3953. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3954. RemoveCurrentp(p, hp1);
  3955. Result := True;
  3956. JumpTracking.Free;
  3957. Exit;
  3958. end;
  3959. { Can't go any further }
  3960. Break;
  3961. end;
  3962. A_MOV:
  3963. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3964. ((taicpu(p).oper[0]^.typ=top_const) or
  3965. ((taicpu(p).oper[0]^.typ=top_reg) and
  3966. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3967. )
  3968. ) then
  3969. begin
  3970. { we have
  3971. mov x, %treg
  3972. mov %treg, y
  3973. }
  3974. { We don't need to call UpdateUsedRegs for every instruction between
  3975. p and hp2 because the register we're concerned about will not
  3976. become deallocated (otherwise GetNextInstructionUsingReg would
  3977. have stopped at an earlier instruction). [Kit] }
  3978. TempRegUsed :=
  3979. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3980. RegReadByInstruction(p_TargetReg, hp3) or
  3981. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3982. case taicpu(p).oper[0]^.typ Of
  3983. top_reg:
  3984. begin
  3985. { change
  3986. mov %reg, %treg
  3987. mov %treg, y
  3988. to
  3989. mov %reg, y
  3990. }
  3991. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3992. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3993. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3994. begin
  3995. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3996. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3997. if TempRegUsed then
  3998. begin
  3999. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4000. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4001. { Set the start of the next GetNextInstructionUsingRegCond search
  4002. to start at the entry right before hp2 (which is about to be removed) }
  4003. hp3 := tai(hp2.Previous);
  4004. RemoveInstruction(hp2);
  4005. Include(OptsToCheck, aoc_ForceNewIteration);
  4006. { See if there's more we can optimise }
  4007. Continue;
  4008. end
  4009. else
  4010. begin
  4011. RemoveInstruction(hp2);
  4012. { We can remove the original MOV too }
  4013. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4014. RemoveCurrentP(p, hp1);
  4015. Result:=true;
  4016. JumpTracking.Free;
  4017. Exit;
  4018. end;
  4019. end
  4020. else
  4021. begin
  4022. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4023. taicpu(hp2).loadReg(0, p_SourceReg);
  4024. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4025. { Check to see if the register also appears in the reference }
  4026. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4027. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4028. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4029. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4030. begin
  4031. { Don't remove the first instruction if the temporary register is in use }
  4032. if not TempRegUsed then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4035. RemoveCurrentP(p, hp1);
  4036. Result:=true;
  4037. JumpTracking.Free;
  4038. Exit;
  4039. end;
  4040. { No need to set Result to True here. If there's another instruction later
  4041. on that can be optimised, it will be detected when the main Pass 1 loop
  4042. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4043. hp3 := hp2;
  4044. Continue;
  4045. end;
  4046. end;
  4047. end;
  4048. top_const:
  4049. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4050. begin
  4051. { change
  4052. mov const, %treg
  4053. mov %treg, y
  4054. to
  4055. mov const, y
  4056. }
  4057. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4058. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4059. begin
  4060. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4061. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4062. if TempRegUsed then
  4063. begin
  4064. { Don't remove the first instruction if the temporary register is in use }
  4065. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4066. { No need to set Result to True. If there's another instruction later on
  4067. that can be optimised, it will be detected when the main Pass 1 loop
  4068. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4069. end
  4070. else
  4071. begin
  4072. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4073. RemoveCurrentP(p, hp1);
  4074. Result:=true;
  4075. Exit;
  4076. end;
  4077. end;
  4078. end;
  4079. else
  4080. Internalerror(2019103001);
  4081. end;
  4082. end
  4083. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4084. begin
  4085. if not CrossJump and
  4086. not RegUsedBetween(p_TargetReg, p, hp2) and
  4087. not RegReadByInstruction(p_TargetReg, hp2) then
  4088. begin
  4089. { Register is not used before it is overwritten }
  4090. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4091. RemoveCurrentp(p, hp1);
  4092. Result := True;
  4093. Exit;
  4094. end;
  4095. if (taicpu(p).oper[0]^.typ = top_const) and
  4096. (taicpu(hp2).oper[0]^.typ = top_const) then
  4097. begin
  4098. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4099. begin
  4100. { Same value - register hasn't changed }
  4101. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4102. RemoveInstruction(hp2);
  4103. Include(OptsToCheck, aoc_ForceNewIteration);
  4104. { See if there's more we can optimise }
  4105. Continue;
  4106. end;
  4107. end;
  4108. {$ifdef x86_64}
  4109. end
  4110. { Change:
  4111. movl %reg1l,%reg2l
  4112. ...
  4113. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4114. To:
  4115. movl %reg1l,%reg2l
  4116. ...
  4117. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4118. If %reg1 = %reg3, convert to:
  4119. movl %reg1l,%reg2l
  4120. ...
  4121. andl %reg1l,%reg1l
  4122. }
  4123. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4124. (taicpu(p).oper[0]^.typ = top_reg) and
  4125. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4126. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4127. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4128. begin
  4129. TempRegUsed :=
  4130. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4131. RegReadByInstruction(p_TargetReg, hp3) or
  4132. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4133. taicpu(hp2).opsize := S_L;
  4134. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4135. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4136. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4137. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4138. begin
  4139. { %reg1 = %reg3 }
  4140. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4141. taicpu(hp2).opcode := A_AND;
  4142. end
  4143. else
  4144. begin
  4145. { %reg1 <> %reg3 }
  4146. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4147. end;
  4148. if not TempRegUsed then
  4149. begin
  4150. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4151. RemoveCurrentP(p, hp1);
  4152. Result := True;
  4153. Exit;
  4154. end
  4155. else
  4156. begin
  4157. { Initial instruction wasn't actually changed }
  4158. Include(OptsToCheck, aoc_ForceNewIteration);
  4159. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4160. appears below since %reg1 has technically changed }
  4161. if taicpu(hp2).opcode = A_AND then
  4162. Break;
  4163. end;
  4164. {$endif x86_64}
  4165. end
  4166. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4167. GetNextInstruction(hp2, hp4) and
  4168. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4169. { Optimise the following first:
  4170. movl [mem1],reg1
  4171. movl [mem1],reg2
  4172. to
  4173. movl [mem1],reg1
  4174. movl reg1,reg2
  4175. If [mem1] contains the target register and reg1 is the
  4176. the source register, this optimisation will get missed
  4177. and produce less efficient code later on.
  4178. }
  4179. if CheckMovMov2MovMov2(hp2, hp4) then
  4180. { Initial instruction wasn't actually changed }
  4181. Include(OptsToCheck, aoc_ForceNewIteration);
  4182. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4183. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4184. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4185. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4186. begin
  4187. {
  4188. Change from:
  4189. mov ###, %reg
  4190. ...
  4191. movs/z %reg,%reg (Same register, just different sizes)
  4192. To:
  4193. movs/z ###, %reg (Longer version)
  4194. ...
  4195. (remove)
  4196. }
  4197. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4198. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4199. { Keep the first instruction as mov if ### is a constant }
  4200. if taicpu(p).oper[0]^.typ = top_const then
  4201. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4202. else
  4203. begin
  4204. taicpu(p).opcode := taicpu(hp2).opcode;
  4205. taicpu(p).opsize := taicpu(hp2).opsize;
  4206. end;
  4207. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4208. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4209. RemoveInstruction(hp2);
  4210. Result := True;
  4211. JumpTracking.Free;
  4212. Exit;
  4213. end;
  4214. else
  4215. { Move down to the if-block below };
  4216. end;
  4217. { Also catches MOV/S/Z instructions that aren't modified }
  4218. if taicpu(p).oper[0]^.typ = top_reg then
  4219. begin
  4220. p_SourceReg := taicpu(p).oper[0]^.reg;
  4221. if
  4222. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4223. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4224. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4225. begin
  4226. Result := True;
  4227. { Just in case something didn't get modified (e.g. an
  4228. implicit register). Also, if it does read from this
  4229. register, then there's no longer an advantage to
  4230. changing the register on subsequent instructions.}
  4231. if not RegReadByInstruction(p_TargetReg, hp2) then
  4232. begin
  4233. { If a conditional jump was crossed, do not delete
  4234. the original MOV no matter what }
  4235. if not CrossJump and
  4236. { RegEndOfLife returns True if the register is
  4237. deallocated before the next instruction or has
  4238. been loaded with a new value }
  4239. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4240. begin
  4241. { We can remove the original MOV }
  4242. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4243. RemoveCurrentp(p, hp1);
  4244. JumpTracking.Free;
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4249. begin
  4250. { See if there's more we can optimise }
  4251. hp3 := hp2;
  4252. Continue;
  4253. end;
  4254. end;
  4255. end;
  4256. end;
  4257. { Break out of the while loop under normal circumstances }
  4258. Break;
  4259. end;
  4260. JumpTracking.Free;
  4261. end;
  4262. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4263. (taicpu(p).oper[1]^.typ = top_reg) and
  4264. (taicpu(p).opsize = S_L) and
  4265. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4266. (hp2.typ = ait_instruction) and
  4267. (taicpu(hp2).opcode = A_AND) and
  4268. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4269. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4270. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4271. ) then
  4272. begin
  4273. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4274. begin
  4275. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4276. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4277. begin
  4278. { Optimize out:
  4279. mov x, %reg
  4280. and ffffffffh, %reg
  4281. }
  4282. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4283. RemoveInstruction(hp2);
  4284. Result:=true;
  4285. exit;
  4286. end;
  4287. end;
  4288. end;
  4289. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4290. x >= RetOffset) as it doesn't do anything (it writes either to a
  4291. parameter or to the temporary storage room for the function
  4292. result)
  4293. }
  4294. if IsExitCode(hp1) and
  4295. (taicpu(p).oper[1]^.typ = top_ref) and
  4296. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4297. (
  4298. (
  4299. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4300. not (
  4301. assigned(current_procinfo.procdef.funcretsym) and
  4302. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4303. )
  4304. ) or
  4305. { Also discard writes to the stack that are below the base pointer,
  4306. as this is temporary storage rather than a function result on the
  4307. stack, say. }
  4308. (
  4309. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4310. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4311. )
  4312. ) then
  4313. begin
  4314. RemoveCurrentp(p, hp1);
  4315. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4316. RemoveLastDeallocForFuncRes(p);
  4317. Result:=true;
  4318. exit;
  4319. end;
  4320. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4321. begin
  4322. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4323. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4324. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4325. begin
  4326. { change
  4327. mov reg1, mem1
  4328. test/cmp x, mem1
  4329. to
  4330. mov reg1, mem1
  4331. test/cmp x, reg1
  4332. }
  4333. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4334. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4335. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4336. Result := True;
  4337. Exit;
  4338. end;
  4339. if DoMovCmpMemOpt(p, hp1) then
  4340. begin
  4341. Result := True;
  4342. Exit;
  4343. end;
  4344. end;
  4345. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4346. { If the flags register is in use, don't change the instruction to an
  4347. ADD otherwise this will scramble the flags. [Kit] }
  4348. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4349. begin
  4350. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4351. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4352. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4353. ) or
  4354. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4355. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4356. )
  4357. ) then
  4358. { mov reg1,ref
  4359. lea reg2,[reg1,reg2]
  4360. to
  4361. add reg2,ref}
  4362. begin
  4363. TransferUsedRegs(TmpUsedRegs);
  4364. { reg1 may not be used afterwards }
  4365. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4366. begin
  4367. Taicpu(hp1).opcode:=A_ADD;
  4368. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4369. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4370. RemoveCurrentp(p, hp1);
  4371. result:=true;
  4372. exit;
  4373. end;
  4374. end;
  4375. { If the LEA instruction can be converted into an arithmetic instruction,
  4376. it may be possible to then fold it in the next optimisation, otherwise
  4377. there's nothing more that can be optimised here. }
  4378. if not ConvertLEA(taicpu(hp1)) then
  4379. Exit;
  4380. end;
  4381. if (taicpu(p).oper[1]^.typ = top_reg) and
  4382. (hp1.typ = ait_instruction) and
  4383. GetNextInstruction(hp1, hp2) and
  4384. MatchInstruction(hp2,A_MOV,[]) and
  4385. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4386. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4387. (
  4388. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4389. {$ifdef x86_64}
  4390. or
  4391. (
  4392. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4393. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4394. )
  4395. {$endif x86_64}
  4396. ) then
  4397. begin
  4398. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4399. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4400. { change movsX/movzX reg/ref, reg2
  4401. add/sub/or/... reg3/$const, reg2
  4402. mov reg2 reg/ref
  4403. dealloc reg2
  4404. to
  4405. add/sub/or/... reg3/$const, reg/ref }
  4406. begin
  4407. TransferUsedRegs(TmpUsedRegs);
  4408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4409. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4411. begin
  4412. { by example:
  4413. movswl %si,%eax movswl %si,%eax p
  4414. decl %eax addl %edx,%eax hp1
  4415. movw %ax,%si movw %ax,%si hp2
  4416. ->
  4417. movswl %si,%eax movswl %si,%eax p
  4418. decw %eax addw %edx,%eax hp1
  4419. movw %ax,%si movw %ax,%si hp2
  4420. }
  4421. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4422. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4423. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4424. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4425. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4426. {
  4427. ->
  4428. movswl %si,%eax movswl %si,%eax p
  4429. decw %si addw %dx,%si hp1
  4430. movw %ax,%si movw %ax,%si hp2
  4431. }
  4432. case taicpu(hp1).ops of
  4433. 1:
  4434. begin
  4435. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4436. if taicpu(hp1).oper[0]^.typ=top_reg then
  4437. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4438. end;
  4439. 2:
  4440. begin
  4441. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4442. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4443. (taicpu(hp1).opcode<>A_SHL) and
  4444. (taicpu(hp1).opcode<>A_SHR) and
  4445. (taicpu(hp1).opcode<>A_SAR) then
  4446. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4447. end;
  4448. else
  4449. internalerror(2008042701);
  4450. end;
  4451. {
  4452. ->
  4453. decw %si addw %dx,%si p
  4454. }
  4455. RemoveInstruction(hp2);
  4456. RemoveCurrentP(p, hp1);
  4457. Result:=True;
  4458. Exit;
  4459. end;
  4460. end;
  4461. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4462. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4463. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4464. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4465. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4466. )
  4467. {$ifdef i386}
  4468. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4469. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4470. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4471. {$endif i386}
  4472. then
  4473. { change movsX/movzX reg/ref, reg2
  4474. add/sub/or/... regX/$const, reg2
  4475. mov reg2, reg3
  4476. dealloc reg2
  4477. to
  4478. movsX/movzX reg/ref, reg3
  4479. add/sub/or/... reg3/$const, reg3
  4480. }
  4481. begin
  4482. TransferUsedRegs(TmpUsedRegs);
  4483. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4484. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4485. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4486. begin
  4487. { by example:
  4488. movswl %si,%eax movswl %si,%eax p
  4489. decl %eax addl %edx,%eax hp1
  4490. movw %ax,%si movw %ax,%si hp2
  4491. ->
  4492. movswl %si,%eax movswl %si,%eax p
  4493. decw %eax addw %edx,%eax hp1
  4494. movw %ax,%si movw %ax,%si hp2
  4495. }
  4496. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4497. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4498. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4499. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4500. { limit size of constants as well to avoid assembler errors, but
  4501. check opsize to avoid overflow when left shifting the 1 }
  4502. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4503. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4504. {$ifdef x86_64}
  4505. { Be careful of, for example:
  4506. movl %reg1,%reg2
  4507. addl %reg3,%reg2
  4508. movq %reg2,%reg4
  4509. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4510. }
  4511. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4512. begin
  4513. taicpu(hp2).changeopsize(S_L);
  4514. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4515. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4516. end;
  4517. {$endif x86_64}
  4518. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4519. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4520. if taicpu(p).oper[0]^.typ=top_reg then
  4521. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4522. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4523. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4524. {
  4525. ->
  4526. movswl %si,%eax movswl %si,%eax p
  4527. decw %si addw %dx,%si hp1
  4528. movw %ax,%si movw %ax,%si hp2
  4529. }
  4530. case taicpu(hp1).ops of
  4531. 1:
  4532. begin
  4533. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4534. if taicpu(hp1).oper[0]^.typ=top_reg then
  4535. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4536. end;
  4537. 2:
  4538. begin
  4539. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4540. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4541. (taicpu(hp1).opcode<>A_SHL) and
  4542. (taicpu(hp1).opcode<>A_SHR) and
  4543. (taicpu(hp1).opcode<>A_SAR) then
  4544. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4545. end;
  4546. else
  4547. internalerror(2018111801);
  4548. end;
  4549. {
  4550. ->
  4551. decw %si addw %dx,%si p
  4552. }
  4553. RemoveInstruction(hp2);
  4554. end;
  4555. end;
  4556. end;
  4557. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4558. GetNextInstruction(hp1, hp2) and
  4559. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4560. MatchOperand(Taicpu(p).oper[0]^,0) and
  4561. (Taicpu(p).oper[1]^.typ = top_reg) and
  4562. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4563. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4564. { mov reg1,0
  4565. bts reg1,operand1 --> mov reg1,operand2
  4566. or reg1,operand2 bts reg1,operand1}
  4567. begin
  4568. Taicpu(hp2).opcode:=A_MOV;
  4569. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4570. asml.remove(hp1);
  4571. insertllitem(hp2,hp2.next,hp1);
  4572. RemoveCurrentp(p, hp1);
  4573. Result:=true;
  4574. exit;
  4575. end;
  4576. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4577. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4578. GetNextInstruction(hp1, hp2) and
  4579. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4580. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4581. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4582. { change
  4583. mov reg1,reg2
  4584. sub reg3,reg2
  4585. cmp reg3,reg1
  4586. into
  4587. mov reg1,reg2
  4588. sub reg3,reg2
  4589. }
  4590. begin
  4591. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4592. RemoveInstruction(hp2);
  4593. Result:=true;
  4594. exit;
  4595. end;
  4596. {
  4597. mov ref,reg0
  4598. <op> reg0,reg1
  4599. dealloc reg0
  4600. to
  4601. <op> ref,reg1
  4602. }
  4603. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4604. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4606. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4607. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4608. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4609. begin
  4610. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4611. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4612. RemoveCurrentp(p, hp1);
  4613. Result:=true;
  4614. exit;
  4615. end;
  4616. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4617. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4618. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4619. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4620. begin
  4621. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4622. {$ifdef x86_64}
  4623. { Convert:
  4624. movq x(ref),%reg64
  4625. shrq y,%reg64
  4626. To:
  4627. movl x+4(ref),%reg32
  4628. shrl y-32,%reg32 (Remove if y = 32)
  4629. }
  4630. if (taicpu(p).opsize = S_Q) and
  4631. (taicpu(hp1).opcode = A_SHR) and
  4632. (taicpu(hp1).oper[0]^.val >= 32) then
  4633. begin
  4634. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4635. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4636. { Convert to 32-bit }
  4637. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4638. taicpu(p).opsize := S_L;
  4639. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4640. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4641. if (taicpu(hp1).oper[0]^.val = 32) then
  4642. begin
  4643. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4644. RemoveInstruction(hp1);
  4645. end
  4646. else
  4647. begin
  4648. { This will potentially open up more arithmetic operations since
  4649. the peephole optimizer now has a big hint that only the lower
  4650. 32 bits are currently in use (and opcodes are smaller in size) }
  4651. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4652. taicpu(hp1).opsize := S_L;
  4653. Dec(taicpu(hp1).oper[0]^.val, 32);
  4654. DebugMsg(SPeepholeOptimization + PreMessage +
  4655. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4656. end;
  4657. Result := True;
  4658. Exit;
  4659. end;
  4660. {$endif x86_64}
  4661. { Convert:
  4662. movl x(ref),%reg
  4663. shrl $24,%reg
  4664. To:
  4665. movzbl x+3(ref),%reg
  4666. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4667. Also accept sar instead of shr, but convert to movsx instead of movzx
  4668. }
  4669. if taicpu(hp1).opcode = A_SHR then
  4670. MovUnaligned := A_MOVZX
  4671. else
  4672. MovUnaligned := A_MOVSX;
  4673. NewSize := S_NO;
  4674. NewOffset := 0;
  4675. case taicpu(p).opsize of
  4676. S_B:
  4677. { No valid combinations };
  4678. S_W:
  4679. if (taicpu(hp1).oper[0]^.val = 8) then
  4680. begin
  4681. NewSize := S_BW;
  4682. NewOffset := 1;
  4683. end;
  4684. S_L:
  4685. case taicpu(hp1).oper[0]^.val of
  4686. 16:
  4687. begin
  4688. NewSize := S_WL;
  4689. NewOffset := 2;
  4690. end;
  4691. 24:
  4692. begin
  4693. NewSize := S_BL;
  4694. NewOffset := 3;
  4695. end;
  4696. else
  4697. ;
  4698. end;
  4699. {$ifdef x86_64}
  4700. S_Q:
  4701. case taicpu(hp1).oper[0]^.val of
  4702. 32:
  4703. begin
  4704. if taicpu(hp1).opcode = A_SAR then
  4705. begin
  4706. { 32-bit to 64-bit is a distinct instruction }
  4707. MovUnaligned := A_MOVSXD;
  4708. NewSize := S_LQ;
  4709. NewOffset := 4;
  4710. end
  4711. else
  4712. { Should have been handled by MovShr2Mov above }
  4713. InternalError(2022081811);
  4714. end;
  4715. 48:
  4716. begin
  4717. NewSize := S_WQ;
  4718. NewOffset := 6;
  4719. end;
  4720. 56:
  4721. begin
  4722. NewSize := S_BQ;
  4723. NewOffset := 7;
  4724. end;
  4725. else
  4726. ;
  4727. end;
  4728. {$endif x86_64}
  4729. else
  4730. InternalError(2022081810);
  4731. end;
  4732. if (NewSize <> S_NO) and
  4733. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4734. begin
  4735. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4736. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4737. debug_op2str(MovUnaligned);
  4738. {$ifdef x86_64}
  4739. if MovUnaligned <> A_MOVSXD then
  4740. { Don't add size suffix for MOVSXD }
  4741. {$endif x86_64}
  4742. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4743. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4744. taicpu(p).opcode := MovUnaligned;
  4745. taicpu(p).opsize := NewSize;
  4746. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4747. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4748. RemoveInstruction(hp1);
  4749. Result := True;
  4750. Exit;
  4751. end;
  4752. end;
  4753. { Backward optimisation shared with OptPass2MOV }
  4754. if FuncMov2Func(p, hp1) then
  4755. begin
  4756. Result := True;
  4757. Exit;
  4758. end;
  4759. end;
  4760. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4761. var
  4762. hp1 : tai;
  4763. begin
  4764. Result:=false;
  4765. if taicpu(p).ops <> 2 then
  4766. exit;
  4767. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4768. GetNextInstruction(p,hp1) then
  4769. begin
  4770. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4771. (taicpu(hp1).ops = 2) then
  4772. begin
  4773. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4774. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4775. { movXX reg1, mem1 or movXX mem1, reg1
  4776. movXX mem2, reg2 movXX reg2, mem2}
  4777. begin
  4778. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4779. { movXX reg1, mem1 or movXX mem1, reg1
  4780. movXX mem2, reg1 movXX reg2, mem1}
  4781. begin
  4782. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4783. begin
  4784. { Removes the second statement from
  4785. movXX reg1, mem1/reg2
  4786. movXX mem1/reg2, reg1
  4787. }
  4788. if taicpu(p).oper[0]^.typ=top_reg then
  4789. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4790. { Removes the second statement from
  4791. movXX mem1/reg1, reg2
  4792. movXX reg2, mem1/reg1
  4793. }
  4794. if (taicpu(p).oper[1]^.typ=top_reg) and
  4795. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4796. begin
  4797. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4798. RemoveInstruction(hp1);
  4799. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4800. Result:=true;
  4801. exit;
  4802. end
  4803. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4804. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4805. begin
  4806. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4807. RemoveInstruction(hp1);
  4808. Result:=true;
  4809. exit;
  4810. end;
  4811. end
  4812. end;
  4813. end;
  4814. end;
  4815. end;
  4816. end;
  4817. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4818. var
  4819. hp1 : tai;
  4820. begin
  4821. result:=false;
  4822. { replace
  4823. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4824. MovX %mreg2,%mreg1
  4825. dealloc %mreg2
  4826. by
  4827. <Op>X %mreg2,%mreg1
  4828. ?
  4829. }
  4830. if GetNextInstruction(p,hp1) and
  4831. { we mix single and double opperations here because we assume that the compiler
  4832. generates vmovapd only after double operations and vmovaps only after single operations }
  4833. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4834. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4835. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4836. (taicpu(p).oper[0]^.typ=top_reg) then
  4837. begin
  4838. TransferUsedRegs(TmpUsedRegs);
  4839. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4840. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4841. begin
  4842. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4843. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4844. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4845. RemoveInstruction(hp1);
  4846. result:=true;
  4847. end;
  4848. end;
  4849. end;
  4850. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4851. var
  4852. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4853. JumpLabel, JumpLabel_dist: TAsmLabel;
  4854. FirstValue, SecondValue: TCGInt;
  4855. function OptimizeJump(var InputP: tai): Boolean;
  4856. var
  4857. TempBool: Boolean;
  4858. begin
  4859. Result := False;
  4860. TempBool := True;
  4861. if DoJumpOptimizations(InputP, TempBool) or
  4862. not TempBool then
  4863. begin
  4864. Result := True;
  4865. if Assigned(InputP) then
  4866. begin
  4867. { CollapseZeroDistJump will be set to the label or an align
  4868. before it after the jump if it optimises, whether or not
  4869. the label is live or dead }
  4870. if (InputP.typ = ait_align) or
  4871. (
  4872. (InputP.typ = ait_label) and
  4873. not (tai_label(InputP).labsym.is_used)
  4874. ) then
  4875. GetNextInstruction(InputP, InputP);
  4876. end;
  4877. Exit;
  4878. end;
  4879. end;
  4880. begin
  4881. Result := False;
  4882. if (taicpu(p).oper[0]^.typ = top_const) and
  4883. (taicpu(p).oper[0]^.val <> -1) then
  4884. begin
  4885. { Convert unsigned maximum constants to -1 to aid optimisation }
  4886. case taicpu(p).opsize of
  4887. S_B:
  4888. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4889. begin
  4890. taicpu(p).oper[0]^.val := -1;
  4891. Result := True;
  4892. Exit;
  4893. end;
  4894. S_W:
  4895. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4896. begin
  4897. taicpu(p).oper[0]^.val := -1;
  4898. Result := True;
  4899. Exit;
  4900. end;
  4901. S_L:
  4902. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4903. begin
  4904. taicpu(p).oper[0]^.val := -1;
  4905. Result := True;
  4906. Exit;
  4907. end;
  4908. {$ifdef x86_64}
  4909. S_Q:
  4910. { Storing anything greater than $7FFFFFFF is not possible so do
  4911. nothing };
  4912. {$endif x86_64}
  4913. else
  4914. InternalError(2021121001);
  4915. end;
  4916. end;
  4917. if GetNextInstruction(p, hp1) and
  4918. TrySwapMovCmp(p, hp1) then
  4919. begin
  4920. Result := True;
  4921. Exit;
  4922. end;
  4923. p_label := nil;
  4924. JumpLabel := nil;
  4925. if MatchInstruction(hp1, A_Jcc, []) then
  4926. begin
  4927. if OptimizeJump(hp1) then
  4928. begin
  4929. Result := True;
  4930. if Assigned(hp1) then
  4931. begin
  4932. { CollapseZeroDistJump will be set to the label or an align
  4933. before it after the jump if it optimises, whether or not
  4934. the label is live or dead }
  4935. if (hp1.typ = ait_align) or
  4936. (
  4937. (hp1.typ = ait_label) and
  4938. not (tai_label(hp1).labsym.is_used)
  4939. ) then
  4940. GetNextInstruction(hp1, hp1);
  4941. end;
  4942. TransferUsedRegs(TmpUsedRegs);
  4943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4944. if not Assigned(hp1) or
  4945. (
  4946. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4947. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4948. ) then
  4949. begin
  4950. { No more conditional jumps; conditional statement is no longer required }
  4951. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4952. RemoveCurrentP(p);
  4953. end;
  4954. Exit;
  4955. end;
  4956. if IsJumpToLabel(taicpu(hp1)) then
  4957. begin
  4958. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4959. if Assigned(JumpLabel) then
  4960. p_label := getlabelwithsym(JumpLabel);
  4961. end;
  4962. end;
  4963. { Search for:
  4964. test $x,(reg/ref)
  4965. jne @lbl1
  4966. test $y,(reg/ref) (same register or reference)
  4967. jne @lbl1
  4968. Change to:
  4969. test $(x or y),(reg/ref)
  4970. jne @lbl1
  4971. (Note, this doesn't work with je instead of jne)
  4972. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4973. Also search for:
  4974. test $x,(reg/ref)
  4975. je @lbl1
  4976. ...
  4977. test $y,(reg/ref)
  4978. je/jne @lbl2
  4979. If (x or y) = x, then the second jump is deterministic
  4980. }
  4981. if (
  4982. (
  4983. (taicpu(p).oper[0]^.typ = top_const) or
  4984. (
  4985. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4986. (taicpu(p).oper[0]^.typ = top_reg) and
  4987. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4988. )
  4989. ) and
  4990. MatchInstruction(hp1, A_JCC, [])
  4991. ) then
  4992. begin
  4993. if (taicpu(p).oper[0]^.typ = top_reg) and
  4994. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4995. FirstValue := -1
  4996. else
  4997. FirstValue := taicpu(p).oper[0]^.val;
  4998. { If we have several test/jne's in a row, it might be the case that
  4999. the second label doesn't go to the same location, but the one
  5000. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5001. so accommodate for this with a while loop.
  5002. }
  5003. hp1_last := hp1;
  5004. while (
  5005. (
  5006. (taicpu(p).oper[1]^.typ = top_reg) and
  5007. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5008. ) or GetNextInstruction(hp1_last, p_dist)
  5009. ) and (p_dist.typ = ait_instruction) do
  5010. begin
  5011. if (
  5012. (
  5013. (taicpu(p_dist).opcode = A_TEST) and
  5014. (
  5015. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5016. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5017. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5018. )
  5019. ) or
  5020. (
  5021. { cmp 0,%reg = test %reg,%reg }
  5022. (taicpu(p_dist).opcode = A_CMP) and
  5023. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5024. )
  5025. ) and
  5026. { Make sure the destination operands are actually the same }
  5027. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5028. GetNextInstruction(p_dist, hp1_dist) and
  5029. MatchInstruction(hp1_dist, A_JCC, []) then
  5030. begin
  5031. if OptimizeJump(hp1_dist) then
  5032. begin
  5033. Result := True;
  5034. Exit;
  5035. end;
  5036. if
  5037. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5038. (
  5039. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5040. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5041. ) then
  5042. SecondValue := -1
  5043. else
  5044. SecondValue := taicpu(p_dist).oper[0]^.val;
  5045. { If both of the TEST constants are identical, delete the
  5046. second TEST that is unnecessary (be careful though, just
  5047. in case the flags are modified in between) }
  5048. if (FirstValue = SecondValue) then
  5049. begin
  5050. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5051. begin
  5052. { Since the second jump's condition is a subset of the first, we
  5053. know it will never branch because the first jump dominates it.
  5054. Get it out of the way now rather than wait for the jump
  5055. optimisations for a speed boost. }
  5056. if IsJumpToLabel(taicpu(hp1_dist)) then
  5057. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5058. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5059. RemoveInstruction(hp1_dist);
  5060. Result := True;
  5061. end
  5062. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5063. begin
  5064. { If the inverse of the first condition is a subset of the second,
  5065. the second one will definitely branch if the first one doesn't }
  5066. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5067. { We can remove the TEST instruction too }
  5068. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5069. RemoveInstruction(p_dist);
  5070. MakeUnconditional(taicpu(hp1_dist));
  5071. RemoveDeadCodeAfterJump(hp1_dist);
  5072. { Since the jump is now unconditional, we can't
  5073. continue any further with this particular
  5074. optimisation. The original TEST is still intact
  5075. though, so there might be something else we can
  5076. do }
  5077. Include(OptsToCheck, aoc_ForceNewIteration);
  5078. Break;
  5079. end;
  5080. if Result or
  5081. { If a jump wasn't removed or made unconditional, only
  5082. remove the identical TEST instruction if the flags
  5083. weren't modified }
  5084. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5085. begin
  5086. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5087. RemoveInstruction(p_dist);
  5088. { If the jump was removed or made unconditional, we
  5089. don't need to allocate NR_DEFAULTFLAGS over the
  5090. entire range }
  5091. if not Result then
  5092. begin
  5093. { Mark the flags as 'in use' over the entire range }
  5094. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5095. { Speed gain - continue search from the Jcc instruction }
  5096. hp1_last := hp1_dist;
  5097. { Only the TEST instruction was removed, and the
  5098. original was unchanged, so we can safely do
  5099. another iteration of the while loop }
  5100. Include(OptsToCheck, aoc_ForceNewIteration);
  5101. Continue;
  5102. end;
  5103. Exit;
  5104. end;
  5105. end;
  5106. hp1_last := nil;
  5107. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5108. (
  5109. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5110. { Always adjacent under -O2 and under }
  5111. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5112. (
  5113. GetNextInstruction(hp1, hp1_last) and
  5114. (hp1_last = p_dist)
  5115. )
  5116. ) and
  5117. (
  5118. (
  5119. { Test the following variant:
  5120. test $x,(reg/ref)
  5121. jne @lbl1
  5122. test $y,(reg/ref)
  5123. je @lbl2
  5124. @lbl1:
  5125. Becomes:
  5126. test $(x or y),(reg/ref)
  5127. je @lbl2
  5128. @lbl1: (may become a dead label)
  5129. }
  5130. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5131. GetNextInstruction(hp1_dist, hp1_last) and
  5132. (hp1_last = p_label)
  5133. ) or
  5134. (
  5135. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5136. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5137. then the second jump will never branch, so it can also be
  5138. removed regardless of where it goes }
  5139. (
  5140. (FirstValue = -1) or
  5141. (SecondValue = -1) or
  5142. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5143. )
  5144. )
  5145. ) then
  5146. begin
  5147. { Same jump location... can be a register since nothing's changed }
  5148. { If any of the entries are equivalent to test %reg,%reg, then the
  5149. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5150. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5151. if (hp1_last = p_label) then
  5152. begin
  5153. { Variant }
  5154. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5155. RemoveInstruction(p_dist);
  5156. if Assigned(JumpLabel) then
  5157. JumpLabel.decrefs;
  5158. RemoveInstruction(hp1);
  5159. end
  5160. else
  5161. begin
  5162. { Only remove the second test if no jumps or other conditional instructions follow }
  5163. TransferUsedRegs(TmpUsedRegs);
  5164. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5166. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5167. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5168. begin
  5169. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5170. RemoveInstruction(p_dist);
  5171. { Remove the first jump, not the second, to keep
  5172. any register deallocations between the second
  5173. TEST/JNE pair in the same place. Aids future
  5174. optimisation. }
  5175. if Assigned(JumpLabel) then
  5176. JumpLabel.decrefs;
  5177. RemoveInstruction(hp1);
  5178. end
  5179. else
  5180. begin
  5181. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5182. if IsJumpToLabel(taicpu(hp1_dist)) then
  5183. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5184. { Remove second jump in this instance }
  5185. RemoveInstruction(hp1_dist);
  5186. end;
  5187. end;
  5188. Result := True;
  5189. Exit;
  5190. end;
  5191. end;
  5192. if { If -O2 and under, it may stop on any old instruction }
  5193. (cs_opt_level3 in current_settings.optimizerswitches) and
  5194. (taicpu(p).oper[1]^.typ = top_reg) and
  5195. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5196. begin
  5197. hp1_last := p_dist;
  5198. Continue;
  5199. end;
  5200. Break;
  5201. end;
  5202. end;
  5203. { Search for:
  5204. test %reg,%reg
  5205. j(c1) @lbl1
  5206. ...
  5207. @lbl:
  5208. test %reg,%reg (same register)
  5209. j(c2) @lbl2
  5210. If c2 is a subset of c1, change to:
  5211. test %reg,%reg
  5212. j(c1) @lbl2
  5213. (@lbl1 may become a dead label as a result)
  5214. }
  5215. if (taicpu(p).oper[1]^.typ = top_reg) and
  5216. (taicpu(p).oper[0]^.typ = top_reg) and
  5217. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5218. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5219. Assigned(p_label) and
  5220. GetNextInstruction(p_label, p_dist) and
  5221. MatchInstruction(p_dist, A_TEST, []) and
  5222. { It's fine if the second test uses smaller sub-registers }
  5223. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5224. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5225. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5226. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5227. GetNextInstruction(p_dist, hp1_dist) and
  5228. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5229. begin
  5230. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5231. if JumpLabel = JumpLabel_dist then
  5232. { This is an infinite loop }
  5233. Exit;
  5234. { Best optimisation when the first condition is a subset (or equal) of the second }
  5235. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5236. begin
  5237. { Any registers used here will already be allocated }
  5238. if Assigned(JumpLabel) then
  5239. JumpLabel.DecRefs;
  5240. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5241. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5242. Result := True;
  5243. Exit;
  5244. end;
  5245. end;
  5246. end;
  5247. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5248. var
  5249. hp1, hp2: tai;
  5250. ActiveReg: TRegister;
  5251. OldOffset: asizeint;
  5252. ThisConst: TCGInt;
  5253. function RegDeallocated: Boolean;
  5254. begin
  5255. TransferUsedRegs(TmpUsedRegs);
  5256. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5257. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5258. end;
  5259. begin
  5260. result:=false;
  5261. hp1 := nil;
  5262. { replace
  5263. addX const,%reg1
  5264. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5265. dealloc %reg1
  5266. by
  5267. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5268. }
  5269. if MatchOpType(taicpu(p),top_const,top_reg) then
  5270. begin
  5271. ActiveReg := taicpu(p).oper[1]^.reg;
  5272. { Ensures the entire register was updated }
  5273. if (taicpu(p).opsize >= S_L) and
  5274. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5275. MatchInstruction(hp1,A_LEA,[]) and
  5276. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5277. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5278. (
  5279. { Cover the case where the register in the reference is also the destination register }
  5280. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5281. (
  5282. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5283. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5284. RegDeallocated
  5285. )
  5286. ) then
  5287. begin
  5288. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5289. {$push}
  5290. {$R-}{$Q-}
  5291. { Explicitly disable overflow checking for these offset calculation
  5292. as those do not matter for the final result }
  5293. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5295. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5296. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5297. {$pop}
  5298. {$ifdef x86_64}
  5299. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5300. begin
  5301. { Overflow; abort }
  5302. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5303. end
  5304. else
  5305. {$endif x86_64}
  5306. begin
  5307. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5308. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5309. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5310. RemoveCurrentP(p, hp1)
  5311. else
  5312. RemoveCurrentP(p);
  5313. result:=true;
  5314. Exit;
  5315. end;
  5316. end;
  5317. if (
  5318. { Save calling GetNextInstructionUsingReg again }
  5319. Assigned(hp1) or
  5320. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5321. ) and
  5322. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5323. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5324. begin
  5325. if taicpu(hp1).oper[0]^.typ = top_const then
  5326. begin
  5327. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5328. if taicpu(hp1).opcode = A_ADD then
  5329. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5330. else
  5331. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5332. Result := True;
  5333. { Handle any overflows }
  5334. case taicpu(p).opsize of
  5335. S_B:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5337. S_W:
  5338. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5339. S_L:
  5340. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5341. {$ifdef x86_64}
  5342. S_Q:
  5343. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5344. { Overflow; abort }
  5345. Result := False
  5346. else
  5347. taicpu(p).oper[0]^.val := ThisConst;
  5348. {$endif x86_64}
  5349. else
  5350. InternalError(2021102610);
  5351. end;
  5352. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5353. if Result then
  5354. begin
  5355. if (taicpu(p).oper[0]^.val < 0) and
  5356. (
  5357. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5358. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5359. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5360. ) then
  5361. begin
  5362. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5363. taicpu(p).opcode := A_SUB;
  5364. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5365. end
  5366. else
  5367. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5368. RemoveInstruction(hp1);
  5369. end;
  5370. end
  5371. else
  5372. begin
  5373. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5374. TransferUsedRegs(TmpUsedRegs);
  5375. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5376. hp2 := p;
  5377. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5378. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5379. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5380. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5381. begin
  5382. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5383. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5384. Asml.Remove(p);
  5385. Asml.InsertAfter(p, hp1);
  5386. p := hp1;
  5387. Result := True;
  5388. Exit;
  5389. end;
  5390. end;
  5391. end;
  5392. if DoArithCombineOpt(p) then
  5393. Result:=true;
  5394. end;
  5395. end;
  5396. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5397. var
  5398. hp1, hp2: tai;
  5399. ref: Integer;
  5400. saveref: treference;
  5401. offsetcalc: Int64;
  5402. TempReg: TRegister;
  5403. Multiple: TCGInt;
  5404. Adjacent, IntermediateRegDiscarded: Boolean;
  5405. begin
  5406. Result:=false;
  5407. { play save and throw an error if LEA uses a seg register prefix,
  5408. this is most likely an error somewhere else }
  5409. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5410. internalerror(2022022001);
  5411. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5412. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5413. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5414. (
  5415. { do not mess with leas accessing the stack pointer
  5416. unless it's a null operation }
  5417. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5418. (
  5419. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5420. (taicpu(p).oper[0]^.ref^.offset = 0)
  5421. )
  5422. ) and
  5423. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5424. begin
  5425. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5426. begin
  5427. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5428. begin
  5429. taicpu(p).opcode := A_MOV;
  5430. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5431. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5432. end
  5433. else
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5436. RemoveCurrentP(p);
  5437. end;
  5438. Result:=true;
  5439. exit;
  5440. end
  5441. else if (
  5442. { continue to use lea to adjust the stack pointer,
  5443. it is the recommended way, but only if not optimizing for size }
  5444. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5445. (cs_opt_size in current_settings.optimizerswitches)
  5446. ) and
  5447. { If the flags register is in use, don't change the instruction
  5448. to an ADD otherwise this will scramble the flags. [Kit] }
  5449. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5450. ConvertLEA(taicpu(p)) then
  5451. begin
  5452. Result:=true;
  5453. exit;
  5454. end;
  5455. end;
  5456. { Don't optimise if the stack or frame pointer is the destination register }
  5457. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5458. Exit;
  5459. if GetNextInstruction(p,hp1) and
  5460. (hp1.typ=ait_instruction) then
  5461. begin
  5462. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5463. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5464. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5465. begin
  5466. TransferUsedRegs(TmpUsedRegs);
  5467. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5469. begin
  5470. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5471. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5472. RemoveInstruction(hp1);
  5473. result:=true;
  5474. exit;
  5475. end;
  5476. end;
  5477. { changes
  5478. lea <ref1>, reg1
  5479. <op> ...,<ref. with reg1>,...
  5480. to
  5481. <op> ...,<ref1>,... }
  5482. { find a reference which uses reg1 }
  5483. 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
  5484. ref:=0
  5485. 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
  5486. ref:=1
  5487. else
  5488. ref:=-1;
  5489. if (ref<>-1) and
  5490. { reg1 must be either the base or the index }
  5491. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5492. begin
  5493. { reg1 can be removed from the reference }
  5494. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5495. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5496. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5497. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5498. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5499. else
  5500. Internalerror(2019111201);
  5501. { check if the can insert all data of the lea into the second instruction }
  5502. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5503. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5504. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5505. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5506. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5507. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5508. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5509. {$ifdef x86_64}
  5510. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5511. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5512. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5513. )
  5514. {$endif x86_64}
  5515. then
  5516. begin
  5517. { reg1 might not used by the second instruction after it is remove from the reference }
  5518. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5519. begin
  5520. TransferUsedRegs(TmpUsedRegs);
  5521. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5522. { reg1 is not updated so it might not be used afterwards }
  5523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5524. begin
  5525. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5526. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5527. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5528. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5529. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5530. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5531. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5532. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5533. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5534. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5535. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5536. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5537. RemoveCurrentP(p, hp1);
  5538. result:=true;
  5539. exit;
  5540. end
  5541. end;
  5542. end;
  5543. { recover }
  5544. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5545. end;
  5546. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5547. if Adjacent or
  5548. { Check further ahead (up to 2 instructions ahead for -O2) }
  5549. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5550. begin
  5551. { Check common LEA/LEA conditions }
  5552. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5553. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5554. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5555. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5556. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5557. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5558. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5559. (
  5560. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5561. calling it (since it calls GetNextInstruction) }
  5562. Adjacent or
  5563. (
  5564. (
  5565. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5566. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5567. ) and (
  5568. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5569. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5570. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5571. )
  5572. )
  5573. ) then
  5574. begin
  5575. TransferUsedRegs(TmpUsedRegs);
  5576. hp2 := p;
  5577. repeat
  5578. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5579. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5580. IntermediateRegDiscarded :=
  5581. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5582. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5583. { changes
  5584. lea offset1(regX,scale), reg1
  5585. lea offset2(reg1,reg1), reg2
  5586. to
  5587. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5588. and
  5589. lea offset1(regX,scale1), reg1
  5590. lea offset2(reg1,scale2), reg2
  5591. to
  5592. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5593. and
  5594. lea offset1(regX,scale1), reg1
  5595. lea offset2(reg3,reg1,scale2), reg2
  5596. to
  5597. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5598. ... so long as the final scale does not exceed 8
  5599. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5600. }
  5601. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5602. (
  5603. { Don't optimise if size is a concern and the intermediate register remains in use }
  5604. IntermediateRegDiscarded or
  5605. not (cs_opt_size in current_settings.optimizerswitches)
  5606. ) and
  5607. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5608. (
  5609. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5610. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5611. ) and (
  5612. (
  5613. { lea (reg1,scale2), reg2 variant }
  5614. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5615. (
  5616. Adjacent or
  5617. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5618. ) and
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5622. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5623. ) or (
  5624. { lea (regX,regX), reg1 variant }
  5625. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5626. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5627. )
  5628. )
  5629. ) or (
  5630. { lea (reg1,reg1), reg1 variant }
  5631. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5632. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5633. )
  5634. ) then
  5635. begin
  5636. { Make everything homogeneous to make calculations easier }
  5637. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5638. begin
  5639. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5640. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5641. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5642. else
  5643. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5644. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5645. end;
  5646. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5647. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5648. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5649. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5650. begin
  5651. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5652. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5653. begin
  5654. { Put the register to change in the index register }
  5655. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5656. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5657. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5658. end;
  5659. { Change lea (reg,reg) to lea(,reg,2) }
  5660. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5661. begin
  5662. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5663. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5664. end;
  5665. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5666. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5667. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5668. { Just to prevent miscalculations }
  5669. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5671. else
  5672. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5673. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5674. if IntermediateRegDiscarded then
  5675. begin
  5676. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5677. RemoveCurrentP(p);
  5678. end
  5679. else
  5680. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5681. result:=true;
  5682. exit;
  5683. end;
  5684. end;
  5685. { changes
  5686. lea offset1(regX), reg1
  5687. lea offset2(reg1), reg2
  5688. to
  5689. lea offset1+offset2(regX), reg2 }
  5690. if (
  5691. { Don't optimise if size is a concern and the intermediate register remains in use }
  5692. IntermediateRegDiscarded or
  5693. not (cs_opt_size in current_settings.optimizerswitches)
  5694. ) and
  5695. (
  5696. (
  5697. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5698. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5699. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5700. ) or (
  5701. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5702. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5703. (
  5704. (
  5705. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5706. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5707. ) or (
  5708. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5709. (
  5710. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5711. (
  5712. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5713. (
  5714. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5715. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5716. )
  5717. )
  5718. )
  5719. )
  5720. )
  5721. )
  5722. ) then
  5723. begin
  5724. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5725. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5726. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5727. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5728. begin
  5729. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5730. begin
  5731. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5732. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5733. { if the register is used as index and base, we have to increase for base as well
  5734. and adapt base }
  5735. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5736. begin
  5737. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5738. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5739. end;
  5740. end
  5741. else
  5742. begin
  5743. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5744. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5745. end;
  5746. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5747. begin
  5748. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5749. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5750. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5751. { Catch the situation where the base = index
  5752. and treat this as *2. The scalefactor of
  5753. p will be 0 or 1 due to the conditional
  5754. checks above. Fixes i40647 }
  5755. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5756. else
  5757. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5758. end;
  5759. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5760. if IntermediateRegDiscarded then
  5761. begin
  5762. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5763. RemoveCurrentP(p);
  5764. end
  5765. else
  5766. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5767. result:=true;
  5768. exit;
  5769. end;
  5770. end;
  5771. end;
  5772. { Change:
  5773. leal/q $x(%reg1),%reg2
  5774. ...
  5775. shll/q $y,%reg2
  5776. To:
  5777. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5778. }
  5779. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5780. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5781. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5782. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5783. (taicpu(hp1).oper[0]^.val <= 3) then
  5784. begin
  5785. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5786. TransferUsedRegs(TmpUsedRegs);
  5787. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5788. if
  5789. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5790. (this works even if scalefactor is zero) }
  5791. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5792. { Ensure offset doesn't go out of bounds }
  5793. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5794. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5795. (
  5796. (
  5797. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5798. (
  5799. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5800. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5801. (
  5802. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5803. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5804. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5805. )
  5806. )
  5807. ) or (
  5808. (
  5809. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5810. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5811. ) and
  5812. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5813. )
  5814. ) then
  5815. begin
  5816. repeat
  5817. with taicpu(p).oper[0]^.ref^ do
  5818. begin
  5819. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5820. if index = base then
  5821. begin
  5822. if Multiple > 4 then
  5823. { Optimisation will no longer work because resultant
  5824. scale factor will exceed 8 }
  5825. Break;
  5826. base := NR_NO;
  5827. scalefactor := 2;
  5828. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5829. end
  5830. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5831. begin
  5832. { Scale factor only works on the index register }
  5833. index := base;
  5834. base := NR_NO;
  5835. end;
  5836. { For safety }
  5837. if scalefactor <= 1 then
  5838. begin
  5839. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5840. scalefactor := Multiple;
  5841. end
  5842. else
  5843. begin
  5844. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5845. scalefactor := scalefactor * Multiple;
  5846. end;
  5847. offset := offset * Multiple;
  5848. end;
  5849. RemoveInstruction(hp1);
  5850. Result := True;
  5851. Exit;
  5852. { This repeat..until loop exists for the benefit of Break }
  5853. until True;
  5854. end;
  5855. end;
  5856. end;
  5857. end;
  5858. end;
  5859. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5860. var
  5861. hp1 : tai;
  5862. SubInstr: Boolean;
  5863. ThisConst: TCGInt;
  5864. const
  5865. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5866. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5867. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5868. begin
  5869. Result := False;
  5870. if taicpu(p).oper[0]^.typ <> top_const then
  5871. { Should have been confirmed before calling }
  5872. InternalError(2021102601);
  5873. SubInstr := (taicpu(p).opcode = A_SUB);
  5874. if GetLastInstruction(p, hp1) and
  5875. (hp1.typ = ait_instruction) and
  5876. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5877. begin
  5878. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5879. { Bad size }
  5880. InternalError(2022042001);
  5881. case taicpu(hp1).opcode Of
  5882. A_INC:
  5883. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5884. begin
  5885. if SubInstr then
  5886. ThisConst := taicpu(p).oper[0]^.val - 1
  5887. else
  5888. ThisConst := taicpu(p).oper[0]^.val + 1;
  5889. end
  5890. else
  5891. Exit;
  5892. A_DEC:
  5893. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5894. begin
  5895. if SubInstr then
  5896. ThisConst := taicpu(p).oper[0]^.val + 1
  5897. else
  5898. ThisConst := taicpu(p).oper[0]^.val - 1;
  5899. end
  5900. else
  5901. Exit;
  5902. A_SUB:
  5903. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5904. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5905. begin
  5906. if SubInstr then
  5907. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5908. else
  5909. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5910. end
  5911. else
  5912. Exit;
  5913. A_ADD:
  5914. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5915. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5916. begin
  5917. if SubInstr then
  5918. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5919. else
  5920. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5921. end
  5922. else
  5923. Exit;
  5924. else
  5925. Exit;
  5926. end;
  5927. { Check that the values are in range }
  5928. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5929. { Overflow; abort }
  5930. Exit;
  5931. if (ThisConst = 0) then
  5932. begin
  5933. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5934. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5935. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5936. RemoveInstruction(hp1);
  5937. hp1 := tai(p.next);
  5938. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5939. if not GetLastInstruction(hp1, p) then
  5940. p := hp1;
  5941. end
  5942. else
  5943. begin
  5944. if taicpu(hp1).opercnt=1 then
  5945. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5946. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5947. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5948. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5949. else
  5950. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5951. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5952. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5953. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5954. RemoveInstruction(hp1);
  5955. taicpu(p).loadconst(0, ThisConst);
  5956. end;
  5957. Result := True;
  5958. end;
  5959. end;
  5960. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5961. begin
  5962. Result := False;
  5963. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5964. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5965. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5966. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5967. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5968. (
  5969. (
  5970. (taicpu(hp1).opcode = A_TEST)
  5971. ) or (
  5972. (taicpu(hp1).opcode = A_CMP) and
  5973. { A sanity check more than anything }
  5974. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5975. )
  5976. ) then
  5977. begin
  5978. { change
  5979. mov mem, %reg
  5980. ...
  5981. cmp/test x, %reg / test %reg,%reg
  5982. (reg deallocated)
  5983. to
  5984. cmp/test x, mem / cmp 0, mem
  5985. }
  5986. TransferUsedRegs(TmpUsedRegs);
  5987. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5988. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5989. begin
  5990. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5991. if (taicpu(hp1).opcode = A_TEST) and
  5992. (
  5993. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5994. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5995. ) then
  5996. begin
  5997. taicpu(hp1).opcode := A_CMP;
  5998. taicpu(hp1).loadconst(0, 0);
  5999. end;
  6000. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6001. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6002. RemoveCurrentP(p);
  6003. if (p <> hp1) then
  6004. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6005. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6006. { Make sure the flags are allocated across the CMP instruction }
  6007. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6008. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6009. Result := True;
  6010. Exit;
  6011. end;
  6012. end;
  6013. end;
  6014. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6015. var
  6016. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6017. ThisReg, SecondReg: TRegister;
  6018. JumpLoc: TAsmLabel;
  6019. NewSize: TOpSize;
  6020. begin
  6021. Result := False;
  6022. {
  6023. Convert:
  6024. j<c> .L1
  6025. .L2:
  6026. mov 1,reg
  6027. jmp .L3 (or ret, although it might not be a RET yet)
  6028. .L1:
  6029. mov 0,reg
  6030. jmp .L3 (or ret)
  6031. ( As long as .L3 <> .L1 or .L2)
  6032. To:
  6033. mov 0,reg
  6034. set<not(c)> reg
  6035. jmp .L3 (or ret)
  6036. .L2:
  6037. mov 1,reg
  6038. jmp .L3 (or ret)
  6039. .L1:
  6040. mov 0,reg
  6041. jmp .L3 (or ret)
  6042. }
  6043. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6044. Exit;
  6045. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6046. if GetNextInstruction(hp_label, hp2) and
  6047. MatchInstruction(hp2,A_MOV,[]) and
  6048. (taicpu(hp2).oper[0]^.typ = top_const) and
  6049. (
  6050. (
  6051. (taicpu(hp2).oper[1]^.typ = top_reg)
  6052. {$ifdef i386}
  6053. { Under i386, ESI, EDI, EBP and ESP
  6054. don't have an 8-bit representation }
  6055. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6056. {$endif i386}
  6057. ) or (
  6058. {$ifdef i386}
  6059. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6060. {$endif i386}
  6061. (taicpu(hp2).opsize = S_B)
  6062. )
  6063. ) and
  6064. GetNextInstruction(hp2, hp3) and
  6065. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6066. (
  6067. (taicpu(hp3).opcode=A_RET) or
  6068. (
  6069. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6070. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6071. )
  6072. ) and
  6073. GetNextInstruction(hp3, hp4) and
  6074. (hp4.typ=ait_label) and
  6075. (tai_label(hp4).labsym=JumpLoc) and
  6076. (
  6077. not (cs_opt_size in current_settings.optimizerswitches) or
  6078. { If the initial jump is the label's only reference, then it will
  6079. become a dead label if the other conditions are met and hence
  6080. remove at least 2 instructions, including a jump }
  6081. (JumpLoc.getrefs = 1)
  6082. ) and
  6083. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6084. that will be optimised out }
  6085. GetNextInstruction(hp4, hp5) and
  6086. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6087. (taicpu(hp5).oper[0]^.typ = top_const) and
  6088. (
  6089. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6090. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6091. ) and
  6092. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6093. GetNextInstruction(hp5,hp6) and
  6094. (
  6095. (hp6.typ<>ait_label) or
  6096. SkipLabels(hp6, hp6)
  6097. ) and
  6098. (hp6.typ=ait_instruction) then
  6099. begin
  6100. { First, let's look at the two jumps that are hp3 and hp6 }
  6101. if not
  6102. (
  6103. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6104. (
  6105. (taicpu(hp6).opcode=A_RET) or
  6106. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6107. )
  6108. ) then
  6109. { If condition is False, then the JMP/RET instructions matched conventionally }
  6110. begin
  6111. { See if one of the jumps can be instantly converted into a RET }
  6112. if (taicpu(hp3).opcode=A_JMP) then
  6113. begin
  6114. { Reuse hp5 }
  6115. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6116. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6117. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6118. Exit;
  6119. if MatchInstruction(hp5, A_RET, []) then
  6120. begin
  6121. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6122. ConvertJumpToRET(hp3, hp5);
  6123. Result := True;
  6124. end
  6125. else
  6126. Exit;
  6127. end;
  6128. if (taicpu(hp6).opcode=A_JMP) then
  6129. begin
  6130. { Reuse hp5 }
  6131. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6132. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6133. Exit;
  6134. if MatchInstruction(hp5, A_RET, []) then
  6135. begin
  6136. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6137. ConvertJumpToRET(hp6, hp5);
  6138. Result := True;
  6139. end
  6140. else
  6141. Exit;
  6142. end;
  6143. if not
  6144. (
  6145. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6146. (
  6147. (taicpu(hp6).opcode=A_RET) or
  6148. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6149. )
  6150. ) then
  6151. { Still doesn't match }
  6152. Exit;
  6153. end;
  6154. if (taicpu(hp2).oper[0]^.val = 1) then
  6155. begin
  6156. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6157. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6158. end
  6159. else
  6160. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6161. if taicpu(hp2).opsize=S_B then
  6162. begin
  6163. if taicpu(hp2).oper[1]^.typ = top_reg then
  6164. begin
  6165. SecondReg := taicpu(hp2).oper[1]^.reg;
  6166. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6167. end
  6168. else
  6169. begin
  6170. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6171. SecondReg := NR_NO;
  6172. end;
  6173. hp_pos := p;
  6174. hp_allocstart := hp4;
  6175. end
  6176. else
  6177. begin
  6178. { Will be a register because the size can't be S_B otherwise }
  6179. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6180. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6181. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6182. if (cs_opt_size in current_settings.optimizerswitches) then
  6183. begin
  6184. { Favour using MOVZX when optimising for size }
  6185. case taicpu(hp2).opsize of
  6186. S_W:
  6187. NewSize := S_BW;
  6188. S_L:
  6189. NewSize := S_BL;
  6190. {$ifdef x86_64}
  6191. S_Q:
  6192. begin
  6193. NewSize := S_BL;
  6194. { Will implicitly zero-extend to 64-bit }
  6195. setsubreg(SecondReg, R_SUBD);
  6196. end;
  6197. {$endif x86_64}
  6198. else
  6199. InternalError(2022101301);
  6200. end;
  6201. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6202. { Inserting it right before p will guarantee that the flags are also tracked }
  6203. Asml.InsertBefore(hp5, p);
  6204. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6205. hp_pos := hp5;
  6206. hp_allocstart := hp4;
  6207. end
  6208. else
  6209. begin
  6210. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6211. { Inserting it right before p will guarantee that the flags are also tracked }
  6212. Asml.InsertBefore(hp5, p);
  6213. hp_pos := p;
  6214. hp_allocstart := hp5;
  6215. end;
  6216. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6217. end;
  6218. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6219. taicpu(hp4).condition := taicpu(p).condition;
  6220. asml.InsertBefore(hp4, hp_pos);
  6221. if taicpu(hp3).is_jmp then
  6222. begin
  6223. JumpLoc.decrefs;
  6224. MakeUnconditional(taicpu(p));
  6225. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6226. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6227. end
  6228. else
  6229. ConvertJumpToRET(p, hp3);
  6230. if SecondReg <> NR_NO then
  6231. { Ensure the destination register is allocated over this region }
  6232. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6233. if (JumpLoc.getrefs = 0) then
  6234. RemoveDeadCodeAfterJump(hp3);
  6235. Result:=true;
  6236. exit;
  6237. end;
  6238. end;
  6239. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6240. var
  6241. hp1, hp2: tai;
  6242. ActiveReg: TRegister;
  6243. OldOffset: asizeint;
  6244. ThisConst: TCGInt;
  6245. function RegDeallocated: Boolean;
  6246. begin
  6247. TransferUsedRegs(TmpUsedRegs);
  6248. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6249. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6250. end;
  6251. begin
  6252. Result:=false;
  6253. hp1 := nil;
  6254. { replace
  6255. subX const,%reg1
  6256. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6257. dealloc %reg1
  6258. by
  6259. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6260. }
  6261. if MatchOpType(taicpu(p),top_const,top_reg) then
  6262. begin
  6263. ActiveReg := taicpu(p).oper[1]^.reg;
  6264. { Ensures the entire register was updated }
  6265. if (taicpu(p).opsize >= S_L) and
  6266. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6267. MatchInstruction(hp1,A_LEA,[]) and
  6268. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6269. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6270. (
  6271. { Cover the case where the register in the reference is also the destination register }
  6272. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6273. (
  6274. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6275. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6276. RegDeallocated
  6277. )
  6278. ) then
  6279. begin
  6280. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6281. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6282. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6283. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6284. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6285. {$ifdef x86_64}
  6286. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6287. begin
  6288. { Overflow; abort }
  6289. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6290. end
  6291. else
  6292. {$endif x86_64}
  6293. begin
  6294. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6295. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6296. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6297. RemoveCurrentP(p, hp1)
  6298. else
  6299. RemoveCurrentP(p);
  6300. result:=true;
  6301. Exit;
  6302. end;
  6303. end;
  6304. if (
  6305. { Save calling GetNextInstructionUsingReg again }
  6306. Assigned(hp1) or
  6307. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6308. ) and
  6309. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6310. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6311. begin
  6312. if taicpu(hp1).oper[0]^.typ = top_const then
  6313. begin
  6314. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6315. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6316. Result := True;
  6317. { Handle any overflows }
  6318. case taicpu(p).opsize of
  6319. S_B:
  6320. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6321. S_W:
  6322. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6323. S_L:
  6324. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6325. {$ifdef x86_64}
  6326. S_Q:
  6327. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6328. { Overflow; abort }
  6329. Result := False
  6330. else
  6331. taicpu(p).oper[0]^.val := ThisConst;
  6332. {$endif x86_64}
  6333. else
  6334. InternalError(2021102611);
  6335. end;
  6336. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6337. if Result then
  6338. begin
  6339. if (taicpu(p).oper[0]^.val < 0) and
  6340. (
  6341. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6342. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6343. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6344. ) then
  6345. begin
  6346. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6347. taicpu(p).opcode := A_SUB;
  6348. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6349. end
  6350. else
  6351. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6352. RemoveInstruction(hp1);
  6353. end;
  6354. end
  6355. else
  6356. begin
  6357. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6358. TransferUsedRegs(TmpUsedRegs);
  6359. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6360. hp2 := p;
  6361. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6362. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6363. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6364. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6365. begin
  6366. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6367. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6368. Asml.Remove(p);
  6369. Asml.InsertAfter(p, hp1);
  6370. p := hp1;
  6371. Result := True;
  6372. Exit;
  6373. end;
  6374. end;
  6375. end;
  6376. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6377. { * change "sub/add const1, reg" or "dec reg" followed by
  6378. "sub const2, reg" to one "sub ..., reg" }
  6379. {$ifdef i386}
  6380. if (taicpu(p).oper[0]^.val = 2) and
  6381. (ActiveReg = NR_ESP) and
  6382. { Don't do the sub/push optimization if the sub }
  6383. { comes from setting up the stack frame (JM) }
  6384. (not(GetLastInstruction(p,hp1)) or
  6385. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6386. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6387. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6388. begin
  6389. hp1 := tai(p.next);
  6390. while Assigned(hp1) and
  6391. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6392. not RegReadByInstruction(NR_ESP,hp1) and
  6393. not RegModifiedByInstruction(NR_ESP,hp1) do
  6394. hp1 := tai(hp1.next);
  6395. if Assigned(hp1) and
  6396. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6397. begin
  6398. taicpu(hp1).changeopsize(S_L);
  6399. if taicpu(hp1).oper[0]^.typ=top_reg then
  6400. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6401. hp1 := tai(p.next);
  6402. RemoveCurrentp(p, hp1);
  6403. Result:=true;
  6404. exit;
  6405. end;
  6406. end;
  6407. {$endif i386}
  6408. if DoArithCombineOpt(p) then
  6409. Result:=true;
  6410. end;
  6411. end;
  6412. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6413. var
  6414. TmpBool1,TmpBool2 : Boolean;
  6415. tmpref : treference;
  6416. hp1,hp2: tai;
  6417. mask, shiftval: tcgint;
  6418. begin
  6419. Result:=false;
  6420. { All these optimisations work on "shl/sal const,%reg" }
  6421. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6422. Exit;
  6423. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6424. (taicpu(p).oper[0]^.val <= 3) then
  6425. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6426. begin
  6427. { should we check the next instruction? }
  6428. TmpBool1 := True;
  6429. { have we found an add/sub which could be
  6430. integrated in the lea? }
  6431. TmpBool2 := False;
  6432. reference_reset(tmpref,2,[]);
  6433. TmpRef.index := taicpu(p).oper[1]^.reg;
  6434. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6435. while TmpBool1 and
  6436. GetNextInstruction(p, hp1) and
  6437. (tai(hp1).typ = ait_instruction) and
  6438. ((((taicpu(hp1).opcode = A_ADD) or
  6439. (taicpu(hp1).opcode = A_SUB)) and
  6440. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6441. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6442. (((taicpu(hp1).opcode = A_INC) or
  6443. (taicpu(hp1).opcode = A_DEC)) and
  6444. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6445. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6446. ((taicpu(hp1).opcode = A_LEA) and
  6447. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6448. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6449. (not GetNextInstruction(hp1,hp2) or
  6450. not instrReadsFlags(hp2)) Do
  6451. begin
  6452. TmpBool1 := False;
  6453. if taicpu(hp1).opcode=A_LEA then
  6454. begin
  6455. if (TmpRef.base = NR_NO) and
  6456. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6457. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6458. { Segment register isn't a concern here }
  6459. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6460. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6461. begin
  6462. TmpBool1 := True;
  6463. TmpBool2 := True;
  6464. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6465. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6466. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6467. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6468. RemoveInstruction(hp1);
  6469. end
  6470. end
  6471. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6472. begin
  6473. TmpBool1 := True;
  6474. TmpBool2 := True;
  6475. case taicpu(hp1).opcode of
  6476. A_ADD:
  6477. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6478. A_SUB:
  6479. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6480. else
  6481. internalerror(2019050536);
  6482. end;
  6483. RemoveInstruction(hp1);
  6484. end
  6485. else
  6486. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6487. (((taicpu(hp1).opcode = A_ADD) and
  6488. (TmpRef.base = NR_NO)) or
  6489. (taicpu(hp1).opcode = A_INC) or
  6490. (taicpu(hp1).opcode = A_DEC)) then
  6491. begin
  6492. TmpBool1 := True;
  6493. TmpBool2 := True;
  6494. case taicpu(hp1).opcode of
  6495. A_ADD:
  6496. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6497. A_INC:
  6498. inc(TmpRef.offset);
  6499. A_DEC:
  6500. dec(TmpRef.offset);
  6501. else
  6502. internalerror(2019050535);
  6503. end;
  6504. RemoveInstruction(hp1);
  6505. end;
  6506. end;
  6507. if TmpBool2
  6508. {$ifndef x86_64}
  6509. or
  6510. ((current_settings.optimizecputype < cpu_Pentium2) and
  6511. (taicpu(p).oper[0]^.val <= 3) and
  6512. not(cs_opt_size in current_settings.optimizerswitches))
  6513. {$endif x86_64}
  6514. then
  6515. begin
  6516. if not(TmpBool2) and
  6517. (taicpu(p).oper[0]^.val=1) then
  6518. begin
  6519. taicpu(p).opcode := A_ADD;
  6520. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6521. end
  6522. else
  6523. begin
  6524. taicpu(p).opcode := A_LEA;
  6525. taicpu(p).loadref(0, TmpRef);
  6526. end;
  6527. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6528. Result := True;
  6529. end;
  6530. end
  6531. {$ifndef x86_64}
  6532. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6533. begin
  6534. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6535. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6536. (unlike shl, which is only Tairable in the U pipe) }
  6537. if taicpu(p).oper[0]^.val=1 then
  6538. begin
  6539. taicpu(p).opcode := A_ADD;
  6540. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6541. Result := True;
  6542. end
  6543. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6544. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6545. else if (taicpu(p).opsize = S_L) and
  6546. (taicpu(p).oper[0]^.val<= 3) then
  6547. begin
  6548. reference_reset(tmpref,2,[]);
  6549. TmpRef.index := taicpu(p).oper[1]^.reg;
  6550. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6551. taicpu(p).opcode := A_LEA;
  6552. taicpu(p).loadref(0, TmpRef);
  6553. Result := True;
  6554. end;
  6555. end
  6556. {$endif x86_64}
  6557. else if
  6558. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6559. (
  6560. (
  6561. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6562. SetAndTest(hp1, hp2)
  6563. {$ifdef x86_64}
  6564. ) or
  6565. (
  6566. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6567. GetNextInstruction(hp1, hp2) and
  6568. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6569. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6570. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6571. {$endif x86_64}
  6572. )
  6573. ) and
  6574. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6575. begin
  6576. { Change:
  6577. shl x, %reg1
  6578. mov -(1<<x), %reg2
  6579. and %reg2, %reg1
  6580. Or:
  6581. shl x, %reg1
  6582. and -(1<<x), %reg1
  6583. To just:
  6584. shl x, %reg1
  6585. Since the and operation only zeroes bits that are already zero from the shl operation
  6586. }
  6587. case taicpu(p).oper[0]^.val of
  6588. 8:
  6589. mask:=$FFFFFFFFFFFFFF00;
  6590. 16:
  6591. mask:=$FFFFFFFFFFFF0000;
  6592. 32:
  6593. mask:=$FFFFFFFF00000000;
  6594. 63:
  6595. { Constant pre-calculated to prevent overflow errors with Int64 }
  6596. mask:=$8000000000000000;
  6597. else
  6598. begin
  6599. if taicpu(p).oper[0]^.val >= 64 then
  6600. { Shouldn't happen realistically, since the register
  6601. is guaranteed to be set to zero at this point }
  6602. mask := 0
  6603. else
  6604. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6605. end;
  6606. end;
  6607. if taicpu(hp1).oper[0]^.val = mask then
  6608. begin
  6609. { Everything checks out, perform the optimisation, as long as
  6610. the FLAGS register isn't being used}
  6611. TransferUsedRegs(TmpUsedRegs);
  6612. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6613. {$ifdef x86_64}
  6614. if (hp1 <> hp2) then
  6615. begin
  6616. { "shl/mov/and" version }
  6617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6618. { Don't do the optimisation if the FLAGS register is in use }
  6619. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6620. begin
  6621. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6622. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6623. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6624. begin
  6625. RemoveInstruction(hp1);
  6626. Result := True;
  6627. end;
  6628. { Only set Result to True if the 'mov' instruction was removed }
  6629. RemoveInstruction(hp2);
  6630. end;
  6631. end
  6632. else
  6633. {$endif x86_64}
  6634. begin
  6635. { "shl/and" version }
  6636. { Don't do the optimisation if the FLAGS register is in use }
  6637. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6638. begin
  6639. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6640. RemoveInstruction(hp1);
  6641. Result := True;
  6642. end;
  6643. end;
  6644. Exit;
  6645. end
  6646. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6647. begin
  6648. { Even if the mask doesn't allow for its removal, we might be
  6649. able to optimise the mask for the "shl/and" version, which
  6650. may permit other peephole optimisations }
  6651. {$ifdef DEBUG_AOPTCPU}
  6652. mask := taicpu(hp1).oper[0]^.val and mask;
  6653. if taicpu(hp1).oper[0]^.val <> mask then
  6654. begin
  6655. DebugMsg(
  6656. SPeepholeOptimization +
  6657. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6658. ' to $' + debug_tostr(mask) +
  6659. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6660. taicpu(hp1).oper[0]^.val := mask;
  6661. end;
  6662. {$else DEBUG_AOPTCPU}
  6663. { If debugging is off, just set the operand even if it's the same }
  6664. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6665. {$endif DEBUG_AOPTCPU}
  6666. end;
  6667. end;
  6668. {
  6669. change
  6670. shl/sal const,reg
  6671. <op> ...(...,reg,1),...
  6672. into
  6673. <op> ...(...,reg,1 shl const),...
  6674. if const in 1..3
  6675. }
  6676. if MatchOpType(taicpu(p), top_const, top_reg) and
  6677. (taicpu(p).oper[0]^.val in [1..3]) and
  6678. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6679. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6680. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6681. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6682. MatchOpType(taicpu(hp1),top_ref))
  6683. ) and
  6684. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6685. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6686. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6687. begin
  6688. TransferUsedRegs(TmpUsedRegs);
  6689. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6690. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6691. begin
  6692. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6693. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6694. RemoveCurrentP(p);
  6695. Result:=true;
  6696. exit;
  6697. end;
  6698. end;
  6699. if MatchOpType(taicpu(p), top_const, top_reg) and
  6700. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6701. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6702. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6703. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6704. begin
  6705. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6706. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6707. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6708. {$ifdef x86_64}
  6709. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6710. {$endif x86_64}
  6711. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6712. begin
  6713. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6714. taicpu(hp1).opcode:=A_MOV;
  6715. taicpu(hp1).oper[0]^.val:=0;
  6716. end
  6717. else
  6718. begin
  6719. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6720. taicpu(hp1).oper[0]^.val:=shiftval;
  6721. end;
  6722. RemoveCurrentP(p);
  6723. Result:=true;
  6724. exit;
  6725. end;
  6726. end;
  6727. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6728. begin
  6729. case shr_size of
  6730. S_B:
  6731. { No valid combinations }
  6732. Result := False;
  6733. S_W:
  6734. Result := (Shift >= 8) and (movz_size = S_BW);
  6735. S_L:
  6736. Result :=
  6737. (Shift >= 24) { Any opsize is valid for this shift } or
  6738. ((Shift >= 16) and (movz_size = S_WL));
  6739. {$ifdef x86_64}
  6740. S_Q:
  6741. Result :=
  6742. (Shift >= 56) { Any opsize is valid for this shift } or
  6743. ((Shift >= 48) and (movz_size = S_WL));
  6744. {$endif x86_64}
  6745. else
  6746. InternalError(2022081510);
  6747. end;
  6748. end;
  6749. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6750. var
  6751. hp1, hp2: tai;
  6752. Shift: TCGInt;
  6753. LimitSize: Topsize;
  6754. DoNotMerge: Boolean;
  6755. begin
  6756. Result := False;
  6757. { All these optimisations work on "shr const,%reg" }
  6758. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6759. Exit;
  6760. DoNotMerge := False;
  6761. Shift := taicpu(p).oper[0]^.val;
  6762. LimitSize := taicpu(p).opsize;
  6763. hp1 := p;
  6764. repeat
  6765. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6766. Exit;
  6767. case taicpu(hp1).opcode of
  6768. A_TEST, A_CMP, A_Jcc:
  6769. { Skip over conditional jumps and relevant comparisons }
  6770. Continue;
  6771. A_MOVZX:
  6772. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6773. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6774. begin
  6775. { Since the original register is being read as is, subsequent
  6776. SHRs must not be merged at this point }
  6777. DoNotMerge := True;
  6778. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6779. begin
  6780. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6781. begin
  6782. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6783. taicpu(hp1).opcode := A_MOV;
  6784. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6785. case taicpu(hp1).opsize of
  6786. S_BW:
  6787. taicpu(hp1).opsize := S_W;
  6788. S_BL, S_WL:
  6789. taicpu(hp1).opsize := S_L;
  6790. else
  6791. InternalError(2022081503);
  6792. end;
  6793. { p itself hasn't changed, so no need to set Result to True }
  6794. Include(OptsToCheck, aoc_ForceNewIteration);
  6795. { See if there's anything afterwards that can be
  6796. optimised, since the input register hasn't changed }
  6797. Continue;
  6798. end;
  6799. { NOTE: If the MOVZX instruction reads and writes the same
  6800. register, defer this to the post-peephole optimisation stage }
  6801. Exit;
  6802. end;
  6803. end;
  6804. A_SHL, A_SAL, A_SHR:
  6805. if (taicpu(hp1).opsize <= LimitSize) and
  6806. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6807. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6808. begin
  6809. { Make sure the sizes don't exceed the register size limit
  6810. (measured by the shift value falling below the limit) }
  6811. if taicpu(hp1).opsize < LimitSize then
  6812. LimitSize := taicpu(hp1).opsize;
  6813. if taicpu(hp1).opcode = A_SHR then
  6814. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6815. else
  6816. begin
  6817. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6818. DoNotMerge := True;
  6819. end;
  6820. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6821. Exit;
  6822. { Since we've established that the combined shift is within
  6823. limits, we can actually combine the adjacent SHR
  6824. instructions even if they're different sizes }
  6825. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6826. begin
  6827. hp2 := tai(hp1.Previous);
  6828. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6829. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6830. RemoveInstruction(hp1);
  6831. hp1 := hp2;
  6832. { Though p has changed, only the constant has, and its
  6833. effects can still be detected on the next iteration of
  6834. the repeat..until loop }
  6835. Include(OptsToCheck, aoc_ForceNewIteration);
  6836. end;
  6837. { Move onto the next instruction }
  6838. Continue;
  6839. end;
  6840. else
  6841. ;
  6842. end;
  6843. Break;
  6844. until False;
  6845. end;
  6846. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6847. var
  6848. CurrentRef: TReference;
  6849. FullReg: TRegister;
  6850. hp1, hp2: tai;
  6851. begin
  6852. Result := False;
  6853. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6854. Exit;
  6855. { We assume you've checked if the operand is actually a reference by
  6856. this point. If it isn't, you'll most likely get an access violation }
  6857. CurrentRef := first_mov.oper[1]^.ref^;
  6858. { Memory must be aligned }
  6859. if (CurrentRef.offset mod 4) <> 0 then
  6860. Exit;
  6861. Inc(CurrentRef.offset);
  6862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6863. if MatchOperand(second_mov.oper[0]^, 0) and
  6864. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6865. GetNextInstruction(second_mov, hp1) and
  6866. (hp1.typ = ait_instruction) and
  6867. (taicpu(hp1).opcode = A_MOV) and
  6868. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6869. (taicpu(hp1).oper[0]^.val = 0) then
  6870. begin
  6871. Inc(CurrentRef.offset);
  6872. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6873. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6874. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6875. begin
  6876. case taicpu(hp1).opsize of
  6877. S_B:
  6878. if GetNextInstruction(hp1, hp2) and
  6879. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6880. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6881. (taicpu(hp2).oper[0]^.val = 0) then
  6882. begin
  6883. Inc(CurrentRef.offset);
  6884. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6885. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6886. (taicpu(hp2).opsize = S_B) then
  6887. begin
  6888. RemoveInstruction(hp1);
  6889. RemoveInstruction(hp2);
  6890. first_mov.opsize := S_L;
  6891. if first_mov.oper[0]^.typ = top_reg then
  6892. begin
  6893. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6894. { Reuse second_mov as a MOVZX instruction }
  6895. second_mov.opcode := A_MOVZX;
  6896. second_mov.opsize := S_BL;
  6897. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6898. second_mov.loadreg(1, FullReg);
  6899. first_mov.oper[0]^.reg := FullReg;
  6900. asml.Remove(second_mov);
  6901. asml.InsertBefore(second_mov, first_mov);
  6902. end
  6903. else
  6904. { It's a value }
  6905. begin
  6906. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6907. RemoveInstruction(second_mov);
  6908. end;
  6909. Result := True;
  6910. Exit;
  6911. end;
  6912. end;
  6913. S_W:
  6914. begin
  6915. RemoveInstruction(hp1);
  6916. first_mov.opsize := S_L;
  6917. if first_mov.oper[0]^.typ = top_reg then
  6918. begin
  6919. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6920. { Reuse second_mov as a MOVZX instruction }
  6921. second_mov.opcode := A_MOVZX;
  6922. second_mov.opsize := S_BL;
  6923. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6924. second_mov.loadreg(1, FullReg);
  6925. first_mov.oper[0]^.reg := FullReg;
  6926. asml.Remove(second_mov);
  6927. asml.InsertBefore(second_mov, first_mov);
  6928. end
  6929. else
  6930. { It's a value }
  6931. begin
  6932. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6933. RemoveInstruction(second_mov);
  6934. end;
  6935. Result := True;
  6936. Exit;
  6937. end;
  6938. else
  6939. ;
  6940. end;
  6941. end;
  6942. end;
  6943. end;
  6944. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6945. { returns true if a "continue" should be done after this optimization }
  6946. var
  6947. hp1, hp2, hp3: tai;
  6948. begin
  6949. Result := false;
  6950. hp3 := nil;
  6951. if MatchOpType(taicpu(p),top_ref) and
  6952. GetNextInstruction(p, hp1) and
  6953. (hp1.typ = ait_instruction) and
  6954. (((taicpu(hp1).opcode = A_FLD) and
  6955. (taicpu(p).opcode = A_FSTP)) or
  6956. ((taicpu(p).opcode = A_FISTP) and
  6957. (taicpu(hp1).opcode = A_FILD))) and
  6958. MatchOpType(taicpu(hp1),top_ref) and
  6959. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6960. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6961. begin
  6962. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6963. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6964. GetNextInstruction(hp1, hp2) and
  6965. (((hp2.typ = ait_instruction) and
  6966. IsExitCode(hp2) and
  6967. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6968. not(assigned(current_procinfo.procdef.funcretsym) and
  6969. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6970. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6971. { fstp <temp>
  6972. fld <temp>
  6973. <dealloc> <temp>
  6974. }
  6975. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6976. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6977. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6978. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6979. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6980. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6981. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6982. )
  6983. )
  6984. ) then
  6985. begin
  6986. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6987. RemoveInstruction(hp1);
  6988. RemoveCurrentP(p, hp2);
  6989. { first case: exit code }
  6990. if hp2.typ = ait_instruction then
  6991. RemoveLastDeallocForFuncRes(p);
  6992. Result := true;
  6993. end
  6994. else
  6995. { we can do this only in fast math mode as fstp is rounding ...
  6996. ... still disabled as it breaks the compiler and/or rtl }
  6997. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6998. { ... or if another fstp equal to the first one follows }
  6999. GetNextInstruction(hp1,hp2) and
  7000. (hp2.typ = ait_instruction) and
  7001. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7002. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7003. begin
  7004. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7005. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7006. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7007. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7008. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7009. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7010. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7011. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7012. ) then
  7013. begin
  7014. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7015. RemoveCurrentP(p,hp2);
  7016. RemoveInstruction(hp1);
  7017. Result := true;
  7018. end
  7019. else if { fst can't store an extended/comp value }
  7020. (taicpu(p).opsize <> S_FX) and
  7021. (taicpu(p).opsize <> S_IQ) then
  7022. begin
  7023. if (taicpu(p).opcode = A_FSTP) then
  7024. taicpu(p).opcode := A_FST
  7025. else
  7026. taicpu(p).opcode := A_FIST;
  7027. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7028. RemoveInstruction(hp1);
  7029. Result := true;
  7030. end;
  7031. end;
  7032. end;
  7033. end;
  7034. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7035. var
  7036. hp1, hp2, hp3: tai;
  7037. begin
  7038. result:=false;
  7039. if MatchOpType(taicpu(p),top_reg) and
  7040. GetNextInstruction(p, hp1) and
  7041. (hp1.typ = Ait_Instruction) and
  7042. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7043. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7044. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7045. { change to
  7046. fld reg fxxx reg,st
  7047. fxxxp st, st1 (hp1)
  7048. Remark: non commutative operations must be reversed!
  7049. }
  7050. begin
  7051. case taicpu(hp1).opcode Of
  7052. A_FMULP,A_FADDP,
  7053. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7054. begin
  7055. case taicpu(hp1).opcode Of
  7056. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7057. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7058. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7059. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7060. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7061. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7062. else
  7063. internalerror(2019050534);
  7064. end;
  7065. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7066. taicpu(hp1).oper[1]^.reg := NR_ST;
  7067. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7068. RemoveCurrentP(p, hp1);
  7069. Result:=true;
  7070. exit;
  7071. end;
  7072. else
  7073. ;
  7074. end;
  7075. end
  7076. else
  7077. if MatchOpType(taicpu(p),top_ref) and
  7078. GetNextInstruction(p, hp2) and
  7079. (hp2.typ = Ait_Instruction) and
  7080. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7081. (taicpu(p).opsize in [S_FS, S_FL]) and
  7082. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7083. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7084. if GetLastInstruction(p, hp1) and
  7085. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7086. MatchOpType(taicpu(hp1),top_ref) and
  7087. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7088. if ((taicpu(hp2).opcode = A_FMULP) or
  7089. (taicpu(hp2).opcode = A_FADDP)) then
  7090. { change to
  7091. fld/fst mem1 (hp1) fld/fst mem1
  7092. fld mem1 (p) fadd/
  7093. faddp/ fmul st, st
  7094. fmulp st, st1 (hp2) }
  7095. begin
  7096. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7097. RemoveCurrentP(p, hp1);
  7098. if (taicpu(hp2).opcode = A_FADDP) then
  7099. taicpu(hp2).opcode := A_FADD
  7100. else
  7101. taicpu(hp2).opcode := A_FMUL;
  7102. taicpu(hp2).oper[1]^.reg := NR_ST;
  7103. end
  7104. else
  7105. { change to
  7106. fld/fst mem1 (hp1) fld/fst mem1
  7107. fld mem1 (p) fld st
  7108. }
  7109. begin
  7110. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7111. taicpu(p).changeopsize(S_FL);
  7112. taicpu(p).loadreg(0,NR_ST);
  7113. end
  7114. else
  7115. begin
  7116. case taicpu(hp2).opcode Of
  7117. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7118. { change to
  7119. fld/fst mem1 (hp1) fld/fst mem1
  7120. fld mem2 (p) fxxx mem2
  7121. fxxxp st, st1 (hp2) }
  7122. begin
  7123. case taicpu(hp2).opcode Of
  7124. A_FADDP: taicpu(p).opcode := A_FADD;
  7125. A_FMULP: taicpu(p).opcode := A_FMUL;
  7126. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7127. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7128. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7129. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7130. else
  7131. internalerror(2019050533);
  7132. end;
  7133. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7134. RemoveInstruction(hp2);
  7135. end
  7136. else
  7137. ;
  7138. end
  7139. end
  7140. end;
  7141. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7142. begin
  7143. Result := condition_in(cond1, cond2) or
  7144. { Not strictly subsets due to the actual flags checked, but because we're
  7145. comparing integers, E is a subset of AE and GE and their aliases }
  7146. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7147. end;
  7148. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7149. var
  7150. v: TCGInt;
  7151. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7152. FirstMatch, TempBool: Boolean;
  7153. NewReg: TRegister;
  7154. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7155. begin
  7156. Result:=false;
  7157. { All these optimisations need a next instruction }
  7158. if not GetNextInstruction(p, hp1) then
  7159. Exit;
  7160. { Search for:
  7161. cmp ###,###
  7162. j(c1) @lbl1
  7163. ...
  7164. @lbl:
  7165. cmp ###,### (same comparison as above)
  7166. j(c2) @lbl2
  7167. If c1 is a subset of c2, change to:
  7168. cmp ###,###
  7169. j(c1) @lbl2
  7170. (@lbl1 may become a dead label as a result)
  7171. }
  7172. { Also handle cases where there are multiple jumps in a row }
  7173. p_jump := hp1;
  7174. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7175. begin
  7176. Prefetch(p_jump.Next);
  7177. if IsJumpToLabel(taicpu(p_jump)) then
  7178. begin
  7179. { Do jump optimisations first in case the condition becomes
  7180. unnecessary }
  7181. TempBool := True;
  7182. if DoJumpOptimizations(p_jump, TempBool) or
  7183. not TempBool then
  7184. begin
  7185. if Assigned(p_jump) then
  7186. begin
  7187. { CollapseZeroDistJump will be set to the label or an align
  7188. before it after the jump if it optimises, whether or not
  7189. the label is live or dead }
  7190. if (p_jump.typ = ait_align) or
  7191. (
  7192. (p_jump.typ = ait_label) and
  7193. not (tai_label(p_jump).labsym.is_used)
  7194. ) then
  7195. GetNextInstruction(p_jump, p_jump);
  7196. end;
  7197. TransferUsedRegs(TmpUsedRegs);
  7198. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7199. if not Assigned(p_jump) or
  7200. (
  7201. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7202. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7203. ) then
  7204. begin
  7205. { No more conditional jumps; conditional statement is no longer required }
  7206. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7207. RemoveCurrentP(p);
  7208. Result := True;
  7209. Exit;
  7210. end;
  7211. hp1 := p_jump;
  7212. Include(OptsToCheck, aoc_ForceNewIteration);
  7213. Continue;
  7214. end;
  7215. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7216. if GetNextInstruction(p_jump, hp2) and
  7217. (
  7218. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7219. not TempBool
  7220. ) then
  7221. begin
  7222. hp1 := p_jump;
  7223. Include(OptsToCheck, aoc_ForceNewIteration);
  7224. Continue;
  7225. end;
  7226. p_label := nil;
  7227. if Assigned(JumpLabel) then
  7228. p_label := getlabelwithsym(JumpLabel);
  7229. if Assigned(p_label) and
  7230. GetNextInstruction(p_label, p_dist) and
  7231. MatchInstruction(p_dist, A_CMP, []) and
  7232. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7233. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7234. GetNextInstruction(p_dist, hp1_dist) and
  7235. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7236. begin
  7237. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7238. if JumpLabel = JumpLabel_dist then
  7239. { This is an infinite loop }
  7240. Exit;
  7241. { Best optimisation when the first condition is a subset (or equal) of the second }
  7242. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7243. begin
  7244. { Any registers used here will already be allocated }
  7245. if Assigned(JumpLabel) then
  7246. JumpLabel.DecRefs;
  7247. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7248. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7249. Include(OptsToCheck, aoc_ForceNewIteration);
  7250. { Don't exit yet. Since p and p_jump haven't actually been
  7251. removed, we can check for more on this iteration }
  7252. end
  7253. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7254. GetNextInstruction(hp1_dist, hp1_label) and
  7255. (hp1_label.typ = ait_label) then
  7256. begin
  7257. JumpLabel_far := tai_label(hp1_label).labsym;
  7258. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7259. { This is an infinite loop }
  7260. Exit;
  7261. if Assigned(JumpLabel_far) then
  7262. begin
  7263. { In this situation, if the first jump branches, the second one will never,
  7264. branch so change the destination label to after the second jump }
  7265. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7266. if Assigned(JumpLabel) then
  7267. JumpLabel.DecRefs;
  7268. JumpLabel_far.IncRefs;
  7269. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7270. Result := True;
  7271. { Don't exit yet. Since p and p_jump haven't actually been
  7272. removed, we can check for more on this iteration }
  7273. Continue;
  7274. end;
  7275. end;
  7276. end;
  7277. end;
  7278. { Search for:
  7279. cmp ###,###
  7280. j(c1) @lbl1
  7281. cmp ###,### (same as first)
  7282. Remove second cmp
  7283. }
  7284. if GetNextInstruction(p_jump, hp2) and
  7285. (
  7286. (
  7287. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7288. (
  7289. (
  7290. MatchOpType(taicpu(p), top_const, top_reg) and
  7291. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7292. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7293. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7294. ) or (
  7295. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7296. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7297. )
  7298. )
  7299. ) or (
  7300. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7301. MatchOperand(taicpu(p).oper[0]^, 0) and
  7302. (taicpu(p).oper[1]^.typ = top_reg) and
  7303. MatchInstruction(hp2, A_TEST, []) and
  7304. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7305. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7306. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7307. )
  7308. ) then
  7309. begin
  7310. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7311. RemoveInstruction(hp2);
  7312. Result := True;
  7313. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7314. end
  7315. else
  7316. begin
  7317. { hp2 is the next instruction, so save time and just set p_jump
  7318. to it instead of calling GetNextInstruction below }
  7319. p_jump := hp2;
  7320. Continue;
  7321. end;
  7322. GetNextInstruction(p_jump, p_jump);
  7323. end;
  7324. if (
  7325. { Don't call GetNextInstruction again if we already have it }
  7326. (hp1 = p_jump) or
  7327. GetNextInstruction(p, hp1)
  7328. ) and
  7329. MatchInstruction(hp1, A_Jcc, []) and
  7330. IsJumpToLabel(taicpu(hp1)) and
  7331. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7332. GetNextInstruction(hp1, hp2) then
  7333. begin
  7334. {
  7335. cmp x, y (or "cmp y, x")
  7336. je @lbl
  7337. mov x, y
  7338. @lbl:
  7339. (x and y can be constants, registers or references)
  7340. Change to:
  7341. mov x, y (x and y will always be equal in the end)
  7342. @lbl: (may beceome a dead label)
  7343. Also:
  7344. cmp x, y (or "cmp y, x")
  7345. jne @lbl
  7346. mov x, y
  7347. @lbl:
  7348. (x and y can be constants, registers or references)
  7349. Change to:
  7350. Absolutely nothing! (Except @lbl if it's still live)
  7351. }
  7352. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7353. (
  7354. (
  7355. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7356. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7357. ) or (
  7358. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7359. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7360. )
  7361. ) and
  7362. GetNextInstruction(hp2, hp1_label) and
  7363. (hp1_label.typ = ait_label) and
  7364. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7365. begin
  7366. tai_label(hp1_label).labsym.DecRefs;
  7367. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7368. begin
  7369. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7370. RemoveInstruction(hp2);
  7371. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7372. end
  7373. else
  7374. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7375. RemoveInstruction(hp1);
  7376. RemoveCurrentp(p, hp2);
  7377. Result := True;
  7378. Exit;
  7379. end;
  7380. {
  7381. Try to optimise the following:
  7382. cmp $x,### ($x and $y can be registers or constants)
  7383. je @lbl1 (only reference)
  7384. cmp $y,### (### are identical)
  7385. @Lbl:
  7386. sete %reg1
  7387. Change to:
  7388. cmp $x,###
  7389. sete %reg2 (allocate new %reg2)
  7390. cmp $y,###
  7391. sete %reg1
  7392. orb %reg2,%reg1
  7393. (dealloc %reg2)
  7394. This adds an instruction (so don't perform under -Os), but it removes
  7395. a conditional branch.
  7396. }
  7397. if not (cs_opt_size in current_settings.optimizerswitches) and
  7398. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7399. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7400. { The first operand of CMP instructions can only be a register or
  7401. immediate anyway, so no need to check }
  7402. GetNextInstruction(hp2, p_label) and
  7403. (p_label.typ = ait_label) and
  7404. (tai_label(p_label).labsym.getrefs = 1) and
  7405. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7406. GetNextInstruction(p_label, p_dist) and
  7407. MatchInstruction(p_dist, A_SETcc, []) and
  7408. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7409. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7410. begin
  7411. TransferUsedRegs(TmpUsedRegs);
  7412. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7413. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7414. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7415. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7416. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7417. { Get the instruction after the SETcc instruction so we can
  7418. allocate a new register over the entire range }
  7419. GetNextInstruction(p_dist, hp1_dist) then
  7420. begin
  7421. { Register can appear in p if it's not used afterwards, so only
  7422. allocate between hp1 and hp1_dist }
  7423. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7424. if NewReg <> NR_NO then
  7425. begin
  7426. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7427. { Change the jump instruction into a SETcc instruction }
  7428. taicpu(hp1).opcode := A_SETcc;
  7429. taicpu(hp1).opsize := S_B;
  7430. taicpu(hp1).loadreg(0, NewReg);
  7431. { This is now a dead label }
  7432. tai_label(p_label).labsym.decrefs;
  7433. { Prefer adding before the next instruction so the FLAGS
  7434. register is deallicated first }
  7435. AsmL.InsertBefore(
  7436. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7437. hp1_dist
  7438. );
  7439. Result := True;
  7440. { Don't exit yet, as p wasn't changed and hp1, while
  7441. modified, is still intact and might be optimised by the
  7442. SETcc optimisation below }
  7443. end;
  7444. end;
  7445. end;
  7446. end;
  7447. if taicpu(p).oper[0]^.typ = top_const then
  7448. begin
  7449. if (taicpu(p).oper[0]^.val = 0) and
  7450. (taicpu(p).oper[1]^.typ = top_reg) and
  7451. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7452. begin
  7453. hp2 := p;
  7454. FirstMatch := True;
  7455. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7456. anything meaningful once it's converted to "test %reg,%reg";
  7457. additionally, some jumps will always (or never) branch, so
  7458. evaluate every jump immediately following the
  7459. comparison, optimising the conditions if possible.
  7460. Similarly with SETcc... those that are always set to 0 or 1
  7461. are changed to MOV instructions }
  7462. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7463. (
  7464. GetNextInstruction(hp2, hp1) and
  7465. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7466. ) do
  7467. begin
  7468. FirstMatch := False;
  7469. case taicpu(hp1).condition of
  7470. C_B, C_C, C_NAE, C_O:
  7471. { For B/NAE:
  7472. Will never branch since an unsigned integer can never be below zero
  7473. For C/O:
  7474. Result cannot overflow because 0 is being subtracted
  7475. }
  7476. begin
  7477. if taicpu(hp1).opcode = A_Jcc then
  7478. begin
  7479. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7480. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7481. RemoveInstruction(hp1);
  7482. { Since hp1 was deleted, hp2 must not be updated }
  7483. Continue;
  7484. end
  7485. else
  7486. begin
  7487. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7488. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7489. taicpu(hp1).opcode := A_MOV;
  7490. taicpu(hp1).ops := 2;
  7491. taicpu(hp1).condition := C_None;
  7492. taicpu(hp1).opsize := S_B;
  7493. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7494. taicpu(hp1).loadconst(0, 0);
  7495. end;
  7496. end;
  7497. C_BE, C_NA:
  7498. begin
  7499. { Will only branch if equal to zero }
  7500. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7501. taicpu(hp1).condition := C_E;
  7502. end;
  7503. C_A, C_NBE:
  7504. begin
  7505. { Will only branch if not equal to zero }
  7506. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7507. taicpu(hp1).condition := C_NE;
  7508. end;
  7509. C_AE, C_NB, C_NC, C_NO:
  7510. begin
  7511. { Will always branch }
  7512. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7513. if taicpu(hp1).opcode = A_Jcc then
  7514. begin
  7515. MakeUnconditional(taicpu(hp1));
  7516. { Any jumps/set that follow will now be dead code }
  7517. RemoveDeadCodeAfterJump(taicpu(hp1));
  7518. Break;
  7519. end
  7520. else
  7521. begin
  7522. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7523. taicpu(hp1).opcode := A_MOV;
  7524. taicpu(hp1).ops := 2;
  7525. taicpu(hp1).condition := C_None;
  7526. taicpu(hp1).opsize := S_B;
  7527. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7528. taicpu(hp1).loadconst(0, 1);
  7529. end;
  7530. end;
  7531. C_None:
  7532. InternalError(2020012201);
  7533. C_P, C_PE, C_NP, C_PO:
  7534. { We can't handle parity checks and they should never be generated
  7535. after a general-purpose CMP (it's used in some floating-point
  7536. comparisons that don't use CMP) }
  7537. InternalError(2020012202);
  7538. else
  7539. { Zero/Equality, Sign, their complements and all of the
  7540. signed comparisons do not need to be converted };
  7541. end;
  7542. hp2 := hp1;
  7543. end;
  7544. { Convert the instruction to a TEST }
  7545. taicpu(p).opcode := A_TEST;
  7546. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7547. Result := True;
  7548. Exit;
  7549. end
  7550. else if (taicpu(p).oper[0]^.val = 1) and
  7551. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7552. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7553. begin
  7554. { Convert; To:
  7555. cmp $1,r/m cmp $0,r/m
  7556. jl @lbl jle @lbl
  7557. (Also do inverted conditions)
  7558. }
  7559. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7560. taicpu(p).oper[0]^.val := 0;
  7561. if taicpu(hp1).condition in [C_L, C_NGE] then
  7562. taicpu(hp1).condition := C_LE
  7563. else
  7564. taicpu(hp1).condition := C_NLE;
  7565. { If the instruction is now "cmp $0,%reg", convert it to a
  7566. TEST (and effectively do the work of the "cmp $0,%reg" in
  7567. the block above)
  7568. }
  7569. if (taicpu(p).oper[1]^.typ = top_reg) then
  7570. begin
  7571. taicpu(p).opcode := A_TEST;
  7572. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7573. end;
  7574. Result := True;
  7575. Exit;
  7576. end
  7577. else if (taicpu(p).oper[1]^.typ = top_reg)
  7578. {$ifdef x86_64}
  7579. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7580. {$endif x86_64}
  7581. then
  7582. begin
  7583. { cmp register,$8000 neg register
  7584. je target --> jo target
  7585. .... only if register is deallocated before jump.}
  7586. case Taicpu(p).opsize of
  7587. S_B: v:=$80;
  7588. S_W: v:=$8000;
  7589. S_L: v:=qword($80000000);
  7590. else
  7591. internalerror(2013112905);
  7592. end;
  7593. if (taicpu(p).oper[0]^.val=v) and
  7594. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7595. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7596. begin
  7597. TransferUsedRegs(TmpUsedRegs);
  7598. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7599. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7600. begin
  7601. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7602. Taicpu(p).opcode:=A_NEG;
  7603. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7604. Taicpu(p).clearop(1);
  7605. Taicpu(p).ops:=1;
  7606. if Taicpu(hp1).condition=C_E then
  7607. Taicpu(hp1).condition:=C_O
  7608. else
  7609. Taicpu(hp1).condition:=C_NO;
  7610. Result:=true;
  7611. exit;
  7612. end;
  7613. end;
  7614. end;
  7615. end;
  7616. if TrySwapMovCmp(p, hp1) then
  7617. begin
  7618. Result := True;
  7619. Exit;
  7620. end;
  7621. end;
  7622. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7623. var
  7624. hp1: tai;
  7625. begin
  7626. {
  7627. remove the second (v)pxor from
  7628. pxor reg,reg
  7629. ...
  7630. pxor reg,reg
  7631. }
  7632. Result:=false;
  7633. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7634. MatchOpType(taicpu(p),top_reg,top_reg) and
  7635. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7636. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7637. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7638. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7639. begin
  7640. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7641. RemoveInstruction(hp1);
  7642. Result:=true;
  7643. Exit;
  7644. end
  7645. {
  7646. replace
  7647. pxor reg1,reg1
  7648. movapd/s reg1,reg2
  7649. dealloc reg1
  7650. by
  7651. pxor reg2,reg2
  7652. }
  7653. else if GetNextInstruction(p,hp1) and
  7654. { we mix single and double opperations here because we assume that the compiler
  7655. generates vmovapd only after double operations and vmovaps only after single operations }
  7656. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7657. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7658. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7659. (taicpu(p).oper[0]^.typ=top_reg) then
  7660. begin
  7661. TransferUsedRegs(TmpUsedRegs);
  7662. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7663. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7664. begin
  7665. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7666. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7667. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7668. RemoveInstruction(hp1);
  7669. result:=true;
  7670. end;
  7671. end;
  7672. end;
  7673. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7674. var
  7675. hp1: tai;
  7676. begin
  7677. {
  7678. remove the second (v)pxor from
  7679. (v)pxor reg,reg
  7680. ...
  7681. (v)pxor reg,reg
  7682. }
  7683. Result:=false;
  7684. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7685. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7686. begin
  7687. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7688. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7689. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7690. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7691. begin
  7692. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7693. RemoveInstruction(hp1);
  7694. Result:=true;
  7695. Exit;
  7696. end;
  7697. {$ifdef x86_64}
  7698. {
  7699. replace
  7700. vpxor reg1,reg1,reg1
  7701. vmov reg,mem
  7702. by
  7703. movq $0,mem
  7704. }
  7705. if GetNextInstruction(p,hp1) and
  7706. MatchInstruction(hp1,A_VMOVSD,[]) and
  7707. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7708. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7709. begin
  7710. TransferUsedRegs(TmpUsedRegs);
  7711. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7712. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7713. begin
  7714. taicpu(hp1).loadconst(0,0);
  7715. taicpu(hp1).opcode:=A_MOV;
  7716. taicpu(hp1).opsize:=S_Q;
  7717. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7718. RemoveCurrentP(p);
  7719. result:=true;
  7720. Exit;
  7721. end;
  7722. end;
  7723. {$endif x86_64}
  7724. end
  7725. {
  7726. replace
  7727. vpxor reg1,reg1,reg2
  7728. by
  7729. vpxor reg2,reg2,reg2
  7730. to avoid unncessary data dependencies
  7731. }
  7732. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7733. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7734. begin
  7735. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7736. { avoid unncessary data dependency }
  7737. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7738. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7739. result:=true;
  7740. exit;
  7741. end;
  7742. Result:=OptPass1VOP(p);
  7743. end;
  7744. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7745. var
  7746. hp1 : tai;
  7747. begin
  7748. result:=false;
  7749. { replace
  7750. IMul const,%mreg1,%mreg2
  7751. Mov %reg2,%mreg3
  7752. dealloc %mreg3
  7753. by
  7754. Imul const,%mreg1,%mreg23
  7755. }
  7756. if (taicpu(p).ops=3) and
  7757. GetNextInstruction(p,hp1) and
  7758. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7759. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7760. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7761. begin
  7762. TransferUsedRegs(TmpUsedRegs);
  7763. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7764. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7765. begin
  7766. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7767. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7768. RemoveInstruction(hp1);
  7769. result:=true;
  7770. end;
  7771. end;
  7772. end;
  7773. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7774. var
  7775. hp1 : tai;
  7776. begin
  7777. result:=false;
  7778. { replace
  7779. IMul %reg0,%reg1,%reg2
  7780. Mov %reg2,%reg3
  7781. dealloc %reg2
  7782. by
  7783. Imul %reg0,%reg1,%reg3
  7784. }
  7785. if GetNextInstruction(p,hp1) and
  7786. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7787. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7788. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7789. begin
  7790. TransferUsedRegs(TmpUsedRegs);
  7791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7792. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7793. begin
  7794. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7795. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7796. RemoveInstruction(hp1);
  7797. result:=true;
  7798. end;
  7799. end;
  7800. end;
  7801. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7802. var
  7803. hp1: tai;
  7804. begin
  7805. Result:=false;
  7806. { get rid of
  7807. (v)cvtss2sd reg0,<reg1,>reg2
  7808. (v)cvtss2sd reg2,<reg2,>reg0
  7809. }
  7810. if GetNextInstruction(p,hp1) and
  7811. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7812. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7813. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7814. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7815. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7816. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7817. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7818. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7819. )
  7820. ) then
  7821. begin
  7822. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7823. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7824. begin
  7825. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7826. RemoveCurrentP(p);
  7827. RemoveInstruction(hp1);
  7828. end
  7829. else
  7830. begin
  7831. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7832. if taicpu(hp1).opcode=A_CVTSD2SS then
  7833. begin
  7834. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7835. taicpu(p).opcode:=A_MOVAPS;
  7836. end
  7837. else
  7838. begin
  7839. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7840. taicpu(p).opcode:=A_VMOVAPS;
  7841. end;
  7842. taicpu(p).ops:=2;
  7843. RemoveInstruction(hp1);
  7844. end;
  7845. Result:=true;
  7846. Exit;
  7847. end;
  7848. end;
  7849. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7850. var
  7851. hp1, hp2, hp3, hp4, hp5: tai;
  7852. ThisReg: TRegister;
  7853. begin
  7854. Result := False;
  7855. if not GetNextInstruction(p,hp1) then
  7856. Exit;
  7857. {
  7858. convert
  7859. j<c> .L1
  7860. mov 1,reg
  7861. jmp .L2
  7862. .L1
  7863. mov 0,reg
  7864. .L2
  7865. into
  7866. mov 0,reg
  7867. set<not(c)> reg
  7868. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7869. would destroy the flag contents
  7870. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7871. executed at the same time as a previous comparison.
  7872. set<not(c)> reg
  7873. movzx reg, reg
  7874. }
  7875. if MatchInstruction(hp1,A_MOV,[]) and
  7876. (taicpu(hp1).oper[0]^.typ = top_const) and
  7877. (
  7878. (
  7879. (taicpu(hp1).oper[1]^.typ = top_reg)
  7880. {$ifdef i386}
  7881. { Under i386, ESI, EDI, EBP and ESP
  7882. don't have an 8-bit representation }
  7883. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7884. {$endif i386}
  7885. ) or (
  7886. {$ifdef i386}
  7887. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7888. {$endif i386}
  7889. (taicpu(hp1).opsize = S_B)
  7890. )
  7891. ) and
  7892. GetNextInstruction(hp1,hp2) and
  7893. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7894. GetNextInstruction(hp2,hp3) and
  7895. (hp3.typ=ait_label) and
  7896. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7897. GetNextInstruction(hp3,hp4) and
  7898. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7899. (taicpu(hp4).oper[0]^.typ = top_const) and
  7900. (
  7901. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7902. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7903. ) and
  7904. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7905. GetNextInstruction(hp4,hp5) and
  7906. (hp5.typ=ait_label) and
  7907. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7908. begin
  7909. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7910. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7911. tai_label(hp3).labsym.DecRefs;
  7912. { If this isn't the only reference to the middle label, we can
  7913. still make a saving - only that the first jump and everything
  7914. that follows will remain. }
  7915. if (tai_label(hp3).labsym.getrefs = 0) then
  7916. begin
  7917. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7918. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7919. else
  7920. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7921. { remove jump, first label and second MOV (also catching any aligns) }
  7922. repeat
  7923. if not GetNextInstruction(hp2, hp3) then
  7924. InternalError(2021040810);
  7925. RemoveInstruction(hp2);
  7926. hp2 := hp3;
  7927. until hp2 = hp5;
  7928. { Don't decrement reference count before the removal loop
  7929. above, otherwise GetNextInstruction won't stop on the
  7930. the label }
  7931. tai_label(hp5).labsym.DecRefs;
  7932. end
  7933. else
  7934. begin
  7935. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7936. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7937. else
  7938. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7939. end;
  7940. taicpu(p).opcode:=A_SETcc;
  7941. taicpu(p).opsize:=S_B;
  7942. taicpu(p).is_jmp:=False;
  7943. if taicpu(hp1).opsize=S_B then
  7944. begin
  7945. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7946. if taicpu(hp1).oper[1]^.typ = top_reg then
  7947. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7948. RemoveInstruction(hp1);
  7949. end
  7950. else
  7951. begin
  7952. { Will be a register because the size can't be S_B otherwise }
  7953. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7954. taicpu(p).loadreg(0, ThisReg);
  7955. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7956. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7957. begin
  7958. case taicpu(hp1).opsize of
  7959. S_W:
  7960. taicpu(hp1).opsize := S_BW;
  7961. S_L:
  7962. taicpu(hp1).opsize := S_BL;
  7963. {$ifdef x86_64}
  7964. S_Q:
  7965. begin
  7966. taicpu(hp1).opsize := S_BL;
  7967. { Change the destination register to 32-bit }
  7968. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7969. end;
  7970. {$endif x86_64}
  7971. else
  7972. InternalError(2021040820);
  7973. end;
  7974. taicpu(hp1).opcode := A_MOVZX;
  7975. taicpu(hp1).loadreg(0, ThisReg);
  7976. end
  7977. else
  7978. begin
  7979. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7980. { hp1 is already a MOV instruction with the correct register }
  7981. taicpu(hp1).loadconst(0, 0);
  7982. { Inserting it right before p will guarantee that the flags are also tracked }
  7983. asml.Remove(hp1);
  7984. asml.InsertBefore(hp1, p);
  7985. end;
  7986. end;
  7987. Result:=true;
  7988. exit;
  7989. end
  7990. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  7991. Result := TryJccStcClcOpt(p, hp1)
  7992. else if (hp1.typ = ait_label) then
  7993. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7994. end;
  7995. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7996. var
  7997. hp1, hp2, hp3: tai;
  7998. SourceRef, TargetRef: TReference;
  7999. CurrentReg: TRegister;
  8000. begin
  8001. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8002. if not UseAVX then
  8003. InternalError(2021100501);
  8004. Result := False;
  8005. { Look for the following to simplify:
  8006. vmovdqa/u x(mem1), %xmmreg
  8007. vmovdqa/u %xmmreg, y(mem2)
  8008. vmovdqa/u x+16(mem1), %xmmreg
  8009. vmovdqa/u %xmmreg, y+16(mem2)
  8010. Change to:
  8011. vmovdqa/u x(mem1), %ymmreg
  8012. vmovdqa/u %ymmreg, y(mem2)
  8013. vpxor %ymmreg, %ymmreg, %ymmreg
  8014. ( The VPXOR instruction is to zero the upper half, thus removing the
  8015. need to call the potentially expensive VZEROUPPER instruction. Other
  8016. peephole optimisations can remove VPXOR if it's unnecessary )
  8017. }
  8018. TransferUsedRegs(TmpUsedRegs);
  8019. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8020. { NOTE: In the optimisations below, if the references dictate that an
  8021. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8022. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8023. if (taicpu(p).opsize = S_XMM) and
  8024. MatchOpType(taicpu(p), top_ref, top_reg) and
  8025. GetNextInstruction(p, hp1) and
  8026. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8027. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8028. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8029. begin
  8030. SourceRef := taicpu(p).oper[0]^.ref^;
  8031. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8032. if GetNextInstruction(hp1, hp2) and
  8033. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8034. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8035. begin
  8036. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8037. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8038. Inc(SourceRef.offset, 16);
  8039. { Reuse the register in the first block move }
  8040. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8041. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8042. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8043. begin
  8044. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8045. Inc(TargetRef.offset, 16);
  8046. if GetNextInstruction(hp2, hp3) and
  8047. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8048. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8049. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8050. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8051. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8052. begin
  8053. { Update the register tracking to the new size }
  8054. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8055. { Remember that the offsets are 16 ahead }
  8056. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8057. if not (
  8058. ((SourceRef.offset mod 32) = 16) and
  8059. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8060. ) then
  8061. taicpu(p).opcode := A_VMOVDQU;
  8062. taicpu(p).opsize := S_YMM;
  8063. taicpu(p).oper[1]^.reg := CurrentReg;
  8064. if not (
  8065. ((TargetRef.offset mod 32) = 16) and
  8066. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8067. ) then
  8068. taicpu(hp1).opcode := A_VMOVDQU;
  8069. taicpu(hp1).opsize := S_YMM;
  8070. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8071. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8072. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8073. if (pi_uses_ymm in current_procinfo.flags) then
  8074. RemoveInstruction(hp2)
  8075. else
  8076. begin
  8077. taicpu(hp2).opcode := A_VPXOR;
  8078. taicpu(hp2).opsize := S_YMM;
  8079. taicpu(hp2).loadreg(0, CurrentReg);
  8080. taicpu(hp2).loadreg(1, CurrentReg);
  8081. taicpu(hp2).loadreg(2, CurrentReg);
  8082. taicpu(hp2).ops := 3;
  8083. end;
  8084. RemoveInstruction(hp3);
  8085. Result := True;
  8086. Exit;
  8087. end;
  8088. end
  8089. else
  8090. begin
  8091. { See if the next references are 16 less rather than 16 greater }
  8092. Dec(SourceRef.offset, 32); { -16 the other way }
  8093. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8094. begin
  8095. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8096. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8097. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8098. GetNextInstruction(hp2, hp3) and
  8099. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8100. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8101. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8102. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8103. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8104. begin
  8105. { Update the register tracking to the new size }
  8106. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8107. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8108. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8109. if not(
  8110. ((SourceRef.offset mod 32) = 0) and
  8111. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8112. ) then
  8113. taicpu(hp2).opcode := A_VMOVDQU;
  8114. taicpu(hp2).opsize := S_YMM;
  8115. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8116. if not (
  8117. ((TargetRef.offset mod 32) = 0) and
  8118. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8119. ) then
  8120. taicpu(hp3).opcode := A_VMOVDQU;
  8121. taicpu(hp3).opsize := S_YMM;
  8122. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8123. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8124. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8125. if (pi_uses_ymm in current_procinfo.flags) then
  8126. RemoveInstruction(hp1)
  8127. else
  8128. begin
  8129. taicpu(hp1).opcode := A_VPXOR;
  8130. taicpu(hp1).opsize := S_YMM;
  8131. taicpu(hp1).loadreg(0, CurrentReg);
  8132. taicpu(hp1).loadreg(1, CurrentReg);
  8133. taicpu(hp1).loadreg(2, CurrentReg);
  8134. taicpu(hp1).ops := 3;
  8135. Asml.Remove(hp1);
  8136. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8137. end;
  8138. RemoveCurrentP(p, hp2);
  8139. Result := True;
  8140. Exit;
  8141. end;
  8142. end;
  8143. end;
  8144. end;
  8145. end;
  8146. end;
  8147. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8148. var
  8149. hp2, hp3, first_assignment: tai;
  8150. IncCount, OperIdx: Integer;
  8151. OrigLabel: TAsmLabel;
  8152. begin
  8153. Count := 0;
  8154. Result := False;
  8155. first_assignment := nil;
  8156. if (LoopCount >= 20) then
  8157. begin
  8158. { Guard against infinite loops }
  8159. Exit;
  8160. end;
  8161. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8162. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8163. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8164. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8165. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8166. Exit;
  8167. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8168. {
  8169. change
  8170. jmp .L1
  8171. ...
  8172. .L1:
  8173. mov ##, ## ( multiple movs possible )
  8174. jmp/ret
  8175. into
  8176. mov ##, ##
  8177. jmp/ret
  8178. }
  8179. if not Assigned(hp1) then
  8180. begin
  8181. hp1 := GetLabelWithSym(OrigLabel);
  8182. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8183. Exit;
  8184. end;
  8185. hp2 := hp1;
  8186. while Assigned(hp2) do
  8187. begin
  8188. if Assigned(hp2) and (hp2.typ = ait_label) then
  8189. SkipLabels(hp2,hp2);
  8190. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8191. Break;
  8192. case taicpu(hp2).opcode of
  8193. A_MOVSD:
  8194. begin
  8195. if taicpu(hp2).ops = 0 then
  8196. { Wrong MOVSD }
  8197. Break;
  8198. Inc(Count);
  8199. if Count >= 5 then
  8200. { Too many to be worthwhile }
  8201. Break;
  8202. GetNextInstruction(hp2, hp2);
  8203. Continue;
  8204. end;
  8205. A_MOV,
  8206. A_MOVD,
  8207. A_MOVQ,
  8208. A_MOVSX,
  8209. {$ifdef x86_64}
  8210. A_MOVSXD,
  8211. {$endif x86_64}
  8212. A_MOVZX,
  8213. A_MOVAPS,
  8214. A_MOVUPS,
  8215. A_MOVSS,
  8216. A_MOVAPD,
  8217. A_MOVUPD,
  8218. A_MOVDQA,
  8219. A_MOVDQU,
  8220. A_VMOVSS,
  8221. A_VMOVAPS,
  8222. A_VMOVUPS,
  8223. A_VMOVSD,
  8224. A_VMOVAPD,
  8225. A_VMOVUPD,
  8226. A_VMOVDQA,
  8227. A_VMOVDQU:
  8228. begin
  8229. Inc(Count);
  8230. if Count >= 5 then
  8231. { Too many to be worthwhile }
  8232. Break;
  8233. GetNextInstruction(hp2, hp2);
  8234. Continue;
  8235. end;
  8236. A_JMP:
  8237. begin
  8238. { Guard against infinite loops }
  8239. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8240. Exit;
  8241. { Analyse this jump first in case it also duplicates assignments }
  8242. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8243. begin
  8244. { Something did change! }
  8245. Result := True;
  8246. Inc(Count, IncCount);
  8247. if Count >= 5 then
  8248. begin
  8249. { Too many to be worthwhile }
  8250. Exit;
  8251. end;
  8252. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8253. Break;
  8254. end;
  8255. Result := True;
  8256. Break;
  8257. end;
  8258. A_RET:
  8259. begin
  8260. Result := True;
  8261. Break;
  8262. end;
  8263. else
  8264. Break;
  8265. end;
  8266. end;
  8267. if Result then
  8268. begin
  8269. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8270. if Count = 0 then
  8271. begin
  8272. Result := False;
  8273. Exit;
  8274. end;
  8275. hp3 := p;
  8276. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8277. while True do
  8278. begin
  8279. if Assigned(hp1) and (hp1.typ = ait_label) then
  8280. SkipLabels(hp1,hp1);
  8281. if (hp1.typ <> ait_instruction) then
  8282. InternalError(2021040720);
  8283. case taicpu(hp1).opcode of
  8284. A_JMP:
  8285. begin
  8286. { Change the original jump to the new destination }
  8287. OrigLabel.decrefs;
  8288. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8289. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8290. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8291. if not Assigned(first_assignment) then
  8292. InternalError(2021040810)
  8293. else
  8294. p := first_assignment;
  8295. Exit;
  8296. end;
  8297. A_RET:
  8298. begin
  8299. { Now change the jump into a RET instruction }
  8300. ConvertJumpToRET(p, hp1);
  8301. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8302. if not Assigned(first_assignment) then
  8303. InternalError(2021040811)
  8304. else
  8305. p := first_assignment;
  8306. Exit;
  8307. end;
  8308. else
  8309. begin
  8310. { Duplicate the MOV instruction }
  8311. hp3:=tai(hp1.getcopy);
  8312. if first_assignment = nil then
  8313. first_assignment := hp3;
  8314. asml.InsertBefore(hp3, p);
  8315. { Make sure the compiler knows about any final registers written here }
  8316. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8317. with taicpu(hp3).oper[OperIdx]^ do
  8318. begin
  8319. case typ of
  8320. top_ref:
  8321. begin
  8322. if (ref^.base <> NR_NO) and
  8323. (getsupreg(ref^.base) <> RS_ESP) and
  8324. (getsupreg(ref^.base) <> RS_EBP)
  8325. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8326. then
  8327. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8328. if (ref^.index <> NR_NO) and
  8329. (getsupreg(ref^.index) <> RS_ESP) and
  8330. (getsupreg(ref^.index) <> RS_EBP)
  8331. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8332. (ref^.index <> ref^.base) then
  8333. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8334. end;
  8335. top_reg:
  8336. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8337. else
  8338. ;
  8339. end;
  8340. end;
  8341. end;
  8342. end;
  8343. if not GetNextInstruction(hp1, hp1) then
  8344. { Should have dropped out earlier }
  8345. InternalError(2021040710);
  8346. end;
  8347. end;
  8348. end;
  8349. const
  8350. WriteOp: array[0..3] of set of TInsChange = (
  8351. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8352. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8353. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8354. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8355. RegWriteFlags: array[0..7] of set of TInsChange = (
  8356. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8357. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8358. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8359. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8360. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8361. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8362. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8363. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8364. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8365. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8366. var
  8367. hp2: tai;
  8368. X: Integer;
  8369. begin
  8370. { If we have something like:
  8371. op ###,###
  8372. mov ###,###
  8373. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8374. interfere in regards to what they write to.
  8375. NOTE: p must be a 2-operand instruction
  8376. }
  8377. Result := False;
  8378. if (hp1.typ <> ait_instruction) or
  8379. taicpu(hp1).is_jmp or
  8380. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8381. Exit;
  8382. { NOP is a pipeline fence, likely marking the beginning of the function
  8383. epilogue, so drop out. Similarly, drop out if POP or RET are
  8384. encountered }
  8385. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8386. Exit;
  8387. if (taicpu(hp1).opcode = A_MOVSD) and
  8388. (taicpu(hp1).ops = 0) then
  8389. { Wrong MOVSD }
  8390. Exit;
  8391. { Check for writes to specific registers first }
  8392. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8393. for X := 0 to 7 do
  8394. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8395. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8396. Exit;
  8397. for X := 0 to taicpu(hp1).ops - 1 do
  8398. begin
  8399. { Check to see if this operand writes to something }
  8400. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8401. { And matches something in the CMP/TEST instruction }
  8402. (
  8403. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8404. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8405. (
  8406. { If it's a register, make sure the register written to doesn't
  8407. appear in the cmp instruction as part of a reference }
  8408. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8409. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8410. )
  8411. ) then
  8412. Exit;
  8413. end;
  8414. { Check p to make sure it doesn't write to something that affects hp1 }
  8415. { Check for writes to specific registers first }
  8416. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8417. for X := 0 to 7 do
  8418. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8419. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8420. Exit;
  8421. for X := 0 to taicpu(p).ops - 1 do
  8422. begin
  8423. { Check to see if this operand writes to something }
  8424. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8425. { And matches something in hp1 }
  8426. (taicpu(p).oper[X]^.typ = top_reg) and
  8427. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8428. Exit;
  8429. end;
  8430. { The instruction can be safely moved }
  8431. asml.Remove(hp1);
  8432. { Try to insert after the last instructions where the FLAGS register is not
  8433. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8434. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8435. asml.InsertBefore(hp1, hp2)
  8436. { Failing that, try to insert after the last instructions where the
  8437. FLAGS register is not yet in use }
  8438. else if GetLastInstruction(p, hp2) and
  8439. (
  8440. (hp2.typ <> ait_instruction) or
  8441. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8442. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8443. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8444. ) then
  8445. asml.InsertAfter(hp1, hp2)
  8446. else
  8447. { Note, if p.Previous is nil (even if it should logically never be the
  8448. case), FindRegAllocBackward immediately exits with False and so we
  8449. safely land here (we can't just pass p because FindRegAllocBackward
  8450. immediately exits on an instruction). [Kit] }
  8451. asml.InsertBefore(hp1, p);
  8452. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8453. { We can't trust UsedRegs because we're looking backwards, although we
  8454. know the registers are allocated after p at the very least, so manually
  8455. create tai_regalloc objects if needed }
  8456. for X := 0 to taicpu(hp1).ops - 1 do
  8457. case taicpu(hp1).oper[X]^.typ of
  8458. top_reg:
  8459. begin
  8460. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8461. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8462. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8463. end;
  8464. top_ref:
  8465. begin
  8466. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8467. begin
  8468. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8469. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8470. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8471. end;
  8472. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8473. begin
  8474. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8475. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8476. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8477. end;
  8478. end;
  8479. else
  8480. ;
  8481. end;
  8482. Result := True;
  8483. end;
  8484. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8485. var
  8486. hp2: tai;
  8487. X: Integer;
  8488. begin
  8489. { If we have something like:
  8490. cmp ###,%reg1
  8491. mov 0,%reg2
  8492. And no modified registers are shared, move the instruction to before
  8493. the comparison as this means it can be optimised without worrying
  8494. about the FLAGS register. (CMP/MOV is generated by
  8495. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8496. As long as the second instruction doesn't use the flags or one of the
  8497. registers used by CMP or TEST (also check any references that use the
  8498. registers), then it can be moved prior to the comparison.
  8499. }
  8500. Result := False;
  8501. if not TrySwapMovOp(p, hp1) then
  8502. Exit;
  8503. if taicpu(hp1).opcode = A_LEA then
  8504. { The flags will be overwritten by the CMP/TEST instruction }
  8505. ConvertLEA(taicpu(hp1));
  8506. Result := True;
  8507. { Can we move it one further back? }
  8508. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8509. { Check to see if CMP/TEST is a comparison against zero }
  8510. (
  8511. (
  8512. (taicpu(p).opcode = A_CMP) and
  8513. MatchOperand(taicpu(p).oper[0]^, 0)
  8514. ) or
  8515. (
  8516. (taicpu(p).opcode = A_TEST) and
  8517. (
  8518. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8519. MatchOperand(taicpu(p).oper[0]^, -1)
  8520. )
  8521. )
  8522. ) and
  8523. { These instructions set the zero flag if the result is zero }
  8524. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8525. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8526. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8527. TrySwapMovOp(hp2, hp1);
  8528. end;
  8529. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8530. var
  8531. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8532. JumpLabel: TAsmLabel;
  8533. TmpBool: Boolean;
  8534. begin
  8535. Result := False;
  8536. { Look for:
  8537. stc/clc
  8538. j(c) .L1
  8539. ...
  8540. .L1:
  8541. set(n)cb %reg
  8542. (flags deallocated)
  8543. j(c) .L2
  8544. Change to:
  8545. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8546. j(c) .L2
  8547. }
  8548. p_last := p;
  8549. while GetNextInstruction(p_last, hp1) and
  8550. (hp1.typ = ait_instruction) and
  8551. IsJumpToLabel(taicpu(hp1)) do
  8552. begin
  8553. if DoJumpOptimizations(hp1, TmpBool) then
  8554. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8555. Continue;
  8556. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8557. if not Assigned(JumpLabel) then
  8558. InternalError(2024012801);
  8559. { Optimise the J(c); stc/clc optimisation first since this will
  8560. get missed if the main optimisation takes place }
  8561. if (taicpu(hp1).opcode = A_JCC) then
  8562. begin
  8563. if GetNextInstruction(hp1, hp2) and
  8564. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8565. TryJccStcClcOpt(hp1, hp2) then
  8566. begin
  8567. Result := True;
  8568. Exit;
  8569. end;
  8570. hp2 := nil; { Suppress compiler warning }
  8571. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8572. { Make sure the flags aren't used again }
  8573. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8574. begin
  8575. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8576. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8577. begin
  8578. if (taicpu(p).opcode = A_STC) then
  8579. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8580. else
  8581. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8582. MakeUnconditional(taicpu(hp1));
  8583. { Move the jump to after the flag deallocations }
  8584. Asml.Remove(hp1);
  8585. Asml.InsertAfter(hp1, hp2);
  8586. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8587. Result := True;
  8588. Exit;
  8589. end
  8590. else
  8591. begin
  8592. if (taicpu(p).opcode = A_STC) then
  8593. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8594. else
  8595. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8596. { In this case, the jump is deterministic in that it will never be taken }
  8597. JumpLabel.DecRefs;
  8598. RemoveInstruction(hp1);
  8599. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8600. Result := True;
  8601. Exit;
  8602. end;
  8603. end;
  8604. end;
  8605. hp2 := nil; { Suppress compiler warning }
  8606. if
  8607. { Make sure the carry flag doesn't appear in the jump conditions }
  8608. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8609. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8610. GetNextInstruction(hp2, p_dist) and
  8611. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8612. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8613. begin
  8614. case taicpu(p_dist).opcode of
  8615. A_Jcc:
  8616. begin
  8617. if DoJumpOptimizations(p_dist, TmpBool) then
  8618. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8619. Continue;
  8620. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8621. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8622. begin
  8623. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8624. JumpLabel.decrefs;
  8625. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8626. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8627. Result := True;
  8628. Exit;
  8629. end
  8630. else if GetNextInstruction(p_dist, hp1_dist) and
  8631. (hp1_dist.typ = ait_label) then
  8632. begin
  8633. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8634. JumpLabel.decrefs;
  8635. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8636. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8637. Result := True;
  8638. Exit;
  8639. end;
  8640. end;
  8641. A_SETcc:
  8642. if { Make sure the flags aren't used again }
  8643. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8644. GetNextInstruction(hp2, hp1_dist) and
  8645. (hp1_dist.typ = ait_instruction) and
  8646. IsJumpToLabel(taicpu(hp1_dist)) and
  8647. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8648. { This works if hp1_dist or both are regular JMP instructions }
  8649. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  8650. begin
  8651. taicpu(p).allocate_oper(2);
  8652. taicpu(p).ops := 2;
  8653. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8654. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8655. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8656. taicpu(p).opcode := A_MOV;
  8657. taicpu(p).opsize := S_B;
  8658. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8659. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8660. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8661. JumpLabel.decrefs;
  8662. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8663. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8664. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8665. (tai_regalloc(hp2).ratype = ra_alloc) then
  8666. begin
  8667. Asml.Remove(hp2);
  8668. Asml.InsertAfter(hp2, p);
  8669. end;
  8670. Result := True;
  8671. Exit;
  8672. end;
  8673. else
  8674. ;
  8675. end;
  8676. end;
  8677. p_last := hp1;
  8678. end;
  8679. end;
  8680. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8681. var
  8682. hp2, hp3: tai;
  8683. TempBool: Boolean;
  8684. begin
  8685. Result := False;
  8686. {
  8687. j(c) .L1
  8688. stc/clc
  8689. .L1:
  8690. jc/jnc .L2
  8691. (Flags deallocated)
  8692. Change to:
  8693. j)c) .L1
  8694. jmp .L2
  8695. .L1:
  8696. jc/jnc .L2
  8697. Then call DoJumpOptimizations to convert to:
  8698. j(nc) .L2
  8699. .L1: (may become a dead label)
  8700. jc/jnc .L2
  8701. }
  8702. if GetNextInstruction(hp1, hp2) and
  8703. (hp2.typ = ait_label) and
  8704. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8705. GetNextInstruction(hp2, hp3) and
  8706. MatchInstruction(hp3, A_Jcc, []) and
  8707. (
  8708. (
  8709. (taicpu(hp3).condition = C_C) and
  8710. (taicpu(hp1).opcode = A_STC)
  8711. ) or (
  8712. (taicpu(hp3).condition = C_NC) and
  8713. (taicpu(hp1).opcode = A_CLC)
  8714. )
  8715. ) and
  8716. { Make sure the flags aren't used again }
  8717. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8718. begin
  8719. taicpu(hp1).allocate_oper(1);
  8720. taicpu(hp1).ops := 1;
  8721. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8722. taicpu(hp1).opcode := A_JMP;
  8723. taicpu(hp1).is_jmp := True;
  8724. TempBool := True; { Prevent compiler warnings }
  8725. if DoJumpOptimizations(p, TempBool) then
  8726. Result := True
  8727. else
  8728. Include(OptsToCheck, aoc_ForceNewIteration);
  8729. end;
  8730. end;
  8731. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8732. begin
  8733. { This generally only executes under -O3 and above }
  8734. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8735. end;
  8736. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8737. function IsXCHGAcceptable: Boolean; inline;
  8738. begin
  8739. { Always accept if optimising for size }
  8740. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8741. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8742. than 3, so it becomes a saving compared to three MOVs with two of
  8743. them able to execute simultaneously. [Kit] }
  8744. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8745. end;
  8746. var
  8747. NewRef: TReference;
  8748. hp1, hp2, hp3, hp4: Tai;
  8749. {$ifndef x86_64}
  8750. OperIdx: Integer;
  8751. {$endif x86_64}
  8752. NewInstr : Taicpu;
  8753. NewAligh : Tai_align;
  8754. DestLabel: TAsmLabel;
  8755. TempTracking: TAllUsedRegs;
  8756. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8757. var
  8758. NextInstr: tai;
  8759. begin
  8760. Result := False;
  8761. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8762. if not GetNextInstruction(InputInstr, NextInstr) or
  8763. (
  8764. { The FLAGS register isn't always tracked properly, so do not
  8765. perform this optimisation if a conditional statement follows }
  8766. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8767. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8768. ) then
  8769. begin
  8770. reference_reset(NewRef, 1, []);
  8771. NewRef.base := taicpu(p).oper[0]^.reg;
  8772. NewRef.scalefactor := 1;
  8773. if taicpu(InputInstr).opcode = A_ADD then
  8774. begin
  8775. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8776. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8777. end
  8778. else
  8779. begin
  8780. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8781. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8782. end;
  8783. taicpu(p).opcode := A_LEA;
  8784. taicpu(p).loadref(0, NewRef);
  8785. RemoveInstruction(InputInstr);
  8786. Result := True;
  8787. end;
  8788. end;
  8789. begin
  8790. Result:=false;
  8791. { This optimisation adds an instruction, so only do it for speed }
  8792. if not (cs_opt_size in current_settings.optimizerswitches) and
  8793. MatchOpType(taicpu(p), top_const, top_reg) and
  8794. (taicpu(p).oper[0]^.val = 0) then
  8795. begin
  8796. { To avoid compiler warning }
  8797. DestLabel := nil;
  8798. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8799. InternalError(2021040750);
  8800. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8801. Exit;
  8802. case hp1.typ of
  8803. ait_label:
  8804. begin
  8805. { Change:
  8806. mov $0,%reg mov $0,%reg
  8807. @Lbl1: @Lbl1:
  8808. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8809. je @Lbl2 jne @Lbl2
  8810. To: To:
  8811. mov $0,%reg mov $0,%reg
  8812. jmp @Lbl2 jmp @Lbl3
  8813. (align) (align)
  8814. @Lbl1: @Lbl1:
  8815. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8816. je @Lbl2 je @Lbl2
  8817. @Lbl3: <-- Only if label exists
  8818. (Not if it's optimised for size)
  8819. }
  8820. if not GetNextInstruction(hp1, hp2) then
  8821. Exit;
  8822. if (hp2.typ = ait_instruction) and
  8823. (
  8824. { Register sizes must exactly match }
  8825. (
  8826. (taicpu(hp2).opcode = A_CMP) and
  8827. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8828. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8829. ) or (
  8830. (taicpu(hp2).opcode = A_TEST) and
  8831. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8833. )
  8834. ) and GetNextInstruction(hp2, hp3) and
  8835. (hp3.typ = ait_instruction) and
  8836. (taicpu(hp3).opcode = A_JCC) and
  8837. (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
  8838. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8839. begin
  8840. { Check condition of jump }
  8841. { Always true? }
  8842. if condition_in(C_E, taicpu(hp3).condition) then
  8843. begin
  8844. { Copy label symbol and obtain matching label entry for the
  8845. conditional jump, as this will be our destination}
  8846. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8847. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8848. Result := True;
  8849. end
  8850. { Always false? }
  8851. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8852. begin
  8853. { This is only worth it if there's a jump to take }
  8854. case hp2.typ of
  8855. ait_instruction:
  8856. begin
  8857. if taicpu(hp2).opcode = A_JMP then
  8858. begin
  8859. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8860. { An unconditional jump follows the conditional jump which will always be false,
  8861. so use this jump's destination for the new jump }
  8862. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8863. Result := True;
  8864. end
  8865. else if taicpu(hp2).opcode = A_JCC then
  8866. begin
  8867. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8868. if condition_in(C_E, taicpu(hp2).condition) then
  8869. begin
  8870. { A second conditional jump follows the conditional jump which will always be false,
  8871. while the second jump is always True, so use this jump's destination for the new jump }
  8872. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8873. Result := True;
  8874. end;
  8875. { Don't risk it if the jump isn't always true (Result remains False) }
  8876. end;
  8877. end;
  8878. else
  8879. { If anything else don't optimise };
  8880. end;
  8881. end;
  8882. if Result then
  8883. begin
  8884. { Just so we have something to insert as a paremeter}
  8885. reference_reset(NewRef, 1, []);
  8886. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8887. { Now actually load the correct parameter (this also
  8888. increases the reference count) }
  8889. NewInstr.loadsymbol(0, DestLabel, 0);
  8890. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8891. begin
  8892. { Get instruction before original label (may not be p under -O3) }
  8893. if not GetLastInstruction(hp1, hp2) then
  8894. { Shouldn't fail here }
  8895. InternalError(2021040701);
  8896. end
  8897. else
  8898. hp2 := p;
  8899. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8900. AsmL.InsertAfter(NewInstr, hp2);
  8901. { Add new alignment field }
  8902. (* AsmL.InsertAfter(
  8903. cai_align.create_max(
  8904. current_settings.alignment.jumpalign,
  8905. current_settings.alignment.jumpalignskipmax
  8906. ),
  8907. NewInstr
  8908. ); *)
  8909. end;
  8910. Exit;
  8911. end;
  8912. end;
  8913. else
  8914. ;
  8915. end;
  8916. end;
  8917. if not GetNextInstruction(p, hp1) then
  8918. Exit;
  8919. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8920. and DoMovCmpMemOpt(p, hp1) then
  8921. begin
  8922. Result := True;
  8923. Exit;
  8924. end
  8925. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8926. begin
  8927. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8928. further, but we can't just put this jump optimisation in pass 1
  8929. because it tends to perform worse when conditional jumps are
  8930. nearby (e.g. when converting CMOV instructions). [Kit] }
  8931. CopyUsedRegs(TempTracking);
  8932. UpdateUsedRegs(tai(p.Next));
  8933. if OptPass2JMP(hp1) then
  8934. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8935. Result := OptPass1MOV(p);
  8936. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8937. returned True and the instruction is still a MOV, thus checking
  8938. the optimisations below }
  8939. { If OptPass2JMP returned False, no optimisations were done to
  8940. the jump and there are no further optimisations that can be done
  8941. to the MOV instruction on this pass }
  8942. { Restore register state }
  8943. RestoreUsedRegs(TempTracking);
  8944. ReleaseUsedRegs(TempTracking);
  8945. end
  8946. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8947. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8948. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8949. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8950. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8951. begin
  8952. { Change:
  8953. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8954. addl/q $x,%reg2 subl/q $x,%reg2
  8955. To:
  8956. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8957. }
  8958. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8959. { be lazy, checking separately for sub would be slightly better }
  8960. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8961. begin
  8962. TransferUsedRegs(TmpUsedRegs);
  8963. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8964. if TryMovArith2Lea(hp1) then
  8965. begin
  8966. Result := True;
  8967. Exit;
  8968. end
  8969. end
  8970. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8971. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8972. { Same as above, but also adds or subtracts to %reg2 in between.
  8973. It's still valid as long as the flags aren't in use }
  8974. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8975. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8976. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8977. { be lazy, checking separately for sub would be slightly better }
  8978. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8979. begin
  8980. TransferUsedRegs(TmpUsedRegs);
  8981. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8982. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8983. if TryMovArith2Lea(hp2) then
  8984. begin
  8985. Result := True;
  8986. Exit;
  8987. end;
  8988. end;
  8989. end
  8990. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8991. {$ifdef x86_64}
  8992. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8993. {$else x86_64}
  8994. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8995. {$endif x86_64}
  8996. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8997. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8998. { mov reg1, reg2 mov reg1, reg2
  8999. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9000. begin
  9001. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9002. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9003. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9004. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9005. TransferUsedRegs(TmpUsedRegs);
  9006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9007. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9008. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9009. then
  9010. begin
  9011. RemoveCurrentP(p, hp1);
  9012. Result:=true;
  9013. end;
  9014. exit;
  9015. end
  9016. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9017. IsXCHGAcceptable and
  9018. { XCHG doesn't support 8-byte registers }
  9019. (taicpu(p).opsize <> S_B) and
  9020. MatchInstruction(hp1, A_MOV, []) and
  9021. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9022. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9023. GetNextInstruction(hp1, hp2) and
  9024. MatchInstruction(hp2, A_MOV, []) and
  9025. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9026. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9027. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9028. begin
  9029. { mov %reg1,%reg2
  9030. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9031. mov %reg2,%reg3
  9032. (%reg2 not used afterwards)
  9033. Note that xchg takes 3 cycles to execute, and generally mov's take
  9034. only one cycle apiece, but the first two mov's can be executed in
  9035. parallel, only taking 2 cycles overall. Older processors should
  9036. therefore only optimise for size. [Kit]
  9037. }
  9038. TransferUsedRegs(TmpUsedRegs);
  9039. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9040. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9041. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9042. begin
  9043. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9044. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9045. taicpu(hp1).opcode := A_XCHG;
  9046. RemoveCurrentP(p, hp1);
  9047. RemoveInstruction(hp2);
  9048. Result := True;
  9049. Exit;
  9050. end;
  9051. end
  9052. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9053. MatchInstruction(hp1, A_SAR, []) then
  9054. begin
  9055. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9056. begin
  9057. { the use of %edx also covers the opsize being S_L }
  9058. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9059. begin
  9060. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9061. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9062. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9063. begin
  9064. { Change:
  9065. movl %eax,%edx
  9066. sarl $31,%edx
  9067. To:
  9068. cltd
  9069. }
  9070. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9071. RemoveInstruction(hp1);
  9072. taicpu(p).opcode := A_CDQ;
  9073. taicpu(p).opsize := S_NO;
  9074. taicpu(p).clearop(1);
  9075. taicpu(p).clearop(0);
  9076. taicpu(p).ops:=0;
  9077. Result := True;
  9078. end
  9079. else if (cs_opt_size in current_settings.optimizerswitches) and
  9080. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9081. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9082. begin
  9083. { Change:
  9084. movl %edx,%eax
  9085. sarl $31,%edx
  9086. To:
  9087. movl %edx,%eax
  9088. cltd
  9089. Note that this creates a dependency between the two instructions,
  9090. so only perform if optimising for size.
  9091. }
  9092. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9093. taicpu(hp1).opcode := A_CDQ;
  9094. taicpu(hp1).opsize := S_NO;
  9095. taicpu(hp1).clearop(1);
  9096. taicpu(hp1).clearop(0);
  9097. taicpu(hp1).ops:=0;
  9098. end;
  9099. {$ifndef x86_64}
  9100. end
  9101. { Don't bother if CMOV is supported, because a more optimal
  9102. sequence would have been generated for the Abs() intrinsic }
  9103. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9104. { the use of %eax also covers the opsize being S_L }
  9105. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9106. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9107. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9108. GetNextInstruction(hp1, hp2) and
  9109. MatchInstruction(hp2, A_XOR, [S_L]) and
  9110. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9111. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9112. GetNextInstruction(hp2, hp3) and
  9113. MatchInstruction(hp3, A_SUB, [S_L]) and
  9114. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9115. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9116. begin
  9117. { Change:
  9118. movl %eax,%edx
  9119. sarl $31,%eax
  9120. xorl %eax,%edx
  9121. subl %eax,%edx
  9122. (Instruction that uses %edx)
  9123. (%eax deallocated)
  9124. (%edx deallocated)
  9125. To:
  9126. cltd
  9127. xorl %edx,%eax <-- Note the registers have swapped
  9128. subl %edx,%eax
  9129. (Instruction that uses %eax) <-- %eax rather than %edx
  9130. }
  9131. TransferUsedRegs(TmpUsedRegs);
  9132. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9133. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9134. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9135. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9136. begin
  9137. if GetNextInstruction(hp3, hp4) and
  9138. not RegModifiedByInstruction(NR_EDX, hp4) and
  9139. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9140. begin
  9141. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9142. taicpu(p).opcode := A_CDQ;
  9143. taicpu(p).clearop(1);
  9144. taicpu(p).clearop(0);
  9145. taicpu(p).ops:=0;
  9146. RemoveInstruction(hp1);
  9147. taicpu(hp2).loadreg(0, NR_EDX);
  9148. taicpu(hp2).loadreg(1, NR_EAX);
  9149. taicpu(hp3).loadreg(0, NR_EDX);
  9150. taicpu(hp3).loadreg(1, NR_EAX);
  9151. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9152. { Convert references in the following instruction (hp4) from %edx to %eax }
  9153. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9154. with taicpu(hp4).oper[OperIdx]^ do
  9155. case typ of
  9156. top_reg:
  9157. if getsupreg(reg) = RS_EDX then
  9158. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9159. top_ref:
  9160. begin
  9161. if getsupreg(reg) = RS_EDX then
  9162. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9163. if getsupreg(reg) = RS_EDX then
  9164. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9165. end;
  9166. else
  9167. ;
  9168. end;
  9169. end;
  9170. end;
  9171. {$else x86_64}
  9172. end;
  9173. end
  9174. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9175. { the use of %rdx also covers the opsize being S_Q }
  9176. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9177. begin
  9178. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9179. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9180. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9181. begin
  9182. { Change:
  9183. movq %rax,%rdx
  9184. sarq $63,%rdx
  9185. To:
  9186. cqto
  9187. }
  9188. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9189. RemoveInstruction(hp1);
  9190. taicpu(p).opcode := A_CQO;
  9191. taicpu(p).opsize := S_NO;
  9192. taicpu(p).clearop(1);
  9193. taicpu(p).clearop(0);
  9194. taicpu(p).ops:=0;
  9195. Result := True;
  9196. end
  9197. else if (cs_opt_size in current_settings.optimizerswitches) and
  9198. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9199. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9200. begin
  9201. { Change:
  9202. movq %rdx,%rax
  9203. sarq $63,%rdx
  9204. To:
  9205. movq %rdx,%rax
  9206. cqto
  9207. Note that this creates a dependency between the two instructions,
  9208. so only perform if optimising for size.
  9209. }
  9210. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9211. taicpu(hp1).opcode := A_CQO;
  9212. taicpu(hp1).opsize := S_NO;
  9213. taicpu(hp1).clearop(1);
  9214. taicpu(hp1).clearop(0);
  9215. taicpu(hp1).ops:=0;
  9216. {$endif x86_64}
  9217. end;
  9218. end;
  9219. end
  9220. else if MatchInstruction(hp1, A_MOV, []) and
  9221. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9222. { Though "GetNextInstruction" could be factored out, along with
  9223. the instructions that depend on hp2, it is an expensive call that
  9224. should be delayed for as long as possible, hence we do cheaper
  9225. checks first that are likely to be False. [Kit] }
  9226. begin
  9227. if (
  9228. (
  9229. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9230. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9231. (
  9232. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9233. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9234. )
  9235. ) or
  9236. (
  9237. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9238. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9239. (
  9240. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9241. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9242. )
  9243. )
  9244. ) and
  9245. GetNextInstruction(hp1, hp2) and
  9246. MatchInstruction(hp2, A_SAR, []) and
  9247. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9248. begin
  9249. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9250. begin
  9251. { Change:
  9252. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9253. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9254. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9255. To:
  9256. movl r/m,%eax <- Note the change in register
  9257. cltd
  9258. }
  9259. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9260. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9261. taicpu(p).loadreg(1, NR_EAX);
  9262. taicpu(hp1).opcode := A_CDQ;
  9263. taicpu(hp1).clearop(1);
  9264. taicpu(hp1).clearop(0);
  9265. taicpu(hp1).ops:=0;
  9266. RemoveInstruction(hp2);
  9267. (*
  9268. {$ifdef x86_64}
  9269. end
  9270. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9271. { This code sequence does not get generated - however it might become useful
  9272. if and when 128-bit signed integer types make an appearance, so the code
  9273. is kept here for when it is eventually needed. [Kit] }
  9274. (
  9275. (
  9276. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9277. (
  9278. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9279. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9280. )
  9281. ) or
  9282. (
  9283. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9284. (
  9285. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9286. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9287. )
  9288. )
  9289. ) and
  9290. GetNextInstruction(hp1, hp2) and
  9291. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9292. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9293. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9294. begin
  9295. { Change:
  9296. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9297. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9298. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9299. To:
  9300. movq r/m,%rax <- Note the change in register
  9301. cqto
  9302. }
  9303. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9304. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9305. taicpu(p).loadreg(1, NR_RAX);
  9306. taicpu(hp1).opcode := A_CQO;
  9307. taicpu(hp1).clearop(1);
  9308. taicpu(hp1).clearop(0);
  9309. taicpu(hp1).ops:=0;
  9310. RemoveInstruction(hp2);
  9311. {$endif x86_64}
  9312. *)
  9313. end;
  9314. end;
  9315. {$ifdef x86_64}
  9316. end
  9317. else if (taicpu(p).opsize = S_L) and
  9318. (taicpu(p).oper[1]^.typ = top_reg) and
  9319. (
  9320. MatchInstruction(hp1, A_MOV,[]) and
  9321. (taicpu(hp1).opsize = S_L) and
  9322. (taicpu(hp1).oper[1]^.typ = top_reg)
  9323. ) and (
  9324. GetNextInstruction(hp1, hp2) and
  9325. (tai(hp2).typ=ait_instruction) and
  9326. (taicpu(hp2).opsize = S_Q) and
  9327. (
  9328. (
  9329. MatchInstruction(hp2, A_ADD,[]) and
  9330. (taicpu(hp2).opsize = S_Q) and
  9331. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9332. (
  9333. (
  9334. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9335. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9336. ) or (
  9337. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9338. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9339. )
  9340. )
  9341. ) or (
  9342. MatchInstruction(hp2, A_LEA,[]) and
  9343. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9344. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9345. (
  9346. (
  9347. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9348. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9349. ) or (
  9350. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9351. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9352. )
  9353. ) and (
  9354. (
  9355. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9356. ) or (
  9357. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9358. )
  9359. )
  9360. )
  9361. )
  9362. ) and (
  9363. GetNextInstruction(hp2, hp3) and
  9364. MatchInstruction(hp3, A_SHR,[]) and
  9365. (taicpu(hp3).opsize = S_Q) and
  9366. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9367. (taicpu(hp3).oper[0]^.val = 1) and
  9368. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9369. ) then
  9370. begin
  9371. { Change movl x, reg1d movl x, reg1d
  9372. movl y, reg2d movl y, reg2d
  9373. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9374. shrq $1, reg1q shrq $1, reg1q
  9375. ( reg1d and reg2d can be switched around in the first two instructions )
  9376. To movl x, reg1d
  9377. addl y, reg1d
  9378. rcrl $1, reg1d
  9379. This corresponds to the common expression (x + y) shr 1, where
  9380. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9381. smaller code, but won't account for x + y causing an overflow). [Kit]
  9382. }
  9383. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9384. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9385. { Change first MOV command to have the same register as the final output }
  9386. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9387. else
  9388. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9389. { Change second MOV command to an ADD command. This is easier than
  9390. converting the existing command because it means we don't have to
  9391. touch 'y', which might be a complicated reference, and also the
  9392. fact that the third command might either be ADD or LEA. [Kit] }
  9393. taicpu(hp1).opcode := A_ADD;
  9394. { Delete old ADD/LEA instruction }
  9395. RemoveInstruction(hp2);
  9396. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9397. taicpu(hp3).opcode := A_RCR;
  9398. taicpu(hp3).changeopsize(S_L);
  9399. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9400. {$endif x86_64}
  9401. end;
  9402. if FuncMov2Func(p, hp1) then
  9403. begin
  9404. Result := True;
  9405. Exit;
  9406. end;
  9407. end;
  9408. {$push}
  9409. {$q-}{$r-}
  9410. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9411. var
  9412. ThisReg: TRegister;
  9413. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9414. TargetSubReg: TSubRegister;
  9415. hp1, hp2: tai;
  9416. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9417. { Store list of found instructions so we don't have to call
  9418. GetNextInstructionUsingReg multiple times }
  9419. InstrList: array of taicpu;
  9420. InstrMax, Index: Integer;
  9421. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9422. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9423. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9424. WorkingValue: TCgInt;
  9425. PreMessage: string;
  9426. { Data flow analysis }
  9427. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9428. BitwiseOnly, OrXorUsed,
  9429. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9430. function CheckOverflowConditions: Boolean;
  9431. begin
  9432. Result := True;
  9433. if (TestValSignedMax > SignedUpperLimit) then
  9434. UpperSignedOverflow := True;
  9435. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9436. LowerSignedOverflow := True;
  9437. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9438. LowerUnsignedOverflow := True;
  9439. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9440. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9441. begin
  9442. { Absolute overflow }
  9443. Result := False;
  9444. Exit;
  9445. end;
  9446. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9447. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9448. ShiftDownOverflow := True;
  9449. if (TestValMin < 0) or (TestValMax < 0) then
  9450. begin
  9451. LowerUnsignedOverflow := True;
  9452. UpperUnsignedOverflow := True;
  9453. end;
  9454. end;
  9455. function AdjustInitialLoadAndSize: Boolean;
  9456. begin
  9457. Result := False;
  9458. if not p_removed then
  9459. begin
  9460. if TargetSize = MinSize then
  9461. begin
  9462. { Convert the input MOVZX to a MOV }
  9463. if (taicpu(p).oper[0]^.typ = top_reg) and
  9464. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9465. begin
  9466. { Or remove it completely! }
  9467. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9468. RemoveCurrentP(p);
  9469. p_removed := True;
  9470. end
  9471. else
  9472. begin
  9473. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9474. taicpu(p).opcode := A_MOV;
  9475. taicpu(p).oper[1]^.reg := ThisReg;
  9476. taicpu(p).opsize := TargetSize;
  9477. end;
  9478. Result := True;
  9479. end
  9480. else if TargetSize <> MaxSize then
  9481. begin
  9482. case MaxSize of
  9483. S_L:
  9484. if TargetSize = S_W then
  9485. begin
  9486. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9487. taicpu(p).opsize := S_BW;
  9488. taicpu(p).oper[1]^.reg := ThisReg;
  9489. Result := True;
  9490. end
  9491. else
  9492. InternalError(2020112341);
  9493. S_W:
  9494. if TargetSize = S_L then
  9495. begin
  9496. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9497. taicpu(p).opsize := S_BL;
  9498. taicpu(p).oper[1]^.reg := ThisReg;
  9499. Result := True;
  9500. end
  9501. else
  9502. InternalError(2020112342);
  9503. else
  9504. ;
  9505. end;
  9506. end
  9507. else if not hp1_removed and not RegInUse then
  9508. begin
  9509. { If we have something like:
  9510. movzbl (oper),%regd
  9511. add x, %regd
  9512. movzbl %regb, %regd
  9513. We can reduce the register size to the input of the final
  9514. movzbl instruction. Overflows won't have any effect.
  9515. }
  9516. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9517. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9518. begin
  9519. TargetSize := S_B;
  9520. setsubreg(ThisReg, R_SUBL);
  9521. Result := True;
  9522. end
  9523. else if (taicpu(p).opsize = S_WL) and
  9524. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9525. begin
  9526. TargetSize := S_W;
  9527. setsubreg(ThisReg, R_SUBW);
  9528. Result := True;
  9529. end;
  9530. if Result then
  9531. begin
  9532. { Convert the input MOVZX to a MOV }
  9533. if (taicpu(p).oper[0]^.typ = top_reg) and
  9534. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9535. begin
  9536. { Or remove it completely! }
  9537. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9538. RemoveCurrentP(p);
  9539. p_removed := True;
  9540. end
  9541. else
  9542. begin
  9543. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9544. taicpu(p).opcode := A_MOV;
  9545. taicpu(p).oper[1]^.reg := ThisReg;
  9546. taicpu(p).opsize := TargetSize;
  9547. end;
  9548. end;
  9549. end;
  9550. end;
  9551. end;
  9552. procedure AdjustFinalLoad;
  9553. begin
  9554. if not LowerUnsignedOverflow then
  9555. begin
  9556. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9557. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9558. begin
  9559. { Convert the output MOVZX to a MOV }
  9560. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9561. begin
  9562. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9563. if (MinSize = S_B) or
  9564. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9565. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9566. begin
  9567. { Remove it completely! }
  9568. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9569. { Be careful; if p = hp1 and p was also removed, p
  9570. will become a dangling pointer }
  9571. if p = hp1 then
  9572. begin
  9573. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9574. p_removed := True;
  9575. end
  9576. else
  9577. RemoveInstruction(hp1);
  9578. hp1_removed := True;
  9579. end;
  9580. end
  9581. else
  9582. begin
  9583. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9584. taicpu(hp1).opcode := A_MOV;
  9585. taicpu(hp1).oper[0]^.reg := ThisReg;
  9586. taicpu(hp1).opsize := TargetSize;
  9587. end;
  9588. end
  9589. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9590. begin
  9591. { Need to change the size of the output }
  9592. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9593. taicpu(hp1).oper[0]^.reg := ThisReg;
  9594. taicpu(hp1).opsize := S_BL;
  9595. end;
  9596. end;
  9597. end;
  9598. function CompressInstructions: Boolean;
  9599. var
  9600. LocalIndex: Integer;
  9601. begin
  9602. Result := False;
  9603. { The objective here is to try to find a combination that
  9604. removes one of the MOV/Z instructions. }
  9605. if (
  9606. (taicpu(p).oper[0]^.typ <> top_reg) or
  9607. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9608. ) and
  9609. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9610. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9611. begin
  9612. { Make a preference to remove the second MOVZX instruction }
  9613. case taicpu(hp1).opsize of
  9614. S_BL, S_WL:
  9615. begin
  9616. TargetSize := S_L;
  9617. TargetSubReg := R_SUBD;
  9618. end;
  9619. S_BW:
  9620. begin
  9621. TargetSize := S_W;
  9622. TargetSubReg := R_SUBW;
  9623. end;
  9624. else
  9625. InternalError(2020112302);
  9626. end;
  9627. end
  9628. else
  9629. begin
  9630. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9631. begin
  9632. { Exceeded lower bound but not upper bound }
  9633. TargetSize := MaxSize;
  9634. end
  9635. else if not LowerUnsignedOverflow then
  9636. begin
  9637. { Size didn't exceed lower bound }
  9638. TargetSize := MinSize;
  9639. end
  9640. else
  9641. Exit;
  9642. end;
  9643. case TargetSize of
  9644. S_B:
  9645. TargetSubReg := R_SUBL;
  9646. S_W:
  9647. TargetSubReg := R_SUBW;
  9648. S_L:
  9649. TargetSubReg := R_SUBD;
  9650. else
  9651. InternalError(2020112350);
  9652. end;
  9653. { Update the register to its new size }
  9654. setsubreg(ThisReg, TargetSubReg);
  9655. RegInUse := False;
  9656. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9657. begin
  9658. { Check to see if the active register is used afterwards;
  9659. if not, we can change it and make a saving. }
  9660. TransferUsedRegs(TmpUsedRegs);
  9661. { The target register may be marked as in use to cross
  9662. a jump to a distant label, so exclude it }
  9663. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9664. hp2 := p;
  9665. repeat
  9666. { Explicitly check for the excluded register (don't include the first
  9667. instruction as it may be reading from here }
  9668. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9669. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9670. begin
  9671. RegInUse := True;
  9672. Break;
  9673. end;
  9674. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9675. if not GetNextInstruction(hp2, hp2) then
  9676. InternalError(2020112340);
  9677. until (hp2 = hp1);
  9678. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9679. { We might still be able to get away with this }
  9680. RegInUse := not
  9681. (
  9682. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9683. (hp2.typ = ait_instruction) and
  9684. (
  9685. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9686. instruction that doesn't actually contain ThisReg }
  9687. (cs_opt_level3 in current_settings.optimizerswitches) or
  9688. RegInInstruction(ThisReg, hp2)
  9689. ) and
  9690. RegLoadedWithNewValue(ThisReg, hp2)
  9691. );
  9692. if not RegInUse then
  9693. begin
  9694. { Force the register size to the same as this instruction so it can be removed}
  9695. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9696. begin
  9697. TargetSize := S_L;
  9698. TargetSubReg := R_SUBD;
  9699. end
  9700. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9701. begin
  9702. TargetSize := S_W;
  9703. TargetSubReg := R_SUBW;
  9704. end;
  9705. ThisReg := taicpu(hp1).oper[1]^.reg;
  9706. setsubreg(ThisReg, TargetSubReg);
  9707. RegChanged := True;
  9708. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9709. TransferUsedRegs(TmpUsedRegs);
  9710. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9711. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9712. if p = hp1 then
  9713. begin
  9714. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9715. p_removed := True;
  9716. end
  9717. else
  9718. RemoveInstruction(hp1);
  9719. hp1_removed := True;
  9720. { Instruction will become "mov %reg,%reg" }
  9721. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9722. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9723. begin
  9724. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9725. RemoveCurrentP(p);
  9726. p_removed := True;
  9727. end
  9728. else
  9729. taicpu(p).oper[1]^.reg := ThisReg;
  9730. Result := True;
  9731. end
  9732. else
  9733. begin
  9734. if TargetSize <> MaxSize then
  9735. begin
  9736. { Since the register is in use, we have to force it to
  9737. MaxSize otherwise part of it may become undefined later on }
  9738. TargetSize := MaxSize;
  9739. case TargetSize of
  9740. S_B:
  9741. TargetSubReg := R_SUBL;
  9742. S_W:
  9743. TargetSubReg := R_SUBW;
  9744. S_L:
  9745. TargetSubReg := R_SUBD;
  9746. else
  9747. InternalError(2020112351);
  9748. end;
  9749. setsubreg(ThisReg, TargetSubReg);
  9750. end;
  9751. AdjustFinalLoad;
  9752. end;
  9753. end
  9754. else
  9755. AdjustFinalLoad;
  9756. Result := AdjustInitialLoadAndSize or Result;
  9757. { Now go through every instruction we found and change the
  9758. size. If TargetSize = MaxSize, then almost no changes are
  9759. needed and Result can remain False if it hasn't been set
  9760. yet.
  9761. If RegChanged is True, then the register requires changing
  9762. and so the point about TargetSize = MaxSize doesn't apply. }
  9763. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9764. begin
  9765. for LocalIndex := 0 to InstrMax do
  9766. begin
  9767. { If p_removed is true, then the original MOV/Z was removed
  9768. and removing the AND instruction may not be safe if it
  9769. appears first }
  9770. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9771. InternalError(2020112310);
  9772. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9773. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9774. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9775. InstrList[LocalIndex].opsize := TargetSize;
  9776. end;
  9777. Result := True;
  9778. end;
  9779. end;
  9780. begin
  9781. Result := False;
  9782. p_removed := False;
  9783. hp1_removed := False;
  9784. ThisReg := taicpu(p).oper[1]^.reg;
  9785. { Check for:
  9786. movs/z ###,%ecx (or %cx or %rcx)
  9787. ...
  9788. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9789. (dealloc %ecx)
  9790. Change to:
  9791. mov ###,%cl (if ### = %cl, then remove completely)
  9792. ...
  9793. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9794. }
  9795. if (getsupreg(ThisReg) = RS_ECX) and
  9796. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9797. (hp1.typ = ait_instruction) and
  9798. (
  9799. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9800. instruction that doesn't actually contain ECX }
  9801. (cs_opt_level3 in current_settings.optimizerswitches) or
  9802. RegInInstruction(NR_ECX, hp1) or
  9803. (
  9804. { It's common for the shift/rotate's read/write register to be
  9805. initialised in between, so under -O2 and under, search ahead
  9806. one more instruction
  9807. }
  9808. GetNextInstruction(hp1, hp1) and
  9809. (hp1.typ = ait_instruction) and
  9810. RegInInstruction(NR_ECX, hp1)
  9811. )
  9812. ) and
  9813. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9814. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9815. begin
  9816. TransferUsedRegs(TmpUsedRegs);
  9817. hp2 := p;
  9818. repeat
  9819. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9820. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9821. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9822. begin
  9823. case taicpu(p).opsize of
  9824. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9825. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9826. begin
  9827. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9828. RemoveCurrentP(p);
  9829. end
  9830. else
  9831. begin
  9832. taicpu(p).opcode := A_MOV;
  9833. taicpu(p).opsize := S_B;
  9834. taicpu(p).oper[1]^.reg := NR_CL;
  9835. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9836. end;
  9837. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9838. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9839. begin
  9840. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9841. RemoveCurrentP(p);
  9842. end
  9843. else
  9844. begin
  9845. taicpu(p).opcode := A_MOV;
  9846. taicpu(p).opsize := S_W;
  9847. taicpu(p).oper[1]^.reg := NR_CX;
  9848. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9849. end;
  9850. {$ifdef x86_64}
  9851. S_LQ:
  9852. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9853. begin
  9854. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9855. RemoveCurrentP(p);
  9856. end
  9857. else
  9858. begin
  9859. taicpu(p).opcode := A_MOV;
  9860. taicpu(p).opsize := S_L;
  9861. taicpu(p).oper[1]^.reg := NR_ECX;
  9862. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9863. end;
  9864. {$endif x86_64}
  9865. else
  9866. InternalError(2021120401);
  9867. end;
  9868. Result := True;
  9869. Exit;
  9870. end;
  9871. end;
  9872. { This is anything but quick! }
  9873. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9874. Exit;
  9875. SetLength(InstrList, 0);
  9876. InstrMax := -1;
  9877. case taicpu(p).opsize of
  9878. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9879. begin
  9880. {$if defined(i386) or defined(i8086)}
  9881. { If the target size is 8-bit, make sure we can actually encode it }
  9882. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9883. Exit;
  9884. {$endif i386 or i8086}
  9885. LowerLimit := $FF;
  9886. SignedLowerLimit := $7F;
  9887. SignedLowerLimitBottom := -128;
  9888. MinSize := S_B;
  9889. if taicpu(p).opsize = S_BW then
  9890. begin
  9891. MaxSize := S_W;
  9892. UpperLimit := $FFFF;
  9893. SignedUpperLimit := $7FFF;
  9894. SignedUpperLimitBottom := -32768;
  9895. end
  9896. else
  9897. begin
  9898. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9899. MaxSize := S_L;
  9900. UpperLimit := $FFFFFFFF;
  9901. SignedUpperLimit := $7FFFFFFF;
  9902. SignedUpperLimitBottom := -2147483648;
  9903. end;
  9904. end;
  9905. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9906. begin
  9907. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9908. LowerLimit := $FFFF;
  9909. SignedLowerLimit := $7FFF;
  9910. SignedLowerLimitBottom := -32768;
  9911. UpperLimit := $FFFFFFFF;
  9912. SignedUpperLimit := $7FFFFFFF;
  9913. SignedUpperLimitBottom := -2147483648;
  9914. MinSize := S_W;
  9915. MaxSize := S_L;
  9916. end;
  9917. {$ifdef x86_64}
  9918. S_LQ:
  9919. begin
  9920. { Both the lower and upper limits are set to 32-bit. If a limit
  9921. is breached, then optimisation is impossible }
  9922. LowerLimit := $FFFFFFFF;
  9923. SignedLowerLimit := $7FFFFFFF;
  9924. SignedLowerLimitBottom := -2147483648;
  9925. UpperLimit := $FFFFFFFF;
  9926. SignedUpperLimit := $7FFFFFFF;
  9927. SignedUpperLimitBottom := -2147483648;
  9928. MinSize := S_L;
  9929. MaxSize := S_L;
  9930. end;
  9931. {$endif x86_64}
  9932. else
  9933. InternalError(2020112301);
  9934. end;
  9935. TestValMin := 0;
  9936. TestValMax := LowerLimit;
  9937. TestValSignedMax := SignedLowerLimit;
  9938. TryShiftDownLimit := LowerLimit;
  9939. TryShiftDown := S_NO;
  9940. ShiftDownOverflow := False;
  9941. RegChanged := False;
  9942. BitwiseOnly := True;
  9943. OrXorUsed := False;
  9944. UpperSignedOverflow := False;
  9945. LowerSignedOverflow := False;
  9946. UpperUnsignedOverflow := False;
  9947. LowerUnsignedOverflow := False;
  9948. hp1 := p;
  9949. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9950. (hp1.typ = ait_instruction) and
  9951. (
  9952. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9953. instruction that doesn't actually contain ThisReg }
  9954. (cs_opt_level3 in current_settings.optimizerswitches) or
  9955. { This allows this Movx optimisation to work through the SETcc instructions
  9956. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9957. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9958. skip over these SETcc instructions). }
  9959. (taicpu(hp1).opcode = A_SETcc) or
  9960. RegInInstruction(ThisReg, hp1)
  9961. ) do
  9962. begin
  9963. case taicpu(hp1).opcode of
  9964. A_INC,A_DEC:
  9965. begin
  9966. { Has to be an exact match on the register }
  9967. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9968. Break;
  9969. if taicpu(hp1).opcode = A_INC then
  9970. begin
  9971. Inc(TestValMin);
  9972. Inc(TestValMax);
  9973. Inc(TestValSignedMax);
  9974. end
  9975. else
  9976. begin
  9977. Dec(TestValMin);
  9978. Dec(TestValMax);
  9979. Dec(TestValSignedMax);
  9980. end;
  9981. end;
  9982. A_TEST, A_CMP:
  9983. begin
  9984. if (
  9985. { Too high a risk of non-linear behaviour that breaks DFA
  9986. here, unless it's cmp $0,%reg, which is equivalent to
  9987. test %reg,%reg }
  9988. OrXorUsed and
  9989. (taicpu(hp1).opcode = A_CMP) and
  9990. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9991. ) or
  9992. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9993. { Has to be an exact match on the register }
  9994. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9995. (
  9996. { Permit "test %reg,%reg" }
  9997. (taicpu(hp1).opcode = A_TEST) and
  9998. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9999. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10000. ) or
  10001. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10002. { Make sure the comparison value is not smaller than the
  10003. smallest allowed signed value for the minimum size (e.g.
  10004. -128 for 8-bit) }
  10005. not (
  10006. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10007. { Is it in the negative range? }
  10008. (
  10009. (taicpu(hp1).oper[0]^.val < 0) and
  10010. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10011. )
  10012. ) then
  10013. Break;
  10014. { Check to see if the active register is used afterwards }
  10015. TransferUsedRegs(TmpUsedRegs);
  10016. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10017. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10018. begin
  10019. { Make sure the comparison or any previous instructions
  10020. hasn't pushed the test values outside of the range of
  10021. MinSize }
  10022. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10023. begin
  10024. { Exceeded lower bound but not upper bound }
  10025. Exit;
  10026. end
  10027. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10028. begin
  10029. { Size didn't exceed lower bound }
  10030. TargetSize := MinSize;
  10031. end
  10032. else
  10033. Break;
  10034. case TargetSize of
  10035. S_B:
  10036. TargetSubReg := R_SUBL;
  10037. S_W:
  10038. TargetSubReg := R_SUBW;
  10039. S_L:
  10040. TargetSubReg := R_SUBD;
  10041. else
  10042. InternalError(2021051002);
  10043. end;
  10044. if TargetSize <> MaxSize then
  10045. begin
  10046. { Update the register to its new size }
  10047. setsubreg(ThisReg, TargetSubReg);
  10048. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10049. taicpu(hp1).oper[1]^.reg := ThisReg;
  10050. taicpu(hp1).opsize := TargetSize;
  10051. { Convert the input MOVZX to a MOV if necessary }
  10052. AdjustInitialLoadAndSize;
  10053. if (InstrMax >= 0) then
  10054. begin
  10055. for Index := 0 to InstrMax do
  10056. begin
  10057. { If p_removed is true, then the original MOV/Z was removed
  10058. and removing the AND instruction may not be safe if it
  10059. appears first }
  10060. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10061. InternalError(2020112311);
  10062. if InstrList[Index].oper[0]^.typ = top_reg then
  10063. InstrList[Index].oper[0]^.reg := ThisReg;
  10064. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10065. InstrList[Index].opsize := MinSize;
  10066. end;
  10067. end;
  10068. Result := True;
  10069. end;
  10070. Exit;
  10071. end;
  10072. end;
  10073. A_SETcc:
  10074. begin
  10075. { This allows this Movx optimisation to work through the SETcc instructions
  10076. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10077. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10078. skip over these SETcc instructions). }
  10079. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10080. { Of course, break out if the current register is used }
  10081. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10082. Break
  10083. else
  10084. { We must use Continue so the instruction doesn't get added
  10085. to InstrList }
  10086. Continue;
  10087. end;
  10088. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10089. begin
  10090. if
  10091. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10092. { Has to be an exact match on the register }
  10093. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10094. (
  10095. (
  10096. (taicpu(hp1).oper[0]^.typ = top_const) and
  10097. (
  10098. (
  10099. (taicpu(hp1).opcode = A_SHL) and
  10100. (
  10101. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10102. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10103. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10104. )
  10105. ) or (
  10106. (taicpu(hp1).opcode <> A_SHL) and
  10107. (
  10108. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10109. { Is it in the negative range? }
  10110. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10111. )
  10112. )
  10113. )
  10114. ) or (
  10115. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10116. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10117. )
  10118. ) then
  10119. Break;
  10120. { Only process OR and XOR if there are only bitwise operations,
  10121. since otherwise they can too easily fool the data flow
  10122. analysis (they can cause non-linear behaviour) }
  10123. case taicpu(hp1).opcode of
  10124. A_ADD:
  10125. begin
  10126. if OrXorUsed then
  10127. { Too high a risk of non-linear behaviour that breaks DFA here }
  10128. Break
  10129. else
  10130. BitwiseOnly := False;
  10131. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10132. begin
  10133. TestValMin := TestValMin * 2;
  10134. TestValMax := TestValMax * 2;
  10135. TestValSignedMax := TestValSignedMax * 2;
  10136. end
  10137. else
  10138. begin
  10139. WorkingValue := taicpu(hp1).oper[0]^.val;
  10140. TestValMin := TestValMin + WorkingValue;
  10141. TestValMax := TestValMax + WorkingValue;
  10142. TestValSignedMax := TestValSignedMax + WorkingValue;
  10143. end;
  10144. end;
  10145. A_SUB:
  10146. begin
  10147. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10148. begin
  10149. TestValMin := 0;
  10150. TestValMax := 0;
  10151. TestValSignedMax := 0;
  10152. end
  10153. else
  10154. begin
  10155. if OrXorUsed then
  10156. { Too high a risk of non-linear behaviour that breaks DFA here }
  10157. Break
  10158. else
  10159. BitwiseOnly := False;
  10160. WorkingValue := taicpu(hp1).oper[0]^.val;
  10161. TestValMin := TestValMin - WorkingValue;
  10162. TestValMax := TestValMax - WorkingValue;
  10163. TestValSignedMax := TestValSignedMax - WorkingValue;
  10164. end;
  10165. end;
  10166. A_AND:
  10167. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10168. begin
  10169. { we might be able to go smaller if AND appears first }
  10170. if InstrMax = -1 then
  10171. case MinSize of
  10172. S_B:
  10173. ;
  10174. S_W:
  10175. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10176. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10177. begin
  10178. TryShiftDown := S_B;
  10179. TryShiftDownLimit := $FF;
  10180. end;
  10181. S_L:
  10182. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10183. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10184. begin
  10185. TryShiftDown := S_B;
  10186. TryShiftDownLimit := $FF;
  10187. end
  10188. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10189. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10190. begin
  10191. TryShiftDown := S_W;
  10192. TryShiftDownLimit := $FFFF;
  10193. end;
  10194. else
  10195. InternalError(2020112320);
  10196. end;
  10197. WorkingValue := taicpu(hp1).oper[0]^.val;
  10198. TestValMin := TestValMin and WorkingValue;
  10199. TestValMax := TestValMax and WorkingValue;
  10200. TestValSignedMax := TestValSignedMax and WorkingValue;
  10201. end;
  10202. A_OR:
  10203. begin
  10204. if not BitwiseOnly then
  10205. Break;
  10206. OrXorUsed := True;
  10207. WorkingValue := taicpu(hp1).oper[0]^.val;
  10208. TestValMin := TestValMin or WorkingValue;
  10209. TestValMax := TestValMax or WorkingValue;
  10210. TestValSignedMax := TestValSignedMax or WorkingValue;
  10211. end;
  10212. A_XOR:
  10213. begin
  10214. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10215. begin
  10216. TestValMin := 0;
  10217. TestValMax := 0;
  10218. TestValSignedMax := 0;
  10219. end
  10220. else
  10221. begin
  10222. if not BitwiseOnly then
  10223. Break;
  10224. OrXorUsed := True;
  10225. WorkingValue := taicpu(hp1).oper[0]^.val;
  10226. TestValMin := TestValMin xor WorkingValue;
  10227. TestValMax := TestValMax xor WorkingValue;
  10228. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10229. end;
  10230. end;
  10231. A_SHL:
  10232. begin
  10233. BitwiseOnly := False;
  10234. WorkingValue := taicpu(hp1).oper[0]^.val;
  10235. TestValMin := TestValMin shl WorkingValue;
  10236. TestValMax := TestValMax shl WorkingValue;
  10237. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10238. end;
  10239. A_SHR,
  10240. { The first instruction was MOVZX, so the value won't be negative }
  10241. A_SAR:
  10242. begin
  10243. if InstrMax <> -1 then
  10244. BitwiseOnly := False
  10245. else
  10246. { we might be able to go smaller if SHR appears first }
  10247. case MinSize of
  10248. S_B:
  10249. ;
  10250. S_W:
  10251. if (taicpu(hp1).oper[0]^.val >= 8) then
  10252. begin
  10253. TryShiftDown := S_B;
  10254. TryShiftDownLimit := $FF;
  10255. TryShiftDownSignedLimit := $7F;
  10256. TryShiftDownSignedLimitLower := -128;
  10257. end;
  10258. S_L:
  10259. if (taicpu(hp1).oper[0]^.val >= 24) then
  10260. begin
  10261. TryShiftDown := S_B;
  10262. TryShiftDownLimit := $FF;
  10263. TryShiftDownSignedLimit := $7F;
  10264. TryShiftDownSignedLimitLower := -128;
  10265. end
  10266. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10267. begin
  10268. TryShiftDown := S_W;
  10269. TryShiftDownLimit := $FFFF;
  10270. TryShiftDownSignedLimit := $7FFF;
  10271. TryShiftDownSignedLimitLower := -32768;
  10272. end;
  10273. else
  10274. InternalError(2020112321);
  10275. end;
  10276. WorkingValue := taicpu(hp1).oper[0]^.val;
  10277. if taicpu(hp1).opcode = A_SAR then
  10278. begin
  10279. TestValMin := SarInt64(TestValMin, WorkingValue);
  10280. TestValMax := SarInt64(TestValMax, WorkingValue);
  10281. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10282. end
  10283. else
  10284. begin
  10285. TestValMin := TestValMin shr WorkingValue;
  10286. TestValMax := TestValMax shr WorkingValue;
  10287. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10288. end;
  10289. end;
  10290. else
  10291. InternalError(2020112303);
  10292. end;
  10293. end;
  10294. (*
  10295. A_IMUL:
  10296. case taicpu(hp1).ops of
  10297. 2:
  10298. begin
  10299. if not MatchOpType(hp1, top_reg, top_reg) or
  10300. { Has to be an exact match on the register }
  10301. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10302. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10303. Break;
  10304. TestValMin := TestValMin * TestValMin;
  10305. TestValMax := TestValMax * TestValMax;
  10306. TestValSignedMax := TestValSignedMax * TestValMax;
  10307. end;
  10308. 3:
  10309. begin
  10310. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10311. { Has to be an exact match on the register }
  10312. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10313. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10314. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10315. { Is it in the negative range? }
  10316. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10317. Break;
  10318. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10319. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10320. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10321. end;
  10322. else
  10323. Break;
  10324. end;
  10325. A_IDIV:
  10326. case taicpu(hp1).ops of
  10327. 3:
  10328. begin
  10329. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10330. { Has to be an exact match on the register }
  10331. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10332. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10333. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10334. { Is it in the negative range? }
  10335. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10336. Break;
  10337. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10338. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10339. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10340. end;
  10341. else
  10342. Break;
  10343. end;
  10344. *)
  10345. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10346. begin
  10347. { If there are no instructions in between, then we might be able to make a saving }
  10348. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10349. Break;
  10350. { We have something like:
  10351. movzbw %dl,%dx
  10352. ...
  10353. movswl %dx,%edx
  10354. Change the latter to a zero-extension then enter the
  10355. A_MOVZX case branch.
  10356. }
  10357. {$ifdef x86_64}
  10358. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10359. begin
  10360. { this becomes a zero extension from 32-bit to 64-bit, but
  10361. the upper 32 bits are already zero, so just delete the
  10362. instruction }
  10363. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10364. RemoveInstruction(hp1);
  10365. Result := True;
  10366. Exit;
  10367. end
  10368. else
  10369. {$endif x86_64}
  10370. begin
  10371. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10372. taicpu(hp1).opcode := A_MOVZX;
  10373. {$ifdef x86_64}
  10374. case taicpu(hp1).opsize of
  10375. S_BQ:
  10376. begin
  10377. taicpu(hp1).opsize := S_BL;
  10378. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10379. end;
  10380. S_WQ:
  10381. begin
  10382. taicpu(hp1).opsize := S_WL;
  10383. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10384. end;
  10385. S_LQ:
  10386. begin
  10387. taicpu(hp1).opcode := A_MOV;
  10388. taicpu(hp1).opsize := S_L;
  10389. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10390. { In this instance, we need to break out because the
  10391. instruction is no longer MOVZX or MOVSXD }
  10392. Result := True;
  10393. Exit;
  10394. end;
  10395. else
  10396. ;
  10397. end;
  10398. {$endif x86_64}
  10399. Result := CompressInstructions;
  10400. Exit;
  10401. end;
  10402. end;
  10403. A_MOVZX:
  10404. begin
  10405. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10406. Break;
  10407. if (InstrMax = -1) then
  10408. begin
  10409. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10410. begin
  10411. { Optimise around i40003 }
  10412. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10413. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10414. {$ifndef x86_64}
  10415. and (
  10416. (taicpu(p).oper[0]^.typ <> top_reg) or
  10417. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10418. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10419. )
  10420. {$endif not x86_64}
  10421. then
  10422. begin
  10423. if (taicpu(p).oper[0]^.typ = top_reg) then
  10424. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10425. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10426. taicpu(p).opsize := S_BL;
  10427. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10428. RemoveInstruction(hp1);
  10429. Result := True;
  10430. Exit;
  10431. end;
  10432. end
  10433. else
  10434. begin
  10435. { Will return false if the second parameter isn't ThisReg
  10436. (can happen on -O2 and under) }
  10437. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10438. begin
  10439. { The two MOVZX instructions are adjacent, so remove the first one }
  10440. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10441. RemoveCurrentP(p);
  10442. Result := True;
  10443. Exit;
  10444. end;
  10445. Break;
  10446. end;
  10447. end;
  10448. Result := CompressInstructions;
  10449. Exit;
  10450. end;
  10451. else
  10452. { This includes ADC, SBB and IDIV }
  10453. Break;
  10454. end;
  10455. if not CheckOverflowConditions then
  10456. Break;
  10457. { Contains highest index (so instruction count - 1) }
  10458. Inc(InstrMax);
  10459. if InstrMax > High(InstrList) then
  10460. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10461. InstrList[InstrMax] := taicpu(hp1);
  10462. end;
  10463. end;
  10464. {$pop}
  10465. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10466. var
  10467. hp1 : tai;
  10468. begin
  10469. Result:=false;
  10470. if (taicpu(p).ops >= 2) and
  10471. ((taicpu(p).oper[0]^.typ = top_const) or
  10472. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10473. (taicpu(p).oper[1]^.typ = top_reg) and
  10474. ((taicpu(p).ops = 2) or
  10475. ((taicpu(p).oper[2]^.typ = top_reg) and
  10476. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10477. GetLastInstruction(p,hp1) and
  10478. MatchInstruction(hp1,A_MOV,[]) and
  10479. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10480. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10481. begin
  10482. TransferUsedRegs(TmpUsedRegs);
  10483. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10484. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10485. { change
  10486. mov reg1,reg2
  10487. imul y,reg2 to imul y,reg1,reg2 }
  10488. begin
  10489. taicpu(p).ops := 3;
  10490. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10491. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10492. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10493. RemoveInstruction(hp1);
  10494. result:=true;
  10495. end;
  10496. end;
  10497. end;
  10498. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10499. var
  10500. ThisLabel: TAsmLabel;
  10501. begin
  10502. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10503. ThisLabel.decrefs;
  10504. taicpu(p).condition := C_None;
  10505. taicpu(p).opcode := A_RET;
  10506. taicpu(p).is_jmp := false;
  10507. taicpu(p).ops := taicpu(ret_p).ops;
  10508. case taicpu(ret_p).ops of
  10509. 0:
  10510. taicpu(p).clearop(0);
  10511. 1:
  10512. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10513. else
  10514. internalerror(2016041301);
  10515. end;
  10516. { If the original label is now dead, it might turn out that the label
  10517. immediately follows p. As a result, everything beyond it, which will
  10518. be just some final register configuration and a RET instruction, is
  10519. now dead code. [Kit] }
  10520. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10521. running RemoveDeadCodeAfterJump for each RET instruction, because
  10522. this optimisation rarely happens and most RETs appear at the end of
  10523. routines where there is nothing that can be stripped. [Kit] }
  10524. if not ThisLabel.is_used then
  10525. RemoveDeadCodeAfterJump(p);
  10526. end;
  10527. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10528. var
  10529. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10530. Unconditional, PotentialModified: Boolean;
  10531. OperPtr: POper;
  10532. NewRef: TReference;
  10533. InstrList: array of taicpu;
  10534. InstrMax, Index: Integer;
  10535. const
  10536. {$ifdef DEBUG_AOPTCPU}
  10537. SNoFlags: shortstring = ' so the flags aren''t modified';
  10538. {$else DEBUG_AOPTCPU}
  10539. SNoFlags = '';
  10540. {$endif DEBUG_AOPTCPU}
  10541. begin
  10542. Result:=false;
  10543. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10544. begin
  10545. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10546. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10547. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10548. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10549. GetNextInstruction(hp1, hp2) and
  10550. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10551. { Change from: To:
  10552. set(C) %reg j(~C) label
  10553. test %reg,%reg/cmp $0,%reg
  10554. je label
  10555. set(C) %reg j(C) label
  10556. test %reg,%reg/cmp $0,%reg
  10557. jne label
  10558. (Also do something similar with sete/setne instead of je/jne)
  10559. }
  10560. begin
  10561. { Before we do anything else, we need to check the instructions
  10562. in between SETcc and TEST to make sure they don't modify the
  10563. FLAGS register - if -O2 or under, there won't be any
  10564. instructions between SET and TEST }
  10565. TransferUsedRegs(TmpUsedRegs);
  10566. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10567. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10568. begin
  10569. next := p;
  10570. SetLength(InstrList, 0);
  10571. InstrMax := -1;
  10572. PotentialModified := False;
  10573. { Make a note of every instruction that modifies the FLAGS
  10574. register }
  10575. while GetNextInstruction(next, next) and (next <> hp1) do
  10576. begin
  10577. if next.typ <> ait_instruction then
  10578. { GetNextInstructionUsingReg should have returned False }
  10579. InternalError(2021051701);
  10580. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10581. begin
  10582. case taicpu(next).opcode of
  10583. A_SETcc,
  10584. A_CMOVcc,
  10585. A_Jcc:
  10586. begin
  10587. if PotentialModified then
  10588. { Not safe because the flags were modified earlier }
  10589. Exit
  10590. else
  10591. { Condition is the same as the initial SETcc, so this is safe
  10592. (don't add to instruction list though) }
  10593. Continue;
  10594. end;
  10595. A_ADD:
  10596. begin
  10597. if (taicpu(next).opsize = S_B) or
  10598. { LEA doesn't support 8-bit operands }
  10599. (taicpu(next).oper[1]^.typ <> top_reg) or
  10600. { Must write to a register }
  10601. (taicpu(next).oper[0]^.typ = top_ref) then
  10602. { Require a constant or a register }
  10603. Exit;
  10604. PotentialModified := True;
  10605. end;
  10606. A_SUB:
  10607. begin
  10608. if (taicpu(next).opsize = S_B) or
  10609. { LEA doesn't support 8-bit operands }
  10610. (taicpu(next).oper[1]^.typ <> top_reg) or
  10611. { Must write to a register }
  10612. (taicpu(next).oper[0]^.typ <> top_const) or
  10613. (taicpu(next).oper[0]^.val = $80000000) then
  10614. { Can't subtract a register with LEA - also
  10615. check that the value isn't -2^31, as this
  10616. can't be negated }
  10617. Exit;
  10618. PotentialModified := True;
  10619. end;
  10620. A_SAL,
  10621. A_SHL:
  10622. begin
  10623. if (taicpu(next).opsize = S_B) or
  10624. { LEA doesn't support 8-bit operands }
  10625. (taicpu(next).oper[1]^.typ <> top_reg) or
  10626. { Must write to a register }
  10627. (taicpu(next).oper[0]^.typ <> top_const) or
  10628. (taicpu(next).oper[0]^.val < 0) or
  10629. (taicpu(next).oper[0]^.val > 3) then
  10630. Exit;
  10631. PotentialModified := True;
  10632. end;
  10633. A_IMUL:
  10634. begin
  10635. if (taicpu(next).ops <> 3) or
  10636. (taicpu(next).oper[1]^.typ <> top_reg) or
  10637. { Must write to a register }
  10638. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10639. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10640. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10641. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10642. Exit
  10643. else
  10644. PotentialModified := True;
  10645. end;
  10646. else
  10647. { Don't know how to change this, so abort }
  10648. Exit;
  10649. end;
  10650. { Contains highest index (so instruction count - 1) }
  10651. Inc(InstrMax);
  10652. if InstrMax > High(InstrList) then
  10653. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10654. InstrList[InstrMax] := taicpu(next);
  10655. end;
  10656. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10657. end;
  10658. if not Assigned(next) or (next <> hp1) then
  10659. { It should be equal to hp1 }
  10660. InternalError(2021051702);
  10661. { Cycle through each instruction and check to see if we can
  10662. change them to versions that don't modify the flags }
  10663. if (InstrMax >= 0) then
  10664. begin
  10665. for Index := 0 to InstrMax do
  10666. case InstrList[Index].opcode of
  10667. A_ADD:
  10668. begin
  10669. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10670. InstrList[Index].opcode := A_LEA;
  10671. reference_reset(NewRef, 1, []);
  10672. NewRef.base := InstrList[Index].oper[1]^.reg;
  10673. if InstrList[Index].oper[0]^.typ = top_reg then
  10674. begin
  10675. NewRef.index := InstrList[Index].oper[0]^.reg;
  10676. NewRef.scalefactor := 1;
  10677. end
  10678. else
  10679. NewRef.offset := InstrList[Index].oper[0]^.val;
  10680. InstrList[Index].loadref(0, NewRef);
  10681. end;
  10682. A_SUB:
  10683. begin
  10684. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10685. InstrList[Index].opcode := A_LEA;
  10686. reference_reset(NewRef, 1, []);
  10687. NewRef.base := InstrList[Index].oper[1]^.reg;
  10688. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10689. InstrList[Index].loadref(0, NewRef);
  10690. end;
  10691. A_SHL,
  10692. A_SAL:
  10693. begin
  10694. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10695. InstrList[Index].opcode := A_LEA;
  10696. reference_reset(NewRef, 1, []);
  10697. NewRef.index := InstrList[Index].oper[1]^.reg;
  10698. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10699. InstrList[Index].loadref(0, NewRef);
  10700. end;
  10701. A_IMUL:
  10702. begin
  10703. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10704. InstrList[Index].opcode := A_LEA;
  10705. reference_reset(NewRef, 1, []);
  10706. NewRef.index := InstrList[Index].oper[1]^.reg;
  10707. case InstrList[Index].oper[0]^.val of
  10708. 2, 4, 8:
  10709. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10710. else {3, 5 and 9}
  10711. begin
  10712. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10713. NewRef.base := InstrList[Index].oper[1]^.reg;
  10714. end;
  10715. end;
  10716. InstrList[Index].loadref(0, NewRef);
  10717. end;
  10718. else
  10719. InternalError(2021051710);
  10720. end;
  10721. end;
  10722. { Mark the FLAGS register as used across this whole block }
  10723. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10724. end;
  10725. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10726. JumpC := taicpu(hp2).condition;
  10727. Unconditional := False;
  10728. if conditions_equal(JumpC, C_E) then
  10729. SetC := inverse_cond(taicpu(p).condition)
  10730. else if conditions_equal(JumpC, C_NE) then
  10731. SetC := taicpu(p).condition
  10732. else
  10733. { We've got something weird here (and inefficent) }
  10734. begin
  10735. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10736. SetC := C_NONE;
  10737. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10738. if condition_in(C_AE, JumpC) then
  10739. Unconditional := True
  10740. else
  10741. { Not sure what to do with this jump - drop out }
  10742. Exit;
  10743. end;
  10744. RemoveInstruction(hp1);
  10745. if Unconditional then
  10746. MakeUnconditional(taicpu(hp2))
  10747. else
  10748. begin
  10749. if SetC = C_NONE then
  10750. InternalError(2018061402);
  10751. taicpu(hp2).SetCondition(SetC);
  10752. end;
  10753. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10754. TmpUsedRegs }
  10755. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10756. begin
  10757. RemoveCurrentp(p, hp2);
  10758. if taicpu(hp2).opcode = A_SETcc then
  10759. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10760. else
  10761. begin
  10762. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10763. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10764. Include(OptsToCheck, aoc_DoPass2JccOpts);
  10765. end;
  10766. end
  10767. else
  10768. if taicpu(hp2).opcode = A_SETcc then
  10769. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10770. else
  10771. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10772. Result := True;
  10773. end
  10774. else if
  10775. { Make sure the instructions are adjacent }
  10776. (
  10777. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10778. GetNextInstruction(p, hp1)
  10779. ) and
  10780. MatchInstruction(hp1, A_MOV, [S_B]) and
  10781. { Writing to memory is allowed }
  10782. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10783. begin
  10784. {
  10785. Watch out for sequences such as:
  10786. set(c)b %regb
  10787. movb %regb,(ref)
  10788. movb $0,1(ref)
  10789. movb $0,2(ref)
  10790. movb $0,3(ref)
  10791. Much more efficient to turn it into:
  10792. movl $0,%regl
  10793. set(c)b %regb
  10794. movl %regl,(ref)
  10795. Or:
  10796. set(c)b %regb
  10797. movzbl %regb,%regl
  10798. movl %regl,(ref)
  10799. }
  10800. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10801. GetNextInstruction(hp1, hp2) and
  10802. MatchInstruction(hp2, A_MOV, [S_B]) and
  10803. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10804. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10805. begin
  10806. { Don't do anything else except set Result to True }
  10807. end
  10808. else
  10809. begin
  10810. if taicpu(p).oper[0]^.typ = top_reg then
  10811. begin
  10812. TransferUsedRegs(TmpUsedRegs);
  10813. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10814. end;
  10815. { If it's not a register, it's a memory address }
  10816. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10817. begin
  10818. { Even if the register is still in use, we can minimise the
  10819. pipeline stall by changing the MOV into another SETcc. }
  10820. taicpu(hp1).opcode := A_SETcc;
  10821. taicpu(hp1).condition := taicpu(p).condition;
  10822. if taicpu(hp1).oper[1]^.typ = top_ref then
  10823. begin
  10824. { Swapping the operand pointers like this is probably a
  10825. bit naughty, but it is far faster than using loadoper
  10826. to transfer the reference from oper[1] to oper[0] if
  10827. you take into account the extra procedure calls and
  10828. the memory allocation and deallocation required }
  10829. OperPtr := taicpu(hp1).oper[1];
  10830. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10831. taicpu(hp1).oper[0] := OperPtr;
  10832. end
  10833. else
  10834. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10835. taicpu(hp1).clearop(1);
  10836. taicpu(hp1).ops := 1;
  10837. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10838. end
  10839. else
  10840. begin
  10841. if taicpu(hp1).oper[1]^.typ = top_reg then
  10842. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10843. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10844. RemoveInstruction(hp1);
  10845. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10846. end
  10847. end;
  10848. Result := True;
  10849. end;
  10850. end;
  10851. end;
  10852. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10853. var
  10854. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  10855. TargetReg: TRegister;
  10856. condition, inverted_condition: TAsmCond;
  10857. FoundMOV: Boolean;
  10858. begin
  10859. Result := False;
  10860. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10861. create the most optimial instructions possible due to limited
  10862. register availability, and there are situations where two
  10863. complementary "simple" CMOV blocks are created which, after the fact
  10864. can be merged into a "double" block. For example:
  10865. movw $257,%ax
  10866. movw $2,%r8w
  10867. xorl r9d,%r9d
  10868. testw $16,18(%rcx)
  10869. cmovew %ax,%dx
  10870. cmovew %r8w,%bx
  10871. cmovel %r9d,%r14d
  10872. movw $1283,%ax
  10873. movw $4,%r8w
  10874. movl $9,%r9d
  10875. cmovnew %ax,%dx
  10876. cmovnew %r8w,%bx
  10877. cmovnel %r9d,%r14d
  10878. The CMOVNE instructions at the end can be removed, and the
  10879. destination registers copied into the MOV instructions directly
  10880. above them, before finally being moved to before the first CMOVE
  10881. instructions, to produce:
  10882. movw $257,%ax
  10883. movw $2,%r8w
  10884. xorl r9d,%r9d
  10885. testw $16,18(%rcx)
  10886. movw $1283,%dx
  10887. movw $4,%bx
  10888. movl $9,%r14d
  10889. cmovew %ax,%dx
  10890. cmovew %r8w,%bx
  10891. cmovel %r9d,%r14d
  10892. Which can then be later optimised to:
  10893. movw $257,%ax
  10894. movw $2,%r8w
  10895. xorl r9d,%r9d
  10896. movw $1283,%dx
  10897. movw $4,%bx
  10898. movl $9,%r14d
  10899. testw $16,18(%rcx)
  10900. cmovew %ax,%dx
  10901. cmovew %r8w,%bx
  10902. cmovel %r9d,%r14d
  10903. }
  10904. TargetReg := taicpu(hp1).oper[1]^.reg;
  10905. condition := taicpu(hp1).condition;
  10906. inverted_condition := inverse_cond(condition);
  10907. pFirstMov := nil;
  10908. pLastMov := nil;
  10909. pCMOV := nil;
  10910. if (p.typ = ait_instruction) then
  10911. pCond := p
  10912. else if not GetNextInstruction(p, pCond) then
  10913. InternalError(2024012501);
  10914. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  10915. { We should get the CMP or TEST instructeion }
  10916. InternalError(2024012502);
  10917. if (
  10918. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10919. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10920. ) then
  10921. begin
  10922. { We have to tread carefully here, hence why we're not using
  10923. GetNextInstructionUsingReg... we can only accept MOV and other
  10924. CMOV instructions. Anything else and we must drop out}
  10925. hp2 := hp1;
  10926. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  10927. begin
  10928. if (hp2.typ <> ait_instruction) then
  10929. Exit;
  10930. case taicpu(hp2).opcode of
  10931. A_MOV:
  10932. begin
  10933. if not Assigned(pFirstMov) then
  10934. pFirstMov := hp2;
  10935. pLastMOV := hp2;
  10936. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10937. { Something different - drop out }
  10938. Exit;
  10939. { Otherwise, leave it for now }
  10940. end;
  10941. A_CMOVcc:
  10942. begin
  10943. if taicpu(hp2).condition = inverted_condition then
  10944. begin
  10945. { We found what we're looking for }
  10946. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10947. begin
  10948. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10949. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10950. begin
  10951. pCMOV := hp2;
  10952. Break;
  10953. end
  10954. else
  10955. { Unsafe reference - drop out }
  10956. Exit;
  10957. end;
  10958. end
  10959. else if taicpu(hp2).condition <> condition then
  10960. { Something weird - drop out }
  10961. Exit;
  10962. end;
  10963. else
  10964. { Invalid }
  10965. Exit;
  10966. end;
  10967. end;
  10968. if not Assigned(pCMOV) then
  10969. { No complementary CMOV found }
  10970. Exit;
  10971. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10972. begin
  10973. { Don't need to do anything special or search for a matching MOV }
  10974. Asml.Remove(pCMOV);
  10975. if RegInInstruction(TargetReg, pCond) then
  10976. { Make sure we don't overwrite the register if it's being used in the condition }
  10977. Asml.InsertAfter(pCMOV, pCond)
  10978. else
  10979. Asml.InsertBefore(pCMOV, pCond);
  10980. taicpu(pCMOV).opcode := A_MOV;
  10981. taicpu(pCMOV).condition := C_None;
  10982. { Don't need to worry about allocating new registers in these cases }
  10983. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  10984. Result := True;
  10985. Exit;
  10986. end
  10987. else
  10988. begin
  10989. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  10990. FoundMOV := False;
  10991. { Search for the MOV that sets the target register }
  10992. hp2 := pFirstMov;
  10993. repeat
  10994. if (taicpu(hp2).opcode = A_MOV) and
  10995. (taicpu(hp2).oper[1]^.typ = top_reg) and
  10996. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  10997. begin
  10998. { Change the destination }
  10999. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11000. if not FoundMOV then
  11001. begin
  11002. FoundMOV := True;
  11003. { Make sure the register is allocated }
  11004. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11005. end;
  11006. hp1 := tai(hp2.Previous);
  11007. Asml.Remove(hp2);
  11008. if RegInInstruction(TargetReg, pCond) then
  11009. { Make sure we don't overwrite the register if it's being used in the condition }
  11010. Asml.InsertAfter(hp2, pCond)
  11011. else
  11012. Asml.InsertBefore(hp2, pCond);
  11013. if (hp2 = pLastMov) then
  11014. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11015. Break;
  11016. hp2 := hp1;
  11017. end;
  11018. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11019. if FoundMOV then
  11020. { Delete the CMOV }
  11021. RemoveInstruction(pCMOV)
  11022. else
  11023. begin
  11024. { If no MOV was found, we have to actually move and transmute the CMOV }
  11025. Asml.Remove(pCMOV);
  11026. if RegInInstruction(TargetReg, pCond) then
  11027. { Make sure we don't overwrite the register if it's being used in the condition }
  11028. Asml.InsertAfter(pCMOV, pCond)
  11029. else
  11030. Asml.InsertBefore(pCMOV, pCond);
  11031. taicpu(pCMOV).opcode := A_MOV;
  11032. taicpu(pCMOV).condition := C_None;
  11033. end;
  11034. Result := True;
  11035. Exit;
  11036. end;
  11037. end;
  11038. end;
  11039. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11040. var
  11041. hp1, hp2, pCond: tai;
  11042. begin
  11043. Result := False;
  11044. { Search ahead for CMOV instructions }
  11045. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11046. begin
  11047. hp1 := p;
  11048. hp2 := p;
  11049. pCond := nil; { To prevent compiler warnings }
  11050. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11051. DEFAULTFLAGS }
  11052. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11053. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11054. pCond := p;
  11055. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11056. begin
  11057. if (hp1.typ <> ait_instruction) then
  11058. { Break out on markers and labels etc. }
  11059. Break;
  11060. case taicpu(hp1).opcode of
  11061. A_MOV:
  11062. { Ignore regular MOVs unless they are obviously not related
  11063. to a CMOV block }
  11064. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11065. Break;
  11066. A_CMOVcc:
  11067. if TryCmpCMovOpts(pCond, hp1) then
  11068. begin
  11069. hp1 := hp2;
  11070. { p itself isn't changed, and we're still inside a
  11071. while loop to catch subsequent CMOVs, so just flag
  11072. a new iteration }
  11073. Include(OptsToCheck, aoc_ForceNewIteration);
  11074. Continue;
  11075. end;
  11076. else
  11077. { Drop out if we find anything else }
  11078. Break;
  11079. end;
  11080. hp2 := hp1;
  11081. end;
  11082. end;
  11083. end;
  11084. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11085. var
  11086. hp1, hp2, pCond: tai;
  11087. begin
  11088. Result := False;
  11089. { Search ahead for CMOV instructions }
  11090. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11091. begin
  11092. hp1 := p;
  11093. hp2 := p;
  11094. pCond := nil; { To prevent compiler warnings }
  11095. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11096. DEFAULTFLAGS }
  11097. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11098. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11099. pCond := p;
  11100. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11101. begin
  11102. if (hp1.typ <> ait_instruction) then
  11103. { Break out on markers and labels etc. }
  11104. Break;
  11105. case taicpu(hp1).opcode of
  11106. A_MOV:
  11107. { Ignore regular MOVs unless they are obviously not related
  11108. to a CMOV block }
  11109. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11110. Break;
  11111. A_CMOVcc:
  11112. if TryCmpCMovOpts(pCond, hp1) then
  11113. begin
  11114. hp1 := hp2;
  11115. { p itself isn't changed, and we're still inside a
  11116. while loop to catch subsequent CMOVs, so just flag
  11117. a new iteration }
  11118. Include(OptsToCheck, aoc_ForceNewIteration);
  11119. Continue;
  11120. end;
  11121. else
  11122. { Drop out if we find anything else }
  11123. Break;
  11124. end;
  11125. hp2 := hp1;
  11126. end;
  11127. end;
  11128. end;
  11129. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11130. var
  11131. hp1: tai;
  11132. Count: Integer;
  11133. OrigLabel: TAsmLabel;
  11134. begin
  11135. result := False;
  11136. { Sometimes, the optimisations below can permit this }
  11137. RemoveDeadCodeAfterJump(p);
  11138. 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
  11139. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11140. begin
  11141. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11142. { Also a side-effect of optimisations }
  11143. if CollapseZeroDistJump(p, OrigLabel) then
  11144. begin
  11145. Result := True;
  11146. Exit;
  11147. end;
  11148. hp1 := GetLabelWithSym(OrigLabel);
  11149. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11150. begin
  11151. if taicpu(hp1).opcode = A_RET then
  11152. begin
  11153. {
  11154. change
  11155. jmp .L1
  11156. ...
  11157. .L1:
  11158. ret
  11159. into
  11160. ret
  11161. }
  11162. begin
  11163. ConvertJumpToRET(p, hp1);
  11164. result:=true;
  11165. end;
  11166. end
  11167. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11168. not (cs_opt_size in current_settings.optimizerswitches) and
  11169. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11170. begin
  11171. Result := True;
  11172. Exit;
  11173. end;
  11174. end;
  11175. end;
  11176. end;
  11177. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11178. begin
  11179. Result := assigned(p) and
  11180. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11181. (taicpu(p).oper[1]^.typ = top_reg) and
  11182. (
  11183. (taicpu(p).oper[0]^.typ = top_reg) or
  11184. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11185. it is not expected that this can cause a seg. violation }
  11186. (
  11187. (taicpu(p).oper[0]^.typ = top_ref) and
  11188. { TODO: Can we detect which references become constants at this
  11189. stage so we don't have to do a blanket ban? }
  11190. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11191. (
  11192. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11193. (
  11194. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11195. not RefModified and
  11196. { If the reference also appears in the condition, then we know it's safe, otherwise
  11197. any kind of access violation would have occurred already }
  11198. Assigned(cond_p) and
  11199. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11200. (cond_p.typ = ait_instruction) and
  11201. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11202. { Just consider 2-operand comparison instructions for now to be safe }
  11203. (taicpu(cond_p).ops = 2) and
  11204. (
  11205. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11206. (
  11207. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11208. { Don't risk identical registers but different offsets, as we may have constructs
  11209. such as buffer streams with things like length fields that indicate whether
  11210. any more data follows. And there are probably some contrived examples where
  11211. writing to offsets behind the one being read also lead to access violations }
  11212. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11213. (
  11214. { Check that we're not modifying a register that appears in the reference }
  11215. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11216. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11217. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11218. )
  11219. )
  11220. )
  11221. )
  11222. )
  11223. )
  11224. );
  11225. end;
  11226. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11227. begin
  11228. { Update integer registers, ignoring deallocations }
  11229. repeat
  11230. while assigned(p) and
  11231. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11232. (p.typ = ait_label) or
  11233. ((p.typ = ait_marker) and
  11234. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11235. p := tai(p.next);
  11236. while assigned(p) and
  11237. (p.typ=ait_RegAlloc) Do
  11238. begin
  11239. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11240. begin
  11241. case tai_regalloc(p).ratype of
  11242. ra_alloc :
  11243. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11244. else
  11245. ;
  11246. end;
  11247. end;
  11248. p := tai(p.next);
  11249. end;
  11250. until not(assigned(p)) or
  11251. (not(p.typ in SkipInstr) and
  11252. not((p.typ = ait_label) and
  11253. labelCanBeSkipped(tai_label(p))));
  11254. end;
  11255. {$ifndef 8086}
  11256. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11257. begin
  11258. Result := False;
  11259. EndJump := nil;
  11260. BlockStop := nil;
  11261. while (BlockStart <> fOptimizer.BlockEnd) and
  11262. { stop on labels }
  11263. (BlockStart.typ <> ait_label) do
  11264. begin
  11265. { Keep track of all integer registers that are used }
  11266. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11267. if BlockStart.typ = ait_instruction then
  11268. begin
  11269. if (taicpu(BlockStart).opcode = A_JMP) then
  11270. begin
  11271. if not IsJumpToLabel(taicpu(BlockStart)) or
  11272. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11273. Exit;
  11274. EndJump := BlockStart;
  11275. Break;
  11276. end
  11277. { Check to see if we have a valid MOV instruction instead }
  11278. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11279. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11280. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11281. begin
  11282. Exit;
  11283. end
  11284. else
  11285. { This will be a valid MOV }
  11286. fAllocationRange := BlockStart;
  11287. end;
  11288. OneBeforeBlock := BlockStart;
  11289. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11290. end;
  11291. if (BlockStart = fOptimizer.BlockEnd) then
  11292. Exit;
  11293. BlockStop := BlockStart;
  11294. Result := True;
  11295. end;
  11296. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11297. var
  11298. hp1: tai;
  11299. RefModified: Boolean;
  11300. begin
  11301. Result := 0;
  11302. hp1 := BlockStart;
  11303. RefModified := False; { As long as the condition is inverted, this can be reset }
  11304. while assigned(hp1) and
  11305. (hp1 <> BlockStop) do
  11306. begin
  11307. case hp1.typ of
  11308. ait_instruction:
  11309. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11310. begin
  11311. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11312. begin
  11313. Inc(Result);
  11314. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11315. Assigned(fCondition) and
  11316. { Will have 2 operands }
  11317. (
  11318. (
  11319. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11320. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11321. ) or
  11322. (
  11323. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11324. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11325. )
  11326. ) then
  11327. { It is no longer safe to use the reference in the condition.
  11328. this prevents problems such as:
  11329. mov (%reg),%reg
  11330. mov (%reg),...
  11331. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11332. (fixes #40165)
  11333. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11334. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11335. }
  11336. RefModified := True;
  11337. end
  11338. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11339. { CMOV with constants grows the code size }
  11340. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11341. begin
  11342. { Register was reserved by TryCMOVConst and
  11343. stored on ConstRegs }
  11344. end
  11345. else
  11346. begin
  11347. Result := -1;
  11348. Exit;
  11349. end;
  11350. end
  11351. else
  11352. begin
  11353. Result := -1;
  11354. Exit;
  11355. end;
  11356. else
  11357. { Most likely an align };
  11358. end;
  11359. fOptimizer.GetNextInstruction(hp1, hp1);
  11360. end;
  11361. end;
  11362. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11363. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11364. (this is done as a separate stage because the double types are extensions of the branching type,
  11365. but we can't discount the conditional jump until the last step) }
  11366. procedure EvaluateBranchingType;
  11367. begin
  11368. Inc(CMOVScore);
  11369. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11370. { Too many instructions to be worthwhile }
  11371. fState := tsInvalid;
  11372. end;
  11373. var
  11374. hp1: tai;
  11375. Count: Integer;
  11376. begin
  11377. { Table of valid CMOV block types
  11378. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11379. ---------- --------- --------- --------- --------- ---------
  11380. tsSimple X Yes X X X
  11381. tsDetour = 1st X X X X
  11382. tsBranching <> Mid Yes X X X
  11383. tsDouble End-label Yes * Yes X Yes
  11384. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11385. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11386. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11387. * Only one reference allowed
  11388. }
  11389. hp1 := nil; { To prevent compiler warnings }
  11390. Optimizer.CopyUsedRegs(RegisterTracking);
  11391. fOptimizer := Optimizer;
  11392. fLabel := AFirstLabel;
  11393. CMOVScore := 0;
  11394. ConstCount := 0;
  11395. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11396. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11397. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11398. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11399. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11400. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11401. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11402. fInsertionPoint := p_initialjump;
  11403. fCondition := nil;
  11404. fInitialJump := p_initialjump;
  11405. fFirstMovBlock := p_initialmov;
  11406. fFirstMovBlockStop := nil;
  11407. fSecondJump := nil;
  11408. fSecondMovBlock := nil;
  11409. fSecondMovBlockStop := nil;
  11410. fMidLabel := nil;
  11411. fSecondJump := nil;
  11412. fSecondMovBlock := nil;
  11413. fEndLabel := nil;
  11414. fAllocationRange := nil;
  11415. { Assume it all goes horribly wrong! }
  11416. fState := tsInvalid;
  11417. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11418. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11419. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11420. begin
  11421. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11422. for Count := 0 to 1 do
  11423. with taicpu(fCondition).oper[Count]^ do
  11424. case typ of
  11425. top_reg:
  11426. if getregtype(reg) = R_INTREGISTER then
  11427. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11428. top_ref:
  11429. begin
  11430. if
  11431. {$ifdef x86_64}
  11432. (ref^.base <> NR_RIP) and
  11433. {$endif x86_64}
  11434. (ref^.base <> NR_NO) then
  11435. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11436. if (ref^.index <> NR_NO) then
  11437. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11438. end
  11439. else
  11440. ;
  11441. end;
  11442. { When inserting instructions before hp_prev, try to insert them
  11443. before the allocation of the FLAGS register }
  11444. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11445. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11446. { If not found, set it equal to the condition so it's something sensible }
  11447. fInsertionPoint := fCondition;
  11448. { When dealing with a comparison against zero, take note of the
  11449. instruction before it to see if we can move instructions further
  11450. back in order to benefit PostPeepholeOptTestOr.
  11451. }
  11452. if (
  11453. (
  11454. (taicpu(fCondition).opcode = A_CMP) and
  11455. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11456. ) or
  11457. (
  11458. (taicpu(fCondition).opcode = A_TEST) and
  11459. (
  11460. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11461. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11462. )
  11463. )
  11464. ) and
  11465. Optimizer.GetLastInstruction(fCondition, hp1) then
  11466. begin
  11467. { These instructions set the zero flag if the result is zero }
  11468. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11469. begin
  11470. fInsertionPoint := hp1;
  11471. { Also mark all the registers in this previous instruction
  11472. as 'in use', even if they've just been deallocated }
  11473. for Count := 0 to 1 do
  11474. with taicpu(hp1).oper[Count]^ do
  11475. case typ of
  11476. top_reg:
  11477. if getregtype(reg) = R_INTREGISTER then
  11478. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11479. top_ref:
  11480. begin
  11481. if
  11482. {$ifdef x86_64}
  11483. (ref^.base <> NR_RIP) and
  11484. {$endif x86_64}
  11485. (ref^.base <> NR_NO) then
  11486. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11487. if (ref^.index <> NR_NO) then
  11488. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11489. end
  11490. else
  11491. ;
  11492. end;
  11493. end;
  11494. end;
  11495. end
  11496. else
  11497. fCondition := nil;
  11498. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11499. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11500. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11501. { If not found, set it equal to p so it's something sensible }
  11502. fInsertionPoint := hp1;
  11503. hp1 := p_initialmov;
  11504. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11505. Exit;
  11506. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11507. if (hp1.typ <> ait_label) then { should be on a jump }
  11508. begin
  11509. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11510. { Need a label afterwards }
  11511. Exit;
  11512. end
  11513. else
  11514. fMidLabel := hp1;
  11515. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11516. { Not the correct label }
  11517. fMidLabel := nil;
  11518. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11519. { If there's neither a 2nd jump nor correct label, then it's invalid
  11520. (see above table) }
  11521. Exit;
  11522. { Analyse the first block of MOVs more closely }
  11523. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11524. if Assigned(fSecondJump) then
  11525. begin
  11526. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11527. begin
  11528. fState := tsDetour
  11529. end
  11530. else
  11531. begin
  11532. { Need the correct mid-label for this one }
  11533. if not Assigned(fMidLabel) then
  11534. Exit;
  11535. fState := tsBranching;
  11536. end;
  11537. end
  11538. else
  11539. { No jump. but mid-label is present }
  11540. fState := tsSimple;
  11541. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11542. begin
  11543. { Invalid or too many instructions to be worthwhile }
  11544. fState := tsInvalid;
  11545. Exit;
  11546. end;
  11547. { check further for
  11548. jCC xxx
  11549. <several movs 1>
  11550. jmp yyy
  11551. xxx:
  11552. <several movs 2>
  11553. yyy:
  11554. etc.
  11555. }
  11556. if (fState = tsBranching) and
  11557. { Estimate for required savings for extra jump }
  11558. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11559. { Only one reference is allowed for double blocks }
  11560. (AFirstLabel.getrefs = 1) then
  11561. begin
  11562. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11563. fSecondMovBlock := hp1;
  11564. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11565. begin
  11566. EvaluateBranchingType;
  11567. Exit;
  11568. end;
  11569. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11570. if (hp1.typ <> ait_label) then { should be on a jump }
  11571. begin
  11572. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11573. begin
  11574. { Need a label afterwards }
  11575. EvaluateBranchingType;
  11576. Exit;
  11577. end;
  11578. end
  11579. else
  11580. fEndLabel := hp1;
  11581. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11582. { Second jump doesn't go to the end }
  11583. fEndLabel := nil;
  11584. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11585. begin
  11586. { If there's neither a 3rd jump nor correct end label, then it's
  11587. not a invalid double block, but is a valid single branching
  11588. block (see above table) }
  11589. EvaluateBranchingType;
  11590. Exit;
  11591. end;
  11592. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11593. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11594. { Invalid or too many instructions to be worthwhile }
  11595. Exit;
  11596. Inc(CMOVScore, Count);
  11597. if Assigned(fThirdJump) then
  11598. begin
  11599. if not Assigned(fSecondJump) then
  11600. fState := tsDoubleSecondBranching
  11601. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11602. fState := tsDoubleBranchSame
  11603. else
  11604. fState := tsDoubleBranchDifferent;
  11605. end
  11606. else
  11607. fState := tsDouble;
  11608. end;
  11609. if fState = tsBranching then
  11610. EvaluateBranchingType;
  11611. end;
  11612. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11613. new register to store the constant }
  11614. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11615. var
  11616. RegSize: TSubRegister;
  11617. CurrentVal: TCGInt;
  11618. ANewReg: TRegister;
  11619. X: ShortInt;
  11620. begin
  11621. Result := False;
  11622. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11623. Exit;
  11624. if ConstCount >= MAX_CMOV_REGISTERS then
  11625. { Arrays are full }
  11626. Exit;
  11627. { Remember that CMOV can't encode 8-bit registers }
  11628. case taicpu(p).opsize of
  11629. S_W:
  11630. RegSize := R_SUBW;
  11631. S_L:
  11632. RegSize := R_SUBD;
  11633. {$ifdef x86_64}
  11634. S_Q:
  11635. RegSize := R_SUBQ;
  11636. {$endif x86_64}
  11637. else
  11638. InternalError(2021100401);
  11639. end;
  11640. { See if the value has already been reserved for another CMOV instruction }
  11641. CurrentVal := taicpu(p).oper[0]^.val;
  11642. for X := 0 to ConstCount - 1 do
  11643. if ConstVals[X] = CurrentVal then
  11644. begin
  11645. ConstRegs[ConstCount] := ConstRegs[X];
  11646. ConstSizes[ConstCount] := RegSize;
  11647. ConstVals[ConstCount] := CurrentVal;
  11648. Inc(ConstCount);
  11649. Inc(Count);
  11650. Result := True;
  11651. Exit;
  11652. end;
  11653. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11654. if ANewReg = NR_NO then
  11655. { No free registers }
  11656. Exit;
  11657. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11658. up vying for the same register }
  11659. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11660. ConstRegs[ConstCount] := ANewReg;
  11661. ConstSizes[ConstCount] := RegSize;
  11662. ConstVals[ConstCount] := CurrentVal;
  11663. Inc(ConstCount);
  11664. Inc(Count);
  11665. Result := True;
  11666. end;
  11667. destructor TCMOVTracking.Done;
  11668. begin
  11669. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11670. end;
  11671. procedure TCMOVTracking.Process(out new_p: tai);
  11672. var
  11673. Count, Writes: LongInt;
  11674. RegMatch: Boolean;
  11675. hp1, hp_new: tai;
  11676. inverted_condition, condition: TAsmCond;
  11677. begin
  11678. if (fState in [tsInvalid, tsProcessed]) then
  11679. InternalError(2023110701);
  11680. { Repurpose RegisterTracking to mark registers that we've defined }
  11681. RegisterTracking[R_INTREGISTER].Clear;
  11682. Count := 0;
  11683. Writes := 0;
  11684. condition := taicpu(fInitialJump).condition;
  11685. inverted_condition := inverse_cond(condition);
  11686. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11687. doesn't get CMOVs in this case }
  11688. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11689. begin
  11690. { Include the jump in the flag tracking }
  11691. if Assigned(fThirdJump) then
  11692. begin
  11693. if (fState = tsDoubleBranchSame) then
  11694. begin
  11695. { Will be an unconditional jump, so track to the instruction before it }
  11696. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11697. InternalError(2023110710);
  11698. end
  11699. else
  11700. hp1 := fThirdJump;
  11701. end
  11702. else
  11703. hp1 := fSecondMovBlockStop;
  11704. end
  11705. else
  11706. begin
  11707. { Include a conditional jump in the flag tracking }
  11708. if Assigned(fSecondJump) then
  11709. begin
  11710. if (fState = tsDetour) then
  11711. begin
  11712. { Will be an unconditional jump, so track to the instruction before it }
  11713. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11714. InternalError(2023110711);
  11715. end
  11716. else
  11717. hp1 := fSecondJump;
  11718. end
  11719. else
  11720. hp1 := fFirstMovBlockStop;
  11721. end;
  11722. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11723. { Process the second set of MOVs first, because if a destination
  11724. register is shared between the first and second MOV sets, it is more
  11725. efficient to turn the first one into a MOV instruction and place it
  11726. before the CMP if possible, but we won't know which registers are
  11727. shared until we've processed at least one list, so we might as well
  11728. make it the second one since that won't be modified again. }
  11729. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11730. begin
  11731. hp1 := fSecondMovBlock;
  11732. repeat
  11733. if not Assigned(hp1) then
  11734. InternalError(2018062902);
  11735. if (hp1.typ = ait_instruction) then
  11736. begin
  11737. { Extra safeguard }
  11738. if (taicpu(hp1).opcode <> A_MOV) then
  11739. InternalError(2018062903);
  11740. { Note: tsDoubleBranchDifferent is essentially identical to
  11741. tsBranching and the 2nd block is best left largely
  11742. untouched, but we need to evaluate which registers the MOVs
  11743. write to in order to track what would be complementary CMOV
  11744. pairs that can be further optimised. [Kit] }
  11745. if fState <> tsDoubleBranchDifferent then
  11746. begin
  11747. if taicpu(hp1).oper[0]^.typ = top_const then
  11748. begin
  11749. RegMatch := False;
  11750. for Count := 0 to ConstCount - 1 do
  11751. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11752. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11753. begin
  11754. RegMatch := True;
  11755. { If it's in RegisterTracking, then this register
  11756. is being used more than once and hence has
  11757. already had its value defined (it gets added to
  11758. UsedRegs through AllocRegBetween below) }
  11759. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11760. begin
  11761. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11762. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11763. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11764. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11765. ConstMovs[Count] := hp_new;
  11766. end
  11767. else
  11768. { We just need an instruction between hp_prev and hp1
  11769. where we know the register is marked as in use }
  11770. hp_new := fSecondMovBlock;
  11771. { Keep track of largest write for this register so it can be optimised later }
  11772. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11773. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11774. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11775. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11776. Break;
  11777. end;
  11778. if not RegMatch then
  11779. InternalError(2021100411);
  11780. end;
  11781. taicpu(hp1).opcode := A_CMOVcc;
  11782. taicpu(hp1).condition := condition;
  11783. end;
  11784. { Store these writes to search for duplicates later on }
  11785. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11786. Inc(Writes);
  11787. end;
  11788. fOptimizer.GetNextInstruction(hp1, hp1);
  11789. until (hp1 = fSecondMovBlockStop);
  11790. end;
  11791. { Now do the first set of MOVs }
  11792. hp1 := fFirstMovBlock;
  11793. repeat
  11794. if not Assigned(hp1) then
  11795. InternalError(2018062904);
  11796. if (hp1.typ = ait_instruction) then
  11797. begin
  11798. RegMatch := False;
  11799. { Extra safeguard }
  11800. if (taicpu(hp1).opcode <> A_MOV) then
  11801. InternalError(2018062905);
  11802. { Search through the RegWrites list to see if there are any
  11803. opposing CMOV pairs that write to the same register }
  11804. for Count := 0 to Writes - 1 do
  11805. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11806. begin
  11807. { We have a match. Keep this as a MOV }
  11808. { Move ahead in preparation }
  11809. fOptimizer.GetNextInstruction(hp1, hp1);
  11810. RegMatch := True;
  11811. Break;
  11812. end;
  11813. if RegMatch then
  11814. Continue;
  11815. if taicpu(hp1).oper[0]^.typ = top_const then
  11816. begin
  11817. for Count := 0 to ConstCount - 1 do
  11818. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11819. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11820. begin
  11821. RegMatch := True;
  11822. { If it's in RegisterTracking, then this register is
  11823. being used more than once and hence has already had
  11824. its value defined (it gets added to UsedRegs through
  11825. AllocRegBetween below) }
  11826. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11827. begin
  11828. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11829. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11830. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11831. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11832. ConstMovs[Count] := hp_new;
  11833. end
  11834. else
  11835. { We just need an instruction between hp_prev and hp1
  11836. where we know the register is marked as in use }
  11837. hp_new := fFirstMovBlock;
  11838. { Keep track of largest write for this register so it can be optimised later }
  11839. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11840. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11841. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11842. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11843. Break;
  11844. end;
  11845. if not RegMatch then
  11846. InternalError(2021100412);
  11847. end;
  11848. taicpu(hp1).opcode := A_CMOVcc;
  11849. taicpu(hp1).condition := inverted_condition;
  11850. if (fState = tsDoubleBranchDifferent) then
  11851. begin
  11852. { Store these writes to search for duplicates later on }
  11853. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11854. Inc(Writes);
  11855. end;
  11856. end;
  11857. fOptimizer.GetNextInstruction(hp1, hp1);
  11858. until (hp1 = fFirstMovBlockStop);
  11859. { Update initialisation MOVs to the smallest possible size }
  11860. for Count := 0 to ConstCount - 1 do
  11861. if Assigned(ConstMovs[Count]) then
  11862. begin
  11863. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11864. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11865. end;
  11866. case fState of
  11867. tsSimple:
  11868. begin
  11869. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11870. { No branch to delete }
  11871. end;
  11872. tsDetour:
  11873. begin
  11874. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11875. { Preserve jump }
  11876. end;
  11877. tsBranching, tsDoubleBranchDifferent:
  11878. begin
  11879. if (fState = tsBranching) then
  11880. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11881. else
  11882. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11883. taicpu(fSecondJump).opcode := A_JCC;
  11884. taicpu(fSecondJump).condition := inverted_condition;
  11885. end;
  11886. tsDouble, tsDoubleBranchSame:
  11887. begin
  11888. if (fState = tsDouble) then
  11889. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11890. else
  11891. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11892. { Delete second jump }
  11893. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11894. fOptimizer.RemoveInstruction(fSecondJump);
  11895. end;
  11896. tsDoubleSecondBranching:
  11897. begin
  11898. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11899. { Delete second jump, preserve third jump as conditional }
  11900. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11901. fOptimizer.RemoveInstruction(fSecondJump);
  11902. taicpu(fThirdJump).opcode := A_JCC;
  11903. taicpu(fThirdJump).condition := condition;
  11904. end;
  11905. else
  11906. InternalError(2023110720);
  11907. end;
  11908. { Now we can safely decrement the reference count }
  11909. tasmlabel(fLabel).decrefs;
  11910. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11911. { Remove the original jump }
  11912. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11913. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11914. fState := tsProcessed;
  11915. end;
  11916. {$endif 8086}
  11917. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11918. var
  11919. hp1,hp2: tai;
  11920. carryadd_opcode : TAsmOp;
  11921. symbol: TAsmSymbol;
  11922. increg, tmpreg: TRegister;
  11923. {$ifndef i8086}
  11924. CMOVTracking: PCMOVTracking;
  11925. hp3,hp4,hp5: tai;
  11926. {$endif i8086}
  11927. TempBool: Boolean;
  11928. begin
  11929. if (aoc_DoPass2JccOpts in OptsToCheck) and
  11930. DoJumpOptimizations(p, TempBool) then
  11931. Exit(True);
  11932. result:=false;
  11933. if GetNextInstruction(p,hp1) then
  11934. begin
  11935. if (hp1.typ=ait_label) then
  11936. begin
  11937. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11938. Exit;
  11939. end
  11940. else if (hp1.typ<>ait_instruction) then
  11941. Exit;
  11942. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11943. if (
  11944. (
  11945. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11946. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11947. (Taicpu(hp1).oper[0]^.val=1)
  11948. ) or
  11949. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11950. ) and
  11951. GetNextInstruction(hp1,hp2) and
  11952. (hp2.typ = ait_label) and
  11953. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11954. { jb @@1 cmc
  11955. inc/dec operand --> adc/sbb operand,0
  11956. @@1:
  11957. ... and ...
  11958. jnb @@1
  11959. inc/dec operand --> adc/sbb operand,0
  11960. @@1: }
  11961. begin
  11962. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11963. begin
  11964. case taicpu(hp1).opcode of
  11965. A_INC,
  11966. A_ADD:
  11967. carryadd_opcode:=A_ADC;
  11968. A_DEC,
  11969. A_SUB:
  11970. carryadd_opcode:=A_SBB;
  11971. else
  11972. InternalError(2021011001);
  11973. end;
  11974. Taicpu(p).clearop(0);
  11975. Taicpu(p).ops:=0;
  11976. Taicpu(p).is_jmp:=false;
  11977. Taicpu(p).opcode:=A_CMC;
  11978. Taicpu(p).condition:=C_NONE;
  11979. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11980. Taicpu(hp1).ops:=2;
  11981. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11982. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11983. else
  11984. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11985. Taicpu(hp1).loadconst(0,0);
  11986. Taicpu(hp1).opcode:=carryadd_opcode;
  11987. result:=true;
  11988. exit;
  11989. end
  11990. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  11991. begin
  11992. case taicpu(hp1).opcode of
  11993. A_INC,
  11994. A_ADD:
  11995. carryadd_opcode:=A_ADC;
  11996. A_DEC,
  11997. A_SUB:
  11998. carryadd_opcode:=A_SBB;
  11999. else
  12000. InternalError(2021011002);
  12001. end;
  12002. Taicpu(hp1).ops:=2;
  12003. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12004. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12005. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12006. else
  12007. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12008. Taicpu(hp1).loadconst(0,0);
  12009. Taicpu(hp1).opcode:=carryadd_opcode;
  12010. RemoveCurrentP(p, hp1);
  12011. result:=true;
  12012. exit;
  12013. end
  12014. {
  12015. jcc @@1 setcc tmpreg
  12016. inc/dec/add/sub operand -> (movzx tmpreg)
  12017. @@1: add/sub tmpreg,operand
  12018. While this increases code size slightly, it makes the code much faster if the
  12019. jump is unpredictable
  12020. }
  12021. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12022. begin
  12023. { search for an available register which is volatile }
  12024. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12025. if increg <> NR_NO then
  12026. begin
  12027. { We don't need to check if tmpreg is in hp1 or not, because
  12028. it will be marked as in use at p (if not, this is
  12029. indictive of a compiler bug). }
  12030. TAsmLabel(symbol).decrefs;
  12031. Taicpu(p).clearop(0);
  12032. Taicpu(p).ops:=1;
  12033. Taicpu(p).is_jmp:=false;
  12034. Taicpu(p).opcode:=A_SETcc;
  12035. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12036. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12037. Taicpu(p).loadreg(0,increg);
  12038. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12039. begin
  12040. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12041. R_SUBW:
  12042. begin
  12043. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12044. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12045. end;
  12046. R_SUBD:
  12047. begin
  12048. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12049. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12050. end;
  12051. {$ifdef x86_64}
  12052. R_SUBQ:
  12053. begin
  12054. { MOVZX doesn't have a 64-bit variant, because
  12055. the 32-bit version implicitly zeroes the
  12056. upper 32-bits of the destination register }
  12057. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12058. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12059. setsubreg(tmpreg, R_SUBQ);
  12060. end;
  12061. {$endif x86_64}
  12062. else
  12063. Internalerror(2020030601);
  12064. end;
  12065. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12066. asml.InsertAfter(hp2,p);
  12067. end
  12068. else
  12069. tmpreg := increg;
  12070. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12071. begin
  12072. Taicpu(hp1).ops:=2;
  12073. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12074. end;
  12075. Taicpu(hp1).loadreg(0,tmpreg);
  12076. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12077. Result := True;
  12078. { p is no longer a Jcc instruction, so exit }
  12079. Exit;
  12080. end;
  12081. end;
  12082. end;
  12083. { Detect the following:
  12084. jmp<cond> @Lbl1
  12085. jmp @Lbl2
  12086. ...
  12087. @Lbl1:
  12088. ret
  12089. Change to:
  12090. jmp<inv_cond> @Lbl2
  12091. ret
  12092. }
  12093. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12094. begin
  12095. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12096. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12097. MatchInstruction(hp2,A_RET,[S_NO]) then
  12098. begin
  12099. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12100. { Change label address to that of the unconditional jump }
  12101. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12102. TAsmLabel(symbol).DecRefs;
  12103. taicpu(hp1).opcode := A_RET;
  12104. taicpu(hp1).is_jmp := false;
  12105. taicpu(hp1).ops := taicpu(hp2).ops;
  12106. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12107. case taicpu(hp2).ops of
  12108. 0:
  12109. taicpu(hp1).clearop(0);
  12110. 1:
  12111. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12112. else
  12113. internalerror(2016041302);
  12114. end;
  12115. end;
  12116. {$ifndef i8086}
  12117. end
  12118. {
  12119. convert
  12120. j<c> .L1
  12121. mov 1,reg
  12122. jmp .L2
  12123. .L1
  12124. mov 0,reg
  12125. .L2
  12126. into
  12127. mov 0,reg
  12128. set<not(c)> reg
  12129. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12130. would destroy the flag contents
  12131. }
  12132. else if MatchInstruction(hp1,A_MOV,[]) and
  12133. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12134. {$ifdef i386}
  12135. (
  12136. { Under i386, ESI, EDI, EBP and ESP
  12137. don't have an 8-bit representation }
  12138. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12139. ) and
  12140. {$endif i386}
  12141. (taicpu(hp1).oper[0]^.val=1) and
  12142. GetNextInstruction(hp1,hp2) and
  12143. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12144. GetNextInstruction(hp2,hp3) and
  12145. (hp3.typ=ait_label) and
  12146. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12147. (tai_label(hp3).labsym.getrefs=1) and
  12148. GetNextInstruction(hp3,hp4) and
  12149. MatchInstruction(hp4,A_MOV,[]) and
  12150. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12151. (taicpu(hp4).oper[0]^.val=0) and
  12152. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12153. GetNextInstruction(hp4,hp5) and
  12154. (hp5.typ=ait_label) and
  12155. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12156. (tai_label(hp5).labsym.getrefs=1) then
  12157. begin
  12158. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12159. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12160. { remove last label }
  12161. RemoveInstruction(hp5);
  12162. { remove second label }
  12163. RemoveInstruction(hp3);
  12164. { remove jmp }
  12165. RemoveInstruction(hp2);
  12166. if taicpu(hp1).opsize=S_B then
  12167. RemoveInstruction(hp1)
  12168. else
  12169. taicpu(hp1).loadconst(0,0);
  12170. taicpu(hp4).opcode:=A_SETcc;
  12171. taicpu(hp4).opsize:=S_B;
  12172. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12173. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12174. taicpu(hp4).opercnt:=1;
  12175. taicpu(hp4).ops:=1;
  12176. taicpu(hp4).freeop(1);
  12177. RemoveCurrentP(p);
  12178. Result:=true;
  12179. exit;
  12180. end
  12181. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12182. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12183. begin
  12184. { check for
  12185. jCC xxx
  12186. <several movs>
  12187. xxx:
  12188. Also spot:
  12189. Jcc xxx
  12190. <several movs>
  12191. jmp xxx
  12192. Change to:
  12193. <several cmovs with inverted condition>
  12194. jmp xxx (only for the 2nd case)
  12195. }
  12196. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12197. if CMOVTracking^.State <> tsInvalid then
  12198. begin
  12199. CMovTracking^.Process(p);
  12200. Result := True;
  12201. end;
  12202. CMOVTracking^.Done;
  12203. {$endif i8086}
  12204. end;
  12205. end;
  12206. end;
  12207. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12208. var
  12209. hp1,hp2,hp3: tai;
  12210. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12211. NewSize: TOpSize;
  12212. NewRegSize: TSubRegister;
  12213. Limit: TCgInt;
  12214. SwapOper: POper;
  12215. begin
  12216. result:=false;
  12217. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12218. GetNextInstruction(p,hp1) and
  12219. (hp1.typ = ait_instruction);
  12220. if reg_and_hp1_is_instr and
  12221. (
  12222. (taicpu(hp1).opcode <> A_LEA) or
  12223. { If the LEA instruction can be converted into an arithmetic instruction,
  12224. it may be possible to then fold it. }
  12225. (
  12226. { If the flags register is in use, don't change the instruction
  12227. to an ADD otherwise this will scramble the flags. [Kit] }
  12228. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12229. ConvertLEA(taicpu(hp1))
  12230. )
  12231. ) and
  12232. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12233. GetNextInstruction(hp1,hp2) and
  12234. MatchInstruction(hp2,A_MOV,[]) and
  12235. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12236. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12237. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12238. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12239. {$ifdef i386}
  12240. { not all registers have byte size sub registers on i386 }
  12241. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12242. {$endif i386}
  12243. (((taicpu(hp1).ops=2) and
  12244. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12245. ((taicpu(hp1).ops=1) and
  12246. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12247. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12248. begin
  12249. { change movsX/movzX reg/ref, reg2
  12250. add/sub/or/... reg3/$const, reg2
  12251. mov reg2 reg/ref
  12252. to add/sub/or/... reg3/$const, reg/ref }
  12253. { by example:
  12254. movswl %si,%eax movswl %si,%eax p
  12255. decl %eax addl %edx,%eax hp1
  12256. movw %ax,%si movw %ax,%si hp2
  12257. ->
  12258. movswl %si,%eax movswl %si,%eax p
  12259. decw %eax addw %edx,%eax hp1
  12260. movw %ax,%si movw %ax,%si hp2
  12261. }
  12262. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12263. {
  12264. ->
  12265. movswl %si,%eax movswl %si,%eax p
  12266. decw %si addw %dx,%si hp1
  12267. movw %ax,%si movw %ax,%si hp2
  12268. }
  12269. case taicpu(hp1).ops of
  12270. 1:
  12271. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12272. 2:
  12273. begin
  12274. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12275. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12276. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12277. end;
  12278. else
  12279. internalerror(2008042702);
  12280. end;
  12281. {
  12282. ->
  12283. decw %si addw %dx,%si p
  12284. }
  12285. DebugMsg(SPeepholeOptimization + 'var3',p);
  12286. RemoveCurrentP(p, hp1);
  12287. RemoveInstruction(hp2);
  12288. Result := True;
  12289. Exit;
  12290. end;
  12291. if reg_and_hp1_is_instr and
  12292. (taicpu(hp1).opcode = A_MOV) and
  12293. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12294. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12295. {$ifdef x86_64}
  12296. { check for implicit extension to 64 bit }
  12297. or
  12298. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12299. (taicpu(hp1).opsize=S_Q) and
  12300. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12301. )
  12302. {$endif x86_64}
  12303. )
  12304. then
  12305. begin
  12306. { change
  12307. movx %reg1,%reg2
  12308. mov %reg2,%reg3
  12309. dealloc %reg2
  12310. into
  12311. movx %reg,%reg3
  12312. }
  12313. TransferUsedRegs(TmpUsedRegs);
  12314. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12315. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12316. begin
  12317. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12318. {$ifdef x86_64}
  12319. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12320. (taicpu(hp1).opsize=S_Q) then
  12321. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12322. else
  12323. {$endif x86_64}
  12324. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12325. RemoveInstruction(hp1);
  12326. Result := True;
  12327. Exit;
  12328. end;
  12329. end;
  12330. if reg_and_hp1_is_instr and
  12331. ((taicpu(hp1).opcode=A_MOV) or
  12332. (taicpu(hp1).opcode=A_ADD) or
  12333. (taicpu(hp1).opcode=A_SUB) or
  12334. (taicpu(hp1).opcode=A_CMP) or
  12335. (taicpu(hp1).opcode=A_OR) or
  12336. (taicpu(hp1).opcode=A_XOR) or
  12337. (taicpu(hp1).opcode=A_AND)
  12338. ) and
  12339. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12340. begin
  12341. AndTest := (taicpu(hp1).opcode=A_AND) and
  12342. GetNextInstruction(hp1, hp2) and
  12343. (hp2.typ = ait_instruction) and
  12344. (
  12345. (
  12346. (taicpu(hp2).opcode=A_TEST) and
  12347. (
  12348. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12349. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12350. (
  12351. { If the AND and TEST instructions share a constant, this is also valid }
  12352. (taicpu(hp1).oper[0]^.typ = top_const) and
  12353. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12354. )
  12355. ) and
  12356. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12357. ) or
  12358. (
  12359. (taicpu(hp2).opcode=A_CMP) and
  12360. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12361. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12362. )
  12363. );
  12364. { change
  12365. movx (oper),%reg2
  12366. and $x,%reg2
  12367. test %reg2,%reg2
  12368. dealloc %reg2
  12369. into
  12370. op %reg1,%reg3
  12371. if the second op accesses only the bits stored in reg1
  12372. }
  12373. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12374. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12375. (taicpu(hp1).oper[0]^.typ = top_const) and
  12376. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12377. AndTest then
  12378. begin
  12379. { Check if the AND constant is in range }
  12380. case taicpu(p).opsize of
  12381. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12382. begin
  12383. NewSize := S_B;
  12384. Limit := $FF;
  12385. end;
  12386. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12387. begin
  12388. NewSize := S_W;
  12389. Limit := $FFFF;
  12390. end;
  12391. {$ifdef x86_64}
  12392. S_LQ:
  12393. begin
  12394. NewSize := S_L;
  12395. Limit := $FFFFFFFF;
  12396. end;
  12397. {$endif x86_64}
  12398. else
  12399. InternalError(2021120303);
  12400. end;
  12401. if (
  12402. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12403. { Check for negative operands }
  12404. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12405. ) and
  12406. GetNextInstruction(hp2,hp3) and
  12407. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12408. (taicpu(hp3).condition in [C_E,C_NE]) then
  12409. begin
  12410. TransferUsedRegs(TmpUsedRegs);
  12411. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12412. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12413. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12414. begin
  12415. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12416. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12417. taicpu(hp1).opcode := A_TEST;
  12418. taicpu(hp1).opsize := NewSize;
  12419. RemoveInstruction(hp2);
  12420. RemoveCurrentP(p, hp1);
  12421. Result:=true;
  12422. exit;
  12423. end;
  12424. end;
  12425. end;
  12426. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12427. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12428. (taicpu(hp1).opsize=S_B)) or
  12429. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12430. (taicpu(hp1).opsize=S_W))
  12431. {$ifdef x86_64}
  12432. or ((taicpu(p).opsize=S_LQ) and
  12433. (taicpu(hp1).opsize=S_L))
  12434. {$endif x86_64}
  12435. ) and
  12436. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12437. begin
  12438. { change
  12439. movx %reg1,%reg2
  12440. op %reg2,%reg3
  12441. dealloc %reg2
  12442. into
  12443. op %reg1,%reg3
  12444. if the second op accesses only the bits stored in reg1
  12445. }
  12446. TransferUsedRegs(TmpUsedRegs);
  12447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12448. if AndTest then
  12449. begin
  12450. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12451. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12452. end
  12453. else
  12454. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12455. if not RegUsed then
  12456. begin
  12457. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12458. if taicpu(p).oper[0]^.typ=top_reg then
  12459. begin
  12460. case taicpu(hp1).opsize of
  12461. S_B:
  12462. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12463. S_W:
  12464. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12465. S_L:
  12466. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12467. else
  12468. Internalerror(2020102301);
  12469. end;
  12470. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12471. end
  12472. else
  12473. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12474. RemoveCurrentP(p);
  12475. if AndTest then
  12476. RemoveInstruction(hp2);
  12477. result:=true;
  12478. exit;
  12479. end;
  12480. end
  12481. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12482. (
  12483. { Bitwise operations only }
  12484. (taicpu(hp1).opcode=A_AND) or
  12485. (taicpu(hp1).opcode=A_TEST) or
  12486. (
  12487. (taicpu(hp1).oper[0]^.typ = top_const) and
  12488. (
  12489. (taicpu(hp1).opcode=A_OR) or
  12490. (taicpu(hp1).opcode=A_XOR)
  12491. )
  12492. )
  12493. ) and
  12494. (
  12495. (taicpu(hp1).oper[0]^.typ = top_const) or
  12496. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12497. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12498. ) then
  12499. begin
  12500. { change
  12501. movx %reg2,%reg2
  12502. op const,%reg2
  12503. into
  12504. op const,%reg2 (smaller version)
  12505. movx %reg2,%reg2
  12506. also change
  12507. movx %reg1,%reg2
  12508. and/test (oper),%reg2
  12509. dealloc %reg2
  12510. into
  12511. and/test (oper),%reg1
  12512. }
  12513. case taicpu(p).opsize of
  12514. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12515. begin
  12516. NewSize := S_B;
  12517. NewRegSize := R_SUBL;
  12518. Limit := $FF;
  12519. end;
  12520. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12521. begin
  12522. NewSize := S_W;
  12523. NewRegSize := R_SUBW;
  12524. Limit := $FFFF;
  12525. end;
  12526. {$ifdef x86_64}
  12527. S_LQ:
  12528. begin
  12529. NewSize := S_L;
  12530. NewRegSize := R_SUBD;
  12531. Limit := $FFFFFFFF;
  12532. end;
  12533. {$endif x86_64}
  12534. else
  12535. Internalerror(2021120302);
  12536. end;
  12537. TransferUsedRegs(TmpUsedRegs);
  12538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12539. if AndTest then
  12540. begin
  12541. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12542. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12543. end
  12544. else
  12545. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12546. if
  12547. (
  12548. (taicpu(p).opcode = A_MOVZX) and
  12549. (
  12550. (taicpu(hp1).opcode=A_AND) or
  12551. (taicpu(hp1).opcode=A_TEST)
  12552. ) and
  12553. not (
  12554. { If both are references, then the final instruction will have
  12555. both operands as references, which is not allowed }
  12556. (taicpu(p).oper[0]^.typ = top_ref) and
  12557. (taicpu(hp1).oper[0]^.typ = top_ref)
  12558. ) and
  12559. not RegUsed
  12560. ) or
  12561. (
  12562. (
  12563. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12564. not RegUsed
  12565. ) and
  12566. (taicpu(p).oper[0]^.typ = top_reg) and
  12567. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12568. (taicpu(hp1).oper[0]^.typ = top_const) and
  12569. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12570. ) then
  12571. begin
  12572. {$if defined(i386) or defined(i8086)}
  12573. { If the target size is 8-bit, make sure we can actually encode it }
  12574. 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
  12575. Exit;
  12576. {$endif i386 or i8086}
  12577. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12578. taicpu(hp1).opsize := NewSize;
  12579. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12580. if AndTest then
  12581. begin
  12582. RemoveInstruction(hp2);
  12583. if not RegUsed then
  12584. begin
  12585. taicpu(hp1).opcode := A_TEST;
  12586. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12587. begin
  12588. { Make sure the reference is the second operand }
  12589. SwapOper := taicpu(hp1).oper[0];
  12590. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12591. taicpu(hp1).oper[1] := SwapOper;
  12592. end;
  12593. end;
  12594. end;
  12595. case taicpu(hp1).oper[0]^.typ of
  12596. top_reg:
  12597. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12598. top_const:
  12599. { For the AND/TEST case }
  12600. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12601. else
  12602. ;
  12603. end;
  12604. if RegUsed then
  12605. begin
  12606. AsmL.Remove(p);
  12607. AsmL.InsertAfter(p, hp1);
  12608. p := hp1;
  12609. end
  12610. else
  12611. RemoveCurrentP(p, hp1);
  12612. result:=true;
  12613. exit;
  12614. end;
  12615. end;
  12616. end;
  12617. if reg_and_hp1_is_instr and
  12618. (taicpu(p).oper[0]^.typ = top_reg) and
  12619. (
  12620. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12621. ) and
  12622. (taicpu(hp1).oper[0]^.typ = top_const) and
  12623. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12624. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12625. { Minimum shift value allowed is the bit difference between the sizes }
  12626. (taicpu(hp1).oper[0]^.val >=
  12627. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12628. 8 * (
  12629. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12630. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12631. )
  12632. ) then
  12633. begin
  12634. { For:
  12635. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12636. shl/sal ##, %reg1
  12637. Remove the movsx/movzx instruction if the shift overwrites the
  12638. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12639. }
  12640. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12641. RemoveCurrentP(p, hp1);
  12642. Result := True;
  12643. Exit;
  12644. end
  12645. else if reg_and_hp1_is_instr and
  12646. (taicpu(p).oper[0]^.typ = top_reg) and
  12647. (
  12648. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12649. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12650. ) and
  12651. (taicpu(hp1).oper[0]^.typ = top_const) and
  12652. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12653. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12654. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12655. (taicpu(hp1).oper[0]^.val <
  12656. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12657. 8 * (
  12658. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12659. )
  12660. ) then
  12661. begin
  12662. { For:
  12663. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12664. sar ##, %reg1 shr ##, %reg1
  12665. Move the shift to before the movx instruction if the shift value
  12666. is not too large.
  12667. }
  12668. asml.Remove(hp1);
  12669. asml.InsertBefore(hp1, p);
  12670. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12671. case taicpu(p).opsize of
  12672. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12673. taicpu(hp1).opsize := S_B;
  12674. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12675. taicpu(hp1).opsize := S_W;
  12676. {$ifdef x86_64}
  12677. S_LQ:
  12678. taicpu(hp1).opsize := S_L;
  12679. {$endif}
  12680. else
  12681. InternalError(2020112401);
  12682. end;
  12683. if (taicpu(hp1).opcode = A_SHR) then
  12684. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12685. else
  12686. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12687. Result := True;
  12688. end;
  12689. if reg_and_hp1_is_instr and
  12690. (taicpu(p).oper[0]^.typ = top_reg) and
  12691. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12692. (
  12693. (taicpu(hp1).opcode = taicpu(p).opcode)
  12694. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12695. {$ifdef x86_64}
  12696. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12697. {$endif x86_64}
  12698. ) then
  12699. begin
  12700. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12701. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12702. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12703. begin
  12704. {
  12705. For example:
  12706. movzbw %al,%ax
  12707. movzwl %ax,%eax
  12708. Compress into:
  12709. movzbl %al,%eax
  12710. }
  12711. RegUsed := False;
  12712. case taicpu(p).opsize of
  12713. S_BW:
  12714. case taicpu(hp1).opsize of
  12715. S_WL:
  12716. begin
  12717. taicpu(p).opsize := S_BL;
  12718. RegUsed := True;
  12719. end;
  12720. {$ifdef x86_64}
  12721. S_WQ:
  12722. begin
  12723. if taicpu(p).opcode = A_MOVZX then
  12724. begin
  12725. taicpu(p).opsize := S_BL;
  12726. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12727. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12728. end
  12729. else
  12730. taicpu(p).opsize := S_BQ;
  12731. RegUsed := True;
  12732. end;
  12733. {$endif x86_64}
  12734. else
  12735. ;
  12736. end;
  12737. {$ifdef x86_64}
  12738. S_BL:
  12739. case taicpu(hp1).opsize of
  12740. S_LQ:
  12741. begin
  12742. if taicpu(p).opcode = A_MOVZX then
  12743. begin
  12744. taicpu(p).opsize := S_BL;
  12745. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12746. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12747. end
  12748. else
  12749. taicpu(p).opsize := S_BQ;
  12750. RegUsed := True;
  12751. end;
  12752. else
  12753. ;
  12754. end;
  12755. S_WL:
  12756. case taicpu(hp1).opsize of
  12757. S_LQ:
  12758. begin
  12759. if taicpu(p).opcode = A_MOVZX then
  12760. begin
  12761. taicpu(p).opsize := S_WL;
  12762. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12763. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12764. end
  12765. else
  12766. taicpu(p).opsize := S_WQ;
  12767. RegUsed := True;
  12768. end;
  12769. else
  12770. ;
  12771. end;
  12772. {$endif x86_64}
  12773. else
  12774. ;
  12775. end;
  12776. if RegUsed then
  12777. begin
  12778. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12779. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12780. RemoveInstruction(hp1);
  12781. Result := True;
  12782. Exit;
  12783. end;
  12784. end;
  12785. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12786. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12787. GetNextInstruction(hp1, hp2) and
  12788. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12789. (
  12790. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12791. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12792. {$ifdef x86_64}
  12793. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12794. {$endif x86_64}
  12795. ) and
  12796. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12797. (
  12798. (
  12799. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12800. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12801. ) or
  12802. (
  12803. { Only allow the operands in reverse order for TEST instructions }
  12804. (taicpu(hp2).opcode = A_TEST) and
  12805. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12806. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12807. )
  12808. ) then
  12809. begin
  12810. {
  12811. For example:
  12812. movzbl %al,%eax
  12813. movzbl (ref),%edx
  12814. andl %edx,%eax
  12815. (%edx deallocated)
  12816. Change to:
  12817. andb (ref),%al
  12818. movzbl %al,%eax
  12819. Rules are:
  12820. - First two instructions have the same opcode and opsize
  12821. - First instruction's operands are the same super-register
  12822. - Second instruction operates on a different register
  12823. - Third instruction is AND, OR, XOR or TEST
  12824. - Third instruction's operands are the destination registers of the first two instructions
  12825. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12826. - Second instruction's destination register is deallocated afterwards
  12827. }
  12828. TransferUsedRegs(TmpUsedRegs);
  12829. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12830. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12831. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12832. begin
  12833. case taicpu(p).opsize of
  12834. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12835. NewSize := S_B;
  12836. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12837. NewSize := S_W;
  12838. {$ifdef x86_64}
  12839. S_LQ:
  12840. NewSize := S_L;
  12841. {$endif x86_64}
  12842. else
  12843. InternalError(2021120301);
  12844. end;
  12845. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12846. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12847. taicpu(hp2).opsize := NewSize;
  12848. RemoveInstruction(hp1);
  12849. { With TEST, it's best to keep the MOVX instruction at the top }
  12850. if (taicpu(hp2).opcode <> A_TEST) then
  12851. begin
  12852. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12853. asml.Remove(p);
  12854. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12855. asml.InsertAfter(p, hp2);
  12856. p := hp2;
  12857. end
  12858. else
  12859. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12860. Result := True;
  12861. Exit;
  12862. end;
  12863. end;
  12864. end;
  12865. if taicpu(p).opcode=A_MOVZX then
  12866. begin
  12867. { removes superfluous And's after movzx's }
  12868. if reg_and_hp1_is_instr and
  12869. (taicpu(hp1).opcode = A_AND) and
  12870. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12871. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12872. {$ifdef x86_64}
  12873. { check for implicit extension to 64 bit }
  12874. or
  12875. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12876. (taicpu(hp1).opsize=S_Q) and
  12877. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12878. )
  12879. {$endif x86_64}
  12880. )
  12881. then
  12882. begin
  12883. case taicpu(p).opsize Of
  12884. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12885. if (taicpu(hp1).oper[0]^.val = $ff) then
  12886. begin
  12887. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12888. RemoveInstruction(hp1);
  12889. Result:=true;
  12890. exit;
  12891. end;
  12892. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12893. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12894. begin
  12895. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12896. RemoveInstruction(hp1);
  12897. Result:=true;
  12898. exit;
  12899. end;
  12900. {$ifdef x86_64}
  12901. S_LQ:
  12902. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12903. begin
  12904. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12905. RemoveInstruction(hp1);
  12906. Result:=true;
  12907. exit;
  12908. end;
  12909. {$endif x86_64}
  12910. else
  12911. ;
  12912. end;
  12913. { we cannot get rid of the and, but can we get rid of the movz ?}
  12914. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12915. begin
  12916. case taicpu(p).opsize Of
  12917. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12918. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12919. begin
  12920. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12921. RemoveCurrentP(p,hp1);
  12922. Result:=true;
  12923. exit;
  12924. end;
  12925. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12926. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12927. begin
  12928. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12929. RemoveCurrentP(p,hp1);
  12930. Result:=true;
  12931. exit;
  12932. end;
  12933. {$ifdef x86_64}
  12934. S_LQ:
  12935. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12936. begin
  12937. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12938. RemoveCurrentP(p,hp1);
  12939. Result:=true;
  12940. exit;
  12941. end;
  12942. {$endif x86_64}
  12943. else
  12944. ;
  12945. end;
  12946. end;
  12947. end;
  12948. { changes some movzx constructs to faster synonyms (all examples
  12949. are given with eax/ax, but are also valid for other registers)}
  12950. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12951. begin
  12952. case taicpu(p).opsize of
  12953. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12954. (the machine code is equivalent to movzbl %al,%eax), but the
  12955. code generator still generates that assembler instruction and
  12956. it is silently converted. This should probably be checked.
  12957. [Kit] }
  12958. S_BW:
  12959. begin
  12960. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12961. (
  12962. not IsMOVZXAcceptable
  12963. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12964. or (
  12965. (cs_opt_size in current_settings.optimizerswitches) and
  12966. (taicpu(p).oper[1]^.reg = NR_AX)
  12967. )
  12968. ) then
  12969. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12970. begin
  12971. DebugMsg(SPeepholeOptimization + 'var7',p);
  12972. taicpu(p).opcode := A_AND;
  12973. taicpu(p).changeopsize(S_W);
  12974. taicpu(p).loadConst(0,$ff);
  12975. Result := True;
  12976. end
  12977. else if not IsMOVZXAcceptable and
  12978. GetNextInstruction(p, hp1) and
  12979. (tai(hp1).typ = ait_instruction) and
  12980. (taicpu(hp1).opcode = A_AND) and
  12981. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12982. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12983. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12984. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12985. begin
  12986. DebugMsg(SPeepholeOptimization + 'var8',p);
  12987. taicpu(p).opcode := A_MOV;
  12988. taicpu(p).changeopsize(S_W);
  12989. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12990. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12991. Result := True;
  12992. end;
  12993. end;
  12994. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12995. S_BL:
  12996. if not IsMOVZXAcceptable then
  12997. begin
  12998. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12999. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13000. begin
  13001. DebugMsg(SPeepholeOptimization + 'var9',p);
  13002. taicpu(p).opcode := A_AND;
  13003. taicpu(p).changeopsize(S_L);
  13004. taicpu(p).loadConst(0,$ff);
  13005. Result := True;
  13006. end
  13007. else if GetNextInstruction(p, hp1) and
  13008. (tai(hp1).typ = ait_instruction) and
  13009. (taicpu(hp1).opcode = A_AND) and
  13010. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13011. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13012. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13013. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13014. begin
  13015. DebugMsg(SPeepholeOptimization + 'var10',p);
  13016. taicpu(p).opcode := A_MOV;
  13017. taicpu(p).changeopsize(S_L);
  13018. { do not use R_SUBWHOLE
  13019. as movl %rdx,%eax
  13020. is invalid in assembler PM }
  13021. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13022. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13023. Result := True;
  13024. end;
  13025. end;
  13026. {$endif i8086}
  13027. S_WL:
  13028. if not IsMOVZXAcceptable then
  13029. begin
  13030. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13031. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13032. begin
  13033. DebugMsg(SPeepholeOptimization + 'var11',p);
  13034. taicpu(p).opcode := A_AND;
  13035. taicpu(p).changeopsize(S_L);
  13036. taicpu(p).loadConst(0,$ffff);
  13037. Result := True;
  13038. end
  13039. else if GetNextInstruction(p, hp1) and
  13040. (tai(hp1).typ = ait_instruction) and
  13041. (taicpu(hp1).opcode = A_AND) and
  13042. (taicpu(hp1).oper[0]^.typ = top_const) and
  13043. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13044. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13045. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13046. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13047. begin
  13048. DebugMsg(SPeepholeOptimization + 'var12',p);
  13049. taicpu(p).opcode := A_MOV;
  13050. taicpu(p).changeopsize(S_L);
  13051. { do not use R_SUBWHOLE
  13052. as movl %rdx,%eax
  13053. is invalid in assembler PM }
  13054. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13055. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13056. Result := True;
  13057. end;
  13058. end;
  13059. else
  13060. InternalError(2017050705);
  13061. end;
  13062. end
  13063. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13064. begin
  13065. if GetNextInstruction(p, hp1) and
  13066. (tai(hp1).typ = ait_instruction) and
  13067. (taicpu(hp1).opcode = A_AND) and
  13068. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13069. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13070. begin
  13071. //taicpu(p).opcode := A_MOV;
  13072. case taicpu(p).opsize Of
  13073. S_BL:
  13074. begin
  13075. DebugMsg(SPeepholeOptimization + 'var13',p);
  13076. taicpu(hp1).changeopsize(S_L);
  13077. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13078. end;
  13079. S_WL:
  13080. begin
  13081. DebugMsg(SPeepholeOptimization + 'var14',p);
  13082. taicpu(hp1).changeopsize(S_L);
  13083. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13084. end;
  13085. S_BW:
  13086. begin
  13087. DebugMsg(SPeepholeOptimization + 'var15',p);
  13088. taicpu(hp1).changeopsize(S_W);
  13089. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13090. end;
  13091. else
  13092. Internalerror(2017050704)
  13093. end;
  13094. Result := True;
  13095. end;
  13096. end;
  13097. end;
  13098. end;
  13099. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13100. var
  13101. hp1, hp2 : tai;
  13102. MaskLength : Cardinal;
  13103. MaskedBits : TCgInt;
  13104. ActiveReg : TRegister;
  13105. begin
  13106. Result:=false;
  13107. { There are no optimisations for reference targets }
  13108. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13109. Exit;
  13110. while GetNextInstruction(p, hp1) and
  13111. (hp1.typ = ait_instruction) do
  13112. begin
  13113. if (taicpu(p).oper[0]^.typ = top_const) then
  13114. begin
  13115. case taicpu(hp1).opcode of
  13116. A_AND:
  13117. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13118. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13119. { the second register must contain the first one, so compare their subreg types }
  13120. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13121. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13122. { change
  13123. and const1, reg
  13124. and const2, reg
  13125. to
  13126. and (const1 and const2), reg
  13127. }
  13128. begin
  13129. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13130. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13131. RemoveCurrentP(p, hp1);
  13132. Result:=true;
  13133. exit;
  13134. end;
  13135. A_CMP:
  13136. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13137. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13138. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13139. { Just check that the condition on the next instruction is compatible }
  13140. GetNextInstruction(hp1, hp2) and
  13141. (hp2.typ = ait_instruction) and
  13142. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13143. then
  13144. { change
  13145. and 2^n, reg
  13146. cmp 2^n, reg
  13147. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13148. to
  13149. and 2^n, reg
  13150. test reg, reg
  13151. j(~c) / set(~c) / cmov(~c)
  13152. }
  13153. begin
  13154. { Keep TEST instruction in, rather than remove it, because
  13155. it may trigger other optimisations such as MovAndTest2Test }
  13156. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13157. taicpu(hp1).opcode := A_TEST;
  13158. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13159. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13160. Result := True;
  13161. Exit;
  13162. end
  13163. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13164. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13165. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13166. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13167. { change
  13168. and $ff/$ff/$ffff, reg
  13169. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13170. dealloc reg
  13171. to
  13172. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13173. }
  13174. begin
  13175. TransferUsedRegs(TmpUsedRegs);
  13176. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13177. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13178. begin
  13179. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13180. case taicpu(p).oper[0]^.val of
  13181. $ff:
  13182. begin
  13183. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13184. taicpu(hp1).opsize:=S_B;
  13185. end;
  13186. $ffff:
  13187. begin
  13188. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13189. taicpu(hp1).opsize:=S_W;
  13190. end;
  13191. $ffffffff:
  13192. begin
  13193. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13194. taicpu(hp1).opsize:=S_L;
  13195. end;
  13196. else
  13197. Internalerror(2023030401);
  13198. end;
  13199. RemoveCurrentP(p);
  13200. Result := True;
  13201. Exit;
  13202. end;
  13203. end;
  13204. A_MOVZX:
  13205. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13206. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13207. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13208. (
  13209. (
  13210. (taicpu(p).opsize=S_W) and
  13211. (taicpu(hp1).opsize=S_BW)
  13212. ) or
  13213. (
  13214. (taicpu(p).opsize=S_L) and
  13215. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13216. )
  13217. {$ifdef x86_64}
  13218. or
  13219. (
  13220. (taicpu(p).opsize=S_Q) and
  13221. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13222. )
  13223. {$endif x86_64}
  13224. ) then
  13225. begin
  13226. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13227. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13228. ) or
  13229. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13230. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13231. then
  13232. begin
  13233. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13234. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13235. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13236. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13237. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13238. }
  13239. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13240. RemoveInstruction(hp1);
  13241. { See if there are other optimisations possible }
  13242. Continue;
  13243. end;
  13244. end;
  13245. A_SHL:
  13246. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13247. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13248. begin
  13249. {$ifopt R+}
  13250. {$define RANGE_WAS_ON}
  13251. {$R-}
  13252. {$endif}
  13253. { get length of potential and mask }
  13254. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13255. { really a mask? }
  13256. {$ifdef RANGE_WAS_ON}
  13257. {$R+}
  13258. {$endif}
  13259. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13260. { unmasked part shifted out? }
  13261. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13262. begin
  13263. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13264. RemoveCurrentP(p, hp1);
  13265. Result:=true;
  13266. exit;
  13267. end;
  13268. end;
  13269. A_SHR:
  13270. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13271. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13272. (taicpu(hp1).oper[0]^.val <= 63) then
  13273. begin
  13274. { Does SHR combined with the AND cover all the bits?
  13275. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13276. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13277. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13278. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13279. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13280. begin
  13281. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13282. RemoveCurrentP(p, hp1);
  13283. Result := True;
  13284. Exit;
  13285. end;
  13286. end;
  13287. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13288. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13289. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13290. begin
  13291. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13292. (
  13293. (
  13294. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13295. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13296. ) or (
  13297. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13298. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13299. {$ifdef x86_64}
  13300. ) or (
  13301. (taicpu(hp1).opsize = S_LQ) and
  13302. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13303. {$endif x86_64}
  13304. )
  13305. ) then
  13306. begin
  13307. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13308. begin
  13309. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13310. RemoveInstruction(hp1);
  13311. { See if there are other optimisations possible }
  13312. Continue;
  13313. end;
  13314. { The super-registers are the same though.
  13315. Note that this change by itself doesn't improve
  13316. code speed, but it opens up other optimisations. }
  13317. {$ifdef x86_64}
  13318. { Convert 64-bit register to 32-bit }
  13319. case taicpu(hp1).opsize of
  13320. S_BQ:
  13321. begin
  13322. taicpu(hp1).opsize := S_BL;
  13323. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13324. end;
  13325. S_WQ:
  13326. begin
  13327. taicpu(hp1).opsize := S_WL;
  13328. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13329. end
  13330. else
  13331. ;
  13332. end;
  13333. {$endif x86_64}
  13334. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13335. taicpu(hp1).opcode := A_MOVZX;
  13336. { See if there are other optimisations possible }
  13337. Continue;
  13338. end;
  13339. end;
  13340. else
  13341. ;
  13342. end;
  13343. end
  13344. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13345. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13346. begin
  13347. {$ifdef x86_64}
  13348. if (taicpu(p).opsize = S_Q) then
  13349. begin
  13350. { Never necessary }
  13351. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13352. RemoveCurrentP(p, hp1);
  13353. Result := True;
  13354. Exit;
  13355. end;
  13356. {$endif x86_64}
  13357. { Forward check to determine necessity of and %reg,%reg }
  13358. TransferUsedRegs(TmpUsedRegs);
  13359. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13360. { Saves on a bunch of dereferences }
  13361. ActiveReg := taicpu(p).oper[1]^.reg;
  13362. case taicpu(hp1).opcode of
  13363. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13364. if (
  13365. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13366. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13367. ) and
  13368. (
  13369. (taicpu(hp1).opcode <> A_MOV) or
  13370. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13371. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13372. ) and
  13373. not (
  13374. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13375. (taicpu(hp1).opcode = A_MOV) and
  13376. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13377. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13378. ) and
  13379. (
  13380. (
  13381. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13382. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13383. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13384. ) or
  13385. (
  13386. {$ifdef x86_64}
  13387. (
  13388. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13389. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13390. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13391. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13392. ) and
  13393. {$endif x86_64}
  13394. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13395. )
  13396. ) then
  13397. begin
  13398. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13399. RemoveCurrentP(p, hp1);
  13400. Result := True;
  13401. Exit;
  13402. end;
  13403. A_ADD,
  13404. A_AND,
  13405. A_BSF,
  13406. A_BSR,
  13407. A_BTC,
  13408. A_BTR,
  13409. A_BTS,
  13410. A_OR,
  13411. A_SUB,
  13412. A_XOR:
  13413. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13414. if (
  13415. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13416. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13417. ) and
  13418. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13419. begin
  13420. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13421. RemoveCurrentP(p, hp1);
  13422. Result := True;
  13423. Exit;
  13424. end;
  13425. A_CMP,
  13426. A_TEST:
  13427. if (
  13428. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13429. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13430. ) and
  13431. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13432. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13433. begin
  13434. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13435. RemoveCurrentP(p, hp1);
  13436. Result := True;
  13437. Exit;
  13438. end;
  13439. A_BSWAP,
  13440. A_NEG,
  13441. A_NOT:
  13442. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13443. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13444. begin
  13445. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13446. RemoveCurrentP(p, hp1);
  13447. Result := True;
  13448. Exit;
  13449. end;
  13450. else
  13451. ;
  13452. end;
  13453. end;
  13454. if (taicpu(hp1).is_jmp) and
  13455. (taicpu(hp1).opcode<>A_JMP) and
  13456. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13457. begin
  13458. { change
  13459. and x, reg
  13460. jxx
  13461. to
  13462. test x, reg
  13463. jxx
  13464. if reg is deallocated before the
  13465. jump, but only if it's a conditional jump (PFV)
  13466. }
  13467. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13468. taicpu(p).opcode := A_TEST;
  13469. Exit;
  13470. end;
  13471. Break;
  13472. end;
  13473. { Lone AND tests }
  13474. if (taicpu(p).oper[0]^.typ = top_const) then
  13475. begin
  13476. {
  13477. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13478. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13479. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13480. }
  13481. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13482. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13483. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13484. begin
  13485. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13486. if taicpu(p).opsize = S_L then
  13487. begin
  13488. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13489. Result := True;
  13490. end;
  13491. end;
  13492. end;
  13493. { Backward check to determine necessity of and %reg,%reg }
  13494. if (taicpu(p).oper[0]^.typ = top_reg) and
  13495. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13496. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13497. GetLastInstruction(p, hp2) and
  13498. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13499. { Check size of adjacent instruction to determine if the AND is
  13500. effectively a null operation }
  13501. (
  13502. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13503. { Note: Don't include S_Q }
  13504. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13505. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13506. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13507. ) then
  13508. begin
  13509. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13510. { If GetNextInstruction returned False, hp1 will be nil }
  13511. RemoveCurrentP(p, hp1);
  13512. Result := True;
  13513. Exit;
  13514. end;
  13515. end;
  13516. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13517. var
  13518. hp1, hp2: tai;
  13519. NewRef: TReference;
  13520. Distance: Cardinal;
  13521. TempTracking: TAllUsedRegs;
  13522. { This entire nested function is used in an if-statement below, but we
  13523. want to avoid all the used reg transfers and GetNextInstruction calls
  13524. until we really have to check }
  13525. function MemRegisterNotUsedLater: Boolean; inline;
  13526. var
  13527. hp2: tai;
  13528. begin
  13529. TransferUsedRegs(TmpUsedRegs);
  13530. hp2 := p;
  13531. repeat
  13532. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13533. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13534. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13535. end;
  13536. begin
  13537. Result := False;
  13538. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13539. (taicpu(p).oper[1]^.typ = top_reg) then
  13540. begin
  13541. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13542. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13543. (hp1.typ <> ait_instruction) or
  13544. not
  13545. (
  13546. (cs_opt_level3 in current_settings.optimizerswitches) or
  13547. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13548. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13549. ) then
  13550. Exit;
  13551. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13552. addq $x, %rax
  13553. movq %rax, %rdx
  13554. sarq $63, %rdx
  13555. (%rax still in use)
  13556. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13557. leaq $x(%rax),%rdx
  13558. addq $x, %rax
  13559. sarq $63, %rdx
  13560. ...which is okay since it breaks the dependency chain between
  13561. addq and movq, but if OptPass2MOV is called first:
  13562. addq $x, %rax
  13563. cqto
  13564. ...which is better in all ways, taking only 2 cycles to execute
  13565. and much smaller in code size.
  13566. }
  13567. { The extra register tracking is quite strenuous }
  13568. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13569. MatchInstruction(hp1, A_MOV, []) then
  13570. begin
  13571. { Update the register tracking to the MOV instruction }
  13572. CopyUsedRegs(TempTracking);
  13573. hp2 := p;
  13574. repeat
  13575. UpdateUsedRegs(tai(hp2.Next));
  13576. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13577. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13578. OptPass2ADD get called again }
  13579. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13580. begin
  13581. { Reset the tracking to the current instruction }
  13582. RestoreUsedRegs(TempTracking);
  13583. ReleaseUsedRegs(TempTracking);
  13584. Result := True;
  13585. Exit;
  13586. end;
  13587. { Reset the tracking to the current instruction }
  13588. RestoreUsedRegs(TempTracking);
  13589. ReleaseUsedRegs(TempTracking);
  13590. { If OptPass2MOV returned True, we don't need to set Result to
  13591. True if hp1 didn't change because the ADD instruction didn't
  13592. get modified and we'll be evaluating hp1 again when the
  13593. peephole optimizer reaches it }
  13594. end;
  13595. { Change:
  13596. add %reg2,%reg1
  13597. (%reg2 not modified in between)
  13598. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13599. To:
  13600. mov/s/z #(%reg1,%reg2),%reg1
  13601. }
  13602. if (taicpu(p).oper[0]^.typ = top_reg) and
  13603. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13604. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13605. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13606. (
  13607. (
  13608. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13609. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13610. { r/esp cannot be an index }
  13611. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13612. ) or (
  13613. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13614. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13615. )
  13616. ) and (
  13617. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13618. (
  13619. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13620. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13621. MemRegisterNotUsedLater
  13622. )
  13623. ) then
  13624. begin
  13625. if (
  13626. { Instructions are guaranteed to be adjacent on -O2 and under }
  13627. (cs_opt_level3 in current_settings.optimizerswitches) and
  13628. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13629. ) then
  13630. begin
  13631. { If the other register is used in between, move the MOV
  13632. instruction to right after the ADD instruction so a
  13633. saving can still be made }
  13634. Asml.Remove(hp1);
  13635. Asml.InsertAfter(hp1, p);
  13636. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13637. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13638. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13639. RemoveCurrentp(p, hp1);
  13640. end
  13641. else
  13642. begin
  13643. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13644. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13645. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13646. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13647. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13648. { hp1 may not be the immediate next instruction under -O3 }
  13649. RemoveCurrentp(p)
  13650. else
  13651. RemoveCurrentp(p, hp1);
  13652. end;
  13653. Result := True;
  13654. Exit;
  13655. end;
  13656. { Change:
  13657. addl/q $x,%reg1
  13658. movl/q %reg1,%reg2
  13659. To:
  13660. leal/q $x(%reg1),%reg2
  13661. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13662. Breaks the dependency chain.
  13663. }
  13664. if (taicpu(p).oper[0]^.typ = top_const) and
  13665. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13666. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13667. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13668. (
  13669. { Instructions are guaranteed to be adjacent on -O2 and under }
  13670. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13671. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13672. ) then
  13673. begin
  13674. TransferUsedRegs(TmpUsedRegs);
  13675. hp2 := p;
  13676. repeat
  13677. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13678. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13679. if (
  13680. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13681. not (cs_opt_size in current_settings.optimizerswitches) or
  13682. (
  13683. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13684. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13685. )
  13686. ) then
  13687. begin
  13688. { Change the MOV instruction to a LEA instruction, and update the
  13689. first operand }
  13690. reference_reset(NewRef, 1, []);
  13691. NewRef.base := taicpu(p).oper[1]^.reg;
  13692. NewRef.scalefactor := 1;
  13693. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13694. taicpu(hp1).opcode := A_LEA;
  13695. taicpu(hp1).loadref(0, NewRef);
  13696. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13697. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13698. begin
  13699. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13700. { Move what is now the LEA instruction to before the ADD instruction }
  13701. Asml.Remove(hp1);
  13702. Asml.InsertBefore(hp1, p);
  13703. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13704. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13705. p := hp1;
  13706. end
  13707. else
  13708. begin
  13709. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13710. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13711. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13712. { hp1 may not be the immediate next instruction under -O3 }
  13713. RemoveCurrentp(p)
  13714. else
  13715. RemoveCurrentp(p, hp1);
  13716. end;
  13717. Result := True;
  13718. end;
  13719. end;
  13720. end;
  13721. end;
  13722. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13723. var
  13724. SubReg: TSubRegister;
  13725. hp1, hp2: tai;
  13726. CallJmp: Boolean;
  13727. begin
  13728. Result := False;
  13729. CallJmp := False;
  13730. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13731. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13732. with taicpu(p).oper[0]^.ref^ do
  13733. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13734. if (offset = 0) then
  13735. begin
  13736. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13737. begin
  13738. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13739. taicpu(p).opcode := A_ADD;
  13740. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13741. Result := True;
  13742. end
  13743. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13744. begin
  13745. if (base <> NR_NO) then
  13746. begin
  13747. if (scalefactor <= 1) then
  13748. begin
  13749. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13750. taicpu(p).opcode := A_ADD;
  13751. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13752. Result := True;
  13753. end;
  13754. end
  13755. else
  13756. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13757. if (scalefactor in [2, 4, 8]) then
  13758. begin
  13759. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13760. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13761. taicpu(p).opcode := A_SHL;
  13762. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13763. Result := True;
  13764. end;
  13765. end;
  13766. end
  13767. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  13768. lot of latency, so break off the offset if %reg3 is used soon
  13769. afterwards }
  13770. else if not (cs_opt_size in current_settings.optimizerswitches) and
  13771. { If 3-component addresses don't have additional latency, don't
  13772. perform this optimisation }
  13773. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  13774. GetNextInstruction(p, hp1) and
  13775. (
  13776. (
  13777. { Permit jumps and calls since they have a larger degree of overhead }
  13778. (
  13779. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  13780. (
  13781. { ... unless the register specifies the location }
  13782. (taicpu(hp1).ops > 0) and
  13783. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13784. )
  13785. ) and
  13786. (
  13787. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13788. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13789. )
  13790. )
  13791. or
  13792. (
  13793. { Check up to two instructions ahead }
  13794. GetNextInstruction(hp1, hp2) and
  13795. (
  13796. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  13797. (
  13798. { Same as above }
  13799. (taicpu(hp2).ops > 0) and
  13800. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  13801. )
  13802. ) and
  13803. (
  13804. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13805. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  13806. )
  13807. )
  13808. ) then
  13809. begin
  13810. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  13811. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  13812. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13813. offset := 0;
  13814. if Assigned(symbol) or Assigned(relsymbol) then
  13815. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  13816. else
  13817. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  13818. { Inserting before the next instruction rather than after the
  13819. current instruction gives more accurate register tracking }
  13820. asml.InsertBefore(hp2, hp1);
  13821. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  13822. Result := True;
  13823. end;
  13824. end;
  13825. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13826. var
  13827. hp1, hp2: tai;
  13828. NewRef: TReference;
  13829. Distance: Cardinal;
  13830. TempTracking: TAllUsedRegs;
  13831. begin
  13832. Result := False;
  13833. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13834. MatchOpType(taicpu(p),top_const,top_reg) then
  13835. begin
  13836. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13837. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13838. (hp1.typ <> ait_instruction) or
  13839. not
  13840. (
  13841. (cs_opt_level3 in current_settings.optimizerswitches) or
  13842. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13843. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13844. ) then
  13845. Exit;
  13846. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13847. subq $x, %rax
  13848. movq %rax, %rdx
  13849. sarq $63, %rdx
  13850. (%rax still in use)
  13851. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13852. leaq $-x(%rax),%rdx
  13853. movq $x, %rax
  13854. sarq $63, %rdx
  13855. ...which is okay since it breaks the dependency chain between
  13856. subq and movq, but if OptPass2MOV is called first:
  13857. subq $x, %rax
  13858. cqto
  13859. ...which is better in all ways, taking only 2 cycles to execute
  13860. and much smaller in code size.
  13861. }
  13862. { The extra register tracking is quite strenuous }
  13863. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13864. MatchInstruction(hp1, A_MOV, []) then
  13865. begin
  13866. { Update the register tracking to the MOV instruction }
  13867. CopyUsedRegs(TempTracking);
  13868. hp2 := p;
  13869. repeat
  13870. UpdateUsedRegs(tai(hp2.Next));
  13871. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13872. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13873. OptPass2SUB get called again }
  13874. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13875. begin
  13876. { Reset the tracking to the current instruction }
  13877. RestoreUsedRegs(TempTracking);
  13878. ReleaseUsedRegs(TempTracking);
  13879. Result := True;
  13880. Exit;
  13881. end;
  13882. { Reset the tracking to the current instruction }
  13883. RestoreUsedRegs(TempTracking);
  13884. ReleaseUsedRegs(TempTracking);
  13885. { If OptPass2MOV returned True, we don't need to set Result to
  13886. True if hp1 didn't change because the SUB instruction didn't
  13887. get modified and we'll be evaluating hp1 again when the
  13888. peephole optimizer reaches it }
  13889. end;
  13890. { Change:
  13891. subl/q $x,%reg1
  13892. movl/q %reg1,%reg2
  13893. To:
  13894. leal/q $-x(%reg1),%reg2
  13895. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13896. Breaks the dependency chain and potentially permits the removal of
  13897. a CMP instruction if one follows.
  13898. }
  13899. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13900. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13901. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13902. (
  13903. { Instructions are guaranteed to be adjacent on -O2 and under }
  13904. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13905. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13906. ) then
  13907. begin
  13908. TransferUsedRegs(TmpUsedRegs);
  13909. hp2 := p;
  13910. repeat
  13911. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13912. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13913. if (
  13914. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13915. not (cs_opt_size in current_settings.optimizerswitches) or
  13916. (
  13917. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13918. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13919. )
  13920. ) then
  13921. begin
  13922. { Change the MOV instruction to a LEA instruction, and update the
  13923. first operand }
  13924. reference_reset(NewRef, 1, []);
  13925. NewRef.base := taicpu(p).oper[1]^.reg;
  13926. NewRef.scalefactor := 1;
  13927. NewRef.offset := -taicpu(p).oper[0]^.val;
  13928. taicpu(hp1).opcode := A_LEA;
  13929. taicpu(hp1).loadref(0, NewRef);
  13930. TransferUsedRegs(TmpUsedRegs);
  13931. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13932. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13933. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13934. begin
  13935. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13936. { Move what is now the LEA instruction to before the SUB instruction }
  13937. Asml.Remove(hp1);
  13938. Asml.InsertBefore(hp1, p);
  13939. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13940. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13941. p := hp1;
  13942. end
  13943. else
  13944. begin
  13945. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13946. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13947. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13948. { hp1 may not be the immediate next instruction under -O3 }
  13949. RemoveCurrentp(p)
  13950. else
  13951. RemoveCurrentp(p, hp1);
  13952. end;
  13953. Result := True;
  13954. end;
  13955. end;
  13956. end;
  13957. end;
  13958. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13959. begin
  13960. { we can skip all instructions not messing with the stack pointer }
  13961. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13962. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13963. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13964. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13965. ({(taicpu(hp1).ops=0) or }
  13966. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13967. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13968. ) and }
  13969. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13970. )
  13971. ) do
  13972. GetNextInstruction(hp1,hp1);
  13973. Result:=assigned(hp1);
  13974. end;
  13975. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13976. var
  13977. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  13978. begin
  13979. Result:=false;
  13980. hp5:=nil;
  13981. hp6:=nil;
  13982. hp7:=nil;
  13983. hp8:=nil;
  13984. { replace
  13985. leal(q) x(<stackpointer>),<stackpointer>
  13986. <optional .seh_stackalloc ...>
  13987. <optional .seh_endprologue ...>
  13988. call procname
  13989. <optional NOP>
  13990. leal(q) -x(<stackpointer>),<stackpointer>
  13991. <optional VZEROUPPER>
  13992. ret
  13993. by
  13994. jmp procname
  13995. but do it only on level 4 because it destroys stack back traces
  13996. }
  13997. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13998. MatchOpType(taicpu(p),top_ref,top_reg) and
  13999. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14000. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14001. { the -8, -24, -40 are not required, but bail out early if possible,
  14002. higher values are unlikely }
  14003. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14004. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14005. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14006. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14007. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14008. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14009. GetNextInstruction(p, hp1) and
  14010. { Take a copy of hp1 }
  14011. SetAndTest(hp1, hp4) and
  14012. { trick to skip label }
  14013. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14014. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14015. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14016. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14017. SkipSimpleInstructions(hp1) and
  14018. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14019. GetNextInstruction(hp1, hp2) and
  14020. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14021. { skip nop instruction on win64 }
  14022. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14023. SetAndTest(hp2,hp6) and
  14024. GetNextInstruction(hp2,hp2) and
  14025. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14026. ) and
  14027. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14028. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14029. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14030. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14031. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14032. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14033. { Segment register will be NR_NO }
  14034. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14035. GetNextInstruction(hp2, hp3) and
  14036. { trick to skip label }
  14037. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14038. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14039. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14040. SetAndTest(hp3,hp5) and
  14041. GetNextInstruction(hp3,hp3) and
  14042. MatchInstruction(hp3,A_RET,[S_NO])
  14043. )
  14044. ) and
  14045. (taicpu(hp3).ops=0) then
  14046. begin
  14047. taicpu(hp1).opcode := A_JMP;
  14048. taicpu(hp1).is_jmp := true;
  14049. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14050. { search for the stackalloc directive and remove it }
  14051. hp7:=tai(p.next);
  14052. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14053. begin
  14054. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14055. begin
  14056. { sanity check }
  14057. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14058. Internalerror(2024012201);
  14059. hp8:=tai(hp7.next);
  14060. RemoveInstruction(tai(hp7));
  14061. hp7:=hp8;
  14062. break;
  14063. end
  14064. else
  14065. hp7:=tai(hp7.next);
  14066. end;
  14067. RemoveCurrentP(p, hp4);
  14068. RemoveInstruction(hp2);
  14069. RemoveInstruction(hp3);
  14070. { if there is a vzeroupper instruction then move it before the jmp }
  14071. if Assigned(hp5) then
  14072. begin
  14073. AsmL.Remove(hp5);
  14074. ASmL.InsertBefore(hp5,hp1)
  14075. end;
  14076. { remove nop on win64 }
  14077. if Assigned(hp6) then
  14078. RemoveInstruction(hp6);
  14079. Result:=true;
  14080. end;
  14081. end;
  14082. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14083. {$ifdef x86_64}
  14084. var
  14085. hp1, hp2, hp3, hp4, hp5: tai;
  14086. {$endif x86_64}
  14087. begin
  14088. Result:=false;
  14089. {$ifdef x86_64}
  14090. hp5:=nil;
  14091. { replace
  14092. push %rax
  14093. call procname
  14094. pop %rcx
  14095. ret
  14096. by
  14097. jmp procname
  14098. but do it only on level 4 because it destroys stack back traces
  14099. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14100. for all supported calling conventions
  14101. }
  14102. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14103. MatchOpType(taicpu(p),top_reg) and
  14104. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14105. GetNextInstruction(p, hp1) and
  14106. { Take a copy of hp1 }
  14107. SetAndTest(hp1, hp4) and
  14108. { trick to skip label }
  14109. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14110. SkipSimpleInstructions(hp1) and
  14111. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14112. GetNextInstruction(hp1, hp2) and
  14113. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14114. MatchOpType(taicpu(hp2),top_reg) and
  14115. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14116. GetNextInstruction(hp2, hp3) and
  14117. { trick to skip label }
  14118. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14119. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14120. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14121. SetAndTest(hp3,hp5) and
  14122. GetNextInstruction(hp3,hp3) and
  14123. MatchInstruction(hp3,A_RET,[S_NO])
  14124. )
  14125. ) and
  14126. (taicpu(hp3).ops=0) then
  14127. begin
  14128. taicpu(hp1).opcode := A_JMP;
  14129. taicpu(hp1).is_jmp := true;
  14130. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14131. RemoveCurrentP(p, hp4);
  14132. RemoveInstruction(hp2);
  14133. RemoveInstruction(hp3);
  14134. if Assigned(hp5) then
  14135. begin
  14136. AsmL.Remove(hp5);
  14137. ASmL.InsertBefore(hp5,hp1)
  14138. end;
  14139. Result:=true;
  14140. end;
  14141. {$endif x86_64}
  14142. end;
  14143. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14144. var
  14145. Value, RegName: string;
  14146. hp1: tai;
  14147. begin
  14148. Result:=false;
  14149. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14150. begin
  14151. case taicpu(p).oper[0]^.val of
  14152. 0:
  14153. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14154. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14155. (
  14156. { See if we can still convert the instruction }
  14157. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14158. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14159. ) then
  14160. begin
  14161. { change "mov $0,%reg" into "xor %reg,%reg" }
  14162. taicpu(p).opcode := A_XOR;
  14163. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14164. Result := True;
  14165. {$ifdef x86_64}
  14166. end
  14167. else if (taicpu(p).opsize = S_Q) then
  14168. begin
  14169. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14170. { The actual optimization }
  14171. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14172. taicpu(p).changeopsize(S_L);
  14173. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14174. Result := True;
  14175. end;
  14176. $1..$FFFFFFFF:
  14177. begin
  14178. { Code size reduction by J. Gareth "Kit" Moreton }
  14179. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14180. case taicpu(p).opsize of
  14181. S_Q:
  14182. begin
  14183. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14184. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14185. { The actual optimization }
  14186. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14187. taicpu(p).changeopsize(S_L);
  14188. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14189. Result := True;
  14190. end;
  14191. else
  14192. { Do nothing };
  14193. end;
  14194. {$endif x86_64}
  14195. end;
  14196. -1:
  14197. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14198. if (cs_opt_size in current_settings.optimizerswitches) and
  14199. (taicpu(p).opsize <> S_B) and
  14200. (
  14201. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14202. (
  14203. { See if we can still convert the instruction }
  14204. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14205. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14206. )
  14207. ) then
  14208. begin
  14209. { change "mov $-1,%reg" into "or $-1,%reg" }
  14210. { NOTES:
  14211. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14212. - This operation creates a false dependency on the register, so only do it when optimising for size
  14213. - 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
  14214. }
  14215. taicpu(p).opcode := A_OR;
  14216. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14217. Result := True;
  14218. end;
  14219. else
  14220. { Do nothing };
  14221. end;
  14222. end;
  14223. end;
  14224. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14225. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14226. begin
  14227. Result := False;
  14228. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14229. Exit;
  14230. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14231. so don't bother optimising }
  14232. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14233. Exit;
  14234. if (taicpu(p).oper[0]^.typ <> top_const) or
  14235. { If the value can fit into an 8-bit signed integer, a smaller
  14236. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14237. falls within this range }
  14238. (
  14239. (taicpu(p).oper[0]^.val > -128) and
  14240. (taicpu(p).oper[0]^.val <= 127)
  14241. ) then
  14242. Exit;
  14243. { If we're optimising for size, this is acceptable }
  14244. if (cs_opt_size in current_settings.optimizerswitches) then
  14245. Exit(True);
  14246. if (taicpu(p).oper[1]^.typ = top_reg) and
  14247. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14248. Exit(True);
  14249. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14250. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14251. Exit(True);
  14252. end;
  14253. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14254. var
  14255. hp1: tai;
  14256. Value: TCGInt;
  14257. begin
  14258. Result := False;
  14259. if MatchOpType(taicpu(p), top_const, top_reg) then
  14260. begin
  14261. { Detect:
  14262. andw x, %ax (0 <= x < $8000)
  14263. ...
  14264. movzwl %ax,%eax
  14265. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14266. }
  14267. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14268. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14269. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14270. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14271. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14272. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14273. begin
  14274. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14275. taicpu(hp1).opcode := A_CWDE;
  14276. taicpu(hp1).clearop(0);
  14277. taicpu(hp1).clearop(1);
  14278. taicpu(hp1).ops := 0;
  14279. { A change was made, but not with p, so don't set Result, but
  14280. notify the compiler that a change was made }
  14281. Include(OptsToCheck, aoc_ForceNewIteration);
  14282. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14283. end;
  14284. end;
  14285. { If "not x" is a power of 2 (popcnt = 1), change:
  14286. and $x, %reg/ref
  14287. To:
  14288. btr lb(x), %reg/ref
  14289. }
  14290. if IsBTXAcceptable(p) and
  14291. (
  14292. { Make sure a TEST doesn't follow that plays with the register }
  14293. not GetNextInstruction(p, hp1) or
  14294. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14295. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14296. ) then
  14297. begin
  14298. {$push}{$R-}{$Q-}
  14299. { Value is a sign-extended 32-bit integer - just correct it
  14300. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14301. checks to see if this operand is an immediate. }
  14302. Value := not taicpu(p).oper[0]^.val;
  14303. {$pop}
  14304. {$ifdef x86_64}
  14305. if taicpu(p).opsize = S_L then
  14306. {$endif x86_64}
  14307. Value := Value and $FFFFFFFF;
  14308. if (PopCnt(QWord(Value)) = 1) then
  14309. begin
  14310. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14311. taicpu(p).opcode := A_BTR;
  14312. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14313. Result := True;
  14314. Exit;
  14315. end;
  14316. end;
  14317. end;
  14318. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14319. begin
  14320. Result := False;
  14321. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14322. Exit;
  14323. { Convert:
  14324. movswl %ax,%eax -> cwtl
  14325. movslq %eax,%rax -> cdqe
  14326. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14327. refer to the same opcode and depends only on the assembler's
  14328. current operand-size attribute. [Kit]
  14329. }
  14330. with taicpu(p) do
  14331. case opsize of
  14332. S_WL:
  14333. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14334. begin
  14335. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14336. opcode := A_CWDE;
  14337. clearop(0);
  14338. clearop(1);
  14339. ops := 0;
  14340. Result := True;
  14341. end;
  14342. {$ifdef x86_64}
  14343. S_LQ:
  14344. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14345. begin
  14346. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14347. opcode := A_CDQE;
  14348. clearop(0);
  14349. clearop(1);
  14350. ops := 0;
  14351. Result := True;
  14352. end;
  14353. {$endif x86_64}
  14354. else
  14355. ;
  14356. end;
  14357. end;
  14358. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14359. var
  14360. hp1, hp2: tai;
  14361. IdentityMask, Shift: TCGInt;
  14362. LimitSize: Topsize;
  14363. DoNotMerge: Boolean;
  14364. begin
  14365. Result := False;
  14366. { All these optimisations work on "shr const,%reg" }
  14367. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14368. Exit;
  14369. DoNotMerge := False;
  14370. Shift := taicpu(p).oper[0]^.val;
  14371. LimitSize := taicpu(p).opsize;
  14372. hp1 := p;
  14373. repeat
  14374. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14375. Break;
  14376. { Detect:
  14377. shr x, %reg
  14378. and y, %reg
  14379. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14380. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14381. }
  14382. case taicpu(hp1).opcode of
  14383. A_AND:
  14384. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14385. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14386. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14387. begin
  14388. { Make sure the FLAGS register isn't in use }
  14389. TransferUsedRegs(TmpUsedRegs);
  14390. hp2 := p;
  14391. repeat
  14392. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14393. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14394. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14395. begin
  14396. { Generate the identity mask }
  14397. case taicpu(p).opsize of
  14398. S_B:
  14399. IdentityMask := $FF shr Shift;
  14400. S_W:
  14401. IdentityMask := $FFFF shr Shift;
  14402. S_L:
  14403. IdentityMask := $FFFFFFFF shr Shift;
  14404. {$ifdef x86_64}
  14405. S_Q:
  14406. { We need to force the operands to be unsigned 64-bit
  14407. integers otherwise the wrong value is generated }
  14408. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14409. {$endif x86_64}
  14410. else
  14411. InternalError(2022081501);
  14412. end;
  14413. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14414. begin
  14415. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14416. { All the possible 1 bits are covered, so we can remove the AND }
  14417. hp2 := tai(hp1.Previous);
  14418. RemoveInstruction(hp1);
  14419. { p wasn't actually changed, so don't set Result to True,
  14420. but a change was nonetheless made elsewhere }
  14421. Include(OptsToCheck, aoc_ForceNewIteration);
  14422. { Do another pass in case other AND or MOVZX instructions
  14423. follow }
  14424. hp1 := hp2;
  14425. Continue;
  14426. end;
  14427. end;
  14428. end;
  14429. A_TEST, A_CMP, A_Jcc:
  14430. { Skip over conditional jumps and relevant comparisons }
  14431. Continue;
  14432. A_MOVZX:
  14433. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14434. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14435. begin
  14436. { Since the original register is being read as is, subsequent
  14437. SHRs must not be merged at this point }
  14438. DoNotMerge := True;
  14439. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14440. begin
  14441. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14442. begin
  14443. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14444. { All the possible 1 bits are covered, so we can remove the AND }
  14445. hp2 := tai(hp1.Previous);
  14446. RemoveInstruction(hp1);
  14447. hp1 := hp2;
  14448. end
  14449. else { Different register target }
  14450. begin
  14451. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14452. taicpu(hp1).opcode := A_MOV;
  14453. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14454. case taicpu(hp1).opsize of
  14455. S_BW:
  14456. taicpu(hp1).opsize := S_W;
  14457. S_BL, S_WL:
  14458. taicpu(hp1).opsize := S_L;
  14459. else
  14460. InternalError(2022081503);
  14461. end;
  14462. end;
  14463. end
  14464. else if (Shift > 0) and
  14465. (taicpu(p).opsize = S_W) and
  14466. (taicpu(hp1).opsize = S_WL) and
  14467. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14468. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14469. begin
  14470. { Detect:
  14471. shr x, %ax (x > 0)
  14472. ...
  14473. movzwl %ax,%eax
  14474. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14475. }
  14476. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14477. taicpu(hp1).opcode := A_CWDE;
  14478. taicpu(hp1).clearop(0);
  14479. taicpu(hp1).clearop(1);
  14480. taicpu(hp1).ops := 0;
  14481. end;
  14482. { Move onto the next instruction }
  14483. Continue;
  14484. end;
  14485. A_SHL, A_SAL, A_SHR:
  14486. if (taicpu(hp1).opsize <= LimitSize) and
  14487. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14488. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14489. begin
  14490. { Make sure the sizes don't exceed the register size limit
  14491. (measured by the shift value falling below the limit) }
  14492. if taicpu(hp1).opsize < LimitSize then
  14493. LimitSize := taicpu(hp1).opsize;
  14494. if taicpu(hp1).opcode = A_SHR then
  14495. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14496. else
  14497. begin
  14498. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14499. DoNotMerge := True;
  14500. end;
  14501. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14502. Break;
  14503. { Since we've established that the combined shift is within
  14504. limits, we can actually combine the adjacent SHR
  14505. instructions even if they're different sizes }
  14506. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14507. begin
  14508. hp2 := tai(hp1.Previous);
  14509. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14510. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14511. RemoveInstruction(hp1);
  14512. hp1 := hp2;
  14513. end;
  14514. { Move onto the next instruction }
  14515. Continue;
  14516. end;
  14517. else
  14518. ;
  14519. end;
  14520. Break;
  14521. until False;
  14522. { Detect the following (looking backwards):
  14523. shr %cl,%reg
  14524. shr x, %reg
  14525. Swap the two SHR instructions to minimise a pipeline stall.
  14526. }
  14527. if GetLastInstruction(p, hp1) and
  14528. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14529. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14530. { First operand will be %cl }
  14531. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14532. { Just to be sure }
  14533. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14534. begin
  14535. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14536. { Moving the entries this way ensures the register tracking remains correct }
  14537. Asml.Remove(p);
  14538. Asml.InsertBefore(p, hp1);
  14539. p := hp1;
  14540. { Don't set Result to True because the current instruction is now
  14541. "shr %cl,%reg" and there's nothing more we can do with it }
  14542. end;
  14543. end;
  14544. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14545. var
  14546. hp1, hp2: tai;
  14547. Opposite, SecondOpposite: TAsmOp;
  14548. NewCond: TAsmCond;
  14549. begin
  14550. Result := False;
  14551. { Change:
  14552. add/sub 128,(dest)
  14553. To:
  14554. sub/add -128,(dest)
  14555. This generaally takes fewer bytes to encode because -128 can be stored
  14556. in a signed byte, whereas +128 cannot.
  14557. }
  14558. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14559. begin
  14560. if taicpu(p).opcode = A_ADD then
  14561. Opposite := A_SUB
  14562. else
  14563. Opposite := A_ADD;
  14564. { Be careful if the flags are in use, because the CF flag inverts
  14565. when changing from ADD to SUB and vice versa }
  14566. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14567. GetNextInstruction(p, hp1) then
  14568. begin
  14569. TransferUsedRegs(TmpUsedRegs);
  14570. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14571. hp2 := hp1;
  14572. { Scan ahead to check if everything's safe }
  14573. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14574. begin
  14575. if (hp1.typ <> ait_instruction) then
  14576. { Probably unsafe since the flags are still in use }
  14577. Exit;
  14578. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14579. { Stop searching at an unconditional jump }
  14580. Break;
  14581. if not
  14582. (
  14583. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14584. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14585. ) and
  14586. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14587. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14588. Exit;
  14589. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14590. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14591. { Move to the next instruction }
  14592. GetNextInstruction(hp1, hp1);
  14593. end;
  14594. while Assigned(hp2) and (hp2 <> hp1) do
  14595. begin
  14596. NewCond := C_None;
  14597. case taicpu(hp2).condition of
  14598. C_A, C_NBE:
  14599. NewCond := C_BE;
  14600. C_B, C_C, C_NAE:
  14601. NewCond := C_AE;
  14602. C_AE, C_NB, C_NC:
  14603. NewCond := C_B;
  14604. C_BE, C_NA:
  14605. NewCond := C_A;
  14606. else
  14607. { No change needed };
  14608. end;
  14609. if NewCond <> C_None then
  14610. begin
  14611. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14612. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14613. taicpu(hp2).condition := NewCond;
  14614. end
  14615. else
  14616. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14617. begin
  14618. { Because of the flipping of the carry bit, to ensure
  14619. the operation remains equivalent, ADC becomes SBB
  14620. and vice versa, and the constant is not-inverted.
  14621. If multiple ADCs or SBBs appear in a row, each one
  14622. changed causes the carry bit to invert, so they all
  14623. need to be flipped }
  14624. if taicpu(hp2).opcode = A_ADC then
  14625. SecondOpposite := A_SBB
  14626. else
  14627. SecondOpposite := A_ADC;
  14628. if taicpu(hp2).oper[0]^.typ <> top_const then
  14629. { Should have broken out of this optimisation already }
  14630. InternalError(2021112901);
  14631. 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]^) + ' -> ' +
  14632. 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);
  14633. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14634. taicpu(hp2).opcode := SecondOpposite;
  14635. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14636. end;
  14637. { Move to the next instruction }
  14638. GetNextInstruction(hp2, hp2);
  14639. end;
  14640. if (hp2 <> hp1) then
  14641. InternalError(2021111501);
  14642. end;
  14643. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14644. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14645. taicpu(p).opcode := Opposite;
  14646. taicpu(p).oper[0]^.val := -128;
  14647. { No further optimisations can be made on this instruction, so move
  14648. onto the next one to save time }
  14649. p := tai(p.Next);
  14650. UpdateUsedRegs(p);
  14651. Result := True;
  14652. Exit;
  14653. end;
  14654. { Detect:
  14655. add/sub %reg2,(dest)
  14656. add/sub x, (dest)
  14657. (dest can be a register or a reference)
  14658. Swap the instructions to minimise a pipeline stall. This reverses the
  14659. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14660. optimisations could be made.
  14661. }
  14662. if (taicpu(p).oper[0]^.typ = top_reg) and
  14663. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14664. (
  14665. (
  14666. (taicpu(p).oper[1]^.typ = top_reg) and
  14667. { We can try searching further ahead if we're writing to a register }
  14668. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14669. ) or
  14670. (
  14671. (taicpu(p).oper[1]^.typ = top_ref) and
  14672. GetNextInstruction(p, hp1)
  14673. )
  14674. ) and
  14675. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14676. (taicpu(hp1).oper[0]^.typ = top_const) and
  14677. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14678. begin
  14679. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14680. TransferUsedRegs(TmpUsedRegs);
  14681. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14682. hp2 := p;
  14683. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14684. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14685. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14686. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14687. begin
  14688. asml.remove(hp1);
  14689. asml.InsertBefore(hp1, p);
  14690. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14691. Result := True;
  14692. end;
  14693. end;
  14694. end;
  14695. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14696. var
  14697. hp1: tai;
  14698. begin
  14699. Result:=false;
  14700. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14701. while GetNextInstruction(p, hp1) and
  14702. TrySwapMovCmp(p, hp1) do
  14703. begin
  14704. if MatchInstruction(hp1, A_MOV, []) then
  14705. begin
  14706. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14707. begin
  14708. { A little hacky, but since CMP doesn't read the flags, only
  14709. modify them, it's safe if they get scrambled by MOV -> XOR }
  14710. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14711. Result := PostPeepholeOptMov(hp1);
  14712. {$ifdef x86_64}
  14713. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14714. { Used to shrink instruction size }
  14715. PostPeepholeOptXor(hp1);
  14716. {$endif x86_64}
  14717. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14718. end
  14719. else
  14720. begin
  14721. Result := PostPeepholeOptMov(hp1);
  14722. {$ifdef x86_64}
  14723. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14724. { Used to shrink instruction size }
  14725. PostPeepholeOptXor(hp1);
  14726. {$endif x86_64}
  14727. end;
  14728. end;
  14729. { Enabling this flag is actually a null operation, but it marks
  14730. the code as 'modified' during this pass }
  14731. Include(OptsToCheck, aoc_ForceNewIteration);
  14732. end;
  14733. { change "cmp $0, %reg" to "test %reg, %reg" }
  14734. if MatchOpType(taicpu(p),top_const,top_reg) and
  14735. (taicpu(p).oper[0]^.val = 0) then
  14736. begin
  14737. taicpu(p).opcode := A_TEST;
  14738. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14739. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14740. Result:=true;
  14741. end;
  14742. end;
  14743. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14744. var
  14745. IsTestConstX, IsValid : Boolean;
  14746. hp1,hp2 : tai;
  14747. begin
  14748. Result:=false;
  14749. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14750. if (taicpu(p).opcode = A_TEST) then
  14751. while GetNextInstruction(p, hp1) and
  14752. TrySwapMovCmp(p, hp1) do
  14753. begin
  14754. if MatchInstruction(hp1, A_MOV, []) then
  14755. begin
  14756. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14757. begin
  14758. { A little hacky, but since TEST doesn't read the flags, only
  14759. modify them, it's safe if they get scrambled by MOV -> XOR }
  14760. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14761. Result := PostPeepholeOptMov(hp1);
  14762. {$ifdef x86_64}
  14763. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14764. { Used to shrink instruction size }
  14765. PostPeepholeOptXor(hp1);
  14766. {$endif x86_64}
  14767. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14768. end
  14769. else
  14770. begin
  14771. Result := PostPeepholeOptMov(hp1);
  14772. {$ifdef x86_64}
  14773. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14774. { Used to shrink instruction size }
  14775. PostPeepholeOptXor(hp1);
  14776. {$endif x86_64}
  14777. end;
  14778. end;
  14779. { Enabling this flag is actually a null operation, but it marks
  14780. the code as 'modified' during this pass }
  14781. Include(OptsToCheck, aoc_ForceNewIteration);
  14782. end;
  14783. { If x is a power of 2 (popcnt = 1), change:
  14784. or $x, %reg/ref
  14785. To:
  14786. bts lb(x), %reg/ref
  14787. }
  14788. if (taicpu(p).opcode = A_OR) and
  14789. IsBTXAcceptable(p) and
  14790. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14791. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14792. (
  14793. { Don't optimise if a test instruction follows }
  14794. not GetNextInstruction(p, hp1) or
  14795. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14796. ) then
  14797. begin
  14798. 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);
  14799. taicpu(p).opcode := A_BTS;
  14800. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14801. Result := True;
  14802. Exit;
  14803. end;
  14804. { If x is a power of 2 (popcnt = 1), change:
  14805. test $x, %reg/ref
  14806. je / sete / cmove (or jne / setne)
  14807. To:
  14808. bt lb(x), %reg/ref
  14809. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14810. }
  14811. if (taicpu(p).opcode = A_TEST) and
  14812. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14813. (taicpu(p).oper[0]^.typ = top_const) and
  14814. (
  14815. (cs_opt_size in current_settings.optimizerswitches) or
  14816. (
  14817. (taicpu(p).oper[1]^.typ = top_reg) and
  14818. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14819. ) or
  14820. (
  14821. (taicpu(p).oper[1]^.typ <> top_reg) and
  14822. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14823. )
  14824. ) and
  14825. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14826. { For sizes less than S_L, the byte size is equal or larger with BT,
  14827. so don't bother optimising }
  14828. (taicpu(p).opsize >= S_L) then
  14829. begin
  14830. IsValid := True;
  14831. { Check the next set of instructions, watching the FLAGS register
  14832. and the conditions used }
  14833. TransferUsedRegs(TmpUsedRegs);
  14834. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14835. hp1 := p;
  14836. hp2 := nil;
  14837. while GetNextInstruction(hp1, hp1) do
  14838. begin
  14839. if not Assigned(hp2) then
  14840. { The first instruction after TEST }
  14841. hp2 := hp1;
  14842. if (hp1.typ <> ait_instruction) then
  14843. begin
  14844. { If the flags are no longer in use, everything is fine }
  14845. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14846. IsValid := False;
  14847. Break;
  14848. end;
  14849. case taicpu(hp1).condition of
  14850. C_None:
  14851. begin
  14852. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14853. { Something is not quite normal, so play safe and don't change }
  14854. IsValid := False;
  14855. Break;
  14856. end;
  14857. C_E, C_Z, C_NE, C_NZ:
  14858. { This is fine };
  14859. else
  14860. begin
  14861. { Unsupported condition }
  14862. IsValid := False;
  14863. Break;
  14864. end;
  14865. end;
  14866. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14867. end;
  14868. if IsValid then
  14869. begin
  14870. while hp2 <> hp1 do
  14871. begin
  14872. case taicpu(hp2).condition of
  14873. C_Z, C_E:
  14874. taicpu(hp2).condition := C_NC;
  14875. C_NZ, C_NE:
  14876. taicpu(hp2).condition := C_C;
  14877. else
  14878. { Should not get this by this point }
  14879. InternalError(2022110701);
  14880. end;
  14881. GetNextInstruction(hp2, hp2);
  14882. end;
  14883. 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);
  14884. taicpu(p).opcode := A_BT;
  14885. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14886. Result := True;
  14887. Exit;
  14888. end;
  14889. end;
  14890. { removes the line marked with (x) from the sequence
  14891. and/or/xor/add/sub/... $x, %y
  14892. test/or %y, %y | test $-1, %y (x)
  14893. j(n)z _Label
  14894. as the first instruction already adjusts the ZF
  14895. %y operand may also be a reference }
  14896. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14897. MatchOperand(taicpu(p).oper[0]^,-1);
  14898. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14899. GetLastInstruction(p, hp1) and
  14900. (tai(hp1).typ = ait_instruction) and
  14901. GetNextInstruction(p,hp2) and
  14902. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14903. case taicpu(hp1).opcode Of
  14904. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14905. { These two instructions set the zero flag if the result is zero }
  14906. A_POPCNT, A_LZCNT:
  14907. begin
  14908. if (
  14909. { With POPCNT, an input of zero will set the zero flag
  14910. because the population count of zero is zero }
  14911. (taicpu(hp1).opcode = A_POPCNT) and
  14912. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14913. (
  14914. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14915. { Faster than going through the second half of the 'or'
  14916. condition below }
  14917. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14918. )
  14919. ) or (
  14920. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14921. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14922. { and in case of carry for A(E)/B(E)/C/NC }
  14923. (
  14924. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14925. (
  14926. (taicpu(hp1).opcode <> A_ADD) and
  14927. (taicpu(hp1).opcode <> A_SUB) and
  14928. (taicpu(hp1).opcode <> A_LZCNT)
  14929. )
  14930. )
  14931. ) then
  14932. begin
  14933. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14934. RemoveCurrentP(p, hp2);
  14935. Result:=true;
  14936. Exit;
  14937. end;
  14938. end;
  14939. A_SHL, A_SAL, A_SHR, A_SAR:
  14940. begin
  14941. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14942. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14943. { therefore, it's only safe to do this optimization for }
  14944. { shifts by a (nonzero) constant }
  14945. (taicpu(hp1).oper[0]^.typ = top_const) and
  14946. (taicpu(hp1).oper[0]^.val <> 0) and
  14947. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14948. { and in case of carry for A(E)/B(E)/C/NC }
  14949. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14950. begin
  14951. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14952. RemoveCurrentP(p, hp2);
  14953. Result:=true;
  14954. Exit;
  14955. end;
  14956. end;
  14957. A_DEC, A_INC, A_NEG:
  14958. begin
  14959. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14960. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14961. { and in case of carry for A(E)/B(E)/C/NC }
  14962. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14963. begin
  14964. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14965. RemoveCurrentP(p, hp2);
  14966. Result:=true;
  14967. Exit;
  14968. end;
  14969. end;
  14970. A_ANDN, A_BZHI:
  14971. begin
  14972. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14973. { Only the zero and sign flags are consistent with what the result is }
  14974. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14975. begin
  14976. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14977. RemoveCurrentP(p, hp2);
  14978. Result:=true;
  14979. Exit;
  14980. end;
  14981. end;
  14982. A_BEXTR:
  14983. begin
  14984. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14985. { Only the zero flag is set }
  14986. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14987. begin
  14988. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14989. RemoveCurrentP(p, hp2);
  14990. Result:=true;
  14991. Exit;
  14992. end;
  14993. end;
  14994. else
  14995. ;
  14996. end; { case }
  14997. { change "test $-1,%reg" into "test %reg,%reg" }
  14998. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14999. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15000. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15001. if MatchInstruction(p, A_OR, []) and
  15002. { Can only match if they're both registers }
  15003. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15004. begin
  15005. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15006. taicpu(p).opcode := A_TEST;
  15007. { No need to set Result to True, as we've done all the optimisations we can }
  15008. end;
  15009. end;
  15010. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15011. var
  15012. hp1,hp3 : tai;
  15013. {$ifndef x86_64}
  15014. hp2 : taicpu;
  15015. {$endif x86_64}
  15016. begin
  15017. Result:=false;
  15018. hp3:=nil;
  15019. {$ifndef x86_64}
  15020. { don't do this on modern CPUs, this really hurts them due to
  15021. broken call/ret pairing }
  15022. if (current_settings.optimizecputype < cpu_Pentium2) and
  15023. not(cs_create_pic in current_settings.moduleswitches) and
  15024. GetNextInstruction(p, hp1) and
  15025. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15026. MatchOpType(taicpu(hp1),top_ref) and
  15027. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15028. begin
  15029. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15030. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15031. InsertLLItem(p.previous, p, hp2);
  15032. taicpu(p).opcode := A_JMP;
  15033. taicpu(p).is_jmp := true;
  15034. RemoveInstruction(hp1);
  15035. Result:=true;
  15036. end
  15037. else
  15038. {$endif x86_64}
  15039. { replace
  15040. call procname
  15041. ret
  15042. by
  15043. jmp procname
  15044. but do it only on level 4 because it destroys stack back traces
  15045. else if the subroutine is marked as no return, remove the ret
  15046. }
  15047. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15048. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15049. GetNextInstruction(p, hp1) and
  15050. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15051. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15052. SetAndTest(hp1,hp3) and
  15053. GetNextInstruction(hp1,hp1) and
  15054. MatchInstruction(hp1,A_RET,[S_NO])
  15055. )
  15056. ) and
  15057. (taicpu(hp1).ops=0) then
  15058. begin
  15059. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15060. { we might destroy stack alignment here if we do not do a call }
  15061. (target_info.stackalign<=sizeof(SizeUInt)) then
  15062. begin
  15063. taicpu(p).opcode := A_JMP;
  15064. taicpu(p).is_jmp := true;
  15065. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15066. end
  15067. else
  15068. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15069. RemoveInstruction(hp1);
  15070. if Assigned(hp3) then
  15071. begin
  15072. AsmL.Remove(hp3);
  15073. AsmL.InsertBefore(hp3,p)
  15074. end;
  15075. Result:=true;
  15076. end;
  15077. end;
  15078. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15079. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15080. begin
  15081. case OpSize of
  15082. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15083. Result := (Val <= $FF) and (Val >= -128);
  15084. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15085. Result := (Val <= $FFFF) and (Val >= -32768);
  15086. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15087. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15088. else
  15089. Result := True;
  15090. end;
  15091. end;
  15092. var
  15093. hp1, hp2 : tai;
  15094. SizeChange: Boolean;
  15095. PreMessage: string;
  15096. begin
  15097. Result := False;
  15098. if (taicpu(p).oper[0]^.typ = top_reg) and
  15099. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15100. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15101. begin
  15102. { Change (using movzbl %al,%eax as an example):
  15103. movzbl %al, %eax movzbl %al, %eax
  15104. cmpl x, %eax testl %eax,%eax
  15105. To:
  15106. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15107. movzbl %al, %eax movzbl %al, %eax
  15108. Smaller instruction and minimises pipeline stall as the CPU
  15109. doesn't have to wait for the register to get zero-extended. [Kit]
  15110. Also allow if the smaller of the two registers is being checked,
  15111. as this still removes the false dependency.
  15112. }
  15113. if
  15114. (
  15115. (
  15116. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15117. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15118. ) or (
  15119. { If MatchOperand returns True, they must both be registers }
  15120. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15121. )
  15122. ) and
  15123. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15124. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15125. begin
  15126. 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);
  15127. asml.Remove(hp1);
  15128. asml.InsertBefore(hp1, p);
  15129. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15130. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15131. begin
  15132. taicpu(hp1).opcode := A_TEST;
  15133. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15134. end;
  15135. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15136. case taicpu(p).opsize of
  15137. S_BW, S_BL:
  15138. begin
  15139. SizeChange := taicpu(hp1).opsize <> S_B;
  15140. taicpu(hp1).changeopsize(S_B);
  15141. end;
  15142. S_WL:
  15143. begin
  15144. SizeChange := taicpu(hp1).opsize <> S_W;
  15145. taicpu(hp1).changeopsize(S_W);
  15146. end
  15147. else
  15148. InternalError(2020112701);
  15149. end;
  15150. UpdateUsedRegs(tai(p.Next));
  15151. { Check if the register is used aferwards - if not, we can
  15152. remove the movzx instruction completely }
  15153. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15154. begin
  15155. { Hp1 is a better position than p for debugging purposes }
  15156. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15157. RemoveCurrentp(p, hp1);
  15158. Result := True;
  15159. end;
  15160. if SizeChange then
  15161. DebugMsg(SPeepholeOptimization + PreMessage +
  15162. 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)
  15163. else
  15164. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15165. Exit;
  15166. end;
  15167. { Change (using movzwl %ax,%eax as an example):
  15168. movzwl %ax, %eax
  15169. movb %al, (dest) (Register is smaller than read register in movz)
  15170. To:
  15171. movb %al, (dest) (Move one back to avoid a false dependency)
  15172. movzwl %ax, %eax
  15173. }
  15174. if (taicpu(hp1).opcode = A_MOV) and
  15175. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15176. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15177. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15178. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15179. begin
  15180. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15181. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15182. asml.Remove(hp1);
  15183. asml.InsertBefore(hp1, p);
  15184. if taicpu(hp1).oper[1]^.typ = top_reg then
  15185. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15186. { Check if the register is used aferwards - if not, we can
  15187. remove the movzx instruction completely }
  15188. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15189. begin
  15190. { Hp1 is a better position than p for debugging purposes }
  15191. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15192. RemoveCurrentp(p, hp1);
  15193. Result := True;
  15194. end;
  15195. Exit;
  15196. end;
  15197. end;
  15198. end;
  15199. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15200. var
  15201. hp1: tai;
  15202. {$ifdef x86_64}
  15203. PreMessage, RegName: string;
  15204. {$endif x86_64}
  15205. begin
  15206. Result := False;
  15207. { If x is a power of 2 (popcnt = 1), change:
  15208. xor $x, %reg/ref
  15209. To:
  15210. btc lb(x), %reg/ref
  15211. }
  15212. if IsBTXAcceptable(p) and
  15213. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15214. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15215. (
  15216. { Don't optimise if a test instruction follows }
  15217. not GetNextInstruction(p, hp1) or
  15218. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15219. ) then
  15220. begin
  15221. 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);
  15222. taicpu(p).opcode := A_BTC;
  15223. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15224. Result := True;
  15225. Exit;
  15226. end;
  15227. {$ifdef x86_64}
  15228. { Code size reduction by J. Gareth "Kit" Moreton }
  15229. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15230. as this removes the REX prefix }
  15231. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15232. Exit;
  15233. if taicpu(p).oper[0]^.typ <> top_reg then
  15234. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15235. InternalError(2018011500);
  15236. case taicpu(p).opsize of
  15237. S_Q:
  15238. begin
  15239. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15240. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15241. { The actual optimization }
  15242. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15243. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15244. taicpu(p).changeopsize(S_L);
  15245. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15246. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15247. end;
  15248. else
  15249. ;
  15250. end;
  15251. {$endif x86_64}
  15252. end;
  15253. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15254. var
  15255. XReg: TRegister;
  15256. begin
  15257. Result := False;
  15258. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15259. Smaller encoding and slightly faster on some platforms (also works for
  15260. ZMM-sized registers) }
  15261. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15262. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15263. begin
  15264. XReg := taicpu(p).oper[0]^.reg;
  15265. if (taicpu(p).oper[1]^.reg = XReg) then
  15266. begin
  15267. taicpu(p).changeopsize(S_XMM);
  15268. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15269. if (cs_opt_size in current_settings.optimizerswitches) then
  15270. begin
  15271. { Change input registers to %xmm0 to reduce size. Note that
  15272. there's a risk of a false dependency doing this, so only
  15273. optimise for size here }
  15274. XReg := NR_XMM0;
  15275. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15276. end
  15277. else
  15278. begin
  15279. setsubreg(XReg, R_SUBMMX);
  15280. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15281. end;
  15282. taicpu(p).oper[0]^.reg := XReg;
  15283. taicpu(p).oper[1]^.reg := XReg;
  15284. Result := True;
  15285. end;
  15286. end;
  15287. end;
  15288. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15289. var
  15290. OperIdx: Integer;
  15291. begin
  15292. for OperIdx := 0 to p.ops - 1 do
  15293. if p.oper[OperIdx]^.typ = top_ref then
  15294. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15295. end;
  15296. end.