aoptx86.pas 757 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1Movx(var p : tai) : boolean;
  137. function OptPass1MOVXX(var p : tai) : boolean;
  138. function OptPass1OP(var p : tai) : boolean;
  139. function OptPass1LEA(var p : tai) : boolean;
  140. function OptPass1Sub(var p : tai) : boolean;
  141. function OptPass1SHLSAL(var p : tai) : boolean;
  142. function OptPass1SHR(var p : tai) : boolean;
  143. function OptPass1FSTP(var p : tai) : boolean;
  144. function OptPass1FLD(var p : tai) : boolean;
  145. function OptPass1Cmp(var p : tai) : boolean;
  146. function OptPass1PXor(var p : tai) : boolean;
  147. function OptPass1VPXor(var p: tai): boolean;
  148. function OptPass1Imul(var p : tai) : boolean;
  149. function OptPass1Jcc(var p : tai) : boolean;
  150. function OptPass1SHXX(var p: tai): boolean;
  151. function OptPass1VMOVDQ(var p: tai): Boolean;
  152. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  153. function OptPass1STCCLC(var p: tai): Boolean;
  154. function OptPass2STCCLC(var p: tai): Boolean;
  155. function OptPass2CMOVcc(var p: tai): Boolean;
  156. function OptPass2Movx(var p : tai): Boolean;
  157. function OptPass2MOV(var p : tai) : boolean;
  158. function OptPass2Imul(var p : tai) : boolean;
  159. function OptPass2Jmp(var p : tai) : boolean;
  160. function OptPass2Jcc(var p : tai) : boolean;
  161. function OptPass2Lea(var p: tai): Boolean;
  162. function OptPass2SUB(var p: tai): Boolean;
  163. function OptPass2ADD(var p : tai): Boolean;
  164. function OptPass2SETcc(var p : tai) : boolean;
  165. function OptPass2Cmp(var p: tai): Boolean;
  166. function OptPass2Test(var p: tai): Boolean;
  167. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  168. function PostPeepholeOptMov(var p : tai) : Boolean;
  169. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  170. function PostPeepholeOptXor(var p : tai) : Boolean;
  171. function PostPeepholeOptAnd(var p : tai) : boolean;
  172. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  173. function PostPeepholeOptCmp(var p : tai) : Boolean;
  174. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  175. function PostPeepholeOptCall(var p : tai) : Boolean;
  176. function PostPeepholeOptLea(var p : tai) : Boolean;
  177. function PostPeepholeOptPush(var p: tai): Boolean;
  178. function PostPeepholeOptShr(var p : tai) : boolean;
  179. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  180. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  181. function PostPeepholeOptRET(var p: tai): Boolean;
  182. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  183. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  184. function TrySwapMovOp(var p, hp1: tai): Boolean;
  185. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  186. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  187. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  188. { Processor-dependent reference optimisation }
  189. class procedure OptimizeRefs(var p: taicpu); static;
  190. end;
  191. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  195. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  196. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  197. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  198. {$if max_operands>2}
  199. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  200. {$endif max_operands>2}
  201. function RefsEqual(const r1, r2: treference): boolean;
  202. { Like RefsEqual, but doesn't compare the offsets }
  203. function RefsAlmostEqual(const r1, r2: treference): boolean;
  204. { Note that Result is set to True if the references COULD overlap but the
  205. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  206. might still overlap because %reg2 could be equal to %reg1-4 }
  207. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  208. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  209. { returns true, if ref is a reference using only the registers passed as base and index
  210. and having an offset }
  211. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  212. implementation
  213. uses
  214. cutils,verbose,
  215. systems,
  216. globals,
  217. cpuinfo,
  218. procinfo,
  219. paramgr,
  220. aasmbase,
  221. aoptbase,aoptutils,
  222. symconst,symsym,
  223. cgx86,
  224. itcpugas;
  225. {$ifndef 8086}
  226. const
  227. MAX_CMOV_INSTRUCTIONS = 4;
  228. MAX_CMOV_REGISTERS = 8;
  229. type
  230. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  231. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  232. tsProcessed);
  233. { For OptPass2Jcc }
  234. TCMOVTracking = object
  235. private
  236. CMOVScore, ConstCount: LongInt;
  237. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  238. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  239. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  240. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  241. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  242. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  243. fOptimizer: TX86AsmOptimizer;
  244. fLabel: TAsmSymbol;
  245. fInsertionPoint,
  246. fCondition,
  247. fInitialJump,
  248. fFirstMovBlock,
  249. fFirstMovBlockStop,
  250. fSecondJump,
  251. fThirdJump,
  252. fSecondMovBlock,
  253. fSecondMovBlockStop,
  254. fMidLabel,
  255. fEndLabel,
  256. fAllocationRange: tai;
  257. fState: TCMovTrackingState;
  258. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  259. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  260. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  261. public
  262. RegisterTracking: TAllUsedRegs;
  263. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  264. destructor Done;
  265. procedure Process(out new_p: tai);
  266. property State: TCMovTrackingState read fState;
  267. end;
  268. PCMOVTracking = ^TCMOVTracking;
  269. {$endif 8086}
  270. {$ifdef DEBUG_AOPTCPU}
  271. const
  272. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  273. {$else DEBUG_AOPTCPU}
  274. { Empty strings help the optimizer to remove string concatenations that won't
  275. ever appear to the user on release builds. [Kit] }
  276. const
  277. SPeepholeOptimization = '';
  278. {$endif DEBUG_AOPTCPU}
  279. LIST_STEP_SIZE = 4;
  280. type
  281. TJumpTrackingItem = class(TLinkedListItem)
  282. private
  283. FSymbol: TAsmSymbol;
  284. FRefs: LongInt;
  285. public
  286. constructor Create(ASymbol: TAsmSymbol);
  287. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. property Symbol: TAsmSymbol read FSymbol;
  289. property Refs: LongInt read FRefs;
  290. end;
  291. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  292. begin
  293. inherited Create;
  294. FSymbol := ASymbol;
  295. FRefs := 0;
  296. end;
  297. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  298. begin
  299. Inc(FRefs);
  300. end;
  301. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  302. begin
  303. result :=
  304. (instr.typ = ait_instruction) and
  305. (taicpu(instr).opcode = op) and
  306. ((opsize = []) or (taicpu(instr).opsize in opsize));
  307. end;
  308. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  309. begin
  310. result :=
  311. (instr.typ = ait_instruction) and
  312. ((taicpu(instr).opcode = op1) or
  313. (taicpu(instr).opcode = op2)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  318. begin
  319. result :=
  320. (instr.typ = ait_instruction) and
  321. ((taicpu(instr).opcode = op1) or
  322. (taicpu(instr).opcode = op2) or
  323. (taicpu(instr).opcode = op3)
  324. ) and
  325. ((opsize = []) or (taicpu(instr).opsize in opsize));
  326. end;
  327. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  328. const opsize : topsizes) : boolean;
  329. var
  330. op : TAsmOp;
  331. begin
  332. result:=false;
  333. if (instr.typ <> ait_instruction) or
  334. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  335. exit;
  336. for op in ops do
  337. begin
  338. if taicpu(instr).opcode = op then
  339. begin
  340. result:=true;
  341. exit;
  342. end;
  343. end;
  344. end;
  345. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  346. begin
  347. result := (oper.typ = top_reg) and (oper.reg = reg);
  348. end;
  349. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  350. begin
  351. result := (oper.typ = top_const) and (oper.val = a);
  352. end;
  353. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  354. begin
  355. result := oper1.typ = oper2.typ;
  356. if result then
  357. case oper1.typ of
  358. top_const:
  359. Result:=oper1.val = oper2.val;
  360. top_reg:
  361. Result:=oper1.reg = oper2.reg;
  362. top_ref:
  363. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  364. else
  365. internalerror(2013102801);
  366. end
  367. end;
  368. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  369. begin
  370. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  371. if result then
  372. case oper1.typ of
  373. top_const:
  374. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  375. top_reg:
  376. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  377. top_ref:
  378. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  379. else
  380. internalerror(2020052401);
  381. end
  382. end;
  383. function RefsEqual(const r1, r2: treference): boolean;
  384. begin
  385. RefsEqual :=
  386. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  387. (r1.relsymbol = r2.relsymbol) and
  388. (r1.segment = r2.segment) and (r1.base = r2.base) and
  389. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  390. (r1.offset = r2.offset) and
  391. (r1.volatility + r2.volatility = []);
  392. end;
  393. function RefsAlmostEqual(const r1, r2: treference): boolean;
  394. begin
  395. RefsAlmostEqual :=
  396. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  397. (r1.relsymbol = r2.relsymbol) and
  398. (r1.segment = r2.segment) and (r1.base = r2.base) and
  399. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  400. { Don't compare the offsets }
  401. (r1.volatility + r2.volatility = []);
  402. end;
  403. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  404. begin
  405. if (r1.symbol<>r2.symbol) then
  406. { If the index registers are different, there's a chance one could
  407. be set so it equals the other symbol }
  408. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  409. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  410. (r1.relsymbol = r2.relsymbol) and
  411. (r1.segment = r2.segment) and (r1.base = r2.base) and
  412. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  413. (r1.volatility + r2.volatility = []) then
  414. { In this case, it all depends on the offsets }
  415. Exit(abs(r1.offset - r2.offset) < Range);
  416. { There's a chance things MIGHT overlap, so take no chances }
  417. Result := True;
  418. end;
  419. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  420. begin
  421. Result:=(ref.offset=0) and
  422. (ref.scalefactor in [0,1]) and
  423. (ref.segment=NR_NO) and
  424. (ref.symbol=nil) and
  425. (ref.relsymbol=nil) and
  426. ((base=NR_INVALID) or
  427. (ref.base=base)) and
  428. ((index=NR_INVALID) or
  429. (ref.index=index)) and
  430. (ref.volatility=[]);
  431. end;
  432. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  433. begin
  434. Result:=(ref.scalefactor in [0,1]) and
  435. (ref.segment=NR_NO) and
  436. (ref.symbol=nil) and
  437. (ref.relsymbol=nil) and
  438. ((base=NR_INVALID) or
  439. (ref.base=base)) and
  440. ((index=NR_INVALID) or
  441. (ref.index=index)) and
  442. (ref.volatility=[]);
  443. end;
  444. function InstrReadsFlags(p: tai): boolean;
  445. begin
  446. InstrReadsFlags := true;
  447. case p.typ of
  448. ait_instruction:
  449. if InsProp[taicpu(p).opcode].Ch*
  450. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  451. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  452. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  453. exit;
  454. ait_label:
  455. exit;
  456. else
  457. ;
  458. end;
  459. InstrReadsFlags := false;
  460. end;
  461. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  462. begin
  463. Next:=Current;
  464. repeat
  465. Result:=GetNextInstruction(Next,Next);
  466. until not (Result) or
  467. not(cs_opt_level3 in current_settings.optimizerswitches) or
  468. (Next.typ<>ait_instruction) or
  469. RegInInstruction(reg,Next) or
  470. is_calljmp(taicpu(Next).opcode);
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  473. var
  474. GetNextResult: Boolean;
  475. begin
  476. Result:=0;
  477. Next:=Current;
  478. repeat
  479. GetNextResult := GetNextInstruction(Next,Next);
  480. if GetNextResult then
  481. Inc(Result)
  482. else
  483. { Must return zero upon hitting the end of the linked list without a match }
  484. Result := 0;
  485. until not (GetNextResult) or
  486. not(cs_opt_level3 in current_settings.optimizerswitches) or
  487. (Next.typ<>ait_instruction) or
  488. RegInInstruction(reg,Next) or
  489. is_calljmp(taicpu(Next).opcode);
  490. end;
  491. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  492. procedure TrackJump(Symbol: TAsmSymbol);
  493. var
  494. Search: TJumpTrackingItem;
  495. begin
  496. { See if an entry already exists in our jump tracking list
  497. (faster to search backwards due to the higher chance of
  498. matching destinations) }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - remove it so it can be pushed to the front }
  505. JumpTracking.Remove(Search);
  506. Break;
  507. end;
  508. Search := TJumpTrackingItem(Search.Previous);
  509. end;
  510. if not Assigned(Search) then
  511. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  512. JumpTracking.Concat(Search);
  513. Search.IncRefs;
  514. end;
  515. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  516. var
  517. Search: TJumpTrackingItem;
  518. begin
  519. Result := False;
  520. { See if this label appears in the tracking list }
  521. Search := TJumpTrackingItem(JumpTracking.Last);
  522. while Assigned(Search) do
  523. begin
  524. if Search.Symbol = Symbol then
  525. begin
  526. { Found it - let's see what we can discover }
  527. if Search.Symbol.getrefs = Search.Refs then
  528. begin
  529. { Success - all the references are accounted for }
  530. JumpTracking.Remove(Search);
  531. Search.Free;
  532. { It is logically impossible for CrossJump to be false here
  533. because we must have run into a conditional jump for
  534. this label at some point }
  535. if not CrossJump then
  536. InternalError(2022041710);
  537. if JumpTracking.First = nil then
  538. { Tracking list is now empty - no more cross jumps }
  539. CrossJump := False;
  540. Result := True;
  541. Exit;
  542. end;
  543. { If the references don't match, it's possible to enter
  544. this label through other means, so drop out }
  545. Exit;
  546. end;
  547. Search := TJumpTrackingItem(Search.Previous);
  548. end;
  549. end;
  550. var
  551. Next_Label: tai;
  552. begin
  553. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  554. Next := Current;
  555. repeat
  556. Result := GetNextInstruction(Next,Next);
  557. if not Result then
  558. Break;
  559. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  560. if is_calljmpuncondret(taicpu(Next).opcode) then
  561. begin
  562. if (taicpu(Next).opcode = A_JMP) and
  563. { Remove dead code now to save time }
  564. RemoveDeadCodeAfterJump(taicpu(Next)) then
  565. { A jump was removed, but not the current instruction, and
  566. Result doesn't necessarily translate into an optimisation
  567. routine's Result, so use the "Force New Iteration" flag so
  568. mark a new pass }
  569. Include(OptsToCheck, aoc_ForceNewIteration);
  570. if not Assigned(JumpTracking) then
  571. begin
  572. { Cross-label optimisations often causes other optimisations
  573. to perform worse because they're not given the chance to
  574. optimise locally. In this case, don't do the cross-label
  575. optimisations yet, but flag them as a potential possibility
  576. for the next iteration of Pass 1 }
  577. if not NotFirstIteration then
  578. Include(OptsToCheck, aoc_ForceNewIteration);
  579. end
  580. else if IsJumpToLabel(taicpu(Next)) and
  581. GetNextInstruction(Next, Next_Label) then
  582. begin
  583. { If we have JMP .lbl, and the label after it has all of its
  584. references tracked, then this is probably an if-else style of
  585. block and we can keep tracking. If the label for this jump
  586. then appears later and is fully tracked, then it's the end
  587. of the if-else blocks and the code paths converge (thus
  588. marking the end of the cross-jump) }
  589. if (Next_Label.typ = ait_label) then
  590. begin
  591. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  592. begin
  593. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  594. Next := Next_Label;
  595. { CrossJump gets set to false by LabelAccountedFor if the
  596. list is completely emptied (as it indicates that all
  597. code paths have converged). We could avoid this nuance
  598. by moving the TrackJump call to before the
  599. LabelAccountedFor call, but this is slower in situations
  600. where LabelAccountedFor would return False due to the
  601. creation of a new object that is not used and destroyed
  602. soon after. }
  603. CrossJump := True;
  604. Continue;
  605. end;
  606. end
  607. else if (Next_Label.typ <> ait_marker) then
  608. { We just did a RemoveDeadCodeAfterJump, so either we find
  609. a label, the end of the procedure or some kind of marker}
  610. InternalError(2022041720);
  611. end;
  612. Result := False;
  613. Exit;
  614. end
  615. else
  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 IsJumpToLabel(taicpu(Next)) then
  628. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  629. else
  630. { Conditional jumps should always be a jump to label }
  631. InternalError(2022041701);
  632. CrossJump := True;
  633. Continue;
  634. end;
  635. if Next.typ = ait_label then
  636. begin
  637. if not Assigned(JumpTracking) then
  638. begin
  639. { Cross-label optimisations often causes other optimisations
  640. to perform worse because they're not given the chance to
  641. optimise locally. In this case, don't do the cross-label
  642. optimisations yet, but flag them as a potential possibility
  643. for the next iteration of Pass 1 }
  644. if not NotFirstIteration then
  645. Include(OptsToCheck, aoc_ForceNewIteration);
  646. end
  647. else if LabelAccountedFor(tai_label(Next).labsym) then
  648. Continue;
  649. { If we reach here, we're at a label that hasn't been seen before
  650. (or JumpTracking was nil) }
  651. Break;
  652. end;
  653. until not Result or
  654. not (cs_opt_level3 in current_settings.optimizerswitches) or
  655. not (Next.typ in [ait_label, ait_instruction]) or
  656. RegInInstruction(reg,Next);
  657. end;
  658. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  659. begin
  660. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  661. begin
  662. Result:=GetNextInstruction(Current,Next);
  663. exit;
  664. end;
  665. Next:=tai(Current.Next);
  666. Result:=false;
  667. while assigned(Next) do
  668. begin
  669. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  670. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  671. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  672. exit
  673. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  674. begin
  675. Result:=true;
  676. exit;
  677. end;
  678. Next:=tai(Next.Next);
  679. end;
  680. end;
  681. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  682. begin
  683. Result:=RegReadByInstruction(reg,hp);
  684. end;
  685. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  686. var
  687. p: taicpu;
  688. opcount: longint;
  689. begin
  690. RegReadByInstruction := false;
  691. if hp.typ <> ait_instruction then
  692. exit;
  693. p := taicpu(hp);
  694. case p.opcode of
  695. A_CALL:
  696. regreadbyinstruction := true;
  697. A_IMUL:
  698. case p.ops of
  699. 1:
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  703. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  704. );
  705. 2,3:
  706. regReadByInstruction :=
  707. reginop(reg,p.oper[0]^) or
  708. reginop(reg,p.oper[1]^);
  709. else
  710. InternalError(2019112801);
  711. end;
  712. A_MUL:
  713. begin
  714. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  715. (
  716. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  717. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  718. );
  719. end;
  720. A_IDIV,A_DIV:
  721. begin
  722. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  723. (
  724. (getregtype(reg)=R_INTREGISTER) and
  725. (
  726. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  727. )
  728. );
  729. end;
  730. else
  731. begin
  732. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  733. begin
  734. RegReadByInstruction := false;
  735. exit;
  736. end;
  737. for opcount := 0 to p.ops-1 do
  738. if (p.oper[opCount]^.typ = top_ref) and
  739. RegInRef(reg,p.oper[opcount]^.ref^) then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. { special handling for SSE MOVSD }
  745. if (p.opcode=A_MOVSD) and (p.ops>0) then
  746. begin
  747. if p.ops<>2 then
  748. internalerror(2017042702);
  749. regReadByInstruction := reginop(reg,p.oper[0]^) or
  750. (
  751. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  752. );
  753. exit;
  754. end;
  755. with insprop[p.opcode] do
  756. begin
  757. case getregtype(reg) of
  758. R_INTREGISTER:
  759. begin
  760. case getsupreg(reg) of
  761. RS_EAX:
  762. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ECX:
  768. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EDX:
  774. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EBX:
  780. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_ESP:
  786. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. RS_EBP:
  792. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. RS_ESI:
  798. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  799. begin
  800. RegReadByInstruction := true;
  801. exit
  802. end;
  803. RS_EDI:
  804. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  805. begin
  806. RegReadByInstruction := true;
  807. exit
  808. end;
  809. end;
  810. end;
  811. R_MMREGISTER:
  812. begin
  813. case getsupreg(reg) of
  814. RS_XMM0:
  815. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. else
  823. ;
  824. end;
  825. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  826. begin
  827. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  828. begin
  829. case p.condition of
  830. C_A,C_NBE, { CF=0 and ZF=0 }
  831. C_BE,C_NA: { CF=1 or ZF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  833. C_AE,C_NB,C_NC, { CF=0 }
  834. C_B,C_NAE,C_C: { CF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  836. C_NE,C_NZ, { ZF=0 }
  837. C_E,C_Z: { ZF=1 }
  838. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  839. C_G,C_NLE, { ZF=0 and SF=OF }
  840. C_LE,C_NG: { ZF=1 or SF<>OF }
  841. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  842. C_GE,C_NL, { SF=OF }
  843. C_L,C_NGE: { SF<>OF }
  844. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  845. C_NO, { OF=0 }
  846. C_O: { OF=1 }
  847. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  848. C_NP,C_PO, { PF=0 }
  849. C_P,C_PE: { PF=1 }
  850. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  851. C_NS, { SF=0 }
  852. C_S: { SF=1 }
  853. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  854. else
  855. internalerror(2017042701);
  856. end;
  857. if RegReadByInstruction then
  858. exit;
  859. end;
  860. case getsubreg(reg) of
  861. R_SUBW,R_SUBD,R_SUBQ:
  862. RegReadByInstruction :=
  863. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  864. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  865. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  866. R_SUBFLAGCARRY:
  867. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGPARITY:
  869. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGAUXILIARY:
  871. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGZERO:
  873. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGSIGN:
  875. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGOVERFLOW:
  877. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGINTERRUPT:
  879. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. R_SUBFLAGDIRECTION:
  881. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  882. else
  883. internalerror(2017042601);
  884. end;
  885. exit;
  886. end;
  887. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  888. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  889. (p.oper[0]^.reg=p.oper[1]^.reg) then
  890. exit;
  891. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  892. begin
  893. RegReadByInstruction := true;
  894. exit
  895. end;
  896. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  897. begin
  898. RegReadByInstruction := true;
  899. exit
  900. end;
  901. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  902. begin
  903. RegReadByInstruction := true;
  904. exit
  905. end;
  906. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  907. begin
  908. RegReadByInstruction := true;
  909. exit
  910. end;
  911. end;
  912. end;
  913. end;
  914. end;
  915. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  916. begin
  917. result:=false;
  918. if p1.typ<>ait_instruction then
  919. exit;
  920. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  921. exit(true);
  922. if (getregtype(reg)=R_INTREGISTER) and
  923. { change information for xmm movsd are not correct }
  924. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  925. begin
  926. { Handle instructions that behave differently depending on the size and operand count }
  927. case taicpu(p1).opcode of
  928. A_MUL, A_DIV, A_IDIV:
  929. if taicpu(p1).opsize = S_B then
  930. Result := (getsupreg(Reg) = RS_EAX)
  931. else
  932. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  933. A_IMUL:
  934. if taicpu(p1).ops = 1 then
  935. begin
  936. if taicpu(p1).opsize = S_B then
  937. Result := (getsupreg(Reg) = RS_EAX)
  938. else
  939. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  940. end;
  941. { If ops are greater than 1, call inherited method }
  942. else
  943. case getsupreg(reg) of
  944. { RS_EAX = RS_RAX on x86-64 }
  945. RS_EAX:
  946. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_ECX:
  948. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EDX:
  950. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_EBX:
  952. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_ESP:
  954. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_EBP:
  956. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_ESI:
  958. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. RS_EDI:
  960. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  961. else
  962. ;
  963. end;
  964. end;
  965. if result then
  966. exit;
  967. end
  968. else if getregtype(reg)=R_MMREGISTER then
  969. begin
  970. case getsupreg(reg) of
  971. RS_XMM0:
  972. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  973. else
  974. ;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  980. begin
  981. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  982. exit(true);
  983. case getsubreg(reg) of
  984. R_SUBFLAGCARRY:
  985. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGPARITY:
  987. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGAUXILIARY:
  989. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGZERO:
  991. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGSIGN:
  993. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGOVERFLOW:
  995. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGINTERRUPT:
  997. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBFLAGDIRECTION:
  999. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1000. R_SUBW,R_SUBD,R_SUBQ:
  1001. { Everything except the direction bits }
  1002. Result:=
  1003. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1004. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1005. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1006. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1007. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1008. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1009. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1010. else
  1011. ;
  1012. end;
  1013. if result then
  1014. exit;
  1015. end
  1016. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1017. exit(true);
  1018. Result:=inherited RegInInstruction(Reg, p1);
  1019. end;
  1020. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1021. const
  1022. WriteOps: array[0..3] of set of TInsChange =
  1023. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1024. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1025. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1026. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1027. var
  1028. OperIdx: Integer;
  1029. begin
  1030. Result := False;
  1031. if p1.typ <> ait_instruction then
  1032. exit;
  1033. with insprop[taicpu(p1).opcode] do
  1034. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1035. begin
  1036. case getsubreg(reg) of
  1037. R_SUBW,R_SUBD,R_SUBQ:
  1038. Result :=
  1039. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1040. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1041. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1042. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1043. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1044. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGCARRY:
  1046. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGPARITY:
  1048. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGAUXILIARY:
  1050. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGZERO:
  1052. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGSIGN:
  1054. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGOVERFLOW:
  1056. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGINTERRUPT:
  1058. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. R_SUBFLAGDIRECTION:
  1060. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1061. else
  1062. internalerror(2017042602);
  1063. end;
  1064. exit;
  1065. end;
  1066. case taicpu(p1).opcode of
  1067. A_CALL:
  1068. { We could potentially set Result to False if the register in
  1069. question is non-volatile for the subroutine's calling convention,
  1070. but this would require detecting the calling convention in use and
  1071. also assuming that the routine doesn't contain malformed assembly
  1072. language, for example... so it could only be done under -O4 as it
  1073. would be considered a side-effect. [Kit] }
  1074. Result := True;
  1075. A_MOVSD:
  1076. { special handling for SSE MOVSD }
  1077. if (taicpu(p1).ops>0) then
  1078. begin
  1079. if taicpu(p1).ops<>2 then
  1080. internalerror(2017042703);
  1081. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1082. end;
  1083. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1084. so fix it here (FK)
  1085. }
  1086. A_VMOVSS,
  1087. A_VMOVSD:
  1088. begin
  1089. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1090. exit;
  1091. end;
  1092. A_MUL, A_DIV, A_IDIV:
  1093. begin
  1094. if taicpu(p1).opsize = S_B then
  1095. Result := (getsupreg(Reg) = RS_EAX)
  1096. else
  1097. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1098. end;
  1099. A_IMUL:
  1100. begin
  1101. if taicpu(p1).ops = 1 then
  1102. begin
  1103. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1104. end
  1105. else
  1106. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1107. Exit;
  1108. end;
  1109. else
  1110. ;
  1111. end;
  1112. if Result then
  1113. exit;
  1114. with insprop[taicpu(p1).opcode] do
  1115. begin
  1116. if getregtype(reg)=R_INTREGISTER then
  1117. begin
  1118. case getsupreg(reg) of
  1119. RS_EAX:
  1120. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ECX:
  1126. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EDX:
  1132. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EBX:
  1138. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_ESP:
  1144. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. RS_EBP:
  1150. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1151. begin
  1152. Result := True;
  1153. exit
  1154. end;
  1155. RS_ESI:
  1156. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1157. begin
  1158. Result := True;
  1159. exit
  1160. end;
  1161. RS_EDI:
  1162. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1163. begin
  1164. Result := True;
  1165. exit
  1166. end;
  1167. end;
  1168. end;
  1169. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1170. if (WriteOps[OperIdx]*Ch<>[]) and
  1171. { The register doesn't get modified inside a reference }
  1172. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1173. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1174. begin
  1175. Result := true;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1181. const
  1182. WriteOps: array[0..3] of set of TInsChange =
  1183. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1184. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1185. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1186. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1187. var
  1188. X: Integer;
  1189. CurrentP1Size: asizeint;
  1190. begin
  1191. Result := (
  1192. (Ref.base <> NR_NO) and
  1193. {$ifdef x86_64}
  1194. (Ref.base <> NR_RIP) and
  1195. {$endif x86_64}
  1196. RegModifiedBetween(Ref.base, p1, p2)
  1197. ) or
  1198. (
  1199. (Ref.index <> NR_NO) and
  1200. (Ref.index <> Ref.base) and
  1201. RegModifiedBetween(Ref.index, p1, p2)
  1202. );
  1203. { Now check to see if the memory itself is written to }
  1204. if not Result then
  1205. begin
  1206. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1207. if p1.typ = ait_instruction then
  1208. begin
  1209. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1210. with insprop[taicpu(p1).opcode] do
  1211. for X := 0 to taicpu(p1).ops - 1 do
  1212. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1213. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1214. { Catch any potential overlaps }
  1215. (
  1216. (RefSize = 0) or
  1217. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1218. ) and
  1219. (
  1220. (CurrentP1Size = 0) or
  1221. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1222. ) and
  1223. { Reference is used, but does the instruction write to it? }
  1224. (
  1225. (Ch_All in Ch) or
  1226. ((WriteOps[X] * Ch) <> [])
  1227. ) then
  1228. begin
  1229. Result := True;
  1230. Break;
  1231. end;
  1232. end;
  1233. end;
  1234. end;
  1235. {$ifdef DEBUG_AOPTCPU}
  1236. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1237. begin
  1238. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1239. end;
  1240. function debug_tostr(i: tcgint): string; inline;
  1241. begin
  1242. Result := tostr(i);
  1243. end;
  1244. function debug_hexstr(i: tcgint): string;
  1245. begin
  1246. Result := '0x';
  1247. case i of
  1248. 0..$FF:
  1249. Result := Result + hexstr(i, 2);
  1250. $100..$FFFF:
  1251. Result := Result + hexstr(i, 4);
  1252. $10000..$FFFFFF:
  1253. Result := Result + hexstr(i, 6);
  1254. $1000000..$FFFFFFFF:
  1255. Result := Result + hexstr(i, 8);
  1256. else
  1257. Result := Result + hexstr(i, 16);
  1258. end;
  1259. end;
  1260. function debug_regname(r: TRegister): string; inline;
  1261. begin
  1262. Result := '%' + std_regname(r);
  1263. end;
  1264. { Debug output function - creates a string representation of an operator }
  1265. function debug_operstr(oper: TOper): string;
  1266. begin
  1267. case oper.typ of
  1268. top_const:
  1269. Result := '$' + debug_tostr(oper.val);
  1270. top_reg:
  1271. Result := debug_regname(oper.reg);
  1272. top_ref:
  1273. begin
  1274. if oper.ref^.offset <> 0 then
  1275. Result := debug_tostr(oper.ref^.offset) + '('
  1276. else
  1277. Result := '(';
  1278. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1279. begin
  1280. Result := Result + debug_regname(oper.ref^.base);
  1281. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1282. Result := Result + ',' + debug_regname(oper.ref^.index);
  1283. end
  1284. else
  1285. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1286. Result := Result + debug_regname(oper.ref^.index);
  1287. if (oper.ref^.scalefactor > 1) then
  1288. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1289. else
  1290. Result := Result + ')';
  1291. end;
  1292. else
  1293. Result := '[UNKNOWN]';
  1294. end;
  1295. end;
  1296. function debug_op2str(opcode: tasmop): string; inline;
  1297. begin
  1298. Result := std_op2str[opcode];
  1299. end;
  1300. function debug_opsize2str(opsize: topsize): string; inline;
  1301. begin
  1302. Result := gas_opsize2str[opsize];
  1303. end;
  1304. {$else DEBUG_AOPTCPU}
  1305. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1306. begin
  1307. end;
  1308. function debug_tostr(i: tcgint): string; inline;
  1309. begin
  1310. Result := '';
  1311. end;
  1312. function debug_hexstr(i: tcgint): string; inline;
  1313. begin
  1314. Result := '';
  1315. end;
  1316. function debug_regname(r: TRegister): string; inline;
  1317. begin
  1318. Result := '';
  1319. end;
  1320. function debug_operstr(oper: TOper): string; inline;
  1321. begin
  1322. Result := '';
  1323. end;
  1324. function debug_op2str(opcode: tasmop): string; inline;
  1325. begin
  1326. Result := '';
  1327. end;
  1328. function debug_opsize2str(opsize: topsize): string; inline;
  1329. begin
  1330. Result := '';
  1331. end;
  1332. {$endif DEBUG_AOPTCPU}
  1333. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1334. begin
  1335. {$ifdef x86_64}
  1336. { Always fine on x86-64 }
  1337. Result := True;
  1338. {$else x86_64}
  1339. Result :=
  1340. {$ifdef i8086}
  1341. (current_settings.cputype >= cpu_386) and
  1342. {$endif i8086}
  1343. (
  1344. { Always accept if optimising for size }
  1345. (cs_opt_size in current_settings.optimizerswitches) or
  1346. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1347. (current_settings.optimizecputype >= cpu_Pentium2)
  1348. );
  1349. {$endif x86_64}
  1350. end;
  1351. { Attempts to allocate a volatile integer register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_int;
  1366. (*
  1367. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1368. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1369. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1370. *)
  1371. for CurrentSuperReg in RegSet do
  1372. begin
  1373. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1374. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1375. {$if defined(i386) or defined(i8086)}
  1376. { If the target size is 8-bit, make sure we can actually encode it }
  1377. and (
  1378. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1379. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1380. )
  1381. {$endif i386 or i8086}
  1382. then
  1383. begin
  1384. Currentp := p;
  1385. Breakout := False;
  1386. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1387. begin
  1388. case Currentp.typ of
  1389. ait_instruction:
  1390. begin
  1391. if RegInInstruction(CurrentReg, Currentp) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. { Cannot allocate across an unconditional jump }
  1397. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1398. Exit;
  1399. end;
  1400. ait_marker:
  1401. { Don't try anything more if a marker is hit }
  1402. Exit;
  1403. ait_regalloc:
  1404. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1405. begin
  1406. Breakout := True;
  1407. Break;
  1408. end;
  1409. else
  1410. ;
  1411. end;
  1412. end;
  1413. if Breakout then
  1414. { Try the next register }
  1415. Continue;
  1416. { We have a free register available }
  1417. Result := CurrentReg;
  1418. if not DontAlloc then
  1419. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1420. Exit;
  1421. end;
  1422. end;
  1423. end;
  1424. { Attempts to allocate a volatile MM register for use between p and hp,
  1425. using AUsedRegs for the current register usage information. Returns NR_NO
  1426. if no free register could be found }
  1427. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1428. var
  1429. RegSet: TCPURegisterSet;
  1430. CurrentSuperReg: Integer;
  1431. CurrentReg: TRegister;
  1432. Currentp: tai;
  1433. Breakout: Boolean;
  1434. begin
  1435. Result := NR_NO;
  1436. RegSet :=
  1437. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1438. current_procinfo.saved_regs_mm;
  1439. for CurrentSuperReg in RegSet do
  1440. begin
  1441. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1442. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1443. begin
  1444. Currentp := p;
  1445. Breakout := False;
  1446. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1447. begin
  1448. case Currentp.typ of
  1449. ait_instruction:
  1450. begin
  1451. if RegInInstruction(CurrentReg, Currentp) then
  1452. begin
  1453. Breakout := True;
  1454. Break;
  1455. end;
  1456. { Cannot allocate across an unconditional jump }
  1457. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1458. Exit;
  1459. end;
  1460. ait_marker:
  1461. { Don't try anything more if a marker is hit }
  1462. Exit;
  1463. ait_regalloc:
  1464. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1465. begin
  1466. Breakout := True;
  1467. Break;
  1468. end;
  1469. else
  1470. ;
  1471. end;
  1472. end;
  1473. if Breakout then
  1474. { Try the next register }
  1475. Continue;
  1476. { We have a free register available }
  1477. Result := CurrentReg;
  1478. if not DontAlloc then
  1479. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1480. Exit;
  1481. end;
  1482. end;
  1483. end;
  1484. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1485. begin
  1486. if not SuperRegistersEqual(reg1,reg2) then
  1487. exit(false);
  1488. if getregtype(reg1)<>R_INTREGISTER then
  1489. exit(true); {because SuperRegisterEqual is true}
  1490. case getsubreg(reg1) of
  1491. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1492. higher, it preserves the high bits, so the new value depends on
  1493. reg2's previous value. In other words, it is equivalent to doing:
  1494. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1495. R_SUBL:
  1496. exit(getsubreg(reg2)=R_SUBL);
  1497. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1498. higher, it actually does a:
  1499. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1500. R_SUBH:
  1501. exit(getsubreg(reg2)=R_SUBH);
  1502. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1503. bits of reg2:
  1504. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1505. R_SUBW:
  1506. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1507. { a write to R_SUBD always overwrites every other subregister,
  1508. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1509. R_SUBD,
  1510. R_SUBQ:
  1511. exit(true);
  1512. else
  1513. internalerror(2017042801);
  1514. end;
  1515. end;
  1516. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1517. begin
  1518. if not SuperRegistersEqual(reg1,reg2) then
  1519. exit(false);
  1520. if getregtype(reg1)<>R_INTREGISTER then
  1521. exit(true); {because SuperRegisterEqual is true}
  1522. case getsubreg(reg1) of
  1523. R_SUBL:
  1524. exit(getsubreg(reg2)<>R_SUBH);
  1525. R_SUBH:
  1526. exit(getsubreg(reg2)<>R_SUBL);
  1527. R_SUBW,
  1528. R_SUBD,
  1529. R_SUBQ:
  1530. exit(true);
  1531. else
  1532. internalerror(2017042802);
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1536. var
  1537. hp1 : tai;
  1538. l : TCGInt;
  1539. begin
  1540. result:=false;
  1541. if not(GetNextInstruction(p, hp1)) then
  1542. exit;
  1543. { changes the code sequence
  1544. shr/sar const1, x
  1545. shl const2, x
  1546. to
  1547. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1548. if (taicpu(p).oper[0]^.typ = top_const) and
  1549. MatchInstruction(hp1,A_SHL,[]) and
  1550. (taicpu(hp1).oper[0]^.typ = top_const) and
  1551. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1552. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1553. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1554. begin
  1555. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1556. not(cs_opt_size in current_settings.optimizerswitches) then
  1557. begin
  1558. { shr/sar const1, %reg
  1559. shl const2, %reg
  1560. with const1 > const2 }
  1561. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1562. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1563. taicpu(hp1).opcode := A_AND;
  1564. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1565. case taicpu(p).opsize Of
  1566. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1567. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1568. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1569. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1570. else
  1571. Internalerror(2017050703)
  1572. end;
  1573. end
  1574. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1575. not(cs_opt_size in current_settings.optimizerswitches) then
  1576. begin
  1577. { shr/sar const1, %reg
  1578. shl const2, %reg
  1579. with const1 < const2 }
  1580. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1581. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1582. taicpu(p).opcode := A_AND;
  1583. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1584. case taicpu(p).opsize Of
  1585. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1586. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1587. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1588. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1589. else
  1590. Internalerror(2017050702)
  1591. end;
  1592. end
  1593. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1594. begin
  1595. { shr/sar const1, %reg
  1596. shl const2, %reg
  1597. with const1 = const2 }
  1598. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1599. taicpu(p).opcode := A_AND;
  1600. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1601. case taicpu(p).opsize Of
  1602. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1603. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1604. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1605. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1606. else
  1607. Internalerror(2017050701)
  1608. end;
  1609. RemoveInstruction(hp1);
  1610. end;
  1611. end;
  1612. end;
  1613. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1614. var
  1615. opsize : topsize;
  1616. hp1, hp2 : tai;
  1617. tmpref : treference;
  1618. ShiftValue : Cardinal;
  1619. BaseValue : TCGInt;
  1620. begin
  1621. result:=false;
  1622. opsize:=taicpu(p).opsize;
  1623. { changes certain "imul const, %reg"'s to lea sequences }
  1624. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1625. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1626. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1627. if (taicpu(p).oper[0]^.val = 1) then
  1628. if (taicpu(p).ops = 2) then
  1629. { remove "imul $1, reg" }
  1630. begin
  1631. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1632. Result := RemoveCurrentP(p);
  1633. end
  1634. else
  1635. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1636. begin
  1637. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1638. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1639. asml.InsertAfter(hp1, p);
  1640. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1641. RemoveCurrentP(p, hp1);
  1642. Result := True;
  1643. end
  1644. else if ((taicpu(p).ops <= 2) or
  1645. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1646. not(cs_opt_size in current_settings.optimizerswitches) and
  1647. (not(GetNextInstruction(p, hp1)) or
  1648. not((tai(hp1).typ = ait_instruction) and
  1649. ((taicpu(hp1).opcode=A_Jcc) and
  1650. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1651. begin
  1652. {
  1653. imul X, reg1, reg2 to
  1654. lea (reg1,reg1,Y), reg2
  1655. shl ZZ,reg2
  1656. imul XX, reg1 to
  1657. lea (reg1,reg1,YY), reg1
  1658. shl ZZ,reg2
  1659. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1660. it does not exist as a separate optimization target in FPC though.
  1661. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1662. at most two zeros
  1663. }
  1664. reference_reset(tmpref,1,[]);
  1665. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1666. begin
  1667. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1668. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1669. TmpRef.base := taicpu(p).oper[1]^.reg;
  1670. TmpRef.index := taicpu(p).oper[1]^.reg;
  1671. if not(BaseValue in [3,5,9]) then
  1672. Internalerror(2018110101);
  1673. TmpRef.ScaleFactor := BaseValue-1;
  1674. if (taicpu(p).ops = 2) then
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1676. else
  1677. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1678. AsmL.InsertAfter(hp1,p);
  1679. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1680. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1681. RemoveCurrentP(p, hp1);
  1682. if ShiftValue>0 then
  1683. begin
  1684. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1685. AsmL.InsertAfter(hp2,hp1);
  1686. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1687. end;
  1688. Result := True;
  1689. end;
  1690. end;
  1691. end;
  1692. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1693. begin
  1694. Result := False;
  1695. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1696. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1697. begin
  1698. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1699. taicpu(p).opcode := A_MOV;
  1700. Result := True;
  1701. end;
  1702. end;
  1703. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1704. var
  1705. p: taicpu absolute hp; { Implicit typecast }
  1706. i: Integer;
  1707. begin
  1708. Result := False;
  1709. if not assigned(hp) or
  1710. (hp.typ <> ait_instruction) then
  1711. Exit;
  1712. Prefetch(insprop[p.opcode]);
  1713. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1714. with insprop[p.opcode] do
  1715. begin
  1716. case getsubreg(reg) of
  1717. R_SUBW,R_SUBD,R_SUBQ:
  1718. Result:=
  1719. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1720. uncommon flags are checked first }
  1721. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1722. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1725. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1726. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1727. R_SUBFLAGCARRY:
  1728. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGPARITY:
  1730. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGAUXILIARY:
  1732. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGZERO:
  1734. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGSIGN:
  1736. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGOVERFLOW:
  1738. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGINTERRUPT:
  1740. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1741. R_SUBFLAGDIRECTION:
  1742. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1743. else
  1744. internalerror(2017050501);
  1745. end;
  1746. exit;
  1747. end;
  1748. { Handle special cases first }
  1749. case p.opcode of
  1750. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1751. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1752. begin
  1753. Result :=
  1754. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1755. (p.oper[1]^.typ = top_reg) and
  1756. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1757. (
  1758. (p.oper[0]^.typ = top_const) or
  1759. (
  1760. (p.oper[0]^.typ = top_reg) and
  1761. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1762. ) or (
  1763. (p.oper[0]^.typ = top_ref) and
  1764. not RegInRef(reg,p.oper[0]^.ref^)
  1765. )
  1766. );
  1767. end;
  1768. A_MUL, A_IMUL:
  1769. Result :=
  1770. (
  1771. (p.ops=3) and { IMUL only }
  1772. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1773. (
  1774. (
  1775. (p.oper[1]^.typ=top_reg) and
  1776. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1777. ) or (
  1778. (p.oper[1]^.typ=top_ref) and
  1779. not RegInRef(reg,p.oper[1]^.ref^)
  1780. )
  1781. )
  1782. ) or (
  1783. (
  1784. (p.ops=1) and
  1785. (
  1786. (
  1787. (
  1788. (p.oper[0]^.typ=top_reg) and
  1789. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1790. )
  1791. ) or (
  1792. (p.oper[0]^.typ=top_ref) and
  1793. not RegInRef(reg,p.oper[0]^.ref^)
  1794. )
  1795. ) and (
  1796. (
  1797. (p.opsize=S_B) and
  1798. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1799. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1800. ) or (
  1801. (p.opsize=S_W) and
  1802. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1803. ) or (
  1804. (p.opsize=S_L) and
  1805. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1806. {$ifdef x86_64}
  1807. ) or (
  1808. (p.opsize=S_Q) and
  1809. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1810. {$endif x86_64}
  1811. )
  1812. )
  1813. )
  1814. );
  1815. A_CBW:
  1816. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1817. {$ifndef x86_64}
  1818. A_LDS:
  1819. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. A_LES:
  1821. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1822. {$endif not x86_64}
  1823. A_LFS:
  1824. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LGS:
  1826. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LSS:
  1828. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1829. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1831. A_LODSB:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1833. A_LODSW:
  1834. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1835. {$ifdef x86_64}
  1836. A_LODSQ:
  1837. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1838. {$endif x86_64}
  1839. A_LODSD:
  1840. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1841. A_FSTSW, A_FNSTSW:
  1842. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1843. else
  1844. begin
  1845. with insprop[p.opcode] do
  1846. begin
  1847. if (
  1848. { xor %reg,%reg etc. is classed as a new value }
  1849. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1850. MatchOpType(p, top_reg, top_reg) and
  1851. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1852. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1853. ) then
  1854. begin
  1855. Result := True;
  1856. Exit;
  1857. end;
  1858. { Make sure the entire register is overwritten }
  1859. if (getregtype(reg) = R_INTREGISTER) then
  1860. begin
  1861. if (p.ops > 0) then
  1862. begin
  1863. if RegInOp(reg, p.oper[0]^) then
  1864. begin
  1865. if (p.oper[0]^.typ = top_ref) then
  1866. begin
  1867. if RegInRef(reg, p.oper[0]^.ref^) then
  1868. begin
  1869. Result := False;
  1870. Exit;
  1871. end;
  1872. end
  1873. else if (p.oper[0]^.typ = top_reg) then
  1874. begin
  1875. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1876. begin
  1877. Result := False;
  1878. Exit;
  1879. end
  1880. else if ([Ch_WOp1]*Ch<>[]) then
  1881. begin
  1882. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1883. Result := True
  1884. else
  1885. begin
  1886. Result := False;
  1887. Exit;
  1888. end;
  1889. end;
  1890. end;
  1891. end;
  1892. if (p.ops > 1) then
  1893. begin
  1894. if RegInOp(reg, p.oper[1]^) then
  1895. begin
  1896. if (p.oper[1]^.typ = top_ref) then
  1897. begin
  1898. if RegInRef(reg, p.oper[1]^.ref^) then
  1899. begin
  1900. Result := False;
  1901. Exit;
  1902. end;
  1903. end
  1904. else if (p.oper[1]^.typ = top_reg) then
  1905. begin
  1906. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1907. begin
  1908. Result := False;
  1909. Exit;
  1910. end
  1911. else if ([Ch_WOp2]*Ch<>[]) then
  1912. begin
  1913. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1914. Result := True
  1915. else
  1916. begin
  1917. Result := False;
  1918. Exit;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. if (p.ops > 2) then
  1924. begin
  1925. if RegInOp(reg, p.oper[2]^) then
  1926. begin
  1927. if (p.oper[2]^.typ = top_ref) then
  1928. begin
  1929. if RegInRef(reg, p.oper[2]^.ref^) then
  1930. begin
  1931. Result := False;
  1932. Exit;
  1933. end;
  1934. end
  1935. else if (p.oper[2]^.typ = top_reg) then
  1936. begin
  1937. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1938. begin
  1939. Result := False;
  1940. Exit;
  1941. end
  1942. else if ([Ch_WOp3]*Ch<>[]) then
  1943. begin
  1944. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1945. Result := True
  1946. else
  1947. begin
  1948. Result := False;
  1949. Exit;
  1950. end;
  1951. end;
  1952. end;
  1953. end;
  1954. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1955. begin
  1956. if (p.oper[3]^.typ = top_ref) then
  1957. begin
  1958. if RegInRef(reg, p.oper[3]^.ref^) then
  1959. begin
  1960. Result := False;
  1961. Exit;
  1962. end;
  1963. end
  1964. else if (p.oper[3]^.typ = top_reg) then
  1965. begin
  1966. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1967. begin
  1968. Result := False;
  1969. Exit;
  1970. end
  1971. else if ([Ch_WOp4]*Ch<>[]) then
  1972. begin
  1973. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1974. Result := True
  1975. else
  1976. begin
  1977. Result := False;
  1978. Exit;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. end;
  1985. end;
  1986. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1987. case getsupreg(reg) of
  1988. RS_EAX:
  1989. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1990. begin
  1991. Result := True;
  1992. Exit;
  1993. end;
  1994. RS_ECX:
  1995. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1996. begin
  1997. Result := True;
  1998. Exit;
  1999. end;
  2000. RS_EDX:
  2001. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2002. begin
  2003. Result := True;
  2004. Exit;
  2005. end;
  2006. RS_EBX:
  2007. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2008. begin
  2009. Result := True;
  2010. Exit;
  2011. end;
  2012. RS_ESP:
  2013. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2014. begin
  2015. Result := True;
  2016. Exit;
  2017. end;
  2018. RS_EBP:
  2019. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2020. begin
  2021. Result := True;
  2022. Exit;
  2023. end;
  2024. RS_ESI:
  2025. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2026. begin
  2027. Result := True;
  2028. Exit;
  2029. end;
  2030. RS_EDI:
  2031. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2032. begin
  2033. Result := True;
  2034. Exit;
  2035. end;
  2036. else
  2037. ;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. end;
  2043. end;
  2044. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2045. var
  2046. hp2,hp3 : tai;
  2047. begin
  2048. { some x86-64 issue a NOP before the real exit code }
  2049. if MatchInstruction(p,A_NOP,[]) then
  2050. GetNextInstruction(p,p);
  2051. result:=assigned(p) and (p.typ=ait_instruction) and
  2052. ((taicpu(p).opcode = A_RET) or
  2053. ((taicpu(p).opcode=A_LEAVE) and
  2054. GetNextInstruction(p,hp2) and
  2055. MatchInstruction(hp2,A_RET,[S_NO])
  2056. ) or
  2057. (((taicpu(p).opcode=A_LEA) and
  2058. MatchOpType(taicpu(p),top_ref,top_reg) and
  2059. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2060. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2061. ) and
  2062. GetNextInstruction(p,hp2) and
  2063. MatchInstruction(hp2,A_RET,[S_NO])
  2064. ) or
  2065. ((((taicpu(p).opcode=A_MOV) and
  2066. MatchOpType(taicpu(p),top_reg,top_reg) and
  2067. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2068. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2069. ((taicpu(p).opcode=A_LEA) and
  2070. MatchOpType(taicpu(p),top_ref,top_reg) and
  2071. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2072. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2073. )
  2074. ) and
  2075. GetNextInstruction(p,hp2) and
  2076. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2077. MatchOpType(taicpu(hp2),top_reg) and
  2078. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2079. GetNextInstruction(hp2,hp3) and
  2080. MatchInstruction(hp3,A_RET,[S_NO])
  2081. )
  2082. );
  2083. end;
  2084. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2085. begin
  2086. isFoldableArithOp := False;
  2087. case hp1.opcode of
  2088. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2089. isFoldableArithOp :=
  2090. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2091. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2093. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2094. (taicpu(hp1).oper[1]^.reg = reg);
  2095. A_INC,A_DEC,A_NEG,A_NOT:
  2096. isFoldableArithOp :=
  2097. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2098. (taicpu(hp1).oper[0]^.reg = reg);
  2099. else
  2100. ;
  2101. end;
  2102. end;
  2103. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2104. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2105. var
  2106. hp2: tai;
  2107. begin
  2108. hp2 := p;
  2109. repeat
  2110. hp2 := tai(hp2.previous);
  2111. if assigned(hp2) and
  2112. (hp2.typ = ait_regalloc) and
  2113. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2114. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2115. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2116. begin
  2117. RemoveInstruction(hp2);
  2118. break;
  2119. end;
  2120. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2121. end;
  2122. begin
  2123. case current_procinfo.procdef.returndef.typ of
  2124. arraydef,recorddef,pointerdef,
  2125. stringdef,enumdef,procdef,objectdef,errordef,
  2126. filedef,setdef,procvardef,
  2127. classrefdef,forwarddef:
  2128. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2129. orddef:
  2130. if current_procinfo.procdef.returndef.size <> 0 then
  2131. begin
  2132. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2133. { for int64/qword }
  2134. if current_procinfo.procdef.returndef.size = 8 then
  2135. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2136. end;
  2137. else
  2138. ;
  2139. end;
  2140. end;
  2141. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2142. var
  2143. hp1: tai;
  2144. operswap: poper;
  2145. begin
  2146. Result := False;
  2147. { Optimise:
  2148. cmov(c) %reg1,%reg2
  2149. mov %reg2,%reg1
  2150. (%reg2 dealloc.)
  2151. To:
  2152. cmov(~c) %reg2,%reg1
  2153. }
  2154. if (taicpu(p).oper[0]^.typ = top_reg) then
  2155. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2156. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2157. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2158. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2159. begin
  2160. TransferUsedRegs(TmpUsedRegs);
  2161. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2162. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2163. begin
  2164. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2165. { Save time by swapping the pointers (they're both registers, so
  2166. we don't need to worry about reference counts) }
  2167. operswap := taicpu(p).oper[0];
  2168. taicpu(p).oper[0] := taicpu(p).oper[1];
  2169. taicpu(p).oper[1] := operswap;
  2170. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2171. RemoveInstruction(hp1);
  2172. { It's still a CMOV, so we can look further ahead }
  2173. Include(OptsToCheck, aoc_ForceNewIteration);
  2174. { But first, let's see if this will get optimised again
  2175. (probably won't happen, but best to be sure) }
  2176. Continue;
  2177. end;
  2178. Break;
  2179. end;
  2180. end;
  2181. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2182. var
  2183. hp1,hp2 : tai;
  2184. begin
  2185. result:=false;
  2186. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2187. begin
  2188. { vmova* reg1,reg1
  2189. =>
  2190. <nop> }
  2191. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2192. begin
  2193. RemoveCurrentP(p);
  2194. result:=true;
  2195. exit;
  2196. end;
  2197. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2198. (hp1.typ = ait_instruction) and
  2199. (
  2200. { Under -O2 and below, the instructions are always adjacent }
  2201. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2202. (taicpu(hp1).ops <= 1) or
  2203. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2204. { If reg1 = reg3, reg1 must not be modified in between }
  2205. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2206. ) then
  2207. begin
  2208. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2209. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2210. begin
  2211. { vmova* reg1,reg2
  2212. ...
  2213. vmova* reg2,reg3
  2214. dealloc reg2
  2215. =>
  2216. vmova* reg1,reg3 }
  2217. TransferUsedRegs(TmpUsedRegs);
  2218. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2219. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2220. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2221. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2222. begin
  2223. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2224. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2225. TransferUsedRegs(TmpUsedRegs);
  2226. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2227. RemoveInstruction(hp1);
  2228. result:=true;
  2229. exit;
  2230. end;
  2231. { special case:
  2232. vmova* reg1,<op>
  2233. ...
  2234. vmova* <op>,reg1
  2235. =>
  2236. vmova* reg1,<op> }
  2237. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2238. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2239. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2240. ) then
  2241. begin
  2242. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2243. RemoveInstruction(hp1);
  2244. result:=true;
  2245. exit;
  2246. end
  2247. end
  2248. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2250. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2251. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2252. ) and
  2253. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2254. begin
  2255. { vmova* reg1,reg2
  2256. ...
  2257. vmovs* reg2,<op>
  2258. dealloc reg2
  2259. =>
  2260. vmovs* reg1,<op> }
  2261. TransferUsedRegs(TmpUsedRegs);
  2262. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2263. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2264. begin
  2265. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2266. taicpu(p).opcode:=taicpu(hp1).opcode;
  2267. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2268. TransferUsedRegs(TmpUsedRegs);
  2269. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2270. RemoveInstruction(hp1);
  2271. result:=true;
  2272. exit;
  2273. end
  2274. end;
  2275. if MatchInstruction(hp1,[A_VFMADDPD,
  2276. A_VFMADD132PD,
  2277. A_VFMADD132PS,
  2278. A_VFMADD132SD,
  2279. A_VFMADD132SS,
  2280. A_VFMADD213PD,
  2281. A_VFMADD213PS,
  2282. A_VFMADD213SD,
  2283. A_VFMADD213SS,
  2284. A_VFMADD231PD,
  2285. A_VFMADD231PS,
  2286. A_VFMADD231SD,
  2287. A_VFMADD231SS,
  2288. A_VFMADDSUB132PD,
  2289. A_VFMADDSUB132PS,
  2290. A_VFMADDSUB213PD,
  2291. A_VFMADDSUB213PS,
  2292. A_VFMADDSUB231PD,
  2293. A_VFMADDSUB231PS,
  2294. A_VFMSUB132PD,
  2295. A_VFMSUB132PS,
  2296. A_VFMSUB132SD,
  2297. A_VFMSUB132SS,
  2298. A_VFMSUB213PD,
  2299. A_VFMSUB213PS,
  2300. A_VFMSUB213SD,
  2301. A_VFMSUB213SS,
  2302. A_VFMSUB231PD,
  2303. A_VFMSUB231PS,
  2304. A_VFMSUB231SD,
  2305. A_VFMSUB231SS,
  2306. A_VFMSUBADD132PD,
  2307. A_VFMSUBADD132PS,
  2308. A_VFMSUBADD213PD,
  2309. A_VFMSUBADD213PS,
  2310. A_VFMSUBADD231PD,
  2311. A_VFMSUBADD231PS,
  2312. A_VFNMADD132PD,
  2313. A_VFNMADD132PS,
  2314. A_VFNMADD132SD,
  2315. A_VFNMADD132SS,
  2316. A_VFNMADD213PD,
  2317. A_VFNMADD213PS,
  2318. A_VFNMADD213SD,
  2319. A_VFNMADD213SS,
  2320. A_VFNMADD231PD,
  2321. A_VFNMADD231PS,
  2322. A_VFNMADD231SD,
  2323. A_VFNMADD231SS,
  2324. A_VFNMSUB132PD,
  2325. A_VFNMSUB132PS,
  2326. A_VFNMSUB132SD,
  2327. A_VFNMSUB132SS,
  2328. A_VFNMSUB213PD,
  2329. A_VFNMSUB213PS,
  2330. A_VFNMSUB213SD,
  2331. A_VFNMSUB213SS,
  2332. A_VFNMSUB231PD,
  2333. A_VFNMSUB231PS,
  2334. A_VFNMSUB231SD,
  2335. A_VFNMSUB231SS],[S_NO]) and
  2336. { we mix single and double opperations here because we assume that the compiler
  2337. generates vmovapd only after double operations and vmovaps only after single operations }
  2338. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2339. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2340. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2341. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2342. begin
  2343. TransferUsedRegs(TmpUsedRegs);
  2344. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2345. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2346. begin
  2347. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2348. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2349. RemoveCurrentP(p)
  2350. else
  2351. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2352. RemoveInstruction(hp2);
  2353. end;
  2354. end
  2355. else if (hp1.typ = ait_instruction) and
  2356. (((taicpu(p).opcode=A_MOVAPS) and
  2357. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2358. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2359. ((taicpu(p).opcode=A_MOVAPD) and
  2360. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2361. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2362. ) and
  2363. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2364. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2365. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2366. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2367. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2368. { change
  2369. movapX reg,reg2
  2370. addsX/subsX/... reg3, reg2
  2371. movapX reg2,reg
  2372. to
  2373. addsX/subsX/... reg3,reg
  2374. }
  2375. begin
  2376. TransferUsedRegs(TmpUsedRegs);
  2377. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2378. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2379. begin
  2380. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2381. debug_op2str(taicpu(p).opcode)+' '+
  2382. debug_op2str(taicpu(hp1).opcode)+' '+
  2383. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2384. { we cannot eliminate the first move if
  2385. the operations uses the same register for source and dest }
  2386. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2387. { Remember that hp1 is not necessarily the immediate
  2388. next instruction }
  2389. RemoveCurrentP(p);
  2390. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2391. RemoveInstruction(hp2);
  2392. result:=true;
  2393. end;
  2394. end
  2395. else if (hp1.typ = ait_instruction) and
  2396. (((taicpu(p).opcode=A_VMOVAPD) and
  2397. (taicpu(hp1).opcode=A_VCOMISD)) or
  2398. ((taicpu(p).opcode=A_VMOVAPS) and
  2399. ((taicpu(hp1).opcode=A_VCOMISS))
  2400. )
  2401. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2402. { change
  2403. movapX reg,reg1
  2404. vcomisX reg1,reg1
  2405. to
  2406. vcomisX reg,reg
  2407. }
  2408. begin
  2409. TransferUsedRegs(TmpUsedRegs);
  2410. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2411. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2412. begin
  2413. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2414. debug_op2str(taicpu(p).opcode)+' '+
  2415. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2417. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2418. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2419. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2420. RemoveCurrentP(p);
  2421. result:=true;
  2422. exit;
  2423. end;
  2424. end
  2425. end;
  2426. end;
  2427. end;
  2428. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2429. var
  2430. hp1 : tai;
  2431. begin
  2432. result:=false;
  2433. { replace
  2434. V<Op>X %mreg1,%mreg2,%mreg3
  2435. VMovX %mreg3,%mreg4
  2436. dealloc %mreg3
  2437. by
  2438. V<Op>X %mreg1,%mreg2,%mreg4
  2439. ?
  2440. }
  2441. if GetNextInstruction(p,hp1) and
  2442. { we mix single and double operations here because we assume that the compiler
  2443. generates vmovapd only after double operations and vmovaps only after single operations }
  2444. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2445. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2446. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2447. begin
  2448. TransferUsedRegs(TmpUsedRegs);
  2449. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2450. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2451. begin
  2452. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2453. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2454. RemoveInstruction(hp1);
  2455. result:=true;
  2456. end;
  2457. end;
  2458. end;
  2459. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2460. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2461. begin
  2462. Result := False;
  2463. { For safety reasons, only check for exact register matches }
  2464. { Check base register }
  2465. if (ref.base = AOldReg) then
  2466. begin
  2467. ref.base := ANewReg;
  2468. Result := True;
  2469. end;
  2470. { Check index register }
  2471. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2472. begin
  2473. ref.index := ANewReg;
  2474. Result := True;
  2475. end;
  2476. end;
  2477. { Replaces all references to AOldReg in an operand to ANewReg }
  2478. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2479. var
  2480. OldSupReg, NewSupReg: TSuperRegister;
  2481. OldSubReg, NewSubReg: TSubRegister;
  2482. OldRegType: TRegisterType;
  2483. ThisOper: POper;
  2484. begin
  2485. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2486. Result := False;
  2487. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2488. InternalError(2020011801);
  2489. OldSupReg := getsupreg(AOldReg);
  2490. OldSubReg := getsubreg(AOldReg);
  2491. OldRegType := getregtype(AOldReg);
  2492. NewSupReg := getsupreg(ANewReg);
  2493. NewSubReg := getsubreg(ANewReg);
  2494. if OldRegType <> getregtype(ANewReg) then
  2495. InternalError(2020011802);
  2496. if OldSubReg <> NewSubReg then
  2497. InternalError(2020011803);
  2498. case ThisOper^.typ of
  2499. top_reg:
  2500. if (
  2501. (ThisOper^.reg = AOldReg) or
  2502. (
  2503. (OldRegType = R_INTREGISTER) and
  2504. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2505. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2506. (
  2507. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2508. {$ifndef x86_64}
  2509. and (
  2510. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2511. don't have an 8-bit representation }
  2512. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2513. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2514. )
  2515. {$endif x86_64}
  2516. )
  2517. )
  2518. ) then
  2519. begin
  2520. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2521. Result := True;
  2522. end;
  2523. top_ref:
  2524. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2525. Result := True;
  2526. else
  2527. ;
  2528. end;
  2529. end;
  2530. { Replaces all references to AOldReg in an instruction to ANewReg }
  2531. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2532. const
  2533. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2534. var
  2535. OperIdx: Integer;
  2536. begin
  2537. Result := False;
  2538. for OperIdx := 0 to p.ops - 1 do
  2539. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2540. begin
  2541. { The shift and rotate instructions can only use CL }
  2542. if not (
  2543. (OperIdx = 0) and
  2544. { This second condition just helps to avoid unnecessarily
  2545. calling MatchInstruction for 10 different opcodes }
  2546. (p.oper[0]^.reg = NR_CL) and
  2547. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2548. ) then
  2549. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2550. end
  2551. else if p.oper[OperIdx]^.typ = top_ref then
  2552. { It's okay to replace registers in references that get written to }
  2553. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2554. end;
  2555. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2556. begin
  2557. Result :=
  2558. (ref^.index = NR_NO) and
  2559. (
  2560. {$ifdef x86_64}
  2561. (
  2562. (ref^.base = NR_RIP) and
  2563. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2564. ) or
  2565. {$endif x86_64}
  2566. (ref^.refaddr = addr_full) or
  2567. (ref^.base = NR_STACK_POINTER_REG) or
  2568. (ref^.base = current_procinfo.framepointer)
  2569. );
  2570. end;
  2571. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2572. var
  2573. l: asizeint;
  2574. begin
  2575. Result := False;
  2576. { Should have been checked previously }
  2577. if p.opcode <> A_LEA then
  2578. InternalError(2020072501);
  2579. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2580. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2581. not(cs_opt_size in current_settings.optimizerswitches) then
  2582. exit;
  2583. with p.oper[0]^.ref^ do
  2584. begin
  2585. if (base <> p.oper[1]^.reg) or
  2586. (index <> NR_NO) or
  2587. assigned(symbol) then
  2588. exit;
  2589. l:=offset;
  2590. if (l=1) and UseIncDec then
  2591. begin
  2592. p.opcode:=A_INC;
  2593. p.loadreg(0,p.oper[1]^.reg);
  2594. p.ops:=1;
  2595. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2596. end
  2597. else if (l=-1) and UseIncDec then
  2598. begin
  2599. p.opcode:=A_DEC;
  2600. p.loadreg(0,p.oper[1]^.reg);
  2601. p.ops:=1;
  2602. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2603. end
  2604. else
  2605. begin
  2606. if (l<0) and (l<>-2147483648) then
  2607. begin
  2608. p.opcode:=A_SUB;
  2609. p.loadConst(0,-l);
  2610. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2611. end
  2612. else
  2613. begin
  2614. p.opcode:=A_ADD;
  2615. p.loadConst(0,l);
  2616. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2617. end;
  2618. end;
  2619. end;
  2620. Result := True;
  2621. end;
  2622. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2623. var
  2624. CurrentReg, ReplaceReg: TRegister;
  2625. begin
  2626. Result := False;
  2627. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2628. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2629. case hp.opcode of
  2630. A_FSTSW, A_FNSTSW,
  2631. A_IN, A_INS, A_OUT, A_OUTS,
  2632. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2633. { These routines have explicit operands, but they are restricted in
  2634. what they can be (e.g. IN and OUT can only read from AL, AX or
  2635. EAX. }
  2636. Exit;
  2637. A_IMUL:
  2638. begin
  2639. { The 1-operand version writes to implicit registers
  2640. The 2-operand version reads from the first operator, and reads
  2641. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2642. the 3-operand version reads from a register that it doesn't write to
  2643. }
  2644. case hp.ops of
  2645. 1:
  2646. if (
  2647. (
  2648. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2649. ) or
  2650. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2651. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2652. begin
  2653. Result := True;
  2654. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2655. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2656. end;
  2657. 2:
  2658. { Only modify the first parameter }
  2659. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2660. begin
  2661. Result := True;
  2662. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2663. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2664. end;
  2665. 3:
  2666. { Only modify the second parameter }
  2667. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2668. begin
  2669. Result := True;
  2670. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2671. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2672. end;
  2673. else
  2674. InternalError(2020012901);
  2675. end;
  2676. end;
  2677. else
  2678. if (hp.ops > 0) and
  2679. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2680. begin
  2681. Result := True;
  2682. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2683. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2684. end;
  2685. end;
  2686. end;
  2687. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2688. var
  2689. hp2, hp_regalloc: tai;
  2690. p_SourceReg, p_TargetReg: TRegister;
  2691. begin
  2692. Result := False;
  2693. { Backward optimisation. If we have:
  2694. func. %reg1,%reg2
  2695. mov %reg2,%reg3
  2696. (dealloc %reg2)
  2697. Change to:
  2698. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2699. Perform similar optimisations with 1, 3 and 4-operand instructions
  2700. that only have one output.
  2701. }
  2702. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2703. begin
  2704. p_SourceReg := taicpu(p).oper[0]^.reg;
  2705. p_TargetReg := taicpu(p).oper[1]^.reg;
  2706. TransferUsedRegs(TmpUsedRegs);
  2707. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2708. GetLastInstruction(p, hp2) and
  2709. (hp2.typ = ait_instruction) and
  2710. { Have to make sure it's an instruction that only reads from
  2711. the first operands and only writes (not reads or modifies) to
  2712. the last one; in essence, a pure function such as BSR, POPCNT
  2713. or ANDN }
  2714. (
  2715. (
  2716. (taicpu(hp2).ops = 1) and
  2717. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2718. ) or
  2719. (
  2720. (taicpu(hp2).ops = 2) and
  2721. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2722. ) or
  2723. (
  2724. (taicpu(hp2).ops = 3) and
  2725. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2726. ) or
  2727. (
  2728. (taicpu(hp2).ops = 4) and
  2729. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2730. )
  2731. ) and
  2732. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2733. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2734. begin
  2735. case taicpu(hp2).opcode of
  2736. A_FSTSW, A_FNSTSW,
  2737. A_IN, A_INS, A_OUT, A_OUTS,
  2738. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2739. { These routines have explicit operands, but they are restricted in
  2740. what they can be (e.g. IN and OUT can only read from AL, AX or
  2741. EAX. }
  2742. ;
  2743. else
  2744. begin
  2745. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2746. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2747. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2748. if Assigned(hp_regalloc) then
  2749. begin
  2750. Asml.Remove(hp_regalloc);
  2751. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2752. begin
  2753. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2754. hp_regalloc.Free;
  2755. end
  2756. else
  2757. { If the register is not explicitly deallocated, it's
  2758. being reused, so move the allocation to after func. }
  2759. AsmL.InsertAfter(hp_regalloc, hp2);
  2760. end;
  2761. if not RegInInstruction(p_TargetReg, hp2) then
  2762. begin
  2763. TransferUsedRegs(TmpUsedRegs);
  2764. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2765. end;
  2766. { Actually make the changes }
  2767. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2768. RemoveCurrentp(p, hp1);
  2769. { If the Func was another MOV instruction, we might get
  2770. "mov %reg,%reg" that doesn't get removed in Pass 2
  2771. otherwise, so deal with it here (also do something
  2772. similar with lea (%reg),%reg}
  2773. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2774. begin
  2775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2776. if p = hp2 then
  2777. RemoveCurrentp(p)
  2778. else
  2779. RemoveInstruction(hp2);
  2780. end;
  2781. Result := True;
  2782. Exit;
  2783. end;
  2784. end;
  2785. end;
  2786. end;
  2787. end;
  2788. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2789. begin
  2790. Result := False;
  2791. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2792. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2793. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2794. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2795. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2796. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2797. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2798. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2799. begin
  2800. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2801. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2802. Result := True;
  2803. Include(OptsToCheck, aoc_ForceNewIteration);
  2804. end;
  2805. end;
  2806. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2807. var
  2808. hp1, hp2, hp3, hp4: tai;
  2809. DoOptimisation, TempBool: Boolean;
  2810. {$ifdef x86_64}
  2811. NewConst: TCGInt;
  2812. {$endif x86_64}
  2813. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2814. begin
  2815. if taicpu(hp1).opcode = signed_movop then
  2816. begin
  2817. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2818. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2819. end
  2820. else
  2821. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2822. end;
  2823. function TryConstMerge(var p1, p2: tai): Boolean;
  2824. var
  2825. ThisRef: TReference;
  2826. begin
  2827. Result := False;
  2828. ThisRef := taicpu(p2).oper[1]^.ref^;
  2829. { Only permit writes to the stack, since we can guarantee alignment with that }
  2830. if (ThisRef.index = NR_NO) and
  2831. (
  2832. (ThisRef.base = NR_STACK_POINTER_REG) or
  2833. (ThisRef.base = current_procinfo.framepointer)
  2834. ) then
  2835. begin
  2836. case taicpu(p).opsize of
  2837. S_B:
  2838. begin
  2839. { Word writes must be on a 2-byte boundary }
  2840. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2841. begin
  2842. { Reduce offset of second reference to see if it is sequential with the first }
  2843. Dec(ThisRef.offset, 1);
  2844. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2845. begin
  2846. { Make sure the constants aren't represented as a
  2847. negative number, as these won't merge properly }
  2848. taicpu(p1).opsize := S_W;
  2849. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2850. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2851. RemoveInstruction(p2);
  2852. Result := True;
  2853. end;
  2854. end;
  2855. end;
  2856. S_W:
  2857. begin
  2858. { Longword writes must be on a 4-byte boundary }
  2859. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2860. begin
  2861. { Reduce offset of second reference to see if it is sequential with the first }
  2862. Dec(ThisRef.offset, 2);
  2863. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2864. begin
  2865. { Make sure the constants aren't represented as a
  2866. negative number, as these won't merge properly }
  2867. taicpu(p1).opsize := S_L;
  2868. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2869. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2870. RemoveInstruction(p2);
  2871. Result := True;
  2872. end;
  2873. end;
  2874. end;
  2875. {$ifdef x86_64}
  2876. S_L:
  2877. begin
  2878. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2879. see if the constants can be encoded this way. }
  2880. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2881. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2882. { Quadword writes must be on an 8-byte boundary }
  2883. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2884. begin
  2885. { Reduce offset of second reference to see if it is sequential with the first }
  2886. Dec(ThisRef.offset, 4);
  2887. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2888. begin
  2889. { Make sure the constants aren't represented as a
  2890. negative number, as these won't merge properly }
  2891. taicpu(p1).opsize := S_Q;
  2892. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2893. taicpu(p1).oper[0]^.val := NewConst;
  2894. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2895. RemoveInstruction(p2);
  2896. Result := True;
  2897. end;
  2898. end;
  2899. end;
  2900. {$endif x86_64}
  2901. else
  2902. ;
  2903. end;
  2904. end;
  2905. end;
  2906. var
  2907. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2908. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2909. NewSize: topsize; NewOffset: asizeint;
  2910. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2911. SourceRef, TargetRef: TReference;
  2912. MovAligned, MovUnaligned: TAsmOp;
  2913. ThisRef: TReference;
  2914. JumpTracking: TLinkedList;
  2915. begin
  2916. Result:=false;
  2917. { remove mov reg1,reg1? }
  2918. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2919. then
  2920. begin
  2921. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2922. { take care of the register (de)allocs following p }
  2923. RemoveCurrentP(p);
  2924. Result := True;
  2925. exit;
  2926. end;
  2927. { Prevent compiler warnings }
  2928. p_SourceReg := NR_NO;
  2929. p_TargetReg := NR_NO;
  2930. if taicpu(p).oper[1]^.typ = top_reg then
  2931. begin
  2932. { Saves on a large number of dereferences }
  2933. p_TargetReg := taicpu(p).oper[1]^.reg;
  2934. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2935. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2936. else
  2937. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2938. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2939. while True do
  2940. begin
  2941. if (taicpu(hp1).opcode = A_AND) and
  2942. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2943. begin
  2944. { A change has occurred, just not in p }
  2945. Include(OptsToCheck, aoc_ForceNewIteration);
  2946. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2947. begin
  2948. case taicpu(p).opsize of
  2949. S_L:
  2950. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2951. begin
  2952. { Optimize out:
  2953. mov x, %reg
  2954. and ffffffffh, %reg
  2955. }
  2956. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2957. RemoveInstruction(hp1);
  2958. Result:=true;
  2959. exit;
  2960. end;
  2961. S_Q: { TODO: Confirm if this is even possible }
  2962. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2963. begin
  2964. { Optimize out:
  2965. mov x, %reg
  2966. and ffffffffffffffffh, %reg
  2967. }
  2968. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2969. RemoveInstruction(hp1);
  2970. Result:=true;
  2971. exit;
  2972. end;
  2973. else
  2974. ;
  2975. end;
  2976. if (
  2977. { Make sure that if a reference is used, its registers
  2978. are not modified in between }
  2979. (
  2980. (taicpu(p).oper[0]^.typ = top_reg) and
  2981. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2982. ) or
  2983. (
  2984. (taicpu(p).oper[0]^.typ = top_ref) and
  2985. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2986. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2987. )
  2988. ) and
  2989. GetNextInstruction(hp1,hp2) and
  2990. MatchInstruction(hp2,A_TEST,[]) and
  2991. (
  2992. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2993. (
  2994. { If the register being tested is smaller than the one
  2995. that received a bitwise AND, permit it if the constant
  2996. fits into the smaller size }
  2997. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2998. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2999. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3000. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3001. (
  3002. (
  3003. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3004. (taicpu(hp1).oper[0]^.val <= $FF)
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3009. {$ifdef x86_64}
  3010. ) or
  3011. (
  3012. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3013. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3014. {$endif x86_64}
  3015. )
  3016. )
  3017. )
  3018. ) and
  3019. (
  3020. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3021. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3022. ) and
  3023. GetNextInstruction(hp2,hp3) and
  3024. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3025. (taicpu(hp3).condition in [C_E,C_NE]) then
  3026. begin
  3027. TransferUsedRegs(TmpUsedRegs);
  3028. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3029. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3030. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3031. begin
  3032. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3033. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3034. taicpu(hp1).opcode:=A_TEST;
  3035. { Shrink the TEST instruction down to the smallest possible size }
  3036. case taicpu(hp1).oper[0]^.val of
  3037. 0..255:
  3038. if (taicpu(hp1).opsize <> S_B)
  3039. {$ifndef x86_64}
  3040. and (
  3041. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3042. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3043. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3044. )
  3045. {$endif x86_64}
  3046. then
  3047. begin
  3048. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3049. { Only print debug message if the TEST instruction
  3050. is a different size before and after }
  3051. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3052. taicpu(hp1).opsize := S_B;
  3053. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3054. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3055. end;
  3056. 256..65535:
  3057. if (taicpu(hp1).opsize <> S_W) then
  3058. begin
  3059. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3060. { Only print debug message if the TEST instruction
  3061. is a different size before and after }
  3062. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3063. taicpu(hp1).opsize := S_W;
  3064. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3065. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3066. end;
  3067. {$ifdef x86_64}
  3068. 65536..$7FFFFFFF:
  3069. if (taicpu(hp1).opsize <> S_L) then
  3070. begin
  3071. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3072. { Only print debug message if the TEST instruction
  3073. is a different size before and after }
  3074. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3075. taicpu(hp1).opsize := S_L;
  3076. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3077. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3078. end;
  3079. {$endif x86_64}
  3080. else
  3081. ;
  3082. end;
  3083. RemoveInstruction(hp2);
  3084. RemoveCurrentP(p);
  3085. Result:=true;
  3086. exit;
  3087. end;
  3088. end;
  3089. end;
  3090. if IsMOVZXAcceptable and
  3091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3092. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3093. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3094. then
  3095. begin
  3096. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3097. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3098. case taicpu(p).opsize of
  3099. S_B:
  3100. if (taicpu(hp1).oper[0]^.val = $ff) then
  3101. begin
  3102. { Convert:
  3103. movb x, %regl movb x, %regl
  3104. andw ffh, %regw andl ffh, %regd
  3105. To:
  3106. movzbw x, %regd movzbl x, %regd
  3107. (Identical registers, just different sizes)
  3108. }
  3109. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3110. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3111. case taicpu(hp1).opsize of
  3112. S_W: NewSize := S_BW;
  3113. S_L: NewSize := S_BL;
  3114. {$ifdef x86_64}
  3115. S_Q: NewSize := S_BQ;
  3116. {$endif x86_64}
  3117. else
  3118. InternalError(2018011510);
  3119. end;
  3120. end
  3121. else
  3122. NewSize := S_NO;
  3123. S_W:
  3124. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3125. begin
  3126. { Convert:
  3127. movw x, %regw
  3128. andl ffffh, %regd
  3129. To:
  3130. movzwl x, %regd
  3131. (Identical registers, just different sizes)
  3132. }
  3133. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3134. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3135. case taicpu(hp1).opsize of
  3136. S_L: NewSize := S_WL;
  3137. {$ifdef x86_64}
  3138. S_Q: NewSize := S_WQ;
  3139. {$endif x86_64}
  3140. else
  3141. InternalError(2018011511);
  3142. end;
  3143. end
  3144. else
  3145. NewSize := S_NO;
  3146. else
  3147. NewSize := S_NO;
  3148. end;
  3149. if NewSize <> S_NO then
  3150. begin
  3151. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3152. { The actual optimization }
  3153. taicpu(p).opcode := A_MOVZX;
  3154. taicpu(p).changeopsize(NewSize);
  3155. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3156. { Make sure we deal with any reference counts that were increased }
  3157. if taicpu(hp1).oper[1]^.typ = top_ref then
  3158. begin
  3159. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3160. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3161. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3162. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3163. end;
  3164. { Safeguard if "and" is followed by a conditional command }
  3165. TransferUsedRegs(TmpUsedRegs);
  3166. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3167. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3168. begin
  3169. { At this point, the "and" command is effectively equivalent to
  3170. "test %reg,%reg". This will be handled separately by the
  3171. Peephole Optimizer. [Kit] }
  3172. DebugMsg(SPeepholeOptimization + PreMessage +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. end
  3175. else
  3176. begin
  3177. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3178. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3179. RemoveInstruction(hp1);
  3180. end;
  3181. Result := True;
  3182. Exit;
  3183. { Go through DeepMOVOpt again (jump to "while True do") }
  3184. Continue;
  3185. end;
  3186. end;
  3187. end;
  3188. if taicpu(p).oper[0]^.typ = top_reg then
  3189. begin
  3190. p_SourceReg := taicpu(p).oper[0]^.reg;
  3191. { Look for:
  3192. mov %reg1,%reg2
  3193. ??? %reg2,r/m
  3194. Change to:
  3195. mov %reg1,%reg2
  3196. ??? %reg1,r/m
  3197. }
  3198. if RegReadByInstruction(p_TargetReg, hp1) and
  3199. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3200. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3201. begin
  3202. { A change has occurred, just not in p }
  3203. Include(OptsToCheck, aoc_ForceNewIteration);
  3204. TransferUsedRegs(TmpUsedRegs);
  3205. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3206. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3207. { Just in case something didn't get modified (e.g. an
  3208. implicit register) }
  3209. not RegReadByInstruction(p_TargetReg, hp1) then
  3210. begin
  3211. { We can remove the original MOV }
  3212. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3213. RemoveCurrentP(p);
  3214. { UsedRegs got updated by RemoveCurrentp }
  3215. Result := True;
  3216. Exit;
  3217. end;
  3218. { If we know a MOV instruction has become a null operation, we might as well
  3219. get rid of it now to save time. }
  3220. if (taicpu(hp1).opcode = A_MOV) and
  3221. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3222. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3223. { Just being a register is enough to confirm it's a null operation }
  3224. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3225. begin
  3226. Result := True;
  3227. { Speed-up to reduce a pipeline stall... if we had something like...
  3228. movl %eax,%edx
  3229. movw %dx,%ax
  3230. ... the second instruction would change to movw %ax,%ax, but
  3231. given that it is now %ax that's active rather than %eax,
  3232. penalties might occur due to a partial register write, so instead,
  3233. change it to a MOVZX instruction when optimising for speed.
  3234. }
  3235. if not (cs_opt_size in current_settings.optimizerswitches) and
  3236. IsMOVZXAcceptable and
  3237. (taicpu(hp1).opsize < taicpu(p).opsize)
  3238. {$ifdef x86_64}
  3239. { operations already implicitly set the upper 64 bits to zero }
  3240. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3241. {$endif x86_64}
  3242. then
  3243. begin
  3244. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3245. case taicpu(p).opsize of
  3246. S_W:
  3247. if taicpu(hp1).opsize = S_B then
  3248. taicpu(hp1).opsize := S_BL
  3249. else
  3250. InternalError(2020012911);
  3251. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3252. case taicpu(hp1).opsize of
  3253. S_B:
  3254. taicpu(hp1).opsize := S_BL;
  3255. S_W:
  3256. taicpu(hp1).opsize := S_WL;
  3257. else
  3258. InternalError(2020012912);
  3259. end;
  3260. else
  3261. InternalError(2020012910);
  3262. end;
  3263. taicpu(hp1).opcode := A_MOVZX;
  3264. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3265. end
  3266. else
  3267. begin
  3268. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3269. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3270. RemoveInstruction(hp1);
  3271. { The instruction after what was hp1 is now the immediate next instruction,
  3272. so we can continue to make optimisations if it's present }
  3273. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3274. Exit;
  3275. hp1 := hp2;
  3276. end;
  3277. end;
  3278. end;
  3279. {$ifdef x86_64}
  3280. { Change:
  3281. movl %reg1l,%reg2l
  3282. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3283. To:
  3284. movl %reg1l,%reg2l
  3285. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3286. If %reg1 = %reg3, convert to:
  3287. movl %reg1l,%reg2l
  3288. andl %reg1l,%reg1l
  3289. }
  3290. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3291. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3292. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3293. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3294. begin
  3295. TransferUsedRegs(TmpUsedRegs);
  3296. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3297. taicpu(hp1).opsize := S_L;
  3298. taicpu(hp1).loadreg(0, p_SourceReg);
  3299. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3300. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3301. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3302. begin
  3303. { %reg1 = %reg3 }
  3304. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3305. taicpu(hp1).opcode := A_AND;
  3306. end
  3307. else
  3308. begin
  3309. { %reg1 <> %reg3 }
  3310. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3311. end;
  3312. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3313. begin
  3314. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3315. RemoveCurrentP(p);
  3316. Result := True;
  3317. Exit;
  3318. end
  3319. else
  3320. begin
  3321. { Initial instruction wasn't actually changed }
  3322. Include(OptsToCheck, aoc_ForceNewIteration);
  3323. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3324. appears below since %reg1 has technically changed }
  3325. if taicpu(hp1).opcode = A_AND then
  3326. Exit;
  3327. end;
  3328. end;
  3329. {$endif x86_64}
  3330. end
  3331. else if taicpu(p).oper[0]^.typ = top_const then
  3332. begin
  3333. if (taicpu(hp1).opcode = A_OR) and
  3334. (taicpu(p).oper[1]^.typ = top_reg) and
  3335. MatchOperand(taicpu(p).oper[0]^, 0) and
  3336. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3337. begin
  3338. { mov 0, %reg
  3339. or ###,%reg
  3340. Change to (only if the flags are not used):
  3341. mov ###,%reg
  3342. }
  3343. TransferUsedRegs(TmpUsedRegs);
  3344. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3345. DoOptimisation := True;
  3346. { Even if the flags are used, we might be able to do the optimisation
  3347. if the conditions are predictable }
  3348. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3349. begin
  3350. { Only perform if ### = %reg (the same register) or equal to 0,
  3351. so %reg is guaranteed to still have a value of zero }
  3352. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3353. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3354. begin
  3355. hp2 := hp1;
  3356. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3357. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3358. GetNextInstruction(hp2, hp3) do
  3359. begin
  3360. { Don't continue modifying if the flags state is getting changed }
  3361. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3362. Break;
  3363. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3364. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3365. begin
  3366. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3367. begin
  3368. { Condition is always true }
  3369. case taicpu(hp3).opcode of
  3370. A_Jcc:
  3371. begin
  3372. { Check for jump shortcuts before we destroy the condition }
  3373. hp4 := hp3;
  3374. DoJumpOptimizations(hp3, TempBool);
  3375. { Make sure hp3 hasn't changed }
  3376. if (hp4 = hp3) then
  3377. begin
  3378. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3379. MakeUnconditional(taicpu(hp3));
  3380. end;
  3381. Result := True;
  3382. end;
  3383. A_CMOVcc:
  3384. begin
  3385. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3386. taicpu(hp3).opcode := A_MOV;
  3387. taicpu(hp3).condition := C_None;
  3388. Result := True;
  3389. end;
  3390. A_SETcc:
  3391. begin
  3392. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3393. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3394. taicpu(hp3).opcode := A_MOV;
  3395. taicpu(hp3).ops := 2;
  3396. taicpu(hp3).condition := C_None;
  3397. taicpu(hp3).opsize := S_B;
  3398. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3399. taicpu(hp3).loadconst(0, 1);
  3400. Result := True;
  3401. end;
  3402. else
  3403. InternalError(2021090701);
  3404. end;
  3405. end
  3406. 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
  3407. begin
  3408. { Condition is always false }
  3409. case taicpu(hp3).opcode of
  3410. A_Jcc:
  3411. begin
  3412. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3413. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3414. RemoveInstruction(hp3);
  3415. Result := True;
  3416. { Since hp3 was deleted, hp2 must not be updated }
  3417. Continue;
  3418. end;
  3419. A_CMOVcc:
  3420. begin
  3421. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3422. RemoveInstruction(hp3);
  3423. Result := True;
  3424. { Since hp3 was deleted, hp2 must not be updated }
  3425. Continue;
  3426. end;
  3427. A_SETcc:
  3428. begin
  3429. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3430. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3431. taicpu(hp3).opcode := A_MOV;
  3432. taicpu(hp3).ops := 2;
  3433. taicpu(hp3).condition := C_None;
  3434. taicpu(hp3).opsize := S_B;
  3435. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3436. taicpu(hp3).loadconst(0, 0);
  3437. Result := True;
  3438. end;
  3439. else
  3440. InternalError(2021090702);
  3441. end;
  3442. end
  3443. else
  3444. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3445. DoOptimisation := False;
  3446. end;
  3447. hp2 := hp3;
  3448. end;
  3449. if DoOptimisation then
  3450. begin
  3451. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3452. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3453. { Flags are still in use - don't optimise }
  3454. DoOptimisation := False;
  3455. end;
  3456. end
  3457. else
  3458. DoOptimisation := False;
  3459. end;
  3460. if DoOptimisation then
  3461. begin
  3462. {$ifdef x86_64}
  3463. { OR only supports 32-bit sign-extended constants for 64-bit
  3464. instructions, so compensate for this if the constant is
  3465. encoded as a value greater than or equal to 2^31 }
  3466. if (taicpu(hp1).opsize = S_Q) and
  3467. (taicpu(hp1).oper[0]^.typ = top_const) and
  3468. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3469. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3470. {$endif x86_64}
  3471. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3472. taicpu(hp1).opcode := A_MOV;
  3473. RemoveCurrentP(p);
  3474. Result := True;
  3475. Exit;
  3476. end;
  3477. end;
  3478. end
  3479. else if
  3480. { oper[0] is a reference }
  3481. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3482. begin
  3483. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3484. begin
  3485. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3486. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3487. ) or
  3488. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3489. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3490. )
  3491. ) and
  3492. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3493. { mov ref,reg1
  3494. lea (reg1,reg2),reg2
  3495. to
  3496. add ref,reg2 }
  3497. begin
  3498. TransferUsedRegs(TmpUsedRegs);
  3499. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3500. { If the flags register is in use, don't change the instruction to an
  3501. ADD otherwise this will scramble the flags. [Kit] }
  3502. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3503. { reg1 may not be used afterwards }
  3504. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3505. begin
  3506. Taicpu(hp1).opcode:=A_ADD;
  3507. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3508. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3509. RemoveCurrentp(p);
  3510. result:=true;
  3511. exit;
  3512. end;
  3513. end;
  3514. { If the LEA instruction can be converted into an arithmetic instruction,
  3515. it may be possible to then fold it in the next optimisation. }
  3516. if ConvertLEA(taicpu(hp1)) then
  3517. Include(OptsToCheck, aoc_ForceNewIteration);
  3518. end;
  3519. {
  3520. mov ref,reg0
  3521. <op> reg0,reg1
  3522. dealloc reg0
  3523. to
  3524. <op> ref,reg1
  3525. }
  3526. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3527. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3528. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3529. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3530. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3531. begin
  3532. TransferUsedRegs(TmpUsedRegs);
  3533. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3534. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3535. begin
  3536. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3537. { loadref increases the reference count, so decrement it again }
  3538. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3539. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3540. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3541. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3542. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3543. { See if we can remove the allocation of reg0 }
  3544. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3545. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3546. RemoveCurrentp(p);
  3547. Result:=true;
  3548. exit;
  3549. end;
  3550. end;
  3551. end;
  3552. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3553. overwrites the original destination register. e.g.
  3554. movl ###,%reg2d
  3555. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3556. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3557. }
  3558. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3559. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3560. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3561. begin
  3562. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3563. begin
  3564. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3565. case taicpu(p).oper[0]^.typ of
  3566. top_const:
  3567. { We have something like:
  3568. movb $x, %regb
  3569. movzbl %regb,%regd
  3570. Change to:
  3571. movl $x, %regd
  3572. }
  3573. begin
  3574. case taicpu(hp1).opsize of
  3575. S_BW:
  3576. begin
  3577. convert_mov_value(A_MOVSX, $FF);
  3578. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3579. taicpu(p).opsize := S_W;
  3580. end;
  3581. S_BL:
  3582. begin
  3583. convert_mov_value(A_MOVSX, $FF);
  3584. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3585. taicpu(p).opsize := S_L;
  3586. end;
  3587. S_WL:
  3588. begin
  3589. convert_mov_value(A_MOVSX, $FFFF);
  3590. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3591. taicpu(p).opsize := S_L;
  3592. end;
  3593. {$ifdef x86_64}
  3594. S_BQ:
  3595. begin
  3596. convert_mov_value(A_MOVSX, $FF);
  3597. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3598. taicpu(p).opsize := S_Q;
  3599. end;
  3600. S_WQ:
  3601. begin
  3602. convert_mov_value(A_MOVSX, $FFFF);
  3603. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3604. taicpu(p).opsize := S_Q;
  3605. end;
  3606. S_LQ:
  3607. begin
  3608. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3609. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3610. taicpu(p).opsize := S_Q;
  3611. end;
  3612. {$endif x86_64}
  3613. else
  3614. { If hp1 was a MOV instruction, it should have been
  3615. optimised already }
  3616. InternalError(2020021001);
  3617. end;
  3618. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3619. RemoveInstruction(hp1);
  3620. Result := True;
  3621. Exit;
  3622. end;
  3623. top_ref:
  3624. begin
  3625. { We have something like:
  3626. movb mem, %regb
  3627. movzbl %regb,%regd
  3628. Change to:
  3629. movzbl mem, %regd
  3630. }
  3631. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3632. begin
  3633. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3634. taicpu(p).opcode := taicpu(hp1).opcode;
  3635. taicpu(p).opsize := taicpu(hp1).opsize;
  3636. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3637. RemoveInstruction(hp1);
  3638. Result := True;
  3639. Exit;
  3640. end;
  3641. end;
  3642. else
  3643. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3644. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3645. Exit;
  3646. end;
  3647. end
  3648. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3649. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3650. optimised }
  3651. else
  3652. begin
  3653. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3654. RemoveCurrentP(p);
  3655. Result := True;
  3656. Exit;
  3657. end;
  3658. end;
  3659. if (taicpu(hp1).opcode = A_MOV) and
  3660. (
  3661. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3662. {$ifdef x86_64}
  3663. or (
  3664. { Permit zero extension from 32- to 64-bit when writing
  3665. a constant (it will be checked to see if it fits into
  3666. a signed 32-bit integer) }
  3667. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3668. (
  3669. { Valid situations... writing an unsigned 32-bit
  3670. immediate, or the destination is a 64-bit register }
  3671. (taicpu(p).oper[0]^.typ = top_const) or
  3672. (taicpu(hp1).oper[1]^.typ = top_reg)
  3673. ) and
  3674. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3675. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3676. )
  3677. {$endif x86_64}
  3678. ) then
  3679. begin
  3680. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3681. TransferUsedRegs(TmpUsedRegs);
  3682. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3683. { we have
  3684. mov x, %treg
  3685. mov %treg, y
  3686. }
  3687. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3688. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3689. begin
  3690. { we've got
  3691. mov x, %treg
  3692. mov %treg, y
  3693. with %treg is not used after }
  3694. case taicpu(p).oper[0]^.typ Of
  3695. { top_reg is covered by DeepMOVOpt }
  3696. top_const:
  3697. begin
  3698. { change
  3699. mov const, %treg
  3700. mov %treg, y
  3701. to
  3702. mov const, y
  3703. }
  3704. {$ifdef x86_64}
  3705. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3706. (
  3707. { For 32-to-64-bit zero-extension, the immediate
  3708. must be between 0 and 2^31 - 1}
  3709. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3710. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3711. ) or
  3712. (
  3713. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3714. (
  3715. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3716. )
  3717. ) then
  3718. {$endif x86_64}
  3719. begin
  3720. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3721. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3722. RemoveCurrentP(p);
  3723. Result := True;
  3724. Exit;
  3725. end;
  3726. end;
  3727. top_ref:
  3728. case taicpu(hp1).oper[1]^.typ of
  3729. top_reg:
  3730. { change
  3731. mov mem, %treg
  3732. mov %treg, %reg
  3733. to
  3734. mov mem, %reg"
  3735. }
  3736. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3737. begin
  3738. {$ifdef x86_64}
  3739. { If zero extending from 32-bit to 64-bit,
  3740. we have to make sure the replaced
  3741. register is the right size }
  3742. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3743. {$else}
  3744. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3745. {$endif x86_64}
  3746. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3747. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3748. RemoveInstruction(hp1);
  3749. Result := True;
  3750. Exit;
  3751. end
  3752. else if
  3753. { Make sure that if a reference is used, its
  3754. registers are not modified in between }
  3755. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3756. begin
  3757. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3758. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3759. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3760. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3761. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3762. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3763. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3764. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3765. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3766. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3767. RemoveCurrentP(p);
  3768. Result := True;
  3769. Exit;
  3770. end;
  3771. top_ref:
  3772. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3773. begin
  3774. {$ifdef x86_64}
  3775. { Look for the following to simplify:
  3776. mov x(mem1), %reg
  3777. mov %reg, y(mem2)
  3778. mov x+8(mem1), %reg
  3779. mov %reg, y+8(mem2)
  3780. Change to:
  3781. movdqu x(mem1), %xmmreg
  3782. movdqu %xmmreg, y(mem2)
  3783. ...but only as long as the memory blocks don't overlap
  3784. }
  3785. SourceRef := taicpu(p).oper[0]^.ref^;
  3786. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3787. if (taicpu(p).opsize = S_Q) and
  3788. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3789. GetNextInstruction(hp1, hp2) and
  3790. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3791. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3792. begin
  3793. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3794. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3795. Inc(SourceRef.offset, 8);
  3796. if UseAVX then
  3797. begin
  3798. MovAligned := A_VMOVDQA;
  3799. MovUnaligned := A_VMOVDQU;
  3800. end
  3801. else
  3802. begin
  3803. MovAligned := A_MOVDQA;
  3804. MovUnaligned := A_MOVDQU;
  3805. end;
  3806. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3807. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3808. begin
  3809. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3810. Inc(TargetRef.offset, 8);
  3811. if GetNextInstruction(hp2, hp3) and
  3812. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3813. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3814. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3815. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3816. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3817. begin
  3818. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3819. if NewMMReg <> NR_NO then
  3820. begin
  3821. { Remember that the offsets are 8 ahead }
  3822. if ((SourceRef.offset mod 16) = 8) and
  3823. (
  3824. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3825. (SourceRef.base = current_procinfo.framepointer) or
  3826. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3827. ) then
  3828. taicpu(p).opcode := MovAligned
  3829. else
  3830. taicpu(p).opcode := MovUnaligned;
  3831. taicpu(p).opsize := S_XMM;
  3832. taicpu(p).oper[1]^.reg := NewMMReg;
  3833. if ((TargetRef.offset mod 16) = 8) and
  3834. (
  3835. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3836. (TargetRef.base = current_procinfo.framepointer) or
  3837. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3838. ) then
  3839. taicpu(hp1).opcode := MovAligned
  3840. else
  3841. taicpu(hp1).opcode := MovUnaligned;
  3842. taicpu(hp1).opsize := S_XMM;
  3843. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3844. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3845. RemoveInstruction(hp2);
  3846. RemoveInstruction(hp3);
  3847. Result := True;
  3848. Exit;
  3849. end;
  3850. end;
  3851. end
  3852. else
  3853. begin
  3854. { See if the next references are 8 less rather than 8 greater }
  3855. Dec(SourceRef.offset, 16); { -8 the other way }
  3856. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3857. begin
  3858. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3859. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3860. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3861. GetNextInstruction(hp2, hp3) and
  3862. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3863. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3864. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3865. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3866. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3867. begin
  3868. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3869. if NewMMReg <> NR_NO then
  3870. begin
  3871. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3872. if ((SourceRef.offset mod 16) = 0) and
  3873. (
  3874. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3875. (SourceRef.base = current_procinfo.framepointer) or
  3876. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3877. ) then
  3878. taicpu(hp2).opcode := MovAligned
  3879. else
  3880. taicpu(hp2).opcode := MovUnaligned;
  3881. taicpu(hp2).opsize := S_XMM;
  3882. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3883. if ((TargetRef.offset mod 16) = 0) and
  3884. (
  3885. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3886. (TargetRef.base = current_procinfo.framepointer) or
  3887. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3888. ) then
  3889. taicpu(hp3).opcode := MovAligned
  3890. else
  3891. taicpu(hp3).opcode := MovUnaligned;
  3892. taicpu(hp3).opsize := S_XMM;
  3893. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3894. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3895. RemoveInstruction(hp1);
  3896. RemoveCurrentP(p);
  3897. Result := True;
  3898. Exit;
  3899. end;
  3900. end;
  3901. end;
  3902. end;
  3903. end;
  3904. {$endif x86_64}
  3905. end;
  3906. else
  3907. { The write target should be a reg or a ref }
  3908. InternalError(2021091601);
  3909. end;
  3910. else
  3911. ;
  3912. end;
  3913. end
  3914. else if (taicpu(p).oper[0]^.typ = top_const) and
  3915. { %treg is used afterwards, but all eventualities other
  3916. than the first MOV instruction being a constant are
  3917. covered by DeepMOVOpt, so only check for that }
  3918. (
  3919. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3920. not (cs_opt_size in current_settings.optimizerswitches) or
  3921. (taicpu(hp1).opsize = S_B)
  3922. ) and
  3923. (
  3924. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3925. (
  3926. { For 32-to-64-bit zero-extension, the immediate
  3927. must be between 0 and 2^31 - 1}
  3928. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3929. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3930. ) or
  3931. (
  3932. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3933. (
  3934. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3935. )
  3936. )
  3937. ) then
  3938. begin
  3939. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3940. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3941. Include(OptsToCheck, aoc_ForceNewIteration);
  3942. end;
  3943. end;
  3944. Break;
  3945. end;
  3946. end;
  3947. if taicpu(p).oper[0]^.typ = top_reg then
  3948. begin
  3949. { oper[1] is a reference }
  3950. { Saves on a large number of dereferences }
  3951. p_SourceReg := taicpu(p).oper[0]^.reg;
  3952. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3953. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3954. else
  3955. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3956. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3957. begin
  3958. if taicpu(p).oper[1]^.typ = top_reg then
  3959. begin
  3960. p_TargetReg := taicpu(p).oper[1]^.reg;
  3961. { Change:
  3962. movl %reg1,%reg2
  3963. ...
  3964. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3965. ...
  3966. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3967. To:
  3968. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3969. ...
  3970. movl x(%reg1),%reg1
  3971. ...
  3972. movl %reg1,%regX
  3973. }
  3974. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3975. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3976. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3977. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3978. not RegModifiedBetween(p_TargetReg, p, hp1) and
  3979. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  3980. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3981. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3982. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  3983. begin
  3984. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3985. if RegInRef(p_TargetReg, SourceRef) and
  3986. { If %reg1 also appears in the second reference, then it will
  3987. not refer to the same memory block as the first reference }
  3988. not RegInRef(p_SourceReg, SourceRef) then
  3989. begin
  3990. { Check to see if the references match if %reg2 is changed to %reg1 }
  3991. if SourceRef.base = p_TargetReg then
  3992. SourceRef.base := p_SourceReg;
  3993. if SourceRef.index = p_TargetReg then
  3994. SourceRef.index := p_SourceReg;
  3995. { RefsEqual also checks to ensure both references are non-volatile }
  3996. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3997. begin
  3998. taicpu(hp2).loadreg(0, p_SourceReg);
  3999. TransferUsedRegs(TmpUsedRegs);
  4000. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4001. { Make sure the register is allocated between these instructions
  4002. even though it doesn't change value, since it may cause
  4003. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4004. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4005. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4006. Result := True;
  4007. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4008. begin
  4009. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4010. RemoveCurrentP(p);
  4011. Exit;
  4012. end
  4013. else
  4014. begin
  4015. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4016. begin
  4017. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4018. RemoveCurrentP(p);
  4019. Exit;
  4020. end;
  4021. end;
  4022. { If we reach this point, p and hp1 weren't actually modified,
  4023. so we can do a bit more work on this pass }
  4024. end;
  4025. end;
  4026. end;
  4027. end;
  4028. end;
  4029. end;
  4030. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4031. { All the next optimisations require a next instruction }
  4032. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4033. Exit;
  4034. { Next instruction is also a MOV ? }
  4035. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4036. begin
  4037. if MatchOpType(taicpu(p), top_const, top_ref) and
  4038. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4039. TryConstMerge(p, hp1) then
  4040. begin
  4041. Result := True;
  4042. { In case we have four byte writes in a row, check for 2 more
  4043. right now so we don't have to wait for another iteration of
  4044. pass 1
  4045. }
  4046. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4047. case taicpu(p).opsize of
  4048. S_W:
  4049. begin
  4050. if GetNextInstruction(p, hp1) and
  4051. MatchInstruction(hp1, A_MOV, [S_B]) and
  4052. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4053. GetNextInstruction(hp1, hp2) and
  4054. MatchInstruction(hp2, A_MOV, [S_B]) and
  4055. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4056. { Try to merge the two bytes }
  4057. TryConstMerge(hp1, hp2) then
  4058. { Now try to merge the two words (hp2 will get deleted) }
  4059. TryConstMerge(p, hp1);
  4060. end;
  4061. S_L:
  4062. begin
  4063. { Though this only really benefits x86_64 and not i386, it
  4064. gets a potential optimisation done faster and hence
  4065. reduces the number of times OptPass1MOV is entered }
  4066. if GetNextInstruction(p, hp1) and
  4067. MatchInstruction(hp1, A_MOV, [S_W]) and
  4068. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4069. GetNextInstruction(hp1, hp2) and
  4070. MatchInstruction(hp2, A_MOV, [S_W]) and
  4071. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4072. { Try to merge the two words }
  4073. TryConstMerge(hp1, hp2) then
  4074. { This will always fail on i386, so don't bother
  4075. calling it unless we're doing x86_64 }
  4076. {$ifdef x86_64}
  4077. { Now try to merge the two longwords (hp2 will get deleted) }
  4078. TryConstMerge(p, hp1)
  4079. {$endif x86_64}
  4080. ;
  4081. end;
  4082. else
  4083. ;
  4084. end;
  4085. Exit;
  4086. end;
  4087. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4088. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4089. { mov reg1, mem1 or mov mem1, reg1
  4090. mov mem2, reg2 mov reg2, mem2}
  4091. begin
  4092. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4093. { mov reg1, mem1 or mov mem1, reg1
  4094. mov mem2, reg1 mov reg2, mem1}
  4095. begin
  4096. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4097. { Removes the second statement from
  4098. mov reg1, mem1/reg2
  4099. mov mem1/reg2, reg1 }
  4100. begin
  4101. if taicpu(p).oper[0]^.typ=top_reg then
  4102. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4103. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4104. RemoveInstruction(hp1);
  4105. Result:=true;
  4106. exit;
  4107. end
  4108. else
  4109. begin
  4110. TransferUsedRegs(TmpUsedRegs);
  4111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4112. if (taicpu(p).oper[1]^.typ = top_ref) and
  4113. { mov reg1, mem1
  4114. mov mem2, reg1 }
  4115. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4116. GetNextInstruction(hp1, hp2) and
  4117. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4118. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4119. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4120. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4121. { change to
  4122. mov reg1, mem1 mov reg1, mem1
  4123. mov mem2, reg1 cmp reg1, mem2
  4124. cmp mem1, reg1
  4125. }
  4126. begin
  4127. RemoveInstruction(hp2);
  4128. taicpu(hp1).opcode := A_CMP;
  4129. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4130. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4131. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4132. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4133. end;
  4134. end;
  4135. end
  4136. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4137. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4138. begin
  4139. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4140. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4141. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4142. end
  4143. else
  4144. begin
  4145. TransferUsedRegs(TmpUsedRegs);
  4146. if GetNextInstruction(hp1, hp2) and
  4147. MatchOpType(taicpu(p),top_ref,top_reg) and
  4148. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4149. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4150. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4151. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4152. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4153. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4154. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4155. { mov mem1, %reg1
  4156. mov %reg1, mem2
  4157. mov mem2, reg2
  4158. to:
  4159. mov mem1, reg2
  4160. mov reg2, mem2}
  4161. begin
  4162. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4163. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4164. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4165. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4166. RemoveInstruction(hp2);
  4167. Result := True;
  4168. end
  4169. {$ifdef i386}
  4170. { this is enabled for i386 only, as the rules to create the reg sets below
  4171. are too complicated for x86-64, so this makes this code too error prone
  4172. on x86-64
  4173. }
  4174. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4175. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4176. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4177. { mov mem1, reg1 mov mem1, reg1
  4178. mov reg1, mem2 mov reg1, mem2
  4179. mov mem2, reg2 mov mem2, reg1
  4180. to: to:
  4181. mov mem1, reg1 mov mem1, reg1
  4182. mov mem1, reg2 mov reg1, mem2
  4183. mov reg1, mem2
  4184. or (if mem1 depends on reg1
  4185. and/or if mem2 depends on reg2)
  4186. to:
  4187. mov mem1, reg1
  4188. mov reg1, mem2
  4189. mov reg1, reg2
  4190. }
  4191. begin
  4192. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4193. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4194. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4195. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4196. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4197. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4198. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4199. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4200. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4201. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4202. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4203. end
  4204. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4205. begin
  4206. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4207. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4208. end
  4209. else
  4210. begin
  4211. RemoveInstruction(hp2);
  4212. end
  4213. {$endif i386}
  4214. ;
  4215. end;
  4216. end
  4217. { movl [mem1],reg1
  4218. movl [mem1],reg2
  4219. to
  4220. movl [mem1],reg1
  4221. movl reg1,reg2
  4222. }
  4223. else if not CheckMovMov2MovMov2(p, hp1) and
  4224. { movl const1,[mem1]
  4225. movl [mem1],reg1
  4226. to
  4227. movl const1,reg1
  4228. movl reg1,[mem1]
  4229. }
  4230. MatchOpType(Taicpu(p),top_const,top_ref) and
  4231. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4232. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4233. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4234. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4235. begin
  4236. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4237. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4238. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4239. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4240. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4241. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4242. Result:=true;
  4243. exit;
  4244. end;
  4245. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4246. end;
  4247. { search further than the next instruction for a mov (as long as it's not a jump) }
  4248. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4249. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4250. (taicpu(p).oper[1]^.typ = top_reg) and
  4251. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4252. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4253. begin
  4254. { we work with hp2 here, so hp1 can be still used later on when
  4255. checking for GetNextInstruction_p }
  4256. hp3 := hp1;
  4257. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4258. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4259. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4260. TransferUsedRegs(TmpUsedRegs);
  4261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4262. if NotFirstIteration then
  4263. JumpTracking := TLinkedList.Create
  4264. else
  4265. JumpTracking := nil;
  4266. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4267. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4268. (hp2.typ=ait_instruction) do
  4269. begin
  4270. case taicpu(hp2).opcode of
  4271. A_POP:
  4272. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4273. begin
  4274. if not CrossJump and
  4275. not RegUsedBetween(p_TargetReg, p, hp2) then
  4276. begin
  4277. { We can remove the original MOV since the register
  4278. wasn't used between it and its popping from the stack }
  4279. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4280. RemoveCurrentp(p, hp1);
  4281. Result := True;
  4282. JumpTracking.Free;
  4283. Exit;
  4284. end;
  4285. { Can't go any further }
  4286. Break;
  4287. end;
  4288. A_MOV:
  4289. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4290. ((taicpu(p).oper[0]^.typ=top_const) or
  4291. ((taicpu(p).oper[0]^.typ=top_reg) and
  4292. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4293. )
  4294. ) then
  4295. begin
  4296. { we have
  4297. mov x, %treg
  4298. mov %treg, y
  4299. }
  4300. { We don't need to call UpdateUsedRegs for every instruction between
  4301. p and hp2 because the register we're concerned about will not
  4302. become deallocated (otherwise GetNextInstructionUsingReg would
  4303. have stopped at an earlier instruction). [Kit] }
  4304. TempRegUsed :=
  4305. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4306. RegReadByInstruction(p_TargetReg, hp3) or
  4307. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4308. case taicpu(p).oper[0]^.typ Of
  4309. top_reg:
  4310. begin
  4311. { change
  4312. mov %reg, %treg
  4313. mov %treg, y
  4314. to
  4315. mov %reg, y
  4316. }
  4317. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4318. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4319. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4320. begin
  4321. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4322. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4323. if TempRegUsed then
  4324. begin
  4325. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4326. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4327. { Set the start of the next GetNextInstructionUsingRegCond search
  4328. to start at the entry right before hp2 (which is about to be removed) }
  4329. hp3 := tai(hp2.Previous);
  4330. RemoveInstruction(hp2);
  4331. Include(OptsToCheck, aoc_ForceNewIteration);
  4332. { See if there's more we can optimise }
  4333. Continue;
  4334. end
  4335. else
  4336. begin
  4337. RemoveInstruction(hp2);
  4338. { We can remove the original MOV too }
  4339. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4340. RemoveCurrentP(p, hp1);
  4341. Result:=true;
  4342. JumpTracking.Free;
  4343. Exit;
  4344. end;
  4345. end
  4346. else
  4347. begin
  4348. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4349. taicpu(hp2).loadReg(0, p_SourceReg);
  4350. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4351. { Check to see if the register also appears in the reference }
  4352. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4353. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4354. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4355. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4356. begin
  4357. { Don't remove the first instruction if the temporary register is in use }
  4358. if not TempRegUsed then
  4359. begin
  4360. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4361. RemoveCurrentP(p, hp1);
  4362. Result:=true;
  4363. JumpTracking.Free;
  4364. Exit;
  4365. end;
  4366. { No need to set Result to True here. If there's another instruction later
  4367. on that can be optimised, it will be detected when the main Pass 1 loop
  4368. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4369. hp3 := hp2;
  4370. Continue;
  4371. end;
  4372. end;
  4373. end;
  4374. top_const:
  4375. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4376. begin
  4377. { change
  4378. mov const, %treg
  4379. mov %treg, y
  4380. to
  4381. mov const, y
  4382. }
  4383. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4384. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4385. begin
  4386. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4387. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4388. if TempRegUsed then
  4389. begin
  4390. { Don't remove the first instruction if the temporary register is in use }
  4391. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4392. { No need to set Result to True. If there's another instruction later on
  4393. that can be optimised, it will be detected when the main Pass 1 loop
  4394. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4395. end
  4396. else
  4397. begin
  4398. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4399. RemoveCurrentP(p, hp1);
  4400. Result:=true;
  4401. Exit;
  4402. end;
  4403. end;
  4404. end;
  4405. else
  4406. Internalerror(2019103001);
  4407. end;
  4408. end
  4409. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4410. begin
  4411. if not CrossJump and
  4412. not RegUsedBetween(p_TargetReg, p, hp2) and
  4413. not RegReadByInstruction(p_TargetReg, hp2) then
  4414. begin
  4415. { Register is not used before it is overwritten }
  4416. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4417. RemoveCurrentp(p, hp1);
  4418. Result := True;
  4419. Exit;
  4420. end;
  4421. if (taicpu(p).oper[0]^.typ = top_const) and
  4422. (taicpu(hp2).oper[0]^.typ = top_const) then
  4423. begin
  4424. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4425. begin
  4426. { Same value - register hasn't changed }
  4427. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4428. RemoveInstruction(hp2);
  4429. Include(OptsToCheck, aoc_ForceNewIteration);
  4430. { See if there's more we can optimise }
  4431. Continue;
  4432. end;
  4433. end;
  4434. {$ifdef x86_64}
  4435. end
  4436. { Change:
  4437. movl %reg1l,%reg2l
  4438. ...
  4439. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4440. To:
  4441. movl %reg1l,%reg2l
  4442. ...
  4443. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4444. If %reg1 = %reg3, convert to:
  4445. movl %reg1l,%reg2l
  4446. ...
  4447. andl %reg1l,%reg1l
  4448. }
  4449. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4450. (taicpu(p).oper[0]^.typ = top_reg) and
  4451. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4452. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4453. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4454. begin
  4455. TempRegUsed :=
  4456. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4457. RegReadByInstruction(p_TargetReg, hp3) or
  4458. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4459. taicpu(hp2).opsize := S_L;
  4460. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4461. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4462. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4463. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4464. begin
  4465. { %reg1 = %reg3 }
  4466. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4467. taicpu(hp2).opcode := A_AND;
  4468. end
  4469. else
  4470. begin
  4471. { %reg1 <> %reg3 }
  4472. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4473. end;
  4474. if not TempRegUsed then
  4475. begin
  4476. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4477. RemoveCurrentP(p, hp1);
  4478. Result := True;
  4479. Exit;
  4480. end
  4481. else
  4482. begin
  4483. { Initial instruction wasn't actually changed }
  4484. Include(OptsToCheck, aoc_ForceNewIteration);
  4485. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4486. appears below since %reg1 has technically changed }
  4487. if taicpu(hp2).opcode = A_AND then
  4488. Break;
  4489. end;
  4490. {$endif x86_64}
  4491. end
  4492. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4493. GetNextInstruction(hp2, hp4) and
  4494. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4495. { Optimise the following first:
  4496. movl [mem1],reg1
  4497. movl [mem1],reg2
  4498. to
  4499. movl [mem1],reg1
  4500. movl reg1,reg2
  4501. If [mem1] contains the target register and reg1 is the
  4502. the source register, this optimisation will get missed
  4503. and produce less efficient code later on.
  4504. }
  4505. if CheckMovMov2MovMov2(hp2, hp4) then
  4506. { Initial instruction wasn't actually changed }
  4507. Include(OptsToCheck, aoc_ForceNewIteration);
  4508. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4509. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4510. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4511. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4512. begin
  4513. {
  4514. Change from:
  4515. mov ###, %reg
  4516. ...
  4517. movs/z %reg,%reg (Same register, just different sizes)
  4518. To:
  4519. movs/z ###, %reg (Longer version)
  4520. ...
  4521. (remove)
  4522. }
  4523. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4524. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4525. { Keep the first instruction as mov if ### is a constant }
  4526. if taicpu(p).oper[0]^.typ = top_const then
  4527. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4528. else
  4529. begin
  4530. taicpu(p).opcode := taicpu(hp2).opcode;
  4531. taicpu(p).opsize := taicpu(hp2).opsize;
  4532. end;
  4533. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4534. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4535. RemoveInstruction(hp2);
  4536. Result := True;
  4537. JumpTracking.Free;
  4538. Exit;
  4539. end;
  4540. else
  4541. { Move down to the if-block below };
  4542. end;
  4543. { Also catches MOV/S/Z instructions that aren't modified }
  4544. if taicpu(p).oper[0]^.typ = top_reg then
  4545. begin
  4546. p_SourceReg := taicpu(p).oper[0]^.reg;
  4547. if
  4548. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4549. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4550. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4551. begin
  4552. Result := True;
  4553. { Just in case something didn't get modified (e.g. an
  4554. implicit register). Also, if it does read from this
  4555. register, then there's no longer an advantage to
  4556. changing the register on subsequent instructions.}
  4557. if not RegReadByInstruction(p_TargetReg, hp2) then
  4558. begin
  4559. { If a conditional jump was crossed, do not delete
  4560. the original MOV no matter what }
  4561. if not CrossJump and
  4562. { RegEndOfLife returns True if the register is
  4563. deallocated before the next instruction or has
  4564. been loaded with a new value }
  4565. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4566. begin
  4567. { We can remove the original MOV }
  4568. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4569. RemoveCurrentp(p, hp1);
  4570. JumpTracking.Free;
  4571. Result := True;
  4572. Exit;
  4573. end;
  4574. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4575. begin
  4576. { See if there's more we can optimise }
  4577. hp3 := hp2;
  4578. Continue;
  4579. end;
  4580. end;
  4581. end;
  4582. end;
  4583. { Break out of the while loop under normal circumstances }
  4584. Break;
  4585. end;
  4586. JumpTracking.Free;
  4587. end;
  4588. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4589. (taicpu(p).oper[1]^.typ = top_reg) and
  4590. (taicpu(p).opsize = S_L) and
  4591. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4592. (hp2.typ = ait_instruction) and
  4593. (taicpu(hp2).opcode = A_AND) and
  4594. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4595. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4596. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4597. ) then
  4598. begin
  4599. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4600. begin
  4601. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4602. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4603. begin
  4604. { Optimize out:
  4605. mov x, %reg
  4606. and ffffffffh, %reg
  4607. }
  4608. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4609. RemoveInstruction(hp2);
  4610. Result:=true;
  4611. exit;
  4612. end;
  4613. end;
  4614. end;
  4615. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4616. x >= RetOffset) as it doesn't do anything (it writes either to a
  4617. parameter or to the temporary storage room for the function
  4618. result)
  4619. }
  4620. if IsExitCode(hp1) and
  4621. (taicpu(p).oper[1]^.typ = top_ref) and
  4622. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4623. (
  4624. (
  4625. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4626. not (
  4627. assigned(current_procinfo.procdef.funcretsym) and
  4628. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4629. )
  4630. ) or
  4631. { Also discard writes to the stack that are below the base pointer,
  4632. as this is temporary storage rather than a function result on the
  4633. stack, say. }
  4634. (
  4635. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4636. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4637. )
  4638. ) then
  4639. begin
  4640. RemoveCurrentp(p, hp1);
  4641. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4642. RemoveLastDeallocForFuncRes(p);
  4643. Result:=true;
  4644. exit;
  4645. end;
  4646. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4647. begin
  4648. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4649. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4650. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4651. begin
  4652. { change
  4653. mov reg1, mem1
  4654. test/cmp x, mem1
  4655. to
  4656. mov reg1, mem1
  4657. test/cmp x, reg1
  4658. }
  4659. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4660. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4661. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4662. Result := True;
  4663. Exit;
  4664. end;
  4665. if DoMovCmpMemOpt(p, hp1) then
  4666. begin
  4667. Result := True;
  4668. Exit;
  4669. end;
  4670. end;
  4671. if (taicpu(p).oper[1]^.typ = top_reg) and
  4672. (hp1.typ = ait_instruction) and
  4673. GetNextInstruction(hp1, hp2) and
  4674. MatchInstruction(hp2,A_MOV,[]) and
  4675. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4676. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4677. (
  4678. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4679. {$ifdef x86_64}
  4680. or
  4681. (
  4682. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4683. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4684. )
  4685. {$endif x86_64}
  4686. ) then
  4687. begin
  4688. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4689. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4690. { change movsX/movzX reg/ref, reg2
  4691. add/sub/or/... reg3/$const, reg2
  4692. mov reg2 reg/ref
  4693. dealloc reg2
  4694. to
  4695. add/sub/or/... reg3/$const, reg/ref }
  4696. begin
  4697. TransferUsedRegs(TmpUsedRegs);
  4698. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4699. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4700. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4701. begin
  4702. { by example:
  4703. movswl %si,%eax movswl %si,%eax p
  4704. decl %eax addl %edx,%eax hp1
  4705. movw %ax,%si movw %ax,%si hp2
  4706. ->
  4707. movswl %si,%eax movswl %si,%eax p
  4708. decw %eax addw %edx,%eax hp1
  4709. movw %ax,%si movw %ax,%si hp2
  4710. }
  4711. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4712. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4713. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4714. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4715. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4716. {
  4717. ->
  4718. movswl %si,%eax movswl %si,%eax p
  4719. decw %si addw %dx,%si hp1
  4720. movw %ax,%si movw %ax,%si hp2
  4721. }
  4722. case taicpu(hp1).ops of
  4723. 1:
  4724. begin
  4725. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4726. if taicpu(hp1).oper[0]^.typ=top_reg then
  4727. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4728. end;
  4729. 2:
  4730. begin
  4731. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4732. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4733. (taicpu(hp1).opcode<>A_SHL) and
  4734. (taicpu(hp1).opcode<>A_SHR) and
  4735. (taicpu(hp1).opcode<>A_SAR) then
  4736. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4737. end;
  4738. else
  4739. internalerror(2008042701);
  4740. end;
  4741. {
  4742. ->
  4743. decw %si addw %dx,%si p
  4744. }
  4745. RemoveInstruction(hp2);
  4746. RemoveCurrentP(p, hp1);
  4747. Result:=True;
  4748. Exit;
  4749. end;
  4750. end;
  4751. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4752. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4753. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4754. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4755. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4756. )
  4757. {$ifdef i386}
  4758. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4759. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4760. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4761. {$endif i386}
  4762. then
  4763. { change movsX/movzX reg/ref, reg2
  4764. add/sub/or/... regX/$const, reg2
  4765. mov reg2, reg3
  4766. dealloc reg2
  4767. to
  4768. movsX/movzX reg/ref, reg3
  4769. add/sub/or/... reg3/$const, reg3
  4770. }
  4771. begin
  4772. TransferUsedRegs(TmpUsedRegs);
  4773. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4774. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4775. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4776. begin
  4777. { by example:
  4778. movswl %si,%eax movswl %si,%eax p
  4779. decl %eax addl %edx,%eax hp1
  4780. movw %ax,%si movw %ax,%si hp2
  4781. ->
  4782. movswl %si,%eax movswl %si,%eax p
  4783. decw %eax addw %edx,%eax hp1
  4784. movw %ax,%si movw %ax,%si hp2
  4785. }
  4786. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4787. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4788. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4789. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4790. { limit size of constants as well to avoid assembler errors, but
  4791. check opsize to avoid overflow when left shifting the 1 }
  4792. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4793. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4794. {$ifdef x86_64}
  4795. { Be careful of, for example:
  4796. movl %reg1,%reg2
  4797. addl %reg3,%reg2
  4798. movq %reg2,%reg4
  4799. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4800. }
  4801. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4802. begin
  4803. taicpu(hp2).changeopsize(S_L);
  4804. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4805. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4806. end;
  4807. {$endif x86_64}
  4808. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4809. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4810. if taicpu(p).oper[0]^.typ=top_reg then
  4811. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4812. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4813. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4814. {
  4815. ->
  4816. movswl %si,%eax movswl %si,%eax p
  4817. decw %si addw %dx,%si hp1
  4818. movw %ax,%si movw %ax,%si hp2
  4819. }
  4820. case taicpu(hp1).ops of
  4821. 1:
  4822. begin
  4823. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4824. if taicpu(hp1).oper[0]^.typ=top_reg then
  4825. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4826. end;
  4827. 2:
  4828. begin
  4829. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4830. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4831. (taicpu(hp1).opcode<>A_SHL) and
  4832. (taicpu(hp1).opcode<>A_SHR) and
  4833. (taicpu(hp1).opcode<>A_SAR) then
  4834. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4835. end;
  4836. else
  4837. internalerror(2018111801);
  4838. end;
  4839. {
  4840. ->
  4841. decw %si addw %dx,%si p
  4842. }
  4843. RemoveInstruction(hp2);
  4844. end;
  4845. end;
  4846. end;
  4847. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4848. GetNextInstruction(hp1, hp2) and
  4849. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4850. MatchOperand(Taicpu(p).oper[0]^,0) and
  4851. (Taicpu(p).oper[1]^.typ = top_reg) and
  4852. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4853. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4854. { mov reg1,0
  4855. bts reg1,operand1 --> mov reg1,operand2
  4856. or reg1,operand2 bts reg1,operand1}
  4857. begin
  4858. Taicpu(hp2).opcode:=A_MOV;
  4859. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4860. asml.remove(hp1);
  4861. insertllitem(hp2,hp2.next,hp1);
  4862. RemoveCurrentp(p, hp1);
  4863. Result:=true;
  4864. exit;
  4865. end;
  4866. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4867. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4868. GetNextInstruction(hp1, hp2) and
  4869. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4870. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4871. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4872. { change
  4873. mov reg1,reg2
  4874. sub reg3,reg2
  4875. cmp reg3,reg1
  4876. into
  4877. mov reg1,reg2
  4878. sub reg3,reg2
  4879. }
  4880. begin
  4881. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4882. RemoveInstruction(hp2);
  4883. Result:=true;
  4884. exit;
  4885. end;
  4886. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4887. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4888. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4889. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4890. begin
  4891. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4892. {$ifdef x86_64}
  4893. { Convert:
  4894. movq x(ref),%reg64
  4895. shrq y,%reg64
  4896. To:
  4897. movl x+4(ref),%reg32
  4898. shrl y-32,%reg32 (Remove if y = 32)
  4899. }
  4900. if (taicpu(p).opsize = S_Q) and
  4901. (taicpu(hp1).opcode = A_SHR) and
  4902. (taicpu(hp1).oper[0]^.val >= 32) then
  4903. begin
  4904. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4905. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4906. { Convert to 32-bit }
  4907. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4908. taicpu(p).opsize := S_L;
  4909. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4910. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4911. if (taicpu(hp1).oper[0]^.val = 32) then
  4912. begin
  4913. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4914. RemoveInstruction(hp1);
  4915. end
  4916. else
  4917. begin
  4918. { This will potentially open up more arithmetic operations since
  4919. the peephole optimizer now has a big hint that only the lower
  4920. 32 bits are currently in use (and opcodes are smaller in size) }
  4921. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4922. taicpu(hp1).opsize := S_L;
  4923. Dec(taicpu(hp1).oper[0]^.val, 32);
  4924. DebugMsg(SPeepholeOptimization + PreMessage +
  4925. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4926. end;
  4927. Result := True;
  4928. Exit;
  4929. end;
  4930. {$endif x86_64}
  4931. { Convert:
  4932. movl x(ref),%reg
  4933. shrl $24,%reg
  4934. To:
  4935. movzbl x+3(ref),%reg
  4936. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4937. Also accept sar instead of shr, but convert to movsx instead of movzx
  4938. }
  4939. if taicpu(hp1).opcode = A_SHR then
  4940. MovUnaligned := A_MOVZX
  4941. else
  4942. MovUnaligned := A_MOVSX;
  4943. NewSize := S_NO;
  4944. NewOffset := 0;
  4945. case taicpu(p).opsize of
  4946. S_B:
  4947. { No valid combinations };
  4948. S_W:
  4949. if (taicpu(hp1).oper[0]^.val = 8) then
  4950. begin
  4951. NewSize := S_BW;
  4952. NewOffset := 1;
  4953. end;
  4954. S_L:
  4955. case taicpu(hp1).oper[0]^.val of
  4956. 16:
  4957. begin
  4958. NewSize := S_WL;
  4959. NewOffset := 2;
  4960. end;
  4961. 24:
  4962. begin
  4963. NewSize := S_BL;
  4964. NewOffset := 3;
  4965. end;
  4966. else
  4967. ;
  4968. end;
  4969. {$ifdef x86_64}
  4970. S_Q:
  4971. case taicpu(hp1).oper[0]^.val of
  4972. 32:
  4973. begin
  4974. if taicpu(hp1).opcode = A_SAR then
  4975. begin
  4976. { 32-bit to 64-bit is a distinct instruction }
  4977. MovUnaligned := A_MOVSXD;
  4978. NewSize := S_LQ;
  4979. NewOffset := 4;
  4980. end
  4981. else
  4982. { Should have been handled by MovShr2Mov above }
  4983. InternalError(2022081811);
  4984. end;
  4985. 48:
  4986. begin
  4987. NewSize := S_WQ;
  4988. NewOffset := 6;
  4989. end;
  4990. 56:
  4991. begin
  4992. NewSize := S_BQ;
  4993. NewOffset := 7;
  4994. end;
  4995. else
  4996. ;
  4997. end;
  4998. {$endif x86_64}
  4999. else
  5000. InternalError(2022081810);
  5001. end;
  5002. if (NewSize <> S_NO) and
  5003. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5004. begin
  5005. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5006. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5007. debug_op2str(MovUnaligned);
  5008. {$ifdef x86_64}
  5009. if MovUnaligned <> A_MOVSXD then
  5010. { Don't add size suffix for MOVSXD }
  5011. {$endif x86_64}
  5012. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5013. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5014. taicpu(p).opcode := MovUnaligned;
  5015. taicpu(p).opsize := NewSize;
  5016. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5017. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5018. RemoveInstruction(hp1);
  5019. Result := True;
  5020. Exit;
  5021. end;
  5022. end;
  5023. { Backward optimisation shared with OptPass2MOV }
  5024. if FuncMov2Func(p, hp1) then
  5025. begin
  5026. Result := True;
  5027. Exit;
  5028. end;
  5029. end;
  5030. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5031. var
  5032. hp1 : tai;
  5033. begin
  5034. Result:=false;
  5035. if taicpu(p).ops <> 2 then
  5036. exit;
  5037. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5038. GetNextInstruction(p,hp1) then
  5039. begin
  5040. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5041. (taicpu(hp1).ops = 2) then
  5042. begin
  5043. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5044. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5045. { movXX reg1, mem1 or movXX mem1, reg1
  5046. movXX mem2, reg2 movXX reg2, mem2}
  5047. begin
  5048. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5049. { movXX reg1, mem1 or movXX mem1, reg1
  5050. movXX mem2, reg1 movXX reg2, mem1}
  5051. begin
  5052. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5053. begin
  5054. { Removes the second statement from
  5055. movXX reg1, mem1/reg2
  5056. movXX mem1/reg2, reg1
  5057. }
  5058. if taicpu(p).oper[0]^.typ=top_reg then
  5059. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5060. { Removes the second statement from
  5061. movXX mem1/reg1, reg2
  5062. movXX reg2, mem1/reg1
  5063. }
  5064. if (taicpu(p).oper[1]^.typ=top_reg) and
  5065. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5066. begin
  5067. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5068. RemoveInstruction(hp1);
  5069. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5070. Result:=true;
  5071. exit;
  5072. end
  5073. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5074. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5075. begin
  5076. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5077. RemoveInstruction(hp1);
  5078. Result:=true;
  5079. exit;
  5080. end;
  5081. end
  5082. end;
  5083. end;
  5084. end;
  5085. end;
  5086. end;
  5087. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5088. var
  5089. hp1 : tai;
  5090. begin
  5091. result:=false;
  5092. { replace
  5093. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5094. MovX %mreg2,%mreg1
  5095. dealloc %mreg2
  5096. by
  5097. <Op>X %mreg2,%mreg1
  5098. ?
  5099. }
  5100. if GetNextInstruction(p,hp1) and
  5101. { we mix single and double opperations here because we assume that the compiler
  5102. generates vmovapd only after double operations and vmovaps only after single operations }
  5103. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5104. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5105. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5106. (taicpu(p).oper[0]^.typ=top_reg) then
  5107. begin
  5108. TransferUsedRegs(TmpUsedRegs);
  5109. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5110. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5111. begin
  5112. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5113. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5114. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5115. RemoveInstruction(hp1);
  5116. result:=true;
  5117. end;
  5118. end;
  5119. end;
  5120. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5121. var
  5122. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5123. JumpLabel, JumpLabel_dist: TAsmLabel;
  5124. FirstValue, SecondValue: TCGInt;
  5125. function OptimizeJump(var InputP: tai): Boolean;
  5126. var
  5127. TempBool: Boolean;
  5128. begin
  5129. Result := False;
  5130. TempBool := True;
  5131. if DoJumpOptimizations(InputP, TempBool) or
  5132. not TempBool then
  5133. begin
  5134. Result := True;
  5135. if Assigned(InputP) then
  5136. begin
  5137. { CollapseZeroDistJump will be set to the label or an align
  5138. before it after the jump if it optimises, whether or not
  5139. the label is live or dead }
  5140. if (InputP.typ = ait_align) or
  5141. (
  5142. (InputP.typ = ait_label) and
  5143. not (tai_label(InputP).labsym.is_used)
  5144. ) then
  5145. GetNextInstruction(InputP, InputP);
  5146. end;
  5147. Exit;
  5148. end;
  5149. end;
  5150. begin
  5151. Result := False;
  5152. if (taicpu(p).oper[0]^.typ = top_const) and
  5153. (taicpu(p).oper[0]^.val <> -1) then
  5154. begin
  5155. { Convert unsigned maximum constants to -1 to aid optimisation }
  5156. case taicpu(p).opsize of
  5157. S_B:
  5158. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5159. begin
  5160. taicpu(p).oper[0]^.val := -1;
  5161. Result := True;
  5162. Exit;
  5163. end;
  5164. S_W:
  5165. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5166. begin
  5167. taicpu(p).oper[0]^.val := -1;
  5168. Result := True;
  5169. Exit;
  5170. end;
  5171. S_L:
  5172. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5173. begin
  5174. taicpu(p).oper[0]^.val := -1;
  5175. Result := True;
  5176. Exit;
  5177. end;
  5178. {$ifdef x86_64}
  5179. S_Q:
  5180. { Storing anything greater than $7FFFFFFF is not possible so do
  5181. nothing };
  5182. {$endif x86_64}
  5183. else
  5184. InternalError(2021121001);
  5185. end;
  5186. end;
  5187. if GetNextInstruction(p, hp1) and
  5188. TrySwapMovCmp(p, hp1) then
  5189. begin
  5190. Result := True;
  5191. Exit;
  5192. end;
  5193. p_label := nil;
  5194. JumpLabel := nil;
  5195. if MatchInstruction(hp1, A_Jcc, []) then
  5196. begin
  5197. if OptimizeJump(hp1) then
  5198. begin
  5199. Result := True;
  5200. if Assigned(hp1) then
  5201. begin
  5202. { CollapseZeroDistJump will be set to the label or an align
  5203. before it after the jump if it optimises, whether or not
  5204. the label is live or dead }
  5205. if (hp1.typ = ait_align) or
  5206. (
  5207. (hp1.typ = ait_label) and
  5208. not (tai_label(hp1).labsym.is_used)
  5209. ) then
  5210. GetNextInstruction(hp1, hp1);
  5211. end;
  5212. TransferUsedRegs(TmpUsedRegs);
  5213. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5214. if not Assigned(hp1) or
  5215. (
  5216. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5217. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5218. ) then
  5219. begin
  5220. { No more conditional jumps; conditional statement is no longer required }
  5221. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5222. RemoveCurrentP(p);
  5223. end;
  5224. Exit;
  5225. end;
  5226. if IsJumpToLabel(taicpu(hp1)) then
  5227. begin
  5228. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5229. if Assigned(JumpLabel) then
  5230. p_label := getlabelwithsym(JumpLabel);
  5231. end;
  5232. end;
  5233. { Search for:
  5234. test $x,(reg/ref)
  5235. jne @lbl1
  5236. test $y,(reg/ref) (same register or reference)
  5237. jne @lbl1
  5238. Change to:
  5239. test $(x or y),(reg/ref)
  5240. jne @lbl1
  5241. (Note, this doesn't work with je instead of jne)
  5242. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5243. Also search for:
  5244. test $x,(reg/ref)
  5245. je @lbl1
  5246. ...
  5247. test $y,(reg/ref)
  5248. je/jne @lbl2
  5249. If (x or y) = x, then the second jump is deterministic
  5250. }
  5251. if (
  5252. (
  5253. (taicpu(p).oper[0]^.typ = top_const) or
  5254. (
  5255. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5256. (taicpu(p).oper[0]^.typ = top_reg) and
  5257. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5258. )
  5259. ) and
  5260. MatchInstruction(hp1, A_JCC, [])
  5261. ) then
  5262. begin
  5263. if (taicpu(p).oper[0]^.typ = top_reg) and
  5264. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5265. FirstValue := -1
  5266. else
  5267. FirstValue := taicpu(p).oper[0]^.val;
  5268. { If we have several test/jne's in a row, it might be the case that
  5269. the second label doesn't go to the same location, but the one
  5270. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5271. so accommodate for this with a while loop.
  5272. }
  5273. hp1_last := hp1;
  5274. while (
  5275. (
  5276. (taicpu(p).oper[1]^.typ = top_reg) and
  5277. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5278. ) or GetNextInstruction(hp1_last, p_dist)
  5279. ) and (p_dist.typ = ait_instruction) do
  5280. begin
  5281. if (
  5282. (
  5283. (taicpu(p_dist).opcode = A_TEST) and
  5284. (
  5285. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5286. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5287. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5288. )
  5289. ) or
  5290. (
  5291. { cmp 0,%reg = test %reg,%reg }
  5292. (taicpu(p_dist).opcode = A_CMP) and
  5293. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5294. )
  5295. ) and
  5296. { Make sure the destination operands are actually the same }
  5297. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5298. GetNextInstruction(p_dist, hp1_dist) and
  5299. MatchInstruction(hp1_dist, A_JCC, []) then
  5300. begin
  5301. if OptimizeJump(hp1_dist) then
  5302. begin
  5303. Result := True;
  5304. Exit;
  5305. end;
  5306. if
  5307. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5308. (
  5309. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5310. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5311. ) then
  5312. SecondValue := -1
  5313. else
  5314. SecondValue := taicpu(p_dist).oper[0]^.val;
  5315. { If both of the TEST constants are identical, delete the
  5316. second TEST that is unnecessary (be careful though, just
  5317. in case the flags are modified in between) }
  5318. if (FirstValue = SecondValue) then
  5319. begin
  5320. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5321. begin
  5322. { Since the second jump's condition is a subset of the first, we
  5323. know it will never branch because the first jump dominates it.
  5324. Get it out of the way now rather than wait for the jump
  5325. optimisations for a speed boost. }
  5326. if IsJumpToLabel(taicpu(hp1_dist)) then
  5327. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5328. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5329. RemoveInstruction(hp1_dist);
  5330. Result := True;
  5331. end
  5332. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5333. begin
  5334. { If the inverse of the first condition is a subset of the second,
  5335. the second one will definitely branch if the first one doesn't }
  5336. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5337. { We can remove the TEST instruction too }
  5338. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5339. RemoveInstruction(p_dist);
  5340. MakeUnconditional(taicpu(hp1_dist));
  5341. RemoveDeadCodeAfterJump(hp1_dist);
  5342. { Since the jump is now unconditional, we can't
  5343. continue any further with this particular
  5344. optimisation. The original TEST is still intact
  5345. though, so there might be something else we can
  5346. do }
  5347. Include(OptsToCheck, aoc_ForceNewIteration);
  5348. Break;
  5349. end;
  5350. if Result or
  5351. { If a jump wasn't removed or made unconditional, only
  5352. remove the identical TEST instruction if the flags
  5353. weren't modified }
  5354. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5355. begin
  5356. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5357. RemoveInstruction(p_dist);
  5358. { If the jump was removed or made unconditional, we
  5359. don't need to allocate NR_DEFAULTFLAGS over the
  5360. entire range }
  5361. if not Result then
  5362. begin
  5363. { Mark the flags as 'in use' over the entire range }
  5364. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5365. { Speed gain - continue search from the Jcc instruction }
  5366. hp1_last := hp1_dist;
  5367. { Only the TEST instruction was removed, and the
  5368. original was unchanged, so we can safely do
  5369. another iteration of the while loop }
  5370. Include(OptsToCheck, aoc_ForceNewIteration);
  5371. Continue;
  5372. end;
  5373. Exit;
  5374. end;
  5375. end;
  5376. hp1_last := nil;
  5377. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5378. (
  5379. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5380. { Always adjacent under -O2 and under }
  5381. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5382. (
  5383. GetNextInstruction(hp1, hp1_last) and
  5384. (hp1_last = p_dist)
  5385. )
  5386. ) and
  5387. (
  5388. (
  5389. { Test the following variant:
  5390. test $x,(reg/ref)
  5391. jne @lbl1
  5392. test $y,(reg/ref)
  5393. je @lbl2
  5394. @lbl1:
  5395. Becomes:
  5396. test $(x or y),(reg/ref)
  5397. je @lbl2
  5398. @lbl1: (may become a dead label)
  5399. }
  5400. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5401. GetNextInstruction(hp1_dist, hp1_last) and
  5402. (hp1_last = p_label)
  5403. ) or
  5404. (
  5405. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5406. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5407. then the second jump will never branch, so it can also be
  5408. removed regardless of where it goes }
  5409. (
  5410. (FirstValue = -1) or
  5411. (SecondValue = -1) or
  5412. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5413. )
  5414. )
  5415. ) then
  5416. begin
  5417. { Same jump location... can be a register since nothing's changed }
  5418. { If any of the entries are equivalent to test %reg,%reg, then the
  5419. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5420. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5421. if (hp1_last = p_label) then
  5422. begin
  5423. { Variant }
  5424. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5425. RemoveInstruction(p_dist);
  5426. if Assigned(JumpLabel) then
  5427. JumpLabel.decrefs;
  5428. RemoveInstruction(hp1);
  5429. end
  5430. else
  5431. begin
  5432. { Only remove the second test if no jumps or other conditional instructions follow }
  5433. TransferUsedRegs(TmpUsedRegs);
  5434. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5435. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5436. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5437. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5438. begin
  5439. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5440. RemoveInstruction(p_dist);
  5441. { Remove the first jump, not the second, to keep
  5442. any register deallocations between the second
  5443. TEST/JNE pair in the same place. Aids future
  5444. optimisation. }
  5445. if Assigned(JumpLabel) then
  5446. JumpLabel.decrefs;
  5447. RemoveInstruction(hp1);
  5448. end
  5449. else
  5450. begin
  5451. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5452. if IsJumpToLabel(taicpu(hp1_dist)) then
  5453. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5454. { Remove second jump in this instance }
  5455. RemoveInstruction(hp1_dist);
  5456. end;
  5457. end;
  5458. Result := True;
  5459. Exit;
  5460. end;
  5461. end;
  5462. if { If -O2 and under, it may stop on any old instruction }
  5463. (cs_opt_level3 in current_settings.optimizerswitches) and
  5464. (taicpu(p).oper[1]^.typ = top_reg) and
  5465. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5466. begin
  5467. hp1_last := p_dist;
  5468. Continue;
  5469. end;
  5470. Break;
  5471. end;
  5472. end;
  5473. { Search for:
  5474. test %reg,%reg
  5475. j(c1) @lbl1
  5476. ...
  5477. @lbl:
  5478. test %reg,%reg (same register)
  5479. j(c2) @lbl2
  5480. If c2 is a subset of c1, change to:
  5481. test %reg,%reg
  5482. j(c1) @lbl2
  5483. (@lbl1 may become a dead label as a result)
  5484. }
  5485. if (taicpu(p).oper[1]^.typ = top_reg) and
  5486. (taicpu(p).oper[0]^.typ = top_reg) and
  5487. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5488. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5489. Assigned(p_label) and
  5490. GetNextInstruction(p_label, p_dist) and
  5491. MatchInstruction(p_dist, A_TEST, []) and
  5492. { It's fine if the second test uses smaller sub-registers }
  5493. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5494. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5495. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5496. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5497. GetNextInstruction(p_dist, hp1_dist) and
  5498. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5499. begin
  5500. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5501. if JumpLabel = JumpLabel_dist then
  5502. { This is an infinite loop }
  5503. Exit;
  5504. { Best optimisation when the first condition is a subset (or equal) of the second }
  5505. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5506. begin
  5507. { Any registers used here will already be allocated }
  5508. if Assigned(JumpLabel) then
  5509. JumpLabel.DecRefs;
  5510. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5511. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5512. Result := True;
  5513. Exit;
  5514. end;
  5515. end;
  5516. end;
  5517. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5518. var
  5519. hp1, hp2: tai;
  5520. ActiveReg: TRegister;
  5521. OldOffset: asizeint;
  5522. ThisConst: TCGInt;
  5523. function RegDeallocated: Boolean;
  5524. begin
  5525. TransferUsedRegs(TmpUsedRegs);
  5526. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5527. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5528. end;
  5529. begin
  5530. result:=false;
  5531. hp1 := nil;
  5532. { replace
  5533. addX const,%reg1
  5534. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5535. dealloc %reg1
  5536. by
  5537. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5538. }
  5539. if MatchOpType(taicpu(p),top_const,top_reg) then
  5540. begin
  5541. ActiveReg := taicpu(p).oper[1]^.reg;
  5542. { Ensures the entire register was updated }
  5543. if (taicpu(p).opsize >= S_L) and
  5544. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5545. MatchInstruction(hp1,A_LEA,[]) and
  5546. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5547. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5548. (
  5549. { Cover the case where the register in the reference is also the destination register }
  5550. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5551. (
  5552. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5553. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5554. RegDeallocated
  5555. )
  5556. ) then
  5557. begin
  5558. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5559. {$push}
  5560. {$R-}{$Q-}
  5561. { Explicitly disable overflow checking for these offset calculation
  5562. as those do not matter for the final result }
  5563. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5564. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5565. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5566. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5567. {$pop}
  5568. {$ifdef x86_64}
  5569. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5570. begin
  5571. { Overflow; abort }
  5572. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5573. end
  5574. else
  5575. {$endif x86_64}
  5576. begin
  5577. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5578. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5579. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5580. RemoveCurrentP(p, hp1)
  5581. else
  5582. RemoveCurrentP(p);
  5583. result:=true;
  5584. Exit;
  5585. end;
  5586. end;
  5587. if (
  5588. { Save calling GetNextInstructionUsingReg again }
  5589. Assigned(hp1) or
  5590. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5591. ) and
  5592. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5593. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5594. begin
  5595. if taicpu(hp1).oper[0]^.typ = top_const then
  5596. begin
  5597. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5598. if taicpu(hp1).opcode = A_ADD then
  5599. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5600. else
  5601. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5602. Result := True;
  5603. { Handle any overflows }
  5604. case taicpu(p).opsize of
  5605. S_B:
  5606. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5607. S_W:
  5608. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5609. S_L:
  5610. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5611. {$ifdef x86_64}
  5612. S_Q:
  5613. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5614. { Overflow; abort }
  5615. Result := False
  5616. else
  5617. taicpu(p).oper[0]^.val := ThisConst;
  5618. {$endif x86_64}
  5619. else
  5620. InternalError(2021102610);
  5621. end;
  5622. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5623. if Result then
  5624. begin
  5625. if (taicpu(p).oper[0]^.val < 0) and
  5626. (
  5627. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5628. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5629. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5630. ) then
  5631. begin
  5632. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5633. taicpu(p).opcode := A_SUB;
  5634. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5635. end
  5636. else
  5637. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5638. RemoveInstruction(hp1);
  5639. end;
  5640. end
  5641. else
  5642. begin
  5643. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5644. TransferUsedRegs(TmpUsedRegs);
  5645. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5646. hp2 := p;
  5647. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5648. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5649. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5650. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5651. begin
  5652. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5653. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5654. Asml.Remove(p);
  5655. Asml.InsertAfter(p, hp1);
  5656. p := hp1;
  5657. Result := True;
  5658. Exit;
  5659. end;
  5660. end;
  5661. end;
  5662. if DoArithCombineOpt(p) then
  5663. Result:=true;
  5664. end;
  5665. end;
  5666. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5667. var
  5668. hp1, hp2: tai;
  5669. ref: Integer;
  5670. saveref: treference;
  5671. offsetcalc: Int64;
  5672. TempReg: TRegister;
  5673. Multiple: TCGInt;
  5674. Adjacent, IntermediateRegDiscarded: Boolean;
  5675. begin
  5676. Result:=false;
  5677. { play save and throw an error if LEA uses a seg register prefix,
  5678. this is most likely an error somewhere else }
  5679. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5680. internalerror(2022022001);
  5681. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5682. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5683. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5684. (
  5685. { do not mess with leas accessing the stack pointer
  5686. unless it's a null operation }
  5687. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5688. (
  5689. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5690. (taicpu(p).oper[0]^.ref^.offset = 0)
  5691. )
  5692. ) and
  5693. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5694. begin
  5695. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5696. begin
  5697. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5698. begin
  5699. taicpu(p).opcode := A_MOV;
  5700. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5701. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5702. end
  5703. else
  5704. begin
  5705. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5706. RemoveCurrentP(p);
  5707. end;
  5708. Result:=true;
  5709. exit;
  5710. end
  5711. else if (
  5712. { continue to use lea to adjust the stack pointer,
  5713. it is the recommended way, but only if not optimizing for size }
  5714. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5715. (cs_opt_size in current_settings.optimizerswitches)
  5716. ) and
  5717. { If the flags register is in use, don't change the instruction
  5718. to an ADD otherwise this will scramble the flags. [Kit] }
  5719. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5720. ConvertLEA(taicpu(p)) then
  5721. begin
  5722. Result:=true;
  5723. exit;
  5724. end;
  5725. end;
  5726. { Don't optimise if the stack or frame pointer is the destination register }
  5727. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5728. Exit;
  5729. if GetNextInstruction(p,hp1) and
  5730. (hp1.typ=ait_instruction) then
  5731. begin
  5732. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5733. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5734. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5735. begin
  5736. TransferUsedRegs(TmpUsedRegs);
  5737. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5738. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5739. begin
  5740. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5741. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5742. RemoveInstruction(hp1);
  5743. result:=true;
  5744. exit;
  5745. end;
  5746. end;
  5747. { changes
  5748. lea <ref1>, reg1
  5749. <op> ...,<ref. with reg1>,...
  5750. to
  5751. <op> ...,<ref1>,... }
  5752. { find a reference which uses reg1 }
  5753. 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
  5754. ref:=0
  5755. 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
  5756. ref:=1
  5757. else
  5758. ref:=-1;
  5759. if (ref<>-1) and
  5760. { reg1 must be either the base or the index }
  5761. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5762. begin
  5763. { reg1 can be removed from the reference }
  5764. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5765. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5766. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5767. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5768. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5769. else
  5770. Internalerror(2019111201);
  5771. { check if the can insert all data of the lea into the second instruction }
  5772. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5773. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5774. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5775. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5776. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5777. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5778. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5779. {$ifdef x86_64}
  5780. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5781. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5782. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5783. )
  5784. {$endif x86_64}
  5785. then
  5786. begin
  5787. { reg1 might not used by the second instruction after it is remove from the reference }
  5788. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5789. begin
  5790. TransferUsedRegs(TmpUsedRegs);
  5791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5792. { reg1 is not updated so it might not be used afterwards }
  5793. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5794. begin
  5795. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5796. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5797. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5798. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5799. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5800. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5801. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5802. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5803. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5804. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5805. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5806. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5807. RemoveCurrentP(p, hp1);
  5808. result:=true;
  5809. exit;
  5810. end
  5811. end;
  5812. end;
  5813. { recover }
  5814. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5815. end;
  5816. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5817. if Adjacent or
  5818. { Check further ahead (up to 2 instructions ahead for -O2) }
  5819. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5820. begin
  5821. { Check common LEA/LEA conditions }
  5822. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5823. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5824. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5825. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5826. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5827. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5828. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5829. (
  5830. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5831. calling it (since it calls GetNextInstruction) }
  5832. Adjacent or
  5833. (
  5834. (
  5835. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5836. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5837. ) and (
  5838. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5839. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5840. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5841. )
  5842. )
  5843. ) then
  5844. begin
  5845. TransferUsedRegs(TmpUsedRegs);
  5846. hp2 := p;
  5847. repeat
  5848. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5849. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5850. IntermediateRegDiscarded :=
  5851. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5852. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5853. { changes
  5854. lea offset1(regX,scale), reg1
  5855. lea offset2(reg1,reg1), reg2
  5856. to
  5857. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5858. and
  5859. lea offset1(regX,scale1), reg1
  5860. lea offset2(reg1,scale2), reg2
  5861. to
  5862. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5863. and
  5864. lea offset1(regX,scale1), reg1
  5865. lea offset2(reg3,reg1,scale2), reg2
  5866. to
  5867. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5868. ... so long as the final scale does not exceed 8
  5869. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5870. }
  5871. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5872. (
  5873. { Don't optimise if size is a concern and the intermediate register remains in use }
  5874. IntermediateRegDiscarded or
  5875. (
  5876. not (cs_opt_size in current_settings.optimizerswitches) and
  5877. { If the intermediate register is not discarded, it must not
  5878. appear in the first LEA's reference. (Fixes #41166) }
  5879. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5880. )
  5881. ) and
  5882. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5883. (
  5884. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5885. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5886. ) and (
  5887. (
  5888. { lea (reg1,scale2), reg2 variant }
  5889. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5890. (
  5891. Adjacent or
  5892. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5893. ) and
  5894. (
  5895. (
  5896. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5897. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5898. ) or (
  5899. { lea (regX,regX), reg1 variant }
  5900. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5901. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5902. )
  5903. )
  5904. ) or (
  5905. { lea (reg1,reg1), reg1 variant }
  5906. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5907. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5908. )
  5909. ) then
  5910. begin
  5911. { Make everything homogeneous to make calculations easier }
  5912. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5913. begin
  5914. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5915. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5916. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5917. else
  5918. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5919. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5920. end;
  5921. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5922. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5923. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5924. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5925. begin
  5926. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5927. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5928. begin
  5929. { Put the register to change in the index register }
  5930. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5931. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5932. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5933. end;
  5934. { Change lea (reg,reg) to lea(,reg,2) }
  5935. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5936. begin
  5937. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5938. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5939. end;
  5940. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5941. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5942. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5943. { Just to prevent miscalculations }
  5944. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5945. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5946. else
  5947. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5948. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5949. if IntermediateRegDiscarded then
  5950. begin
  5951. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5952. RemoveCurrentP(p);
  5953. end
  5954. else
  5955. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5956. result:=true;
  5957. exit;
  5958. end;
  5959. end;
  5960. { changes
  5961. lea offset1(regX), reg1
  5962. lea offset2(reg1), reg2
  5963. to
  5964. lea offset1+offset2(regX), reg2 }
  5965. if (
  5966. { Don't optimise if size is a concern and the intermediate register remains in use }
  5967. IntermediateRegDiscarded or
  5968. (
  5969. not (cs_opt_size in current_settings.optimizerswitches) and
  5970. { If the intermediate register is not discarded, it must not
  5971. appear in the first LEA's reference. (Fixes #41166) }
  5972. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5973. )
  5974. ) and
  5975. (
  5976. (
  5977. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5978. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5979. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5980. ) or (
  5981. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5982. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5983. (
  5984. (
  5985. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5986. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5987. ) or (
  5988. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5989. (
  5990. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5991. (
  5992. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5993. (
  5994. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5995. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5996. )
  5997. )
  5998. )
  5999. )
  6000. )
  6001. )
  6002. ) then
  6003. begin
  6004. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6005. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6006. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6007. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6008. begin
  6009. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6010. begin
  6011. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6012. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6013. { if the register is used as index and base, we have to increase for base as well
  6014. and adapt base }
  6015. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6016. begin
  6017. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6018. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6019. end;
  6020. end
  6021. else
  6022. begin
  6023. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6024. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6025. end;
  6026. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6027. begin
  6028. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6029. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6030. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6031. { Catch the situation where the base = index
  6032. and treat this as *2. The scalefactor of
  6033. p will be 0 or 1 due to the conditional
  6034. checks above. Fixes i40647 }
  6035. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6036. else
  6037. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6038. end;
  6039. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6040. if IntermediateRegDiscarded then
  6041. begin
  6042. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6043. RemoveCurrentP(p);
  6044. end
  6045. else
  6046. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6047. result:=true;
  6048. exit;
  6049. end;
  6050. end;
  6051. end;
  6052. { Change:
  6053. leal/q $x(%reg1),%reg2
  6054. ...
  6055. shll/q $y,%reg2
  6056. To:
  6057. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6058. }
  6059. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6060. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6061. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6062. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6063. (taicpu(hp1).oper[0]^.val <= 3) then
  6064. begin
  6065. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6066. TransferUsedRegs(TmpUsedRegs);
  6067. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6068. if
  6069. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6070. (this works even if scalefactor is zero) }
  6071. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6072. { Ensure offset doesn't go out of bounds }
  6073. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6074. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6075. (
  6076. (
  6077. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6078. (
  6079. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6080. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6081. (
  6082. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6083. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6084. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6085. )
  6086. )
  6087. ) or (
  6088. (
  6089. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6090. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6091. ) and
  6092. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6093. )
  6094. ) then
  6095. begin
  6096. repeat
  6097. with taicpu(p).oper[0]^.ref^ do
  6098. begin
  6099. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6100. if index = base then
  6101. begin
  6102. if Multiple > 4 then
  6103. { Optimisation will no longer work because resultant
  6104. scale factor will exceed 8 }
  6105. Break;
  6106. base := NR_NO;
  6107. scalefactor := 2;
  6108. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6109. end
  6110. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6111. begin
  6112. { Scale factor only works on the index register }
  6113. index := base;
  6114. base := NR_NO;
  6115. end;
  6116. { For safety }
  6117. if scalefactor <= 1 then
  6118. begin
  6119. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6120. scalefactor := Multiple;
  6121. end
  6122. else
  6123. begin
  6124. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6125. scalefactor := scalefactor * Multiple;
  6126. end;
  6127. offset := offset * Multiple;
  6128. end;
  6129. RemoveInstruction(hp1);
  6130. Result := True;
  6131. Exit;
  6132. { This repeat..until loop exists for the benefit of Break }
  6133. until True;
  6134. end;
  6135. end;
  6136. end;
  6137. end;
  6138. end;
  6139. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6140. var
  6141. hp1 : tai;
  6142. SubInstr: Boolean;
  6143. ThisConst: TCGInt;
  6144. const
  6145. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6146. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6147. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6148. begin
  6149. Result := False;
  6150. if taicpu(p).oper[0]^.typ <> top_const then
  6151. { Should have been confirmed before calling }
  6152. InternalError(2021102601);
  6153. SubInstr := (taicpu(p).opcode = A_SUB);
  6154. if GetLastInstruction(p, hp1) and
  6155. (hp1.typ = ait_instruction) and
  6156. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6157. begin
  6158. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6159. { Bad size }
  6160. InternalError(2022042001);
  6161. case taicpu(hp1).opcode Of
  6162. A_INC:
  6163. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6164. begin
  6165. if SubInstr then
  6166. ThisConst := taicpu(p).oper[0]^.val - 1
  6167. else
  6168. ThisConst := taicpu(p).oper[0]^.val + 1;
  6169. end
  6170. else
  6171. Exit;
  6172. A_DEC:
  6173. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6174. begin
  6175. if SubInstr then
  6176. ThisConst := taicpu(p).oper[0]^.val + 1
  6177. else
  6178. ThisConst := taicpu(p).oper[0]^.val - 1;
  6179. end
  6180. else
  6181. Exit;
  6182. A_SUB:
  6183. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6184. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6185. begin
  6186. if SubInstr then
  6187. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6188. else
  6189. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6190. end
  6191. else
  6192. Exit;
  6193. A_ADD:
  6194. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6195. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6196. begin
  6197. if SubInstr then
  6198. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6199. else
  6200. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6201. end
  6202. else
  6203. Exit;
  6204. else
  6205. Exit;
  6206. end;
  6207. { Check that the values are in range }
  6208. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6209. { Overflow; abort }
  6210. Exit;
  6211. if (ThisConst = 0) then
  6212. begin
  6213. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6214. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6215. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6216. RemoveInstruction(hp1);
  6217. hp1 := tai(p.next);
  6218. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6219. if not GetLastInstruction(hp1, p) then
  6220. p := hp1;
  6221. end
  6222. else
  6223. begin
  6224. if taicpu(hp1).opercnt=1 then
  6225. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6226. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6227. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6228. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6229. else
  6230. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6231. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6232. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6233. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6234. RemoveInstruction(hp1);
  6235. taicpu(p).loadconst(0, ThisConst);
  6236. end;
  6237. Result := True;
  6238. end;
  6239. end;
  6240. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6241. begin
  6242. Result := False;
  6243. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6244. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6245. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6246. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6247. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6248. (
  6249. (
  6250. (taicpu(hp1).opcode = A_TEST)
  6251. ) or (
  6252. (taicpu(hp1).opcode = A_CMP) and
  6253. { A sanity check more than anything }
  6254. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6255. )
  6256. ) then
  6257. begin
  6258. { change
  6259. mov mem, %reg
  6260. ...
  6261. cmp/test x, %reg / test %reg,%reg
  6262. (reg deallocated)
  6263. to
  6264. cmp/test x, mem / cmp 0, mem
  6265. }
  6266. TransferUsedRegs(TmpUsedRegs);
  6267. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6268. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6269. begin
  6270. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6271. if (taicpu(hp1).opcode = A_TEST) and
  6272. (
  6273. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6274. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6275. ) then
  6276. begin
  6277. taicpu(hp1).opcode := A_CMP;
  6278. taicpu(hp1).loadconst(0, 0);
  6279. end;
  6280. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6281. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6282. RemoveCurrentP(p);
  6283. if (p <> hp1) then
  6284. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6285. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6286. { Make sure the flags are allocated across the CMP instruction }
  6287. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6288. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6289. Result := True;
  6290. Exit;
  6291. end;
  6292. end;
  6293. end;
  6294. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6295. var
  6296. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6297. ThisReg, SecondReg: TRegister;
  6298. JumpLoc: TAsmLabel;
  6299. NewSize: TOpSize;
  6300. begin
  6301. Result := False;
  6302. {
  6303. Convert:
  6304. j<c> .L1
  6305. .L2:
  6306. mov 1,reg
  6307. jmp .L3 (or ret, although it might not be a RET yet)
  6308. .L1:
  6309. mov 0,reg
  6310. jmp .L3 (or ret)
  6311. ( As long as .L3 <> .L1 or .L2)
  6312. To:
  6313. mov 0,reg
  6314. set<not(c)> reg
  6315. jmp .L3 (or ret)
  6316. .L2:
  6317. mov 1,reg
  6318. jmp .L3 (or ret)
  6319. .L1:
  6320. mov 0,reg
  6321. jmp .L3 (or ret)
  6322. }
  6323. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6324. Exit;
  6325. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6326. if GetNextInstruction(hp_label, hp2) and
  6327. MatchInstruction(hp2,A_MOV,[]) and
  6328. (taicpu(hp2).oper[0]^.typ = top_const) and
  6329. (
  6330. (
  6331. (taicpu(hp2).oper[1]^.typ = top_reg)
  6332. {$ifdef i386}
  6333. { Under i386, ESI, EDI, EBP and ESP
  6334. don't have an 8-bit representation }
  6335. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6336. {$endif i386}
  6337. ) or (
  6338. {$ifdef i386}
  6339. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6340. {$endif i386}
  6341. (taicpu(hp2).opsize = S_B)
  6342. )
  6343. ) and
  6344. GetNextInstruction(hp2, hp3) and
  6345. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6346. (
  6347. (taicpu(hp3).opcode=A_RET) or
  6348. (
  6349. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6350. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6351. )
  6352. ) and
  6353. GetNextInstruction(hp3, hp4) and
  6354. FindLabel(JumpLoc, hp4) and
  6355. (
  6356. not (cs_opt_size in current_settings.optimizerswitches) or
  6357. { If the initial jump is the label's only reference, then it will
  6358. become a dead label if the other conditions are met and hence
  6359. remove at least 2 instructions, including a jump }
  6360. (JumpLoc.getrefs = 1)
  6361. ) and
  6362. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6363. that will be optimised out }
  6364. GetNextInstruction(hp4, hp5) and
  6365. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6366. (taicpu(hp5).oper[0]^.typ = top_const) and
  6367. (
  6368. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6369. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6370. ) and
  6371. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6372. GetNextInstruction(hp5,hp6) and
  6373. (
  6374. not (hp6.typ in [ait_align, ait_label]) or
  6375. SkipLabels(hp6, hp6)
  6376. ) and
  6377. (hp6.typ=ait_instruction) then
  6378. begin
  6379. { First, let's look at the two jumps that are hp3 and hp6 }
  6380. if not
  6381. (
  6382. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6383. (
  6384. (taicpu(hp6).opcode=A_RET) or
  6385. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6386. )
  6387. ) then
  6388. { If condition is False, then the JMP/RET instructions matched conventionally }
  6389. begin
  6390. { See if one of the jumps can be instantly converted into a RET }
  6391. if (taicpu(hp3).opcode=A_JMP) then
  6392. begin
  6393. { Reuse hp5 }
  6394. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6395. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6396. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6397. Exit;
  6398. if MatchInstruction(hp5, A_RET, []) then
  6399. begin
  6400. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6401. ConvertJumpToRET(hp3, hp5);
  6402. Result := True;
  6403. end
  6404. else
  6405. Exit;
  6406. end;
  6407. if (taicpu(hp6).opcode=A_JMP) then
  6408. begin
  6409. { Reuse hp5 }
  6410. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6411. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6412. Exit;
  6413. if MatchInstruction(hp5, A_RET, []) then
  6414. begin
  6415. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6416. ConvertJumpToRET(hp6, hp5);
  6417. Result := True;
  6418. end
  6419. else
  6420. Exit;
  6421. end;
  6422. if not
  6423. (
  6424. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6425. (
  6426. (taicpu(hp6).opcode=A_RET) or
  6427. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6428. )
  6429. ) then
  6430. { Still doesn't match }
  6431. Exit;
  6432. end;
  6433. if (taicpu(hp2).oper[0]^.val = 1) then
  6434. begin
  6435. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6436. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6437. end
  6438. else
  6439. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6440. if taicpu(hp2).opsize=S_B then
  6441. begin
  6442. if taicpu(hp2).oper[1]^.typ = top_reg then
  6443. begin
  6444. SecondReg := taicpu(hp2).oper[1]^.reg;
  6445. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6446. end
  6447. else
  6448. begin
  6449. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6450. SecondReg := NR_NO;
  6451. end;
  6452. hp_pos := p;
  6453. hp_allocstart := hp4;
  6454. end
  6455. else
  6456. begin
  6457. { Will be a register because the size can't be S_B otherwise }
  6458. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6459. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6460. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6461. if (cs_opt_size in current_settings.optimizerswitches) then
  6462. begin
  6463. { Favour using MOVZX when optimising for size }
  6464. case taicpu(hp2).opsize of
  6465. S_W:
  6466. NewSize := S_BW;
  6467. S_L:
  6468. NewSize := S_BL;
  6469. {$ifdef x86_64}
  6470. S_Q:
  6471. begin
  6472. NewSize := S_BL;
  6473. { Will implicitly zero-extend to 64-bit }
  6474. setsubreg(SecondReg, R_SUBD);
  6475. end;
  6476. {$endif x86_64}
  6477. else
  6478. InternalError(2022101301);
  6479. end;
  6480. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6481. { Inserting it right before p will guarantee that the flags are also tracked }
  6482. Asml.InsertBefore(hp5, p);
  6483. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6484. hp_pos := hp5;
  6485. hp_allocstart := hp4;
  6486. end
  6487. else
  6488. begin
  6489. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6490. { Inserting it right before p will guarantee that the flags are also tracked }
  6491. Asml.InsertBefore(hp5, p);
  6492. hp_pos := p;
  6493. hp_allocstart := hp5;
  6494. end;
  6495. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6496. end;
  6497. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6498. taicpu(hp4).condition := taicpu(p).condition;
  6499. asml.InsertBefore(hp4, hp_pos);
  6500. if taicpu(hp3).is_jmp then
  6501. begin
  6502. JumpLoc.decrefs;
  6503. MakeUnconditional(taicpu(p));
  6504. { This also increases the reference count }
  6505. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6506. end
  6507. else
  6508. ConvertJumpToRET(p, hp3);
  6509. if SecondReg <> NR_NO then
  6510. { Ensure the destination register is allocated over this region }
  6511. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6512. if (JumpLoc.getrefs = 0) then
  6513. RemoveDeadCodeAfterJump(hp3);
  6514. Result:=true;
  6515. exit;
  6516. end;
  6517. end;
  6518. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6519. var
  6520. hp1, hp2: tai;
  6521. ActiveReg: TRegister;
  6522. OldOffset: asizeint;
  6523. ThisConst: TCGInt;
  6524. function RegDeallocated: Boolean;
  6525. begin
  6526. TransferUsedRegs(TmpUsedRegs);
  6527. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6528. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6529. end;
  6530. begin
  6531. Result:=false;
  6532. hp1 := nil;
  6533. { replace
  6534. subX const,%reg1
  6535. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6536. dealloc %reg1
  6537. by
  6538. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6539. }
  6540. if MatchOpType(taicpu(p),top_const,top_reg) then
  6541. begin
  6542. ActiveReg := taicpu(p).oper[1]^.reg;
  6543. { Ensures the entire register was updated }
  6544. if (taicpu(p).opsize >= S_L) and
  6545. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6546. MatchInstruction(hp1,A_LEA,[]) and
  6547. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6548. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6549. (
  6550. { Cover the case where the register in the reference is also the destination register }
  6551. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6552. (
  6553. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6554. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6555. RegDeallocated
  6556. )
  6557. ) then
  6558. begin
  6559. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6560. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6561. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6562. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6563. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6564. {$ifdef x86_64}
  6565. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6566. begin
  6567. { Overflow; abort }
  6568. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6569. end
  6570. else
  6571. {$endif x86_64}
  6572. begin
  6573. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6574. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6575. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6576. RemoveCurrentP(p, hp1)
  6577. else
  6578. RemoveCurrentP(p);
  6579. result:=true;
  6580. Exit;
  6581. end;
  6582. end;
  6583. if (
  6584. { Save calling GetNextInstructionUsingReg again }
  6585. Assigned(hp1) or
  6586. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6587. ) and
  6588. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6589. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6590. begin
  6591. if taicpu(hp1).oper[0]^.typ = top_const then
  6592. begin
  6593. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6594. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6595. Result := True;
  6596. { Handle any overflows }
  6597. case taicpu(p).opsize of
  6598. S_B:
  6599. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6600. S_W:
  6601. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6602. S_L:
  6603. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6604. {$ifdef x86_64}
  6605. S_Q:
  6606. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6607. { Overflow; abort }
  6608. Result := False
  6609. else
  6610. taicpu(p).oper[0]^.val := ThisConst;
  6611. {$endif x86_64}
  6612. else
  6613. InternalError(2021102611);
  6614. end;
  6615. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6616. if Result then
  6617. begin
  6618. if (taicpu(p).oper[0]^.val < 0) and
  6619. (
  6620. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6621. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6622. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6623. ) then
  6624. begin
  6625. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6626. taicpu(p).opcode := A_SUB;
  6627. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6628. end
  6629. else
  6630. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6631. RemoveInstruction(hp1);
  6632. end;
  6633. end
  6634. else
  6635. begin
  6636. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6637. TransferUsedRegs(TmpUsedRegs);
  6638. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6639. hp2 := p;
  6640. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6641. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6642. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6643. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6644. begin
  6645. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6646. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6647. Asml.Remove(p);
  6648. Asml.InsertAfter(p, hp1);
  6649. p := hp1;
  6650. Result := True;
  6651. Exit;
  6652. end;
  6653. end;
  6654. end;
  6655. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6656. { * change "sub/add const1, reg" or "dec reg" followed by
  6657. "sub const2, reg" to one "sub ..., reg" }
  6658. {$ifdef i386}
  6659. if (taicpu(p).oper[0]^.val = 2) and
  6660. (ActiveReg = NR_ESP) and
  6661. { Don't do the sub/push optimization if the sub }
  6662. { comes from setting up the stack frame (JM) }
  6663. (not(GetLastInstruction(p,hp1)) or
  6664. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6665. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6666. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6667. begin
  6668. hp1 := tai(p.next);
  6669. while Assigned(hp1) and
  6670. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6671. not RegReadByInstruction(NR_ESP,hp1) and
  6672. not RegModifiedByInstruction(NR_ESP,hp1) do
  6673. hp1 := tai(hp1.next);
  6674. if Assigned(hp1) and
  6675. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6676. begin
  6677. taicpu(hp1).changeopsize(S_L);
  6678. if taicpu(hp1).oper[0]^.typ=top_reg then
  6679. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6680. hp1 := tai(p.next);
  6681. RemoveCurrentp(p, hp1);
  6682. Result:=true;
  6683. exit;
  6684. end;
  6685. end;
  6686. {$endif i386}
  6687. if DoArithCombineOpt(p) then
  6688. Result:=true;
  6689. end;
  6690. end;
  6691. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6692. var
  6693. TmpBool1,TmpBool2 : Boolean;
  6694. tmpref : treference;
  6695. hp1,hp2: tai;
  6696. mask, shiftval: tcgint;
  6697. begin
  6698. Result:=false;
  6699. { All these optimisations work on "shl/sal const,%reg" }
  6700. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6701. Exit;
  6702. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6703. (taicpu(p).oper[0]^.val <= 3) then
  6704. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6705. begin
  6706. { should we check the next instruction? }
  6707. TmpBool1 := True;
  6708. { have we found an add/sub which could be
  6709. integrated in the lea? }
  6710. TmpBool2 := False;
  6711. reference_reset(tmpref,2,[]);
  6712. TmpRef.index := taicpu(p).oper[1]^.reg;
  6713. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6714. while TmpBool1 and
  6715. GetNextInstruction(p, hp1) and
  6716. (tai(hp1).typ = ait_instruction) and
  6717. ((((taicpu(hp1).opcode = A_ADD) or
  6718. (taicpu(hp1).opcode = A_SUB)) and
  6719. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6720. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6721. (((taicpu(hp1).opcode = A_INC) or
  6722. (taicpu(hp1).opcode = A_DEC)) and
  6723. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6724. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6725. ((taicpu(hp1).opcode = A_LEA) and
  6726. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6727. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6728. (not GetNextInstruction(hp1,hp2) or
  6729. not instrReadsFlags(hp2)) Do
  6730. begin
  6731. TmpBool1 := False;
  6732. if taicpu(hp1).opcode=A_LEA then
  6733. begin
  6734. if (TmpRef.base = NR_NO) and
  6735. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6736. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6737. { Segment register isn't a concern here }
  6738. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6739. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6740. begin
  6741. TmpBool1 := True;
  6742. TmpBool2 := True;
  6743. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6744. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6745. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6746. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6747. RemoveInstruction(hp1);
  6748. end
  6749. end
  6750. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6751. begin
  6752. TmpBool1 := True;
  6753. TmpBool2 := True;
  6754. case taicpu(hp1).opcode of
  6755. A_ADD:
  6756. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6757. A_SUB:
  6758. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6759. else
  6760. internalerror(2019050536);
  6761. end;
  6762. RemoveInstruction(hp1);
  6763. end
  6764. else
  6765. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6766. (((taicpu(hp1).opcode = A_ADD) and
  6767. (TmpRef.base = NR_NO)) or
  6768. (taicpu(hp1).opcode = A_INC) or
  6769. (taicpu(hp1).opcode = A_DEC)) then
  6770. begin
  6771. TmpBool1 := True;
  6772. TmpBool2 := True;
  6773. case taicpu(hp1).opcode of
  6774. A_ADD:
  6775. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6776. A_INC:
  6777. inc(TmpRef.offset);
  6778. A_DEC:
  6779. dec(TmpRef.offset);
  6780. else
  6781. internalerror(2019050535);
  6782. end;
  6783. RemoveInstruction(hp1);
  6784. end;
  6785. end;
  6786. if TmpBool2
  6787. {$ifndef x86_64}
  6788. or
  6789. ((current_settings.optimizecputype < cpu_Pentium2) and
  6790. (taicpu(p).oper[0]^.val <= 3) and
  6791. not(cs_opt_size in current_settings.optimizerswitches))
  6792. {$endif x86_64}
  6793. then
  6794. begin
  6795. if not(TmpBool2) and
  6796. (taicpu(p).oper[0]^.val=1) then
  6797. begin
  6798. taicpu(p).opcode := A_ADD;
  6799. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6800. end
  6801. else
  6802. begin
  6803. taicpu(p).opcode := A_LEA;
  6804. taicpu(p).loadref(0, TmpRef);
  6805. end;
  6806. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6807. Result := True;
  6808. end;
  6809. end
  6810. {$ifndef x86_64}
  6811. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6812. begin
  6813. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6814. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6815. (unlike shl, which is only Tairable in the U pipe) }
  6816. if taicpu(p).oper[0]^.val=1 then
  6817. begin
  6818. taicpu(p).opcode := A_ADD;
  6819. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6820. Result := True;
  6821. end
  6822. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6823. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6824. else if (taicpu(p).opsize = S_L) and
  6825. (taicpu(p).oper[0]^.val<= 3) then
  6826. begin
  6827. reference_reset(tmpref,2,[]);
  6828. TmpRef.index := taicpu(p).oper[1]^.reg;
  6829. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6830. taicpu(p).opcode := A_LEA;
  6831. taicpu(p).loadref(0, TmpRef);
  6832. Result := True;
  6833. end;
  6834. end
  6835. {$endif x86_64}
  6836. else if
  6837. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6838. (
  6839. (
  6840. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6841. SetAndTest(hp1, hp2)
  6842. {$ifdef x86_64}
  6843. ) or
  6844. (
  6845. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6846. GetNextInstruction(hp1, hp2) and
  6847. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6848. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6849. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6850. {$endif x86_64}
  6851. )
  6852. ) and
  6853. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6854. begin
  6855. { Change:
  6856. shl x, %reg1
  6857. mov -(1<<x), %reg2
  6858. and %reg2, %reg1
  6859. Or:
  6860. shl x, %reg1
  6861. and -(1<<x), %reg1
  6862. To just:
  6863. shl x, %reg1
  6864. Since the and operation only zeroes bits that are already zero from the shl operation
  6865. }
  6866. case taicpu(p).oper[0]^.val of
  6867. 8:
  6868. mask:=$FFFFFFFFFFFFFF00;
  6869. 16:
  6870. mask:=$FFFFFFFFFFFF0000;
  6871. 32:
  6872. mask:=$FFFFFFFF00000000;
  6873. 63:
  6874. { Constant pre-calculated to prevent overflow errors with Int64 }
  6875. mask:=$8000000000000000;
  6876. else
  6877. begin
  6878. if taicpu(p).oper[0]^.val >= 64 then
  6879. { Shouldn't happen realistically, since the register
  6880. is guaranteed to be set to zero at this point }
  6881. mask := 0
  6882. else
  6883. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6884. end;
  6885. end;
  6886. if taicpu(hp1).oper[0]^.val = mask then
  6887. begin
  6888. { Everything checks out, perform the optimisation, as long as
  6889. the FLAGS register isn't being used}
  6890. TransferUsedRegs(TmpUsedRegs);
  6891. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6892. {$ifdef x86_64}
  6893. if (hp1 <> hp2) then
  6894. begin
  6895. { "shl/mov/and" version }
  6896. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6897. { Don't do the optimisation if the FLAGS register is in use }
  6898. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6899. begin
  6900. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6901. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6902. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6903. begin
  6904. RemoveInstruction(hp1);
  6905. Result := True;
  6906. end;
  6907. { Only set Result to True if the 'mov' instruction was removed }
  6908. RemoveInstruction(hp2);
  6909. end;
  6910. end
  6911. else
  6912. {$endif x86_64}
  6913. begin
  6914. { "shl/and" version }
  6915. { Don't do the optimisation if the FLAGS register is in use }
  6916. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6917. begin
  6918. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6919. RemoveInstruction(hp1);
  6920. Result := True;
  6921. end;
  6922. end;
  6923. Exit;
  6924. end
  6925. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6926. begin
  6927. { Even if the mask doesn't allow for its removal, we might be
  6928. able to optimise the mask for the "shl/and" version, which
  6929. may permit other peephole optimisations }
  6930. {$ifdef DEBUG_AOPTCPU}
  6931. mask := taicpu(hp1).oper[0]^.val and mask;
  6932. if taicpu(hp1).oper[0]^.val <> mask then
  6933. begin
  6934. DebugMsg(
  6935. SPeepholeOptimization +
  6936. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6937. ' to $' + debug_tostr(mask) +
  6938. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6939. taicpu(hp1).oper[0]^.val := mask;
  6940. end;
  6941. {$else DEBUG_AOPTCPU}
  6942. { If debugging is off, just set the operand even if it's the same }
  6943. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6944. {$endif DEBUG_AOPTCPU}
  6945. end;
  6946. end;
  6947. {
  6948. change
  6949. shl/sal const,reg
  6950. <op> ...(...,reg,1),...
  6951. into
  6952. <op> ...(...,reg,1 shl const),...
  6953. if const in 1..3
  6954. }
  6955. if MatchOpType(taicpu(p), top_const, top_reg) and
  6956. (taicpu(p).oper[0]^.val in [1..3]) and
  6957. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6958. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6959. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6960. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6961. MatchOpType(taicpu(hp1),top_ref))
  6962. ) and
  6963. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6964. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6965. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6966. begin
  6967. TransferUsedRegs(TmpUsedRegs);
  6968. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6969. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6970. begin
  6971. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6972. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6973. RemoveCurrentP(p);
  6974. Result:=true;
  6975. exit;
  6976. end;
  6977. end;
  6978. if MatchOpType(taicpu(p), top_const, top_reg) and
  6979. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6980. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6981. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6982. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6983. begin
  6984. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6985. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6986. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6987. {$ifdef x86_64}
  6988. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6989. {$endif x86_64}
  6990. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6991. begin
  6992. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6993. taicpu(hp1).opcode:=A_MOV;
  6994. taicpu(hp1).oper[0]^.val:=0;
  6995. end
  6996. else
  6997. begin
  6998. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6999. taicpu(hp1).oper[0]^.val:=shiftval;
  7000. end;
  7001. RemoveCurrentP(p);
  7002. Result:=true;
  7003. exit;
  7004. end;
  7005. end;
  7006. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7007. begin
  7008. case shr_size of
  7009. S_B:
  7010. { No valid combinations }
  7011. Result := False;
  7012. S_W:
  7013. Result := (Shift >= 8) and (movz_size = S_BW);
  7014. S_L:
  7015. Result :=
  7016. (Shift >= 24) { Any opsize is valid for this shift } or
  7017. ((Shift >= 16) and (movz_size = S_WL));
  7018. {$ifdef x86_64}
  7019. S_Q:
  7020. Result :=
  7021. (Shift >= 56) { Any opsize is valid for this shift } or
  7022. ((Shift >= 48) and (movz_size = S_WL));
  7023. {$endif x86_64}
  7024. else
  7025. InternalError(2022081510);
  7026. end;
  7027. end;
  7028. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7029. var
  7030. hp1, hp2: tai;
  7031. IdentityMask, Shift: TCGInt;
  7032. LimitSize: Topsize;
  7033. DoNotMerge: Boolean;
  7034. begin
  7035. if not MatchInstruction(p, A_SHR, []) then
  7036. InternalError(2025040301);
  7037. Result := False;
  7038. DoNotMerge := False;
  7039. Shift := taicpu(p).oper[0]^.val;
  7040. LimitSize := taicpu(p).opsize;
  7041. hp1 := p;
  7042. repeat
  7043. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7044. Exit;
  7045. case taicpu(hp1).opcode of
  7046. A_AND:
  7047. { Detect:
  7048. shr x, %reg
  7049. and y, %reg
  7050. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7051. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7052. (Post-peephole only)
  7053. }
  7054. if PostPeephole and
  7055. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7056. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7057. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7058. begin
  7059. { Make sure the FLAGS register isn't in use }
  7060. TransferUsedRegs(TmpUsedRegs);
  7061. hp2 := p;
  7062. repeat
  7063. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7064. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7065. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7066. begin
  7067. { Generate the identity mask }
  7068. case taicpu(p).opsize of
  7069. S_B:
  7070. IdentityMask := $FF shr Shift;
  7071. S_W:
  7072. IdentityMask := $FFFF shr Shift;
  7073. S_L:
  7074. IdentityMask := $FFFFFFFF shr Shift;
  7075. {$ifdef x86_64}
  7076. S_Q:
  7077. { We need to force the operands to be unsigned 64-bit
  7078. integers otherwise the wrong value is generated }
  7079. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7080. {$endif x86_64}
  7081. else
  7082. InternalError(2022081501);
  7083. end;
  7084. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7085. begin
  7086. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7087. { All the possible 1 bits are covered, so we can remove the AND }
  7088. hp2 := tai(hp1.Previous);
  7089. RemoveInstruction(hp1);
  7090. { p wasn't actually changed, so don't set Result to True,
  7091. but a change was nonetheless made elsewhere }
  7092. Include(OptsToCheck, aoc_ForceNewIteration);
  7093. { Do another pass in case other AND or MOVZX instructions
  7094. follow }
  7095. hp1 := hp2;
  7096. Continue;
  7097. end;
  7098. end;
  7099. end;
  7100. A_TEST, A_CMP:
  7101. { Skip over relevant comparisons, but shift instructions must
  7102. now not be merged since the original value is being read }
  7103. begin
  7104. DoNotMerge := True;
  7105. Continue;
  7106. end;
  7107. A_Jcc:
  7108. { Skip over conditional jumps and relevant comparisons }
  7109. Continue;
  7110. A_MOVZX:
  7111. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7112. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7113. begin
  7114. { Since the original register is being read as is, subsequent
  7115. SHRs must not be merged at this point }
  7116. DoNotMerge := True;
  7117. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7118. begin
  7119. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7120. begin
  7121. { If the MOVZX instruction reads and writes the same register,
  7122. defer this to the post-peephole optimisation stage }
  7123. if PostPeephole then
  7124. begin
  7125. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7126. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7127. hp2 := tai(hp1.Previous);
  7128. RemoveInstruction(hp1);
  7129. hp1 := hp2;
  7130. end;
  7131. end
  7132. else { Different register target }
  7133. begin
  7134. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7135. taicpu(hp1).opcode := A_MOV;
  7136. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7137. case taicpu(hp1).opsize of
  7138. S_BW:
  7139. taicpu(hp1).opsize := S_W;
  7140. S_BL, S_WL:
  7141. taicpu(hp1).opsize := S_L;
  7142. else
  7143. InternalError(2022081503);
  7144. end;
  7145. { p itself hasn't changed, so no need to set Result to True }
  7146. Include(OptsToCheck, aoc_ForceNewIteration);
  7147. { See if there's anything afterwards that can be
  7148. optimised, since the input register hasn't changed }
  7149. Continue;
  7150. end;
  7151. Exit;
  7152. end
  7153. else if PostPeephole and
  7154. (Shift > 0) and
  7155. (taicpu(p).opsize = S_W) and
  7156. (taicpu(hp1).opsize = S_WL) and
  7157. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7158. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7159. begin
  7160. { Detect:
  7161. shr x, %ax (x > 0)
  7162. ...
  7163. movzwl %ax,%eax
  7164. -
  7165. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7166. But first, check to see if movzwl %ax,%eax can be removed...
  7167. }
  7168. hp2 := tai(hp1.Previous);
  7169. TransferUsedRegs(TmpUsedRegs);
  7170. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7171. if PostPeepholeOptMovZX(hp1) then
  7172. hp1 := hp2
  7173. else
  7174. begin
  7175. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7176. taicpu(hp1).opcode := A_CWDE;
  7177. taicpu(hp1).clearop(0);
  7178. taicpu(hp1).clearop(1);
  7179. taicpu(hp1).ops := 0;
  7180. end;
  7181. RestoreUsedRegs(TmpUsedRegs);
  7182. { Don't need to set aoc_ForceNewIteration if
  7183. PostPeepholeOptMovZX returned True because it's the
  7184. post-peephole stage }
  7185. end;
  7186. { Move onto the next instruction }
  7187. Continue;
  7188. end;
  7189. A_SHL, A_SAL, A_SHR:
  7190. if (taicpu(hp1).opsize <= LimitSize) and
  7191. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7192. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7193. begin
  7194. { Make sure the sizes don't exceed the register size limit
  7195. (measured by the shift value falling below the limit) }
  7196. if taicpu(hp1).opsize < LimitSize then
  7197. LimitSize := taicpu(hp1).opsize;
  7198. if taicpu(hp1).opcode = A_SHR then
  7199. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7200. else
  7201. begin
  7202. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7203. DoNotMerge := True;
  7204. end;
  7205. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7206. Exit;
  7207. { Since we've established that the combined shift is within
  7208. limits, we can actually combine the adjacent SHR
  7209. instructions even if they're different sizes }
  7210. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7211. begin
  7212. hp2 := tai(hp1.Previous);
  7213. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7214. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7215. RemoveInstruction(hp1);
  7216. hp1 := hp2;
  7217. { Though p has changed, only the constant has, and its
  7218. effects can still be detected on the next iteration of
  7219. the repeat..until loop }
  7220. Include(OptsToCheck, aoc_ForceNewIteration);
  7221. end;
  7222. { Move onto the next instruction }
  7223. Continue;
  7224. end;
  7225. else
  7226. ;
  7227. end;
  7228. { If the register isn't actually modified, move onto the next instruction,
  7229. but set DoNotMerge to True since the register is being read }
  7230. if (
  7231. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7232. the next instruction, whether or not it contains the register }
  7233. (cs_opt_level3 in current_settings.optimizerswitches) or
  7234. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7235. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7236. begin
  7237. DoNotMerge := True;
  7238. Continue;
  7239. end;
  7240. Break;
  7241. until False;
  7242. end;
  7243. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7244. begin
  7245. Result := False;
  7246. { All these optimisations work on "shr const,%reg" }
  7247. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7248. Exit;
  7249. Result := HandleSHRMerge(p, False);
  7250. end;
  7251. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7252. var
  7253. CurrentRef: TReference;
  7254. FullReg: TRegister;
  7255. hp1, hp2: tai;
  7256. begin
  7257. Result := False;
  7258. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7259. Exit;
  7260. { We assume you've checked if the operand is actually a reference by
  7261. this point. If it isn't, you'll most likely get an access violation }
  7262. CurrentRef := first_mov.oper[1]^.ref^;
  7263. { Memory must be aligned }
  7264. if (CurrentRef.offset mod 4) <> 0 then
  7265. Exit;
  7266. Inc(CurrentRef.offset);
  7267. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7268. if MatchOperand(second_mov.oper[0]^, 0) and
  7269. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7270. GetNextInstruction(second_mov, hp1) and
  7271. (hp1.typ = ait_instruction) and
  7272. (taicpu(hp1).opcode = A_MOV) and
  7273. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7274. (taicpu(hp1).oper[0]^.val = 0) then
  7275. begin
  7276. Inc(CurrentRef.offset);
  7277. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7278. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7279. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7280. begin
  7281. case taicpu(hp1).opsize of
  7282. S_B:
  7283. if GetNextInstruction(hp1, hp2) and
  7284. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7285. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7286. (taicpu(hp2).oper[0]^.val = 0) then
  7287. begin
  7288. Inc(CurrentRef.offset);
  7289. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7290. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7291. (taicpu(hp2).opsize = S_B) then
  7292. begin
  7293. RemoveInstruction(hp1);
  7294. RemoveInstruction(hp2);
  7295. first_mov.opsize := S_L;
  7296. if first_mov.oper[0]^.typ = top_reg then
  7297. begin
  7298. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7299. { Reuse second_mov as a MOVZX instruction }
  7300. second_mov.opcode := A_MOVZX;
  7301. second_mov.opsize := S_BL;
  7302. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7303. second_mov.loadreg(1, FullReg);
  7304. first_mov.oper[0]^.reg := FullReg;
  7305. asml.Remove(second_mov);
  7306. asml.InsertBefore(second_mov, first_mov);
  7307. end
  7308. else
  7309. { It's a value }
  7310. begin
  7311. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7312. RemoveInstruction(second_mov);
  7313. end;
  7314. Result := True;
  7315. Exit;
  7316. end;
  7317. end;
  7318. S_W:
  7319. begin
  7320. RemoveInstruction(hp1);
  7321. first_mov.opsize := S_L;
  7322. if first_mov.oper[0]^.typ = top_reg then
  7323. begin
  7324. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7325. { Reuse second_mov as a MOVZX instruction }
  7326. second_mov.opcode := A_MOVZX;
  7327. second_mov.opsize := S_BL;
  7328. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7329. second_mov.loadreg(1, FullReg);
  7330. first_mov.oper[0]^.reg := FullReg;
  7331. asml.Remove(second_mov);
  7332. asml.InsertBefore(second_mov, first_mov);
  7333. end
  7334. else
  7335. { It's a value }
  7336. begin
  7337. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7338. RemoveInstruction(second_mov);
  7339. end;
  7340. Result := True;
  7341. Exit;
  7342. end;
  7343. else
  7344. ;
  7345. end;
  7346. end;
  7347. end;
  7348. end;
  7349. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7350. { returns true if a "continue" should be done after this optimization }
  7351. var
  7352. hp1, hp2, hp3: tai;
  7353. begin
  7354. Result := false;
  7355. hp3 := nil;
  7356. if MatchOpType(taicpu(p),top_ref) and
  7357. GetNextInstruction(p, hp1) and
  7358. (hp1.typ = ait_instruction) and
  7359. (((taicpu(hp1).opcode = A_FLD) and
  7360. (taicpu(p).opcode = A_FSTP)) or
  7361. ((taicpu(p).opcode = A_FISTP) and
  7362. (taicpu(hp1).opcode = A_FILD))) and
  7363. MatchOpType(taicpu(hp1),top_ref) and
  7364. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7365. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7366. begin
  7367. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7368. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7369. GetNextInstruction(hp1, hp2) and
  7370. (((hp2.typ = ait_instruction) and
  7371. IsExitCode(hp2) and
  7372. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7373. not(assigned(current_procinfo.procdef.funcretsym) and
  7374. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7375. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7376. { fstp <temp>
  7377. fld <temp>
  7378. <dealloc> <temp>
  7379. }
  7380. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7381. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7382. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7383. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7384. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7385. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7386. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7387. )
  7388. )
  7389. ) then
  7390. begin
  7391. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7392. RemoveInstruction(hp1);
  7393. RemoveCurrentP(p, hp2);
  7394. { first case: exit code }
  7395. if hp2.typ = ait_instruction then
  7396. RemoveLastDeallocForFuncRes(p);
  7397. Result := true;
  7398. end
  7399. else
  7400. { we can do this only in fast math mode as fstp is rounding ...
  7401. ... still disabled as it breaks the compiler and/or rtl }
  7402. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7403. { ... or if another fstp equal to the first one follows }
  7404. GetNextInstruction(hp1,hp2) and
  7405. (hp2.typ = ait_instruction) and
  7406. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7407. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7408. begin
  7409. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7410. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7411. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7412. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7413. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7414. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7415. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7416. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7417. ) then
  7418. begin
  7419. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7420. RemoveCurrentP(p,hp2);
  7421. RemoveInstruction(hp1);
  7422. Result := true;
  7423. end
  7424. else if { fst can't store an extended/comp value }
  7425. (taicpu(p).opsize <> S_FX) and
  7426. (taicpu(p).opsize <> S_IQ) then
  7427. begin
  7428. if (taicpu(p).opcode = A_FSTP) then
  7429. taicpu(p).opcode := A_FST
  7430. else
  7431. taicpu(p).opcode := A_FIST;
  7432. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7433. RemoveInstruction(hp1);
  7434. Result := true;
  7435. end;
  7436. end;
  7437. end;
  7438. end;
  7439. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7440. var
  7441. hp1, hp2, hp3: tai;
  7442. begin
  7443. result:=false;
  7444. if MatchOpType(taicpu(p),top_reg) and
  7445. GetNextInstruction(p, hp1) and
  7446. (hp1.typ = Ait_Instruction) and
  7447. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7448. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7449. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7450. { change to
  7451. fld reg fxxx reg,st
  7452. fxxxp st, st1 (hp1)
  7453. Remark: non commutative operations must be reversed!
  7454. }
  7455. begin
  7456. case taicpu(hp1).opcode Of
  7457. A_FMULP,A_FADDP,
  7458. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7459. begin
  7460. case taicpu(hp1).opcode Of
  7461. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7462. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7463. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7464. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7465. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7466. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7467. else
  7468. internalerror(2019050534);
  7469. end;
  7470. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7471. taicpu(hp1).oper[1]^.reg := NR_ST;
  7472. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7473. RemoveCurrentP(p, hp1);
  7474. Result:=true;
  7475. exit;
  7476. end;
  7477. else
  7478. ;
  7479. end;
  7480. end
  7481. else
  7482. if MatchOpType(taicpu(p),top_ref) and
  7483. GetNextInstruction(p, hp2) and
  7484. (hp2.typ = Ait_Instruction) and
  7485. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7486. (taicpu(p).opsize in [S_FS, S_FL]) and
  7487. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7488. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7489. if GetLastInstruction(p, hp1) and
  7490. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7491. MatchOpType(taicpu(hp1),top_ref) and
  7492. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7493. if ((taicpu(hp2).opcode = A_FMULP) or
  7494. (taicpu(hp2).opcode = A_FADDP)) then
  7495. { change to
  7496. fld/fst mem1 (hp1) fld/fst mem1
  7497. fld mem1 (p) fadd/
  7498. faddp/ fmul st, st
  7499. fmulp st, st1 (hp2) }
  7500. begin
  7501. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7502. RemoveCurrentP(p, hp1);
  7503. if (taicpu(hp2).opcode = A_FADDP) then
  7504. taicpu(hp2).opcode := A_FADD
  7505. else
  7506. taicpu(hp2).opcode := A_FMUL;
  7507. taicpu(hp2).oper[1]^.reg := NR_ST;
  7508. end
  7509. else
  7510. { change to
  7511. fld/fst mem1 (hp1) fld/fst mem1
  7512. fld mem1 (p) fld st
  7513. }
  7514. begin
  7515. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7516. taicpu(p).changeopsize(S_FL);
  7517. taicpu(p).loadreg(0,NR_ST);
  7518. end
  7519. else
  7520. begin
  7521. case taicpu(hp2).opcode Of
  7522. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7523. { change to
  7524. fld/fst mem1 (hp1) fld/fst mem1
  7525. fld mem2 (p) fxxx mem2
  7526. fxxxp st, st1 (hp2) }
  7527. begin
  7528. case taicpu(hp2).opcode Of
  7529. A_FADDP: taicpu(p).opcode := A_FADD;
  7530. A_FMULP: taicpu(p).opcode := A_FMUL;
  7531. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7532. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7533. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7534. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7535. else
  7536. internalerror(2019050533);
  7537. end;
  7538. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7539. RemoveInstruction(hp2);
  7540. end
  7541. else
  7542. ;
  7543. end
  7544. end
  7545. end;
  7546. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7547. begin
  7548. Result := condition_in(cond1, cond2) or
  7549. { Not strictly subsets due to the actual flags checked, but because we're
  7550. comparing integers, E is a subset of AE and GE and their aliases }
  7551. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7552. end;
  7553. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7554. var
  7555. v: TCGInt;
  7556. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7557. FirstMatch, TempBool: Boolean;
  7558. NewReg: TRegister;
  7559. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7560. begin
  7561. Result:=false;
  7562. { All these optimisations need a next instruction }
  7563. if not GetNextInstruction(p, hp1) then
  7564. Exit;
  7565. true_hp1 := hp1;
  7566. { Search for:
  7567. cmp ###,###
  7568. j(c1) @lbl1
  7569. ...
  7570. @lbl:
  7571. cmp ###,### (same comparison as above)
  7572. j(c2) @lbl2
  7573. If c1 is a subset of c2, change to:
  7574. cmp ###,###
  7575. j(c1) @lbl2
  7576. (@lbl1 may become a dead label as a result)
  7577. }
  7578. { Also handle cases where there are multiple jumps in a row }
  7579. p_jump := hp1;
  7580. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7581. begin
  7582. Prefetch(p_jump.Next);
  7583. if IsJumpToLabel(taicpu(p_jump)) then
  7584. begin
  7585. { Do jump optimisations first in case the condition becomes
  7586. unnecessary }
  7587. TempBool := True;
  7588. if DoJumpOptimizations(p_jump, TempBool) or
  7589. not TempBool then
  7590. begin
  7591. if Assigned(p_jump) then
  7592. begin
  7593. { CollapseZeroDistJump will be set to the label or an align
  7594. before it after the jump if it optimises, whether or not
  7595. the label is live or dead }
  7596. if (p_jump.typ = ait_align) or
  7597. (
  7598. (p_jump.typ = ait_label) and
  7599. not (tai_label(p_jump).labsym.is_used)
  7600. ) then
  7601. GetNextInstruction(p_jump, p_jump);
  7602. end;
  7603. TransferUsedRegs(TmpUsedRegs);
  7604. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7605. if not Assigned(p_jump) or
  7606. (
  7607. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7608. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7609. ) then
  7610. begin
  7611. { No more conditional jumps; conditional statement is no longer required }
  7612. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7613. RemoveCurrentP(p);
  7614. Result := True;
  7615. Exit;
  7616. end;
  7617. hp1 := p_jump;
  7618. Include(OptsToCheck, aoc_ForceNewIteration);
  7619. Continue;
  7620. end;
  7621. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7622. if GetNextInstruction(p_jump, hp2) and
  7623. (
  7624. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7625. not TempBool
  7626. ) then
  7627. begin
  7628. hp1 := p_jump;
  7629. Include(OptsToCheck, aoc_ForceNewIteration);
  7630. Continue;
  7631. end;
  7632. p_label := nil;
  7633. if Assigned(JumpLabel) then
  7634. p_label := getlabelwithsym(JumpLabel);
  7635. if Assigned(p_label) and
  7636. GetNextInstruction(p_label, p_dist) and
  7637. MatchInstruction(p_dist, A_CMP, []) and
  7638. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7639. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7640. GetNextInstruction(p_dist, hp1_dist) and
  7641. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7642. begin
  7643. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7644. if JumpLabel = JumpLabel_dist then
  7645. { This is an infinite loop }
  7646. Exit;
  7647. { Best optimisation when the first condition is a subset (or equal) of the second }
  7648. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7649. begin
  7650. { Any registers used here will already be allocated }
  7651. if Assigned(JumpLabel) then
  7652. JumpLabel.DecRefs;
  7653. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7654. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7655. Include(OptsToCheck, aoc_ForceNewIteration);
  7656. { Don't exit yet. Since p and p_jump haven't actually been
  7657. removed, we can check for more on this iteration }
  7658. end
  7659. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7660. GetNextInstruction(hp1_dist, hp1_label) and
  7661. (hp1_label.typ = ait_label) then
  7662. begin
  7663. JumpLabel_far := tai_label(hp1_label).labsym;
  7664. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7665. { This is an infinite loop }
  7666. Exit;
  7667. if Assigned(JumpLabel_far) then
  7668. begin
  7669. { In this situation, if the first jump branches, the second one will never,
  7670. branch so change the destination label to after the second jump }
  7671. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7672. if Assigned(JumpLabel) then
  7673. JumpLabel.DecRefs;
  7674. JumpLabel_far.IncRefs;
  7675. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7676. Result := True;
  7677. { Don't exit yet. Since p and p_jump haven't actually been
  7678. removed, we can check for more on this iteration }
  7679. Continue;
  7680. end;
  7681. end;
  7682. end;
  7683. end;
  7684. { Search for:
  7685. cmp ###,###
  7686. j(c1) @lbl1
  7687. cmp ###,### (same as first)
  7688. Remove second cmp
  7689. }
  7690. if GetNextInstruction(p_jump, hp2) and
  7691. (
  7692. (
  7693. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7694. (
  7695. (
  7696. MatchOpType(taicpu(p), top_const, top_reg) and
  7697. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7698. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7699. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7700. ) or (
  7701. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7702. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7703. )
  7704. )
  7705. ) or (
  7706. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7707. MatchOperand(taicpu(p).oper[0]^, 0) and
  7708. (taicpu(p).oper[1]^.typ = top_reg) and
  7709. MatchInstruction(hp2, A_TEST, []) and
  7710. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7711. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7712. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7713. )
  7714. ) then
  7715. begin
  7716. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7717. TransferUsedRegs(TmpUsedRegs);
  7718. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7719. RemoveInstruction(hp2);
  7720. Result := True;
  7721. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7722. end
  7723. else
  7724. begin
  7725. { hp2 is the next instruction, so save time and just set p_jump
  7726. to it instead of calling GetNextInstruction below }
  7727. p_jump := hp2;
  7728. Continue;
  7729. end;
  7730. GetNextInstruction(p_jump, p_jump);
  7731. end;
  7732. if (
  7733. { Don't call GetNextInstruction again if we already have it }
  7734. (true_hp1 = p_jump) or
  7735. GetNextInstruction(p, hp1)
  7736. ) and
  7737. MatchInstruction(hp1, A_Jcc, []) and
  7738. IsJumpToLabel(taicpu(hp1)) and
  7739. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7740. GetNextInstruction(hp1, hp2) then
  7741. begin
  7742. {
  7743. cmp x, y (or "cmp y, x")
  7744. je @lbl
  7745. mov x, y
  7746. @lbl:
  7747. (x and y can be constants, registers or references)
  7748. Change to:
  7749. mov x, y (x and y will always be equal in the end)
  7750. @lbl: (may beceome a dead label)
  7751. Also:
  7752. cmp x, y (or "cmp y, x")
  7753. jne @lbl
  7754. mov x, y
  7755. @lbl:
  7756. (x and y can be constants, registers or references)
  7757. Change to:
  7758. Absolutely nothing! (Except @lbl if it's still live)
  7759. }
  7760. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7761. (
  7762. (
  7763. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7764. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7765. ) or (
  7766. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7767. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7768. )
  7769. ) and
  7770. GetNextInstruction(hp2, hp1_label) and
  7771. (hp1_label.typ = ait_label) and
  7772. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7773. begin
  7774. tai_label(hp1_label).labsym.DecRefs;
  7775. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7776. begin
  7777. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7778. RemoveInstruction(hp2);
  7779. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7780. end
  7781. else
  7782. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7783. RemoveInstruction(hp1);
  7784. RemoveCurrentp(p, hp2);
  7785. Result := True;
  7786. Exit;
  7787. end;
  7788. {
  7789. Try to optimise the following:
  7790. cmp $x,### ($x and $y can be registers or constants)
  7791. je @lbl1 (only reference)
  7792. cmp $y,### (### are identical)
  7793. @Lbl:
  7794. sete %reg1
  7795. Change to:
  7796. cmp $x,###
  7797. sete %reg2 (allocate new %reg2)
  7798. cmp $y,###
  7799. sete %reg1
  7800. orb %reg2,%reg1
  7801. (dealloc %reg2)
  7802. This adds an instruction (so don't perform under -Os), but it removes
  7803. a conditional branch.
  7804. }
  7805. if not (cs_opt_size in current_settings.optimizerswitches) and
  7806. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7807. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7808. { The first operand of CMP instructions can only be a register or
  7809. immediate anyway, so no need to check }
  7810. GetNextInstruction(hp2, p_label) and
  7811. (p_label.typ = ait_label) and
  7812. (tai_label(p_label).labsym.getrefs = 1) and
  7813. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7814. GetNextInstruction(p_label, p_dist) and
  7815. MatchInstruction(p_dist, A_SETcc, []) and
  7816. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7817. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7818. begin
  7819. TransferUsedRegs(TmpUsedRegs);
  7820. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7821. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7822. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7823. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7824. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7825. { Get the instruction after the SETcc instruction so we can
  7826. allocate a new register over the entire range }
  7827. GetNextInstruction(p_dist, hp1_dist) then
  7828. begin
  7829. { Register can appear in p if it's not used afterwards, so only
  7830. allocate between hp1 and hp1_dist }
  7831. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7832. if NewReg <> NR_NO then
  7833. begin
  7834. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7835. { Change the jump instruction into a SETcc instruction }
  7836. taicpu(hp1).opcode := A_SETcc;
  7837. taicpu(hp1).opsize := S_B;
  7838. taicpu(hp1).loadreg(0, NewReg);
  7839. { This is now a dead label }
  7840. tai_label(p_label).labsym.decrefs;
  7841. { Prefer adding before the next instruction so the FLAGS
  7842. register is deallicated first }
  7843. AsmL.InsertBefore(
  7844. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7845. hp1_dist
  7846. );
  7847. Result := True;
  7848. { Don't exit yet, as p wasn't changed and hp1, while
  7849. modified, is still intact and might be optimised by the
  7850. SETcc optimisation below }
  7851. end;
  7852. end;
  7853. end;
  7854. end;
  7855. if (taicpu(p).oper[0]^.typ = top_const) and
  7856. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7857. begin
  7858. if (taicpu(p).oper[0]^.val = 0) and
  7859. (taicpu(p).oper[1]^.typ = top_reg) then
  7860. begin
  7861. hp2 := p;
  7862. FirstMatch := True;
  7863. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7864. anything meaningful once it's converted to "test %reg,%reg";
  7865. additionally, some jumps will always (or never) branch, so
  7866. evaluate every jump immediately following the
  7867. comparison, optimising the conditions if possible.
  7868. Similarly with SETcc... those that are always set to 0 or 1
  7869. are changed to MOV instructions }
  7870. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7871. (
  7872. GetNextInstruction(hp2, hp1) and
  7873. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7874. ) do
  7875. begin
  7876. Prefetch(hp1.Next);
  7877. FirstMatch := False;
  7878. case taicpu(hp1).condition of
  7879. C_B, C_C, C_NAE, C_O:
  7880. { For B/NAE:
  7881. Will never branch since an unsigned integer can never be below zero
  7882. For C/O:
  7883. Result cannot overflow because 0 is being subtracted
  7884. }
  7885. begin
  7886. if taicpu(hp1).opcode = A_Jcc then
  7887. begin
  7888. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7889. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7890. RemoveInstruction(hp1);
  7891. { Since hp1 was deleted, hp2 must not be updated }
  7892. Continue;
  7893. end
  7894. else
  7895. begin
  7896. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7897. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7898. taicpu(hp1).opcode := A_MOV;
  7899. taicpu(hp1).ops := 2;
  7900. taicpu(hp1).condition := C_None;
  7901. taicpu(hp1).opsize := S_B;
  7902. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7903. taicpu(hp1).loadconst(0, 0);
  7904. end;
  7905. end;
  7906. C_BE, C_NA:
  7907. begin
  7908. { Will only branch if equal to zero }
  7909. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7910. taicpu(hp1).condition := C_E;
  7911. end;
  7912. C_A, C_NBE:
  7913. begin
  7914. { Will only branch if not equal to zero }
  7915. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7916. taicpu(hp1).condition := C_NE;
  7917. end;
  7918. C_AE, C_NB, C_NC, C_NO:
  7919. begin
  7920. { Will always branch }
  7921. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7922. if taicpu(hp1).opcode = A_Jcc then
  7923. begin
  7924. MakeUnconditional(taicpu(hp1));
  7925. { Any jumps/set that follow will now be dead code }
  7926. RemoveDeadCodeAfterJump(taicpu(hp1));
  7927. Break;
  7928. end
  7929. else
  7930. begin
  7931. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7932. taicpu(hp1).opcode := A_MOV;
  7933. taicpu(hp1).ops := 2;
  7934. taicpu(hp1).condition := C_None;
  7935. taicpu(hp1).opsize := S_B;
  7936. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7937. taicpu(hp1).loadconst(0, 1);
  7938. end;
  7939. end;
  7940. C_None:
  7941. InternalError(2020012201);
  7942. C_P, C_PE, C_NP, C_PO:
  7943. { We can't handle parity checks and they should never be generated
  7944. after a general-purpose CMP (it's used in some floating-point
  7945. comparisons that don't use CMP) }
  7946. InternalError(2020012202);
  7947. else
  7948. { Zero/Equality, Sign, their complements and all of the
  7949. signed comparisons do not need to be converted };
  7950. end;
  7951. hp2 := hp1;
  7952. end;
  7953. { Convert the instruction to a TEST }
  7954. taicpu(p).opcode := A_TEST;
  7955. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7956. Result := True;
  7957. Exit;
  7958. end
  7959. else
  7960. begin
  7961. TransferUsedRegs(TmpUsedRegs);
  7962. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7963. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7964. begin
  7965. if (taicpu(p).oper[0]^.val = 1) and
  7966. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7967. begin
  7968. { Convert; To:
  7969. cmp $1,r/m cmp $0,r/m
  7970. jl @lbl jle @lbl
  7971. (Also do inverted conditions)
  7972. }
  7973. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7974. taicpu(p).oper[0]^.val := 0;
  7975. if taicpu(hp1).condition in [C_L, C_NGE] then
  7976. taicpu(hp1).condition := C_LE
  7977. else
  7978. taicpu(hp1).condition := C_NLE;
  7979. { If the instruction is now "cmp $0,%reg", convert it to a
  7980. TEST (and effectively do the work of the "cmp $0,%reg" in
  7981. the block above)
  7982. }
  7983. if (taicpu(p).oper[1]^.typ = top_reg) then
  7984. begin
  7985. taicpu(p).opcode := A_TEST;
  7986. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7987. end;
  7988. Result := True;
  7989. Exit;
  7990. end
  7991. else if (taicpu(p).oper[1]^.typ = top_reg)
  7992. {$ifdef x86_64}
  7993. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7994. {$endif x86_64}
  7995. then
  7996. begin
  7997. { cmp register,$8000 neg register
  7998. je target --> jo target
  7999. .... only if register is deallocated before jump.}
  8000. case Taicpu(p).opsize of
  8001. S_B: v:=$80;
  8002. S_W: v:=$8000;
  8003. S_L: v:=qword($80000000);
  8004. else
  8005. internalerror(2013112905);
  8006. end;
  8007. if (taicpu(p).oper[0]^.val=v) and
  8008. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8009. begin
  8010. TransferUsedRegs(TmpUsedRegs);
  8011. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8012. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8013. begin
  8014. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8015. Taicpu(p).opcode:=A_NEG;
  8016. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8017. Taicpu(p).clearop(1);
  8018. Taicpu(p).ops:=1;
  8019. if Taicpu(hp1).condition=C_E then
  8020. Taicpu(hp1).condition:=C_O
  8021. else
  8022. Taicpu(hp1).condition:=C_NO;
  8023. Result:=true;
  8024. exit;
  8025. end;
  8026. end;
  8027. end;
  8028. end;
  8029. end;
  8030. end;
  8031. if TrySwapMovCmp(p, hp1) then
  8032. begin
  8033. Result := True;
  8034. Exit;
  8035. end;
  8036. end;
  8037. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8038. var
  8039. hp1: tai;
  8040. begin
  8041. {
  8042. remove the second (v)pxor from
  8043. pxor reg,reg
  8044. ...
  8045. pxor reg,reg
  8046. }
  8047. Result:=false;
  8048. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8049. MatchOpType(taicpu(p),top_reg,top_reg) and
  8050. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8051. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8052. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8053. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8054. begin
  8055. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8056. RemoveInstruction(hp1);
  8057. Result:=true;
  8058. Exit;
  8059. end
  8060. {
  8061. replace
  8062. pxor reg1,reg1
  8063. movapd/s reg1,reg2
  8064. dealloc reg1
  8065. by
  8066. pxor reg2,reg2
  8067. }
  8068. else if GetNextInstruction(p,hp1) and
  8069. { we mix single and double opperations here because we assume that the compiler
  8070. generates vmovapd only after double operations and vmovaps only after single operations }
  8071. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8072. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8073. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8074. (taicpu(p).oper[0]^.typ=top_reg) then
  8075. begin
  8076. TransferUsedRegs(TmpUsedRegs);
  8077. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8078. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8079. begin
  8080. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8081. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8082. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8083. RemoveInstruction(hp1);
  8084. result:=true;
  8085. end;
  8086. end;
  8087. end;
  8088. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8089. var
  8090. hp1: tai;
  8091. begin
  8092. {
  8093. remove the second (v)pxor from
  8094. (v)pxor reg,reg
  8095. ...
  8096. (v)pxor reg,reg
  8097. }
  8098. Result:=false;
  8099. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8100. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8101. begin
  8102. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8103. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8104. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8105. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8106. begin
  8107. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8108. RemoveInstruction(hp1);
  8109. Result:=true;
  8110. Exit;
  8111. end;
  8112. {$ifdef x86_64}
  8113. {
  8114. replace
  8115. vpxor reg1,reg1,reg1
  8116. vmov reg,mem
  8117. by
  8118. movq $0,mem
  8119. }
  8120. if GetNextInstruction(p,hp1) and
  8121. MatchInstruction(hp1,A_VMOVSD,[]) and
  8122. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8123. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8124. begin
  8125. TransferUsedRegs(TmpUsedRegs);
  8126. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8127. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8128. begin
  8129. taicpu(hp1).loadconst(0,0);
  8130. taicpu(hp1).opcode:=A_MOV;
  8131. taicpu(hp1).opsize:=S_Q;
  8132. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8133. RemoveCurrentP(p);
  8134. result:=true;
  8135. Exit;
  8136. end;
  8137. end;
  8138. {$endif x86_64}
  8139. end
  8140. {
  8141. replace
  8142. vpxor reg1,reg1,reg2
  8143. by
  8144. vpxor reg2,reg2,reg2
  8145. to avoid unncessary data dependencies
  8146. }
  8147. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8148. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8149. begin
  8150. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8151. { avoid unncessary data dependency }
  8152. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8153. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8154. result:=true;
  8155. exit;
  8156. end;
  8157. Result:=OptPass1VOP(p);
  8158. end;
  8159. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8160. var
  8161. hp1 : tai;
  8162. begin
  8163. result:=false;
  8164. { replace
  8165. IMul const,%mreg1,%mreg2
  8166. Mov %reg2,%mreg3
  8167. dealloc %mreg3
  8168. by
  8169. Imul const,%mreg1,%mreg23
  8170. }
  8171. if (taicpu(p).ops=3) and
  8172. GetNextInstruction(p,hp1) and
  8173. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8174. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8175. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8176. begin
  8177. TransferUsedRegs(TmpUsedRegs);
  8178. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8179. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8180. begin
  8181. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8182. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8183. RemoveInstruction(hp1);
  8184. result:=true;
  8185. end;
  8186. end;
  8187. end;
  8188. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8189. var
  8190. hp1 : tai;
  8191. begin
  8192. result:=false;
  8193. { replace
  8194. IMul %reg0,%reg1,%reg2
  8195. Mov %reg2,%reg3
  8196. dealloc %reg2
  8197. by
  8198. Imul %reg0,%reg1,%reg3
  8199. }
  8200. if GetNextInstruction(p,hp1) and
  8201. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8202. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8203. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8204. begin
  8205. TransferUsedRegs(TmpUsedRegs);
  8206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8207. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8208. begin
  8209. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8210. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8211. RemoveInstruction(hp1);
  8212. result:=true;
  8213. end;
  8214. end;
  8215. end;
  8216. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8217. var
  8218. hp1: tai;
  8219. begin
  8220. Result:=false;
  8221. { get rid of
  8222. (v)cvtss2sd reg0,<reg1,>reg2
  8223. (v)cvtss2sd reg2,<reg2,>reg0
  8224. }
  8225. if GetNextInstruction(p,hp1) and
  8226. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8227. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8228. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8229. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8230. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8231. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8232. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8233. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8234. )
  8235. ) then
  8236. begin
  8237. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8238. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8239. begin
  8240. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8241. RemoveCurrentP(p);
  8242. RemoveInstruction(hp1);
  8243. end
  8244. else
  8245. begin
  8246. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8247. if taicpu(hp1).opcode=A_CVTSD2SS then
  8248. begin
  8249. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8250. taicpu(p).opcode:=A_MOVAPS;
  8251. end
  8252. else
  8253. begin
  8254. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8255. taicpu(p).opcode:=A_VMOVAPS;
  8256. end;
  8257. taicpu(p).ops:=2;
  8258. RemoveInstruction(hp1);
  8259. end;
  8260. Result:=true;
  8261. Exit;
  8262. end;
  8263. end;
  8264. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8265. var
  8266. hp1, hp2, hp3, hp4, hp5: tai;
  8267. ThisReg: TRegister;
  8268. begin
  8269. Result := False;
  8270. if not GetNextInstruction(p,hp1) then
  8271. Exit;
  8272. {
  8273. convert
  8274. j<c> .L1
  8275. mov 1,reg
  8276. jmp .L2
  8277. .L1
  8278. mov 0,reg
  8279. .L2
  8280. into
  8281. mov 0,reg
  8282. set<not(c)> reg
  8283. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8284. would destroy the flag contents
  8285. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8286. executed at the same time as a previous comparison.
  8287. set<not(c)> reg
  8288. movzx reg, reg
  8289. }
  8290. if MatchInstruction(hp1,A_MOV,[]) and
  8291. (taicpu(hp1).oper[0]^.typ = top_const) and
  8292. (
  8293. (
  8294. (taicpu(hp1).oper[1]^.typ = top_reg)
  8295. {$ifdef i386}
  8296. { Under i386, ESI, EDI, EBP and ESP
  8297. don't have an 8-bit representation }
  8298. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8299. {$endif i386}
  8300. ) or (
  8301. {$ifdef i386}
  8302. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8303. {$endif i386}
  8304. (taicpu(hp1).opsize = S_B)
  8305. )
  8306. ) and
  8307. GetNextInstruction(hp1,hp2) and
  8308. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8309. GetNextInstruction(hp2,hp3) and
  8310. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8311. GetNextInstruction(hp3,hp4) and
  8312. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8313. (taicpu(hp4).oper[0]^.typ = top_const) and
  8314. (
  8315. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8316. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8317. ) and
  8318. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8319. GetNextInstruction(hp4,hp5) and
  8320. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8321. begin
  8322. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8323. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8324. tai_label(hp3).labsym.DecRefs;
  8325. { If this isn't the only reference to the middle label, we can
  8326. still make a saving - only that the first jump and everything
  8327. that follows will remain. }
  8328. if (tai_label(hp3).labsym.getrefs = 0) then
  8329. begin
  8330. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8331. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8332. else
  8333. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8334. { remove jump, first label and second MOV (also catching any aligns) }
  8335. repeat
  8336. if not GetNextInstruction(hp2, hp3) then
  8337. InternalError(2021040810);
  8338. RemoveInstruction(hp2);
  8339. hp2 := hp3;
  8340. until hp2 = hp5;
  8341. { Don't decrement reference count before the removal loop
  8342. above, otherwise GetNextInstruction won't stop on the
  8343. the label }
  8344. tai_label(hp5).labsym.DecRefs;
  8345. end
  8346. else
  8347. begin
  8348. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8349. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8350. else
  8351. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8352. end;
  8353. taicpu(p).opcode:=A_SETcc;
  8354. taicpu(p).opsize:=S_B;
  8355. taicpu(p).is_jmp:=False;
  8356. if taicpu(hp1).opsize=S_B then
  8357. begin
  8358. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8359. if taicpu(hp1).oper[1]^.typ = top_reg then
  8360. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8361. RemoveInstruction(hp1);
  8362. end
  8363. else
  8364. begin
  8365. { Will be a register because the size can't be S_B otherwise }
  8366. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8367. taicpu(p).loadreg(0, ThisReg);
  8368. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8369. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8370. begin
  8371. case taicpu(hp1).opsize of
  8372. S_W:
  8373. taicpu(hp1).opsize := S_BW;
  8374. S_L:
  8375. taicpu(hp1).opsize := S_BL;
  8376. {$ifdef x86_64}
  8377. S_Q:
  8378. begin
  8379. taicpu(hp1).opsize := S_BL;
  8380. { Change the destination register to 32-bit }
  8381. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8382. end;
  8383. {$endif x86_64}
  8384. else
  8385. InternalError(2021040820);
  8386. end;
  8387. taicpu(hp1).opcode := A_MOVZX;
  8388. taicpu(hp1).loadreg(0, ThisReg);
  8389. end
  8390. else
  8391. begin
  8392. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8393. { hp1 is already a MOV instruction with the correct register }
  8394. taicpu(hp1).loadconst(0, 0);
  8395. { Inserting it right before p will guarantee that the flags are also tracked }
  8396. asml.Remove(hp1);
  8397. asml.InsertBefore(hp1, p);
  8398. end;
  8399. end;
  8400. Result:=true;
  8401. exit;
  8402. end
  8403. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8404. Result := TryJccStcClcOpt(p, hp1)
  8405. else if (hp1.typ = ait_label) then
  8406. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8407. end;
  8408. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8409. var
  8410. hp1, hp2, hp3: tai;
  8411. SourceRef, TargetRef: TReference;
  8412. CurrentReg: TRegister;
  8413. begin
  8414. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8415. if not UseAVX then
  8416. InternalError(2021100501);
  8417. Result := False;
  8418. { Look for the following to simplify:
  8419. vmovdqa/u x(mem1), %xmmreg
  8420. vmovdqa/u %xmmreg, y(mem2)
  8421. vmovdqa/u x+16(mem1), %xmmreg
  8422. vmovdqa/u %xmmreg, y+16(mem2)
  8423. Change to:
  8424. vmovdqa/u x(mem1), %ymmreg
  8425. vmovdqa/u %ymmreg, y(mem2)
  8426. vpxor %ymmreg, %ymmreg, %ymmreg
  8427. ( The VPXOR instruction is to zero the upper half, thus removing the
  8428. need to call the potentially expensive VZEROUPPER instruction. Other
  8429. peephole optimisations can remove VPXOR if it's unnecessary )
  8430. }
  8431. TransferUsedRegs(TmpUsedRegs);
  8432. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8433. { NOTE: In the optimisations below, if the references dictate that an
  8434. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8435. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8436. if (taicpu(p).opsize = S_XMM) and
  8437. MatchOpType(taicpu(p), top_ref, top_reg) and
  8438. GetNextInstruction(p, hp1) and
  8439. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8440. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8441. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8442. begin
  8443. SourceRef := taicpu(p).oper[0]^.ref^;
  8444. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8445. if GetNextInstruction(hp1, hp2) and
  8446. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8447. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8448. begin
  8449. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8450. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8451. Inc(SourceRef.offset, 16);
  8452. { Reuse the register in the first block move }
  8453. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8454. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8455. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8456. begin
  8457. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8458. Inc(TargetRef.offset, 16);
  8459. if GetNextInstruction(hp2, hp3) and
  8460. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8461. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8462. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8463. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8464. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8465. begin
  8466. { Update the register tracking to the new size }
  8467. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8468. { Remember that the offsets are 16 ahead }
  8469. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8470. if not (
  8471. ((SourceRef.offset mod 32) = 16) and
  8472. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8473. ) then
  8474. taicpu(p).opcode := A_VMOVDQU;
  8475. taicpu(p).opsize := S_YMM;
  8476. taicpu(p).oper[1]^.reg := CurrentReg;
  8477. if not (
  8478. ((TargetRef.offset mod 32) = 16) and
  8479. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8480. ) then
  8481. taicpu(hp1).opcode := A_VMOVDQU;
  8482. taicpu(hp1).opsize := S_YMM;
  8483. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8484. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8485. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8486. if (pi_uses_ymm in current_procinfo.flags) then
  8487. RemoveInstruction(hp2)
  8488. else
  8489. begin
  8490. taicpu(hp2).opcode := A_VPXOR;
  8491. taicpu(hp2).opsize := S_YMM;
  8492. taicpu(hp2).loadreg(0, CurrentReg);
  8493. taicpu(hp2).loadreg(1, CurrentReg);
  8494. taicpu(hp2).loadreg(2, CurrentReg);
  8495. taicpu(hp2).ops := 3;
  8496. end;
  8497. RemoveInstruction(hp3);
  8498. Result := True;
  8499. Exit;
  8500. end;
  8501. end
  8502. else
  8503. begin
  8504. { See if the next references are 16 less rather than 16 greater }
  8505. Dec(SourceRef.offset, 32); { -16 the other way }
  8506. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8507. begin
  8508. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8509. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8510. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8511. GetNextInstruction(hp2, hp3) and
  8512. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8513. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8514. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8515. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8516. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8517. begin
  8518. { Update the register tracking to the new size }
  8519. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8520. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8521. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8522. if not(
  8523. ((SourceRef.offset mod 32) = 0) and
  8524. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8525. ) then
  8526. taicpu(hp2).opcode := A_VMOVDQU;
  8527. taicpu(hp2).opsize := S_YMM;
  8528. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8529. if not (
  8530. ((TargetRef.offset mod 32) = 0) and
  8531. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8532. ) then
  8533. taicpu(hp3).opcode := A_VMOVDQU;
  8534. taicpu(hp3).opsize := S_YMM;
  8535. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8536. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8537. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8538. if (pi_uses_ymm in current_procinfo.flags) then
  8539. RemoveInstruction(hp1)
  8540. else
  8541. begin
  8542. taicpu(hp1).opcode := A_VPXOR;
  8543. taicpu(hp1).opsize := S_YMM;
  8544. taicpu(hp1).loadreg(0, CurrentReg);
  8545. taicpu(hp1).loadreg(1, CurrentReg);
  8546. taicpu(hp1).loadreg(2, CurrentReg);
  8547. taicpu(hp1).ops := 3;
  8548. Asml.Remove(hp1);
  8549. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8550. end;
  8551. RemoveCurrentP(p, hp2);
  8552. Result := True;
  8553. Exit;
  8554. end;
  8555. end;
  8556. end;
  8557. end;
  8558. end;
  8559. end;
  8560. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8561. var
  8562. hp2, hp3, first_assignment: tai;
  8563. IncCount, OperIdx: Integer;
  8564. OrigLabel: TAsmLabel;
  8565. begin
  8566. Count := 0;
  8567. Result := False;
  8568. first_assignment := nil;
  8569. if (LoopCount >= 20) then
  8570. begin
  8571. { Guard against infinite loops }
  8572. Exit;
  8573. end;
  8574. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8575. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8576. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8577. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8578. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8579. Exit;
  8580. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8581. {
  8582. change
  8583. jmp .L1
  8584. ...
  8585. .L1:
  8586. mov ##, ## ( multiple movs possible )
  8587. jmp/ret
  8588. into
  8589. mov ##, ##
  8590. jmp/ret
  8591. }
  8592. if not Assigned(hp1) then
  8593. begin
  8594. hp1 := GetLabelWithSym(OrigLabel);
  8595. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8596. Exit;
  8597. end;
  8598. hp2 := hp1;
  8599. while Assigned(hp2) do
  8600. begin
  8601. if Assigned(hp2) and (hp2.typ = ait_label) then
  8602. SkipLabels(hp2,hp2);
  8603. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8604. Break;
  8605. case taicpu(hp2).opcode of
  8606. A_MOVSD:
  8607. begin
  8608. if taicpu(hp2).ops = 0 then
  8609. { Wrong MOVSD }
  8610. Break;
  8611. Inc(Count);
  8612. if Count >= 5 then
  8613. { Too many to be worthwhile }
  8614. Break;
  8615. GetNextInstruction(hp2, hp2);
  8616. Continue;
  8617. end;
  8618. A_MOV,
  8619. A_MOVD,
  8620. A_MOVQ,
  8621. A_MOVSX,
  8622. {$ifdef x86_64}
  8623. A_MOVSXD,
  8624. {$endif x86_64}
  8625. A_MOVZX,
  8626. A_MOVAPS,
  8627. A_MOVUPS,
  8628. A_MOVSS,
  8629. A_MOVAPD,
  8630. A_MOVUPD,
  8631. A_MOVDQA,
  8632. A_MOVDQU,
  8633. A_VMOVSS,
  8634. A_VMOVAPS,
  8635. A_VMOVUPS,
  8636. A_VMOVSD,
  8637. A_VMOVAPD,
  8638. A_VMOVUPD,
  8639. A_VMOVDQA,
  8640. A_VMOVDQU:
  8641. begin
  8642. Inc(Count);
  8643. if Count >= 5 then
  8644. { Too many to be worthwhile }
  8645. Break;
  8646. GetNextInstruction(hp2, hp2);
  8647. Continue;
  8648. end;
  8649. A_JMP:
  8650. begin
  8651. { Guard against infinite loops }
  8652. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8653. Exit;
  8654. { Analyse this jump first in case it also duplicates assignments }
  8655. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8656. begin
  8657. { Something did change! }
  8658. Result := True;
  8659. Inc(Count, IncCount);
  8660. if Count >= 5 then
  8661. begin
  8662. { Too many to be worthwhile }
  8663. Exit;
  8664. end;
  8665. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8666. Break;
  8667. end;
  8668. Result := True;
  8669. Break;
  8670. end;
  8671. A_RET:
  8672. begin
  8673. Result := True;
  8674. Break;
  8675. end;
  8676. else
  8677. Break;
  8678. end;
  8679. end;
  8680. if Result then
  8681. begin
  8682. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8683. if Count = 0 then
  8684. begin
  8685. Result := False;
  8686. Exit;
  8687. end;
  8688. TransferUsedRegs(TmpUsedRegs);
  8689. hp3 := p;
  8690. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8691. while True do
  8692. begin
  8693. if Assigned(hp1) and (hp1.typ = ait_label) then
  8694. SkipLabels(hp1,hp1);
  8695. case hp1.typ of
  8696. ait_regalloc:
  8697. if tai_regalloc(hp1).ratype = ra_dealloc then
  8698. begin
  8699. { Duplicate the register deallocation... }
  8700. hp3:=tai(hp1.getcopy);
  8701. if first_assignment = nil then
  8702. first_assignment := hp3;
  8703. asml.InsertBefore(hp3, p);
  8704. { ... but also reallocate it after the jump }
  8705. hp3:=tai(hp1.getcopy);
  8706. tai_regalloc(hp3).ratype := ra_alloc;
  8707. asml.InsertAfter(hp3, p);
  8708. end;
  8709. ait_instruction:
  8710. case taicpu(hp1).opcode of
  8711. A_JMP:
  8712. begin
  8713. { Change the original jump to the new destination }
  8714. OrigLabel.decrefs;
  8715. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8716. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8717. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8718. if not Assigned(first_assignment) then
  8719. InternalError(2021040810)
  8720. else
  8721. p := first_assignment;
  8722. Exit;
  8723. end;
  8724. A_RET:
  8725. begin
  8726. { Now change the jump into a RET instruction }
  8727. ConvertJumpToRET(p, hp1);
  8728. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8729. if not Assigned(first_assignment) then
  8730. InternalError(2021040811)
  8731. else
  8732. p := first_assignment;
  8733. Exit;
  8734. end;
  8735. else
  8736. begin
  8737. { Duplicate the MOV instruction }
  8738. hp3:=tai(hp1.getcopy);
  8739. if first_assignment = nil then
  8740. first_assignment := hp3;
  8741. asml.InsertBefore(hp3, p);
  8742. { Make sure the compiler knows about any final registers written here }
  8743. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8744. with taicpu(hp3).oper[OperIdx]^ do
  8745. begin
  8746. case typ of
  8747. top_ref:
  8748. begin
  8749. if (ref^.base <> NR_NO) and
  8750. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8751. (
  8752. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8753. (
  8754. { Allow the frame pointer if it's not being used by the procedure as such }
  8755. Assigned(current_procinfo) and
  8756. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8757. )
  8758. )
  8759. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8760. then
  8761. begin
  8762. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8763. if not Assigned(first_assignment) then
  8764. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8765. end;
  8766. if (ref^.index <> NR_NO) and
  8767. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8768. (
  8769. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8770. (
  8771. { Allow the frame pointer if it's not being used by the procedure as such }
  8772. Assigned(current_procinfo) and
  8773. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8774. )
  8775. )
  8776. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8777. (ref^.index <> ref^.base) then
  8778. begin
  8779. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8780. if not Assigned(first_assignment) then
  8781. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8782. end;
  8783. end;
  8784. top_reg:
  8785. begin
  8786. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8787. if not Assigned(first_assignment) then
  8788. IncludeRegInUsedRegs(reg, UsedRegs);
  8789. end;
  8790. else
  8791. ;
  8792. end;
  8793. end;
  8794. end;
  8795. end;
  8796. else
  8797. InternalError(2021040720);
  8798. end;
  8799. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8800. { Should have dropped out earlier }
  8801. InternalError(2021040710);
  8802. end;
  8803. end;
  8804. end;
  8805. const
  8806. WriteOp: array[0..3] of set of TInsChange = (
  8807. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8808. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8809. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8810. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8811. RegWriteFlags: array[0..7] of set of TInsChange = (
  8812. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8813. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8814. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8815. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8816. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8817. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8818. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8819. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8820. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8821. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8822. var
  8823. hp2: tai;
  8824. X: Integer;
  8825. begin
  8826. { If we have something like:
  8827. op ###,###
  8828. mov ###,###
  8829. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8830. interfere in regards to what they write to.
  8831. NOTE: p must be a 2-operand instruction
  8832. }
  8833. Result := False;
  8834. if (hp1.typ <> ait_instruction) or
  8835. taicpu(hp1).is_jmp or
  8836. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8837. Exit;
  8838. { NOP is a pipeline fence, likely marking the beginning of the function
  8839. epilogue, so drop out. Similarly, drop out if POP or RET are
  8840. encountered }
  8841. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8842. Exit;
  8843. if (taicpu(hp1).opcode = A_MOVSD) and
  8844. (taicpu(hp1).ops = 0) then
  8845. { Wrong MOVSD }
  8846. Exit;
  8847. { Check for writes to specific registers first }
  8848. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8849. for X := 0 to 7 do
  8850. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8851. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8852. Exit;
  8853. for X := 0 to taicpu(hp1).ops - 1 do
  8854. begin
  8855. { Check to see if this operand writes to something }
  8856. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8857. { And matches something in the CMP/TEST instruction }
  8858. (
  8859. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8860. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8861. (
  8862. { If it's a register, make sure the register written to doesn't
  8863. appear in the cmp instruction as part of a reference }
  8864. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8865. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8866. )
  8867. ) then
  8868. Exit;
  8869. end;
  8870. { Check p to make sure it doesn't write to something that affects hp1 }
  8871. { Check for writes to specific registers first }
  8872. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8873. for X := 0 to 7 do
  8874. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8875. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8876. Exit;
  8877. for X := 0 to taicpu(p).ops - 1 do
  8878. begin
  8879. { Check to see if this operand writes to something }
  8880. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8881. { And matches something in hp1 }
  8882. (taicpu(p).oper[X]^.typ = top_reg) and
  8883. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8884. Exit;
  8885. end;
  8886. { The instruction can be safely moved }
  8887. asml.Remove(hp1);
  8888. { Try to insert after the last instructions where the FLAGS register is not
  8889. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8890. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8891. asml.InsertBefore(hp1, hp2)
  8892. { Failing that, try to insert after the last instructions where the
  8893. FLAGS register is not yet in use }
  8894. else if GetLastInstruction(p, hp2) and
  8895. (
  8896. (hp2.typ <> ait_instruction) or
  8897. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8898. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8899. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8900. ) then
  8901. asml.InsertAfter(hp1, hp2)
  8902. else
  8903. { Note, if p.Previous is nil (even if it should logically never be the
  8904. case), FindRegAllocBackward immediately exits with False and so we
  8905. safely land here (we can't just pass p because FindRegAllocBackward
  8906. immediately exits on an instruction). [Kit] }
  8907. asml.InsertBefore(hp1, p);
  8908. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8909. { We can't trust UsedRegs because we're looking backwards, although we
  8910. know the registers are allocated after p at the very least, so manually
  8911. create tai_regalloc objects if needed }
  8912. for X := 0 to taicpu(hp1).ops - 1 do
  8913. case taicpu(hp1).oper[X]^.typ of
  8914. top_reg:
  8915. begin
  8916. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8917. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8918. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8919. end;
  8920. top_ref:
  8921. begin
  8922. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8923. begin
  8924. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8925. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8926. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8927. end;
  8928. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8929. begin
  8930. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8931. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8932. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8933. end;
  8934. end;
  8935. else
  8936. ;
  8937. end;
  8938. Result := True;
  8939. end;
  8940. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8941. var
  8942. hp2: tai;
  8943. X: Integer;
  8944. begin
  8945. { If we have something like:
  8946. cmp ###,%reg1
  8947. mov 0,%reg2
  8948. And no modified registers are shared, move the instruction to before
  8949. the comparison as this means it can be optimised without worrying
  8950. about the FLAGS register. (CMP/MOV is generated by
  8951. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8952. As long as the second instruction doesn't use the flags or one of the
  8953. registers used by CMP or TEST (also check any references that use the
  8954. registers), then it can be moved prior to the comparison.
  8955. }
  8956. Result := False;
  8957. if not TrySwapMovOp(p, hp1) then
  8958. Exit;
  8959. if taicpu(hp1).opcode = A_LEA then
  8960. { The flags will be overwritten by the CMP/TEST instruction }
  8961. ConvertLEA(taicpu(hp1));
  8962. Result := True;
  8963. { Can we move it one further back? }
  8964. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8965. { Check to see if CMP/TEST is a comparison against zero }
  8966. (
  8967. (
  8968. (taicpu(p).opcode = A_CMP) and
  8969. MatchOperand(taicpu(p).oper[0]^, 0)
  8970. ) or
  8971. (
  8972. (taicpu(p).opcode = A_TEST) and
  8973. (
  8974. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8975. MatchOperand(taicpu(p).oper[0]^, -1)
  8976. )
  8977. )
  8978. ) and
  8979. { These instructions set the zero flag if the result is zero }
  8980. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8981. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8982. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8983. TrySwapMovOp(hp2, hp1);
  8984. end;
  8985. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8986. var
  8987. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8988. JumpLabel: TAsmLabel;
  8989. TmpBool: Boolean;
  8990. begin
  8991. Result := False;
  8992. { Look for:
  8993. stc/clc
  8994. j(c) .L1
  8995. ...
  8996. .L1:
  8997. set(n)cb %reg
  8998. (flags deallocated)
  8999. j(c) .L2
  9000. Change to:
  9001. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9002. j(c) .L2
  9003. }
  9004. p_last := p;
  9005. while GetNextInstruction(p_last, hp1) and
  9006. (hp1.typ = ait_instruction) and
  9007. IsJumpToLabel(taicpu(hp1)) do
  9008. begin
  9009. if DoJumpOptimizations(hp1, TmpBool) then
  9010. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9011. Continue;
  9012. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9013. if not Assigned(JumpLabel) then
  9014. InternalError(2024012801);
  9015. { Optimise the J(c); stc/clc optimisation first since this will
  9016. get missed if the main optimisation takes place }
  9017. if (taicpu(hp1).opcode = A_JCC) then
  9018. begin
  9019. if GetNextInstruction(hp1, hp2) and
  9020. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9021. TryJccStcClcOpt(hp1, hp2) then
  9022. begin
  9023. Result := True;
  9024. Exit;
  9025. end;
  9026. hp2 := nil; { Suppress compiler warning }
  9027. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9028. { Make sure the flags aren't used again }
  9029. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9030. begin
  9031. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9032. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9033. begin
  9034. if (taicpu(p).opcode = A_STC) then
  9035. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9036. else
  9037. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9038. MakeUnconditional(taicpu(hp1));
  9039. { Move the jump to after the flag deallocations }
  9040. Asml.Remove(hp1);
  9041. Asml.InsertAfter(hp1, hp2);
  9042. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9043. Result := True;
  9044. Exit;
  9045. end
  9046. else
  9047. begin
  9048. if (taicpu(p).opcode = A_STC) then
  9049. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9050. else
  9051. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9052. { In this case, the jump is deterministic in that it will never be taken }
  9053. JumpLabel.DecRefs;
  9054. RemoveInstruction(hp1);
  9055. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9056. Result := True;
  9057. Exit;
  9058. end;
  9059. end;
  9060. end;
  9061. hp2 := nil; { Suppress compiler warning }
  9062. if
  9063. { Make sure the carry flag doesn't appear in the jump conditions }
  9064. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9065. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9066. GetNextInstruction(hp2, p_dist) and
  9067. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9068. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9069. begin
  9070. case taicpu(p_dist).opcode of
  9071. A_Jcc:
  9072. begin
  9073. if DoJumpOptimizations(p_dist, TmpBool) then
  9074. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9075. Continue;
  9076. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9077. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9078. begin
  9079. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9080. JumpLabel.decrefs;
  9081. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9082. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9083. Result := True;
  9084. Exit;
  9085. end
  9086. else if GetNextInstruction(p_dist, hp1_dist) and
  9087. (hp1_dist.typ = ait_label) then
  9088. begin
  9089. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9090. JumpLabel.decrefs;
  9091. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9092. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9093. Result := True;
  9094. Exit;
  9095. end;
  9096. end;
  9097. A_SETcc:
  9098. if { Make sure the flags aren't used again }
  9099. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9100. GetNextInstruction(hp2, hp1_dist) and
  9101. (hp1_dist.typ = ait_instruction) and
  9102. IsJumpToLabel(taicpu(hp1_dist)) and
  9103. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9104. { This works if hp1_dist or both are regular JMP instructions }
  9105. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9106. (
  9107. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9108. { Make sure the register isn't still in use, otherwise it
  9109. may get corrupted (fixes #40659) }
  9110. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9111. ) then
  9112. begin
  9113. taicpu(p).allocate_oper(2);
  9114. taicpu(p).ops := 2;
  9115. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9116. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9117. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9118. taicpu(p).opcode := A_MOV;
  9119. taicpu(p).opsize := S_B;
  9120. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9121. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9122. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9123. JumpLabel.decrefs;
  9124. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9125. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9126. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9127. (tai_regalloc(hp2).ratype = ra_alloc) then
  9128. begin
  9129. Asml.Remove(hp2);
  9130. Asml.InsertAfter(hp2, p);
  9131. end;
  9132. Result := True;
  9133. Exit;
  9134. end;
  9135. else
  9136. ;
  9137. end;
  9138. end;
  9139. p_last := hp1;
  9140. end;
  9141. end;
  9142. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9143. var
  9144. hp2, hp3: tai;
  9145. TempBool: Boolean;
  9146. begin
  9147. Result := False;
  9148. {
  9149. j(c) .L1
  9150. stc/clc
  9151. .L1:
  9152. jc/jnc .L2
  9153. (Flags deallocated)
  9154. Change to:
  9155. j)c) .L1
  9156. jmp .L2
  9157. .L1:
  9158. jc/jnc .L2
  9159. Then call DoJumpOptimizations to convert to:
  9160. j(nc) .L2
  9161. .L1: (may become a dead label)
  9162. jc/jnc .L2
  9163. }
  9164. if GetNextInstruction(hp1, hp2) and
  9165. (hp2.typ = ait_label) and
  9166. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9167. GetNextInstruction(hp2, hp3) and
  9168. MatchInstruction(hp3, A_Jcc, []) and
  9169. (
  9170. (
  9171. (taicpu(hp3).condition = C_C) and
  9172. (taicpu(hp1).opcode = A_STC)
  9173. ) or (
  9174. (taicpu(hp3).condition = C_NC) and
  9175. (taicpu(hp1).opcode = A_CLC)
  9176. )
  9177. ) and
  9178. { Make sure the flags aren't used again }
  9179. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9180. begin
  9181. taicpu(hp1).allocate_oper(1);
  9182. taicpu(hp1).ops := 1;
  9183. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9184. taicpu(hp1).opcode := A_JMP;
  9185. taicpu(hp1).is_jmp := True;
  9186. TempBool := True; { Prevent compiler warnings }
  9187. if DoJumpOptimizations(p, TempBool) then
  9188. Result := True
  9189. else
  9190. Include(OptsToCheck, aoc_ForceNewIteration);
  9191. end;
  9192. end;
  9193. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9194. begin
  9195. { This generally only executes under -O3 and above }
  9196. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9197. end;
  9198. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9199. var
  9200. hp1, hp2: tai;
  9201. FoundComparison: Boolean;
  9202. begin
  9203. { Run the pass 1 optimisations as well, since they may have some effect
  9204. after the CMOV blocks are created in OptPass2Jcc }
  9205. Result := False;
  9206. { Result := OptPass1CMOVcc(p);
  9207. if Result then
  9208. Exit;}
  9209. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9210. and make a slightly inefficent result on branching-type blocks, notably
  9211. when setting a function result then jumping to the function epilogue.
  9212. In this case, change:
  9213. cmov(c) %reg1,%reg2
  9214. j(c) @lbl
  9215. (%reg2 deallocated)
  9216. To:
  9217. mov %reg11,%reg2
  9218. j(c) @lbl
  9219. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9220. jump because if it's not present, we may end up with a jump that's
  9221. completely unrelated.
  9222. }
  9223. hp1 := p;
  9224. while GetNextInstruction(hp1, hp1) and
  9225. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9226. if (hp1.typ = ait_instruction) and
  9227. (taicpu(hp1).opcode = A_Jcc) and
  9228. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9229. begin
  9230. TransferUsedRegs(TmpUsedRegs);
  9231. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9232. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9233. (
  9234. { See if we can find a more distant instruction that overwrites
  9235. the destination register }
  9236. (cs_opt_level3 in current_settings.optimizerswitches) and
  9237. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9238. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9239. ) then
  9240. begin
  9241. if (taicpu(p).oper[0]^.typ = top_reg) then
  9242. begin
  9243. { Search backwards to see if the source register is set to a
  9244. constant }
  9245. FoundComparison := False;
  9246. hp1 := p;
  9247. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9248. begin
  9249. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9250. begin
  9251. FoundComparison := True;
  9252. Continue;
  9253. end;
  9254. { Once we find the CMP, TEST or similar instruction, we
  9255. have to stop if we find anything other than a MOV }
  9256. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9257. Break;
  9258. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9259. { Destination register was modified }
  9260. Break;
  9261. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9262. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9263. begin
  9264. { Found a constant! }
  9265. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9266. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9267. { The source register is no longer in use }
  9268. RemoveInstruction(hp1);
  9269. Break;
  9270. end;
  9271. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9272. { Some other instruction has modified the source register }
  9273. Break;
  9274. end;
  9275. end;
  9276. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9277. taicpu(p).opcode := A_MOV;
  9278. taicpu(p).condition := C_None;
  9279. { Rely on the post peephole stage to put the MOV before the
  9280. CMP/TEST instruction that appears prior }
  9281. Result := True;
  9282. Exit;
  9283. end;
  9284. end;
  9285. end;
  9286. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9287. function IsXCHGAcceptable: Boolean; inline;
  9288. begin
  9289. { Always accept if optimising for size }
  9290. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9291. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9292. than 3, so it becomes a saving compared to three MOVs with two of
  9293. them able to execute simultaneously. [Kit] }
  9294. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9295. end;
  9296. var
  9297. NewRef: TReference;
  9298. hp1, hp2, hp3, hp4: Tai;
  9299. {$ifndef x86_64}
  9300. OperIdx: Integer;
  9301. {$endif x86_64}
  9302. NewInstr : Taicpu;
  9303. NewAligh : Tai_align;
  9304. DestLabel: TAsmLabel;
  9305. TempTracking: TAllUsedRegs;
  9306. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9307. var
  9308. NextInstr: tai;
  9309. begin
  9310. Result := False;
  9311. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9312. if not GetNextInstruction(InputInstr, NextInstr) or
  9313. (
  9314. { The FLAGS register isn't always tracked properly, so do not
  9315. perform this optimisation if a conditional statement follows }
  9316. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9317. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9318. ) then
  9319. begin
  9320. reference_reset(NewRef, 1, []);
  9321. NewRef.base := taicpu(p).oper[0]^.reg;
  9322. NewRef.scalefactor := 1;
  9323. if taicpu(InputInstr).opcode = A_ADD then
  9324. begin
  9325. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9326. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9327. end
  9328. else
  9329. begin
  9330. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9331. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9332. end;
  9333. taicpu(p).opcode := A_LEA;
  9334. taicpu(p).loadref(0, NewRef);
  9335. { For the sake of debugging, have the line info match the
  9336. arithmetic instruction rather than the MOV instruction }
  9337. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9338. RemoveInstruction(InputInstr);
  9339. Result := True;
  9340. end;
  9341. end;
  9342. begin
  9343. Result:=false;
  9344. { This optimisation adds an instruction, so only do it for speed }
  9345. if not (cs_opt_size in current_settings.optimizerswitches) and
  9346. MatchOpType(taicpu(p), top_const, top_reg) and
  9347. (taicpu(p).oper[0]^.val = 0) then
  9348. begin
  9349. { To avoid compiler warning }
  9350. DestLabel := nil;
  9351. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9352. InternalError(2021040750);
  9353. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9354. Exit;
  9355. case hp1.typ of
  9356. ait_label:
  9357. begin
  9358. { Change:
  9359. mov $0,%reg mov $0,%reg
  9360. @Lbl1: @Lbl1:
  9361. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9362. je @Lbl2 jne @Lbl2
  9363. To: To:
  9364. mov $0,%reg mov $0,%reg
  9365. jmp @Lbl2 jmp @Lbl3
  9366. (align) (align)
  9367. @Lbl1: @Lbl1:
  9368. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9369. je @Lbl2 je @Lbl2
  9370. @Lbl3: <-- Only if label exists
  9371. (Not if it's optimised for size)
  9372. }
  9373. if not GetNextInstruction(hp1, hp2) then
  9374. Exit;
  9375. if (hp2.typ = ait_instruction) and
  9376. (
  9377. { Register sizes must exactly match }
  9378. (
  9379. (taicpu(hp2).opcode = A_CMP) and
  9380. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9381. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9382. ) or (
  9383. (taicpu(hp2).opcode = A_TEST) and
  9384. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9385. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9386. )
  9387. ) and GetNextInstruction(hp2, hp3) and
  9388. (hp3.typ = ait_instruction) and
  9389. (taicpu(hp3).opcode = A_JCC) and
  9390. (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
  9391. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9392. begin
  9393. { Check condition of jump }
  9394. { Always true? }
  9395. if condition_in(C_E, taicpu(hp3).condition) then
  9396. begin
  9397. { Copy label symbol and obtain matching label entry for the
  9398. conditional jump, as this will be our destination}
  9399. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9400. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9401. Result := True;
  9402. end
  9403. { Always false? }
  9404. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9405. begin
  9406. { This is only worth it if there's a jump to take }
  9407. case hp2.typ of
  9408. ait_instruction:
  9409. begin
  9410. if taicpu(hp2).opcode = A_JMP then
  9411. begin
  9412. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9413. { An unconditional jump follows the conditional jump which will always be false,
  9414. so use this jump's destination for the new jump }
  9415. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9416. Result := True;
  9417. end
  9418. else if taicpu(hp2).opcode = A_JCC then
  9419. begin
  9420. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9421. if condition_in(C_E, taicpu(hp2).condition) then
  9422. begin
  9423. { A second conditional jump follows the conditional jump which will always be false,
  9424. while the second jump is always True, so use this jump's destination for the new jump }
  9425. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9426. Result := True;
  9427. end;
  9428. { Don't risk it if the jump isn't always true (Result remains False) }
  9429. end;
  9430. end;
  9431. else
  9432. { If anything else don't optimise };
  9433. end;
  9434. end;
  9435. if Result then
  9436. begin
  9437. { Just so we have something to insert as a paremeter}
  9438. reference_reset(NewRef, 1, []);
  9439. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9440. { Now actually load the correct parameter (this also
  9441. increases the reference count) }
  9442. NewInstr.loadsymbol(0, DestLabel, 0);
  9443. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9444. begin
  9445. { Get instruction before original label (may not be p under -O3) }
  9446. if not GetLastInstruction(hp1, hp2) then
  9447. { Shouldn't fail here }
  9448. InternalError(2021040701);
  9449. end
  9450. else
  9451. hp2 := p;
  9452. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9453. AsmL.InsertAfter(NewInstr, hp2);
  9454. { Add new alignment field }
  9455. (* AsmL.InsertAfter(
  9456. cai_align.create_max(
  9457. current_settings.alignment.jumpalign,
  9458. current_settings.alignment.jumpalignskipmax
  9459. ),
  9460. NewInstr
  9461. ); *)
  9462. end;
  9463. Exit;
  9464. end;
  9465. end;
  9466. else
  9467. ;
  9468. end;
  9469. end;
  9470. if not GetNextInstruction(p, hp1) then
  9471. Exit;
  9472. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9473. begin
  9474. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9475. begin
  9476. Result := True;
  9477. Exit;
  9478. end;
  9479. { This optimisation is only effective on a second run of Pass 2,
  9480. hence -O3 or above.
  9481. Change:
  9482. mov %reg1,%reg2
  9483. cmp/test (contains %reg1)
  9484. mov x, %reg1
  9485. (another mov or a j(c))
  9486. To:
  9487. mov %reg1,%reg2
  9488. mov x, %reg1
  9489. cmp (%reg1 replaced with %reg2)
  9490. (another mov or a j(c))
  9491. The requirement of an additional MOV or a jump ensures there
  9492. isn't performance loss, since a j(c) will permit macro-fusion
  9493. with the cmp instruction, while another MOV likely means it's
  9494. not all being executed in a single cycle due to parallelisation.
  9495. }
  9496. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9497. MatchOpType(taicpu(p), top_reg, top_reg) and
  9498. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9499. GetNextInstruction(hp1, hp2) and
  9500. MatchInstruction(hp2, A_MOV, []) and
  9501. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9502. { Registers don't have to be the same size in this case }
  9503. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9504. GetNextInstruction(hp2, hp3) and
  9505. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9506. { Make sure the operands in the camparison can be safely replaced }
  9507. (
  9508. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9509. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9510. ) and
  9511. (
  9512. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9513. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9514. ) then
  9515. begin
  9516. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9517. AsmL.Remove(hp2);
  9518. AsmL.InsertAfter(hp2, p);
  9519. Result := True;
  9520. Exit;
  9521. end;
  9522. end;
  9523. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9524. begin
  9525. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9526. further, but we can't just put this jump optimisation in pass 1
  9527. because it tends to perform worse when conditional jumps are
  9528. nearby (e.g. when converting CMOV instructions). [Kit] }
  9529. CopyUsedRegs(TempTracking);
  9530. UpdateUsedRegs(tai(p.Next));
  9531. if OptPass2JMP(hp1) then
  9532. begin
  9533. { Restore register state }
  9534. RestoreUsedRegs(TempTracking);
  9535. ReleaseUsedRegs(TempTracking);
  9536. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9537. OptPass1MOV(p);
  9538. Result := True;
  9539. Exit;
  9540. end;
  9541. { If OptPass2JMP returned False, no optimisations were done to
  9542. the jump and there are no further optimisations that can be done
  9543. to the MOV instruction on this pass other than FuncMov2Func }
  9544. { Restore register state }
  9545. RestoreUsedRegs(TempTracking);
  9546. ReleaseUsedRegs(TempTracking);
  9547. Result := FuncMov2Func(p, hp1);
  9548. Exit;
  9549. end;
  9550. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9551. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9552. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9553. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9554. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9555. begin
  9556. { Change:
  9557. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9558. addl/q $x,%reg2 subl/q $x,%reg2
  9559. To:
  9560. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9561. }
  9562. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9563. { be lazy, checking separately for sub would be slightly better }
  9564. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9565. begin
  9566. TransferUsedRegs(TmpUsedRegs);
  9567. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9568. if TryMovArith2Lea(hp1) then
  9569. begin
  9570. Result := True;
  9571. Exit;
  9572. end
  9573. end
  9574. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9575. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9576. { Same as above, but also adds or subtracts to %reg2 in between.
  9577. It's still valid as long as the flags aren't in use }
  9578. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9579. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9580. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9581. { be lazy, checking separately for sub would be slightly better }
  9582. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9583. begin
  9584. TransferUsedRegs(TmpUsedRegs);
  9585. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9586. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9587. if TryMovArith2Lea(hp2) then
  9588. begin
  9589. Result := True;
  9590. Exit;
  9591. end;
  9592. end;
  9593. end;
  9594. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9595. {$ifdef x86_64}
  9596. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9597. {$else x86_64}
  9598. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9599. {$endif x86_64}
  9600. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9601. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9602. { mov reg1, reg2 mov reg1, reg2
  9603. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9604. begin
  9605. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9606. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9607. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9608. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9609. TransferUsedRegs(TmpUsedRegs);
  9610. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9611. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9612. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9613. then
  9614. begin
  9615. RemoveCurrentP(p, hp1);
  9616. Result:=true;
  9617. end;
  9618. Exit;
  9619. end;
  9620. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9621. IsXCHGAcceptable and
  9622. { XCHG doesn't support 8-bit registers }
  9623. (taicpu(p).opsize <> S_B) and
  9624. MatchInstruction(hp1, A_MOV, []) and
  9625. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9626. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9627. GetNextInstruction(hp1, hp2) and
  9628. MatchInstruction(hp2, A_MOV, []) and
  9629. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9630. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9631. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9632. begin
  9633. { mov %reg1,%reg2
  9634. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9635. mov %reg2,%reg3
  9636. (%reg2 not used afterwards)
  9637. Note that xchg takes 3 cycles to execute, and generally mov's take
  9638. only one cycle apiece, but the first two mov's can be executed in
  9639. parallel, only taking 2 cycles overall. Older processors should
  9640. therefore only optimise for size. [Kit]
  9641. }
  9642. TransferUsedRegs(TmpUsedRegs);
  9643. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9644. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9645. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9646. begin
  9647. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9648. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9649. taicpu(hp1).opcode := A_XCHG;
  9650. RemoveCurrentP(p, hp1);
  9651. RemoveInstruction(hp2);
  9652. Result := True;
  9653. Exit;
  9654. end;
  9655. end;
  9656. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9657. MatchInstruction(hp1, A_SAR, []) then
  9658. begin
  9659. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9660. begin
  9661. { the use of %edx also covers the opsize being S_L }
  9662. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9663. begin
  9664. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9665. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9666. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9667. begin
  9668. { Change:
  9669. movl %eax,%edx
  9670. sarl $31,%edx
  9671. To:
  9672. cltd
  9673. }
  9674. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9675. RemoveInstruction(hp1);
  9676. taicpu(p).opcode := A_CDQ;
  9677. taicpu(p).opsize := S_NO;
  9678. taicpu(p).clearop(1);
  9679. taicpu(p).clearop(0);
  9680. taicpu(p).ops:=0;
  9681. Result := True;
  9682. Exit;
  9683. end
  9684. else if (cs_opt_size in current_settings.optimizerswitches) and
  9685. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9686. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9687. begin
  9688. { Change:
  9689. movl %edx,%eax
  9690. sarl $31,%edx
  9691. To:
  9692. movl %edx,%eax
  9693. cltd
  9694. Note that this creates a dependency between the two instructions,
  9695. so only perform if optimising for size.
  9696. }
  9697. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9698. taicpu(hp1).opcode := A_CDQ;
  9699. taicpu(hp1).opsize := S_NO;
  9700. taicpu(hp1).clearop(1);
  9701. taicpu(hp1).clearop(0);
  9702. taicpu(hp1).ops:=0;
  9703. Include(OptsToCheck, aoc_ForceNewIteration);
  9704. Exit;
  9705. end;
  9706. {$ifndef x86_64}
  9707. end
  9708. { Don't bother if CMOV is supported, because a more optimal
  9709. sequence would have been generated for the Abs() intrinsic }
  9710. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9711. { the use of %eax also covers the opsize being S_L }
  9712. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9713. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9714. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9715. GetNextInstruction(hp1, hp2) and
  9716. MatchInstruction(hp2, A_XOR, [S_L]) and
  9717. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9718. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9719. GetNextInstruction(hp2, hp3) and
  9720. MatchInstruction(hp3, A_SUB, [S_L]) and
  9721. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9722. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9723. begin
  9724. { Change:
  9725. movl %eax,%edx
  9726. sarl $31,%eax
  9727. xorl %eax,%edx
  9728. subl %eax,%edx
  9729. (Instruction that uses %edx)
  9730. (%eax deallocated)
  9731. (%edx deallocated)
  9732. To:
  9733. cltd
  9734. xorl %edx,%eax <-- Note the registers have swapped
  9735. subl %edx,%eax
  9736. (Instruction that uses %eax) <-- %eax rather than %edx
  9737. }
  9738. TransferUsedRegs(TmpUsedRegs);
  9739. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9740. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9741. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9742. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9743. begin
  9744. if GetNextInstruction(hp3, hp4) and
  9745. not RegModifiedByInstruction(NR_EDX, hp4) and
  9746. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9747. begin
  9748. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9749. taicpu(p).opcode := A_CDQ;
  9750. taicpu(p).clearop(1);
  9751. taicpu(p).clearop(0);
  9752. taicpu(p).ops:=0;
  9753. RemoveInstruction(hp1);
  9754. taicpu(hp2).loadreg(0, NR_EDX);
  9755. taicpu(hp2).loadreg(1, NR_EAX);
  9756. taicpu(hp3).loadreg(0, NR_EDX);
  9757. taicpu(hp3).loadreg(1, NR_EAX);
  9758. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9759. { Convert references in the following instruction (hp4) from %edx to %eax }
  9760. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9761. with taicpu(hp4).oper[OperIdx]^ do
  9762. case typ of
  9763. top_reg:
  9764. if getsupreg(reg) = RS_EDX then
  9765. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9766. top_ref:
  9767. begin
  9768. if getsupreg(reg) = RS_EDX then
  9769. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9770. if getsupreg(reg) = RS_EDX then
  9771. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9772. end;
  9773. else
  9774. ;
  9775. end;
  9776. Result := True;
  9777. Exit;
  9778. end;
  9779. end;
  9780. {$else x86_64}
  9781. end;
  9782. end
  9783. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9784. { the use of %rdx also covers the opsize being S_Q }
  9785. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9786. begin
  9787. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9788. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9789. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9790. begin
  9791. { Change:
  9792. movq %rax,%rdx
  9793. sarq $63,%rdx
  9794. To:
  9795. cqto
  9796. }
  9797. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9798. RemoveInstruction(hp1);
  9799. taicpu(p).opcode := A_CQO;
  9800. taicpu(p).opsize := S_NO;
  9801. taicpu(p).clearop(1);
  9802. taicpu(p).clearop(0);
  9803. taicpu(p).ops:=0;
  9804. Result := True;
  9805. Exit;
  9806. end
  9807. else if (cs_opt_size in current_settings.optimizerswitches) and
  9808. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9809. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9810. begin
  9811. { Change:
  9812. movq %rdx,%rax
  9813. sarq $63,%rdx
  9814. To:
  9815. movq %rdx,%rax
  9816. cqto
  9817. Note that this creates a dependency between the two instructions,
  9818. so only perform if optimising for size.
  9819. }
  9820. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9821. taicpu(hp1).opcode := A_CQO;
  9822. taicpu(hp1).opsize := S_NO;
  9823. taicpu(hp1).clearop(1);
  9824. taicpu(hp1).clearop(0);
  9825. taicpu(hp1).ops:=0;
  9826. Include(OptsToCheck, aoc_ForceNewIteration);
  9827. Exit;
  9828. {$endif x86_64}
  9829. end;
  9830. end;
  9831. end;
  9832. if MatchInstruction(hp1, A_MOV, []) and
  9833. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9834. { Though "GetNextInstruction" could be factored out, along with
  9835. the instructions that depend on hp2, it is an expensive call that
  9836. should be delayed for as long as possible, hence we do cheaper
  9837. checks first that are likely to be False. [Kit] }
  9838. begin
  9839. if (
  9840. (
  9841. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9842. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9843. (
  9844. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9845. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9846. )
  9847. ) or
  9848. (
  9849. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9850. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9851. (
  9852. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9853. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9854. )
  9855. )
  9856. ) and
  9857. GetNextInstruction(hp1, hp2) and
  9858. MatchInstruction(hp2, A_SAR, []) and
  9859. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9860. begin
  9861. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9862. begin
  9863. { Change:
  9864. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9865. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9866. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9867. To:
  9868. movl r/m,%eax <- Note the change in register
  9869. cltd
  9870. }
  9871. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9872. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9873. taicpu(p).loadreg(1, NR_EAX);
  9874. taicpu(hp1).opcode := A_CDQ;
  9875. taicpu(hp1).clearop(1);
  9876. taicpu(hp1).clearop(0);
  9877. taicpu(hp1).ops:=0;
  9878. RemoveInstruction(hp2);
  9879. Include(OptsToCheck, aoc_ForceNewIteration);
  9880. (*
  9881. {$ifdef x86_64}
  9882. end
  9883. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9884. { This code sequence does not get generated - however it might become useful
  9885. if and when 128-bit signed integer types make an appearance, so the code
  9886. is kept here for when it is eventually needed. [Kit] }
  9887. (
  9888. (
  9889. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9890. (
  9891. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9892. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9893. )
  9894. ) or
  9895. (
  9896. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9897. (
  9898. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9899. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9900. )
  9901. )
  9902. ) and
  9903. GetNextInstruction(hp1, hp2) and
  9904. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9905. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9906. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9907. begin
  9908. { Change:
  9909. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9910. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9911. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9912. To:
  9913. movq r/m,%rax <- Note the change in register
  9914. cqto
  9915. }
  9916. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9917. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9918. taicpu(p).loadreg(1, NR_RAX);
  9919. taicpu(hp1).opcode := A_CQO;
  9920. taicpu(hp1).clearop(1);
  9921. taicpu(hp1).clearop(0);
  9922. taicpu(hp1).ops:=0;
  9923. RemoveInstruction(hp2);
  9924. Include(OptsToCheck, aoc_ForceNewIteration);
  9925. {$endif x86_64}
  9926. *)
  9927. end;
  9928. end;
  9929. {$ifdef x86_64}
  9930. end;
  9931. if (taicpu(p).opsize = S_L) and
  9932. (taicpu(p).oper[1]^.typ = top_reg) and
  9933. (
  9934. MatchInstruction(hp1, A_MOV,[]) and
  9935. (taicpu(hp1).opsize = S_L) and
  9936. (taicpu(hp1).oper[1]^.typ = top_reg)
  9937. ) and (
  9938. GetNextInstruction(hp1, hp2) and
  9939. (tai(hp2).typ=ait_instruction) and
  9940. (taicpu(hp2).opsize = S_Q) and
  9941. (
  9942. (
  9943. MatchInstruction(hp2, A_ADD,[]) and
  9944. (taicpu(hp2).opsize = S_Q) and
  9945. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9946. (
  9947. (
  9948. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9949. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9950. ) or (
  9951. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9952. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9953. )
  9954. )
  9955. ) or (
  9956. MatchInstruction(hp2, A_LEA,[]) and
  9957. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9958. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9959. (
  9960. (
  9961. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9962. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9963. ) or (
  9964. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9965. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9966. )
  9967. ) and (
  9968. (
  9969. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9970. ) or (
  9971. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9972. )
  9973. )
  9974. )
  9975. )
  9976. ) and (
  9977. GetNextInstruction(hp2, hp3) and
  9978. MatchInstruction(hp3, A_SHR,[]) and
  9979. (taicpu(hp3).opsize = S_Q) and
  9980. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9981. (taicpu(hp3).oper[0]^.val = 1) and
  9982. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9983. ) then
  9984. begin
  9985. { Change movl x, reg1d movl x, reg1d
  9986. movl y, reg2d movl y, reg2d
  9987. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9988. shrq $1, reg1q shrq $1, reg1q
  9989. ( reg1d and reg2d can be switched around in the first two instructions )
  9990. To movl x, reg1d
  9991. addl y, reg1d
  9992. rcrl $1, reg1d
  9993. This corresponds to the common expression (x + y) shr 1, where
  9994. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9995. smaller code, but won't account for x + y causing an overflow). [Kit]
  9996. }
  9997. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9998. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9999. begin
  10000. { Change first MOV command to have the same register as the final output }
  10001. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10002. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10003. Result := True;
  10004. end
  10005. else
  10006. begin
  10007. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10008. Include(OptsToCheck, aoc_ForceNewIteration);
  10009. end;
  10010. { Change second MOV command to an ADD command. This is easier than
  10011. converting the existing command because it means we don't have to
  10012. touch 'y', which might be a complicated reference, and also the
  10013. fact that the third command might either be ADD or LEA. [Kit] }
  10014. taicpu(hp1).opcode := A_ADD;
  10015. { Delete old ADD/LEA instruction }
  10016. RemoveInstruction(hp2);
  10017. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10018. taicpu(hp3).opcode := A_RCR;
  10019. taicpu(hp3).changeopsize(S_L);
  10020. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10021. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10022. called, so FuncMov2Func below is safe to call }
  10023. {$endif x86_64}
  10024. end;
  10025. if FuncMov2Func(p, hp1) then
  10026. begin
  10027. Result := True;
  10028. Exit;
  10029. end;
  10030. end;
  10031. {$push}
  10032. {$q-}{$r-}
  10033. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10034. var
  10035. ThisReg: TRegister;
  10036. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10037. TargetSubReg: TSubRegister;
  10038. hp1, hp2: tai;
  10039. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10040. { Store list of found instructions so we don't have to call
  10041. GetNextInstructionUsingReg multiple times }
  10042. InstrList: array of taicpu;
  10043. InstrMax, Index: Integer;
  10044. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10045. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10046. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10047. WorkingValue: TCgInt;
  10048. PreMessage: string;
  10049. { Data flow analysis }
  10050. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10051. BitwiseOnly, OrXorUsed,
  10052. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10053. function CheckOverflowConditions: Boolean;
  10054. begin
  10055. Result := True;
  10056. if (TestValSignedMax > SignedUpperLimit) then
  10057. UpperSignedOverflow := True;
  10058. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10059. LowerSignedOverflow := True;
  10060. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10061. LowerUnsignedOverflow := True;
  10062. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10063. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10064. begin
  10065. { Absolute overflow }
  10066. Result := False;
  10067. Exit;
  10068. end;
  10069. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10070. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10071. ShiftDownOverflow := True;
  10072. if (TestValMin < 0) or (TestValMax < 0) then
  10073. begin
  10074. LowerUnsignedOverflow := True;
  10075. UpperUnsignedOverflow := True;
  10076. end;
  10077. end;
  10078. function AdjustInitialLoadAndSize: Boolean;
  10079. begin
  10080. Result := False;
  10081. if not p_removed then
  10082. begin
  10083. if TargetSize = MinSize then
  10084. begin
  10085. { Convert the input MOVZX to a MOV }
  10086. if (taicpu(p).oper[0]^.typ = top_reg) and
  10087. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10088. begin
  10089. { Or remove it completely! }
  10090. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10091. RemoveCurrentP(p);
  10092. p_removed := True;
  10093. end
  10094. else
  10095. begin
  10096. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10097. taicpu(p).opcode := A_MOV;
  10098. taicpu(p).oper[1]^.reg := ThisReg;
  10099. taicpu(p).opsize := TargetSize;
  10100. end;
  10101. Result := True;
  10102. end
  10103. else if TargetSize <> MaxSize then
  10104. begin
  10105. case MaxSize of
  10106. S_L:
  10107. if TargetSize = S_W then
  10108. begin
  10109. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10110. taicpu(p).opsize := S_BW;
  10111. taicpu(p).oper[1]^.reg := ThisReg;
  10112. Result := True;
  10113. end
  10114. else
  10115. InternalError(2020112341);
  10116. S_W:
  10117. if TargetSize = S_L then
  10118. begin
  10119. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10120. taicpu(p).opsize := S_BL;
  10121. taicpu(p).oper[1]^.reg := ThisReg;
  10122. Result := True;
  10123. end
  10124. else
  10125. InternalError(2020112342);
  10126. else
  10127. ;
  10128. end;
  10129. end
  10130. else if not hp1_removed and not RegInUse then
  10131. begin
  10132. { If we have something like:
  10133. movzbl (oper),%regd
  10134. add x, %regd
  10135. movzbl %regb, %regd
  10136. We can reduce the register size to the input of the final
  10137. movzbl instruction. Overflows won't have any effect.
  10138. }
  10139. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10140. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10141. begin
  10142. TargetSize := S_B;
  10143. setsubreg(ThisReg, R_SUBL);
  10144. Result := True;
  10145. end
  10146. else if (taicpu(p).opsize = S_WL) and
  10147. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10148. begin
  10149. TargetSize := S_W;
  10150. setsubreg(ThisReg, R_SUBW);
  10151. Result := True;
  10152. end;
  10153. if Result then
  10154. begin
  10155. { Convert the input MOVZX to a MOV }
  10156. if (taicpu(p).oper[0]^.typ = top_reg) and
  10157. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10158. begin
  10159. { Or remove it completely! }
  10160. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10161. RemoveCurrentP(p);
  10162. p_removed := True;
  10163. end
  10164. else
  10165. begin
  10166. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10167. taicpu(p).opcode := A_MOV;
  10168. taicpu(p).oper[1]^.reg := ThisReg;
  10169. taicpu(p).opsize := TargetSize;
  10170. end;
  10171. end;
  10172. end;
  10173. end;
  10174. end;
  10175. procedure AdjustFinalLoad;
  10176. begin
  10177. if not LowerUnsignedOverflow then
  10178. begin
  10179. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10180. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10181. begin
  10182. { Convert the output MOVZX to a MOV }
  10183. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10184. begin
  10185. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10186. if (MinSize = S_B) or
  10187. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10188. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10189. begin
  10190. { Remove it completely! }
  10191. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10192. { Be careful; if p = hp1 and p was also removed, p
  10193. will become a dangling pointer }
  10194. if p = hp1 then
  10195. begin
  10196. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10197. p_removed := True;
  10198. end
  10199. else
  10200. RemoveInstruction(hp1);
  10201. hp1_removed := True;
  10202. end;
  10203. end
  10204. else
  10205. begin
  10206. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10207. taicpu(hp1).opcode := A_MOV;
  10208. taicpu(hp1).oper[0]^.reg := ThisReg;
  10209. taicpu(hp1).opsize := TargetSize;
  10210. end;
  10211. end
  10212. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10213. begin
  10214. { Need to change the size of the output }
  10215. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10216. taicpu(hp1).oper[0]^.reg := ThisReg;
  10217. taicpu(hp1).opsize := S_BL;
  10218. end;
  10219. end;
  10220. end;
  10221. function CompressInstructions: Boolean;
  10222. var
  10223. LocalIndex: Integer;
  10224. begin
  10225. Result := False;
  10226. { The objective here is to try to find a combination that
  10227. removes one of the MOV/Z instructions. }
  10228. if (
  10229. (taicpu(p).oper[0]^.typ <> top_reg) or
  10230. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10231. ) and
  10232. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10233. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10234. begin
  10235. { Make a preference to remove the second MOVZX instruction }
  10236. case taicpu(hp1).opsize of
  10237. S_BL, S_WL:
  10238. begin
  10239. TargetSize := S_L;
  10240. TargetSubReg := R_SUBD;
  10241. end;
  10242. S_BW:
  10243. begin
  10244. TargetSize := S_W;
  10245. TargetSubReg := R_SUBW;
  10246. end;
  10247. else
  10248. InternalError(2020112302);
  10249. end;
  10250. end
  10251. else
  10252. begin
  10253. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10254. begin
  10255. { Exceeded lower bound but not upper bound }
  10256. TargetSize := MaxSize;
  10257. end
  10258. else if not LowerUnsignedOverflow then
  10259. begin
  10260. { Size didn't exceed lower bound }
  10261. TargetSize := MinSize;
  10262. end
  10263. else
  10264. Exit;
  10265. end;
  10266. case TargetSize of
  10267. S_B:
  10268. TargetSubReg := R_SUBL;
  10269. S_W:
  10270. TargetSubReg := R_SUBW;
  10271. S_L:
  10272. TargetSubReg := R_SUBD;
  10273. else
  10274. InternalError(2020112350);
  10275. end;
  10276. { Update the register to its new size }
  10277. setsubreg(ThisReg, TargetSubReg);
  10278. RegInUse := False;
  10279. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10280. begin
  10281. { Check to see if the active register is used afterwards;
  10282. if not, we can change it and make a saving. }
  10283. TransferUsedRegs(TmpUsedRegs);
  10284. { The target register may be marked as in use to cross
  10285. a jump to a distant label, so exclude it }
  10286. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10287. hp2 := p;
  10288. repeat
  10289. { Explicitly check for the excluded register (don't include the first
  10290. instruction as it may be reading from here }
  10291. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10292. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10293. begin
  10294. RegInUse := True;
  10295. Break;
  10296. end;
  10297. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10298. if not GetNextInstruction(hp2, hp2) then
  10299. InternalError(2020112340);
  10300. until (hp2 = hp1);
  10301. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10302. { We might still be able to get away with this }
  10303. RegInUse := not
  10304. (
  10305. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10306. (hp2.typ = ait_instruction) and
  10307. (
  10308. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10309. instruction that doesn't actually contain ThisReg }
  10310. (cs_opt_level3 in current_settings.optimizerswitches) or
  10311. RegInInstruction(ThisReg, hp2)
  10312. ) and
  10313. RegLoadedWithNewValue(ThisReg, hp2)
  10314. );
  10315. if not RegInUse then
  10316. begin
  10317. { Force the register size to the same as this instruction so it can be removed}
  10318. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10319. begin
  10320. TargetSize := S_L;
  10321. TargetSubReg := R_SUBD;
  10322. end
  10323. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10324. begin
  10325. TargetSize := S_W;
  10326. TargetSubReg := R_SUBW;
  10327. end;
  10328. ThisReg := taicpu(hp1).oper[1]^.reg;
  10329. setsubreg(ThisReg, TargetSubReg);
  10330. RegChanged := True;
  10331. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10332. TransferUsedRegs(TmpUsedRegs);
  10333. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10334. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10335. if p = hp1 then
  10336. begin
  10337. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10338. p_removed := True;
  10339. end
  10340. else
  10341. RemoveInstruction(hp1);
  10342. hp1_removed := True;
  10343. { Instruction will become "mov %reg,%reg" }
  10344. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10345. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10346. begin
  10347. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10348. RemoveCurrentP(p);
  10349. p_removed := True;
  10350. end
  10351. else
  10352. taicpu(p).oper[1]^.reg := ThisReg;
  10353. Result := True;
  10354. end
  10355. else
  10356. begin
  10357. if TargetSize <> MaxSize then
  10358. begin
  10359. { Since the register is in use, we have to force it to
  10360. MaxSize otherwise part of it may become undefined later on }
  10361. TargetSize := MaxSize;
  10362. case TargetSize of
  10363. S_B:
  10364. TargetSubReg := R_SUBL;
  10365. S_W:
  10366. TargetSubReg := R_SUBW;
  10367. S_L:
  10368. TargetSubReg := R_SUBD;
  10369. else
  10370. InternalError(2020112351);
  10371. end;
  10372. setsubreg(ThisReg, TargetSubReg);
  10373. end;
  10374. AdjustFinalLoad;
  10375. end;
  10376. end
  10377. else
  10378. AdjustFinalLoad;
  10379. Result := AdjustInitialLoadAndSize or Result;
  10380. { Now go through every instruction we found and change the
  10381. size. If TargetSize = MaxSize, then almost no changes are
  10382. needed and Result can remain False if it hasn't been set
  10383. yet.
  10384. If RegChanged is True, then the register requires changing
  10385. and so the point about TargetSize = MaxSize doesn't apply. }
  10386. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10387. begin
  10388. for LocalIndex := 0 to InstrMax do
  10389. begin
  10390. { If p_removed is true, then the original MOV/Z was removed
  10391. and removing the AND instruction may not be safe if it
  10392. appears first }
  10393. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10394. InternalError(2020112310);
  10395. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10396. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10397. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10398. InstrList[LocalIndex].opsize := TargetSize;
  10399. end;
  10400. Result := True;
  10401. end;
  10402. end;
  10403. begin
  10404. Result := False;
  10405. p_removed := False;
  10406. hp1_removed := False;
  10407. ThisReg := taicpu(p).oper[1]^.reg;
  10408. { Check for:
  10409. movs/z ###,%ecx (or %cx or %rcx)
  10410. ...
  10411. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10412. (dealloc %ecx)
  10413. Change to:
  10414. mov ###,%cl (if ### = %cl, then remove completely)
  10415. ...
  10416. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10417. }
  10418. if (getsupreg(ThisReg) = RS_ECX) and
  10419. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10420. (hp1.typ = ait_instruction) and
  10421. (
  10422. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10423. instruction that doesn't actually contain ECX }
  10424. (cs_opt_level3 in current_settings.optimizerswitches) or
  10425. RegInInstruction(NR_ECX, hp1) or
  10426. (
  10427. { It's common for the shift/rotate's read/write register to be
  10428. initialised in between, so under -O2 and under, search ahead
  10429. one more instruction
  10430. }
  10431. GetNextInstruction(hp1, hp1) and
  10432. (hp1.typ = ait_instruction) and
  10433. RegInInstruction(NR_ECX, hp1)
  10434. )
  10435. ) and
  10436. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10437. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10438. begin
  10439. TransferUsedRegs(TmpUsedRegs);
  10440. hp2 := p;
  10441. repeat
  10442. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10443. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10444. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10445. begin
  10446. case taicpu(p).opsize of
  10447. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10448. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10449. begin
  10450. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10451. RemoveCurrentP(p);
  10452. end
  10453. else
  10454. begin
  10455. taicpu(p).opcode := A_MOV;
  10456. taicpu(p).opsize := S_B;
  10457. taicpu(p).oper[1]^.reg := NR_CL;
  10458. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10459. end;
  10460. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10461. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10462. begin
  10463. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10464. RemoveCurrentP(p);
  10465. end
  10466. else
  10467. begin
  10468. taicpu(p).opcode := A_MOV;
  10469. taicpu(p).opsize := S_W;
  10470. taicpu(p).oper[1]^.reg := NR_CX;
  10471. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10472. end;
  10473. {$ifdef x86_64}
  10474. S_LQ:
  10475. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10476. begin
  10477. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10478. RemoveCurrentP(p);
  10479. end
  10480. else
  10481. begin
  10482. taicpu(p).opcode := A_MOV;
  10483. taicpu(p).opsize := S_L;
  10484. taicpu(p).oper[1]^.reg := NR_ECX;
  10485. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10486. end;
  10487. {$endif x86_64}
  10488. else
  10489. InternalError(2021120401);
  10490. end;
  10491. Result := True;
  10492. Exit;
  10493. end;
  10494. end;
  10495. { This is anything but quick! }
  10496. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10497. Exit;
  10498. SetLength(InstrList, 0);
  10499. InstrMax := -1;
  10500. case taicpu(p).opsize of
  10501. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10502. begin
  10503. {$if defined(i386) or defined(i8086)}
  10504. { If the target size is 8-bit, make sure we can actually encode it }
  10505. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10506. Exit;
  10507. {$endif i386 or i8086}
  10508. LowerLimit := $FF;
  10509. SignedLowerLimit := $7F;
  10510. SignedLowerLimitBottom := -128;
  10511. MinSize := S_B;
  10512. if taicpu(p).opsize = S_BW then
  10513. begin
  10514. MaxSize := S_W;
  10515. UpperLimit := $FFFF;
  10516. SignedUpperLimit := $7FFF;
  10517. SignedUpperLimitBottom := -32768;
  10518. end
  10519. else
  10520. begin
  10521. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10522. MaxSize := S_L;
  10523. UpperLimit := $FFFFFFFF;
  10524. SignedUpperLimit := $7FFFFFFF;
  10525. SignedUpperLimitBottom := -2147483648;
  10526. end;
  10527. end;
  10528. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10529. begin
  10530. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10531. LowerLimit := $FFFF;
  10532. SignedLowerLimit := $7FFF;
  10533. SignedLowerLimitBottom := -32768;
  10534. UpperLimit := $FFFFFFFF;
  10535. SignedUpperLimit := $7FFFFFFF;
  10536. SignedUpperLimitBottom := -2147483648;
  10537. MinSize := S_W;
  10538. MaxSize := S_L;
  10539. end;
  10540. {$ifdef x86_64}
  10541. S_LQ:
  10542. begin
  10543. { Both the lower and upper limits are set to 32-bit. If a limit
  10544. is breached, then optimisation is impossible }
  10545. LowerLimit := $FFFFFFFF;
  10546. SignedLowerLimit := $7FFFFFFF;
  10547. SignedLowerLimitBottom := -2147483648;
  10548. UpperLimit := $FFFFFFFF;
  10549. SignedUpperLimit := $7FFFFFFF;
  10550. SignedUpperLimitBottom := -2147483648;
  10551. MinSize := S_L;
  10552. MaxSize := S_L;
  10553. end;
  10554. {$endif x86_64}
  10555. else
  10556. InternalError(2020112301);
  10557. end;
  10558. TestValMin := 0;
  10559. TestValMax := LowerLimit;
  10560. TestValSignedMax := SignedLowerLimit;
  10561. TryShiftDownLimit := LowerLimit;
  10562. TryShiftDown := S_NO;
  10563. ShiftDownOverflow := False;
  10564. RegChanged := False;
  10565. BitwiseOnly := True;
  10566. OrXorUsed := False;
  10567. UpperSignedOverflow := False;
  10568. LowerSignedOverflow := False;
  10569. UpperUnsignedOverflow := False;
  10570. LowerUnsignedOverflow := False;
  10571. hp1 := p;
  10572. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10573. (hp1.typ = ait_instruction) and
  10574. (
  10575. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10576. instruction that doesn't actually contain ThisReg }
  10577. (cs_opt_level3 in current_settings.optimizerswitches) or
  10578. { This allows this Movx optimisation to work through the SETcc instructions
  10579. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10580. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10581. skip over these SETcc instructions). }
  10582. (taicpu(hp1).opcode = A_SETcc) or
  10583. RegInInstruction(ThisReg, hp1)
  10584. ) do
  10585. begin
  10586. case taicpu(hp1).opcode of
  10587. A_INC,A_DEC:
  10588. begin
  10589. { Has to be an exact match on the register }
  10590. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10591. Break;
  10592. if taicpu(hp1).opcode = A_INC then
  10593. begin
  10594. Inc(TestValMin);
  10595. Inc(TestValMax);
  10596. Inc(TestValSignedMax);
  10597. end
  10598. else
  10599. begin
  10600. Dec(TestValMin);
  10601. Dec(TestValMax);
  10602. Dec(TestValSignedMax);
  10603. end;
  10604. end;
  10605. A_TEST, A_CMP:
  10606. begin
  10607. if (
  10608. { Too high a risk of non-linear behaviour that breaks DFA
  10609. here, unless it's cmp $0,%reg, which is equivalent to
  10610. test %reg,%reg }
  10611. OrXorUsed and
  10612. (taicpu(hp1).opcode = A_CMP) and
  10613. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10614. ) or
  10615. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10616. { Has to be an exact match on the register }
  10617. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10618. (
  10619. { Permit "test %reg,%reg" }
  10620. (taicpu(hp1).opcode = A_TEST) and
  10621. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10622. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10623. ) or
  10624. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10625. { Make sure the comparison value is not smaller than the
  10626. smallest allowed signed value for the minimum size (e.g.
  10627. -128 for 8-bit) }
  10628. not (
  10629. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10630. { Is it in the negative range? }
  10631. (
  10632. (taicpu(hp1).oper[0]^.val < 0) and
  10633. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10634. )
  10635. ) then
  10636. Break;
  10637. { Check to see if the active register is used afterwards }
  10638. TransferUsedRegs(TmpUsedRegs);
  10639. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10640. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10641. begin
  10642. { Make sure the comparison or any previous instructions
  10643. hasn't pushed the test values outside of the range of
  10644. MinSize }
  10645. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10646. begin
  10647. { Exceeded lower bound but not upper bound }
  10648. Exit;
  10649. end
  10650. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10651. begin
  10652. { Size didn't exceed lower bound }
  10653. TargetSize := MinSize;
  10654. end
  10655. else
  10656. Break;
  10657. case TargetSize of
  10658. S_B:
  10659. TargetSubReg := R_SUBL;
  10660. S_W:
  10661. TargetSubReg := R_SUBW;
  10662. S_L:
  10663. TargetSubReg := R_SUBD;
  10664. else
  10665. InternalError(2021051002);
  10666. end;
  10667. if TargetSize <> MaxSize then
  10668. begin
  10669. { Update the register to its new size }
  10670. setsubreg(ThisReg, TargetSubReg);
  10671. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10672. taicpu(hp1).oper[1]^.reg := ThisReg;
  10673. taicpu(hp1).opsize := TargetSize;
  10674. { Convert the input MOVZX to a MOV if necessary }
  10675. AdjustInitialLoadAndSize;
  10676. if (InstrMax >= 0) then
  10677. begin
  10678. for Index := 0 to InstrMax do
  10679. begin
  10680. { If p_removed is true, then the original MOV/Z was removed
  10681. and removing the AND instruction may not be safe if it
  10682. appears first }
  10683. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10684. InternalError(2020112311);
  10685. if InstrList[Index].oper[0]^.typ = top_reg then
  10686. InstrList[Index].oper[0]^.reg := ThisReg;
  10687. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10688. InstrList[Index].opsize := MinSize;
  10689. end;
  10690. end;
  10691. Result := True;
  10692. end;
  10693. Exit;
  10694. end;
  10695. end;
  10696. A_SETcc:
  10697. begin
  10698. { This allows this Movx optimisation to work through the SETcc instructions
  10699. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10700. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10701. skip over these SETcc instructions). }
  10702. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10703. { Of course, break out if the current register is used }
  10704. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10705. Break
  10706. else
  10707. { We must use Continue so the instruction doesn't get added
  10708. to InstrList }
  10709. Continue;
  10710. end;
  10711. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10712. begin
  10713. if
  10714. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10715. { Has to be an exact match on the register }
  10716. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10717. (
  10718. (
  10719. (taicpu(hp1).oper[0]^.typ = top_const) and
  10720. (
  10721. (
  10722. (taicpu(hp1).opcode = A_SHL) and
  10723. (
  10724. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10725. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10726. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10727. )
  10728. ) or (
  10729. (taicpu(hp1).opcode <> A_SHL) and
  10730. (
  10731. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10732. { Is it in the negative range? }
  10733. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10734. )
  10735. )
  10736. )
  10737. ) or (
  10738. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10739. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10740. )
  10741. ) then
  10742. Break;
  10743. { Only process OR and XOR if there are only bitwise operations,
  10744. since otherwise they can too easily fool the data flow
  10745. analysis (they can cause non-linear behaviour) }
  10746. case taicpu(hp1).opcode of
  10747. A_ADD:
  10748. begin
  10749. if OrXorUsed then
  10750. { Too high a risk of non-linear behaviour that breaks DFA here }
  10751. Break
  10752. else
  10753. BitwiseOnly := False;
  10754. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10755. begin
  10756. TestValMin := TestValMin * 2;
  10757. TestValMax := TestValMax * 2;
  10758. TestValSignedMax := TestValSignedMax * 2;
  10759. end
  10760. else
  10761. begin
  10762. WorkingValue := taicpu(hp1).oper[0]^.val;
  10763. TestValMin := TestValMin + WorkingValue;
  10764. TestValMax := TestValMax + WorkingValue;
  10765. TestValSignedMax := TestValSignedMax + WorkingValue;
  10766. end;
  10767. end;
  10768. A_SUB:
  10769. begin
  10770. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10771. begin
  10772. TestValMin := 0;
  10773. TestValMax := 0;
  10774. TestValSignedMax := 0;
  10775. end
  10776. else
  10777. begin
  10778. if OrXorUsed then
  10779. { Too high a risk of non-linear behaviour that breaks DFA here }
  10780. Break
  10781. else
  10782. BitwiseOnly := False;
  10783. WorkingValue := taicpu(hp1).oper[0]^.val;
  10784. TestValMin := TestValMin - WorkingValue;
  10785. TestValMax := TestValMax - WorkingValue;
  10786. TestValSignedMax := TestValSignedMax - WorkingValue;
  10787. end;
  10788. end;
  10789. A_AND:
  10790. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10791. begin
  10792. { we might be able to go smaller if AND appears first }
  10793. if InstrMax = -1 then
  10794. case MinSize of
  10795. S_B:
  10796. ;
  10797. S_W:
  10798. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10799. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10800. begin
  10801. TryShiftDown := S_B;
  10802. TryShiftDownLimit := $FF;
  10803. end;
  10804. S_L:
  10805. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10806. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10807. begin
  10808. TryShiftDown := S_B;
  10809. TryShiftDownLimit := $FF;
  10810. end
  10811. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10812. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10813. begin
  10814. TryShiftDown := S_W;
  10815. TryShiftDownLimit := $FFFF;
  10816. end;
  10817. else
  10818. InternalError(2020112320);
  10819. end;
  10820. WorkingValue := taicpu(hp1).oper[0]^.val;
  10821. TestValMin := TestValMin and WorkingValue;
  10822. TestValMax := TestValMax and WorkingValue;
  10823. TestValSignedMax := TestValSignedMax and WorkingValue;
  10824. end;
  10825. A_OR:
  10826. begin
  10827. if not BitwiseOnly then
  10828. Break;
  10829. OrXorUsed := True;
  10830. WorkingValue := taicpu(hp1).oper[0]^.val;
  10831. TestValMin := TestValMin or WorkingValue;
  10832. TestValMax := TestValMax or WorkingValue;
  10833. TestValSignedMax := TestValSignedMax or WorkingValue;
  10834. end;
  10835. A_XOR:
  10836. begin
  10837. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10838. begin
  10839. TestValMin := 0;
  10840. TestValMax := 0;
  10841. TestValSignedMax := 0;
  10842. end
  10843. else
  10844. begin
  10845. if not BitwiseOnly then
  10846. Break;
  10847. OrXorUsed := True;
  10848. WorkingValue := taicpu(hp1).oper[0]^.val;
  10849. TestValMin := TestValMin xor WorkingValue;
  10850. TestValMax := TestValMax xor WorkingValue;
  10851. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10852. end;
  10853. end;
  10854. A_SHL:
  10855. begin
  10856. BitwiseOnly := False;
  10857. WorkingValue := taicpu(hp1).oper[0]^.val;
  10858. TestValMin := TestValMin shl WorkingValue;
  10859. TestValMax := TestValMax shl WorkingValue;
  10860. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10861. end;
  10862. A_SHR,
  10863. { The first instruction was MOVZX, so the value won't be negative }
  10864. A_SAR:
  10865. begin
  10866. if InstrMax <> -1 then
  10867. BitwiseOnly := False
  10868. else
  10869. { we might be able to go smaller if SHR appears first }
  10870. case MinSize of
  10871. S_B:
  10872. ;
  10873. S_W:
  10874. if (taicpu(hp1).oper[0]^.val >= 8) then
  10875. begin
  10876. TryShiftDown := S_B;
  10877. TryShiftDownLimit := $FF;
  10878. TryShiftDownSignedLimit := $7F;
  10879. TryShiftDownSignedLimitLower := -128;
  10880. end;
  10881. S_L:
  10882. if (taicpu(hp1).oper[0]^.val >= 24) then
  10883. begin
  10884. TryShiftDown := S_B;
  10885. TryShiftDownLimit := $FF;
  10886. TryShiftDownSignedLimit := $7F;
  10887. TryShiftDownSignedLimitLower := -128;
  10888. end
  10889. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10890. begin
  10891. TryShiftDown := S_W;
  10892. TryShiftDownLimit := $FFFF;
  10893. TryShiftDownSignedLimit := $7FFF;
  10894. TryShiftDownSignedLimitLower := -32768;
  10895. end;
  10896. else
  10897. InternalError(2020112321);
  10898. end;
  10899. WorkingValue := taicpu(hp1).oper[0]^.val;
  10900. if taicpu(hp1).opcode = A_SAR then
  10901. begin
  10902. TestValMin := SarInt64(TestValMin, WorkingValue);
  10903. TestValMax := SarInt64(TestValMax, WorkingValue);
  10904. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10905. end
  10906. else
  10907. begin
  10908. TestValMin := TestValMin shr WorkingValue;
  10909. TestValMax := TestValMax shr WorkingValue;
  10910. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10911. end;
  10912. end;
  10913. else
  10914. InternalError(2020112303);
  10915. end;
  10916. end;
  10917. (*
  10918. A_IMUL:
  10919. case taicpu(hp1).ops of
  10920. 2:
  10921. begin
  10922. if not MatchOpType(hp1, top_reg, top_reg) or
  10923. { Has to be an exact match on the register }
  10924. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10925. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10926. Break;
  10927. TestValMin := TestValMin * TestValMin;
  10928. TestValMax := TestValMax * TestValMax;
  10929. TestValSignedMax := TestValSignedMax * TestValMax;
  10930. end;
  10931. 3:
  10932. begin
  10933. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10934. { Has to be an exact match on the register }
  10935. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10936. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10937. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10938. { Is it in the negative range? }
  10939. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10940. Break;
  10941. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10942. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10943. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10944. end;
  10945. else
  10946. Break;
  10947. end;
  10948. A_IDIV:
  10949. case taicpu(hp1).ops of
  10950. 3:
  10951. begin
  10952. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10953. { Has to be an exact match on the register }
  10954. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10955. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10956. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10957. { Is it in the negative range? }
  10958. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10959. Break;
  10960. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10961. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10962. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10963. end;
  10964. else
  10965. Break;
  10966. end;
  10967. *)
  10968. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10969. begin
  10970. { If there are no instructions in between, then we might be able to make a saving }
  10971. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10972. Break;
  10973. { We have something like:
  10974. movzbw %dl,%dx
  10975. ...
  10976. movswl %dx,%edx
  10977. Change the latter to a zero-extension then enter the
  10978. A_MOVZX case branch.
  10979. }
  10980. {$ifdef x86_64}
  10981. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10982. begin
  10983. { this becomes a zero extension from 32-bit to 64-bit, but
  10984. the upper 32 bits are already zero, so just delete the
  10985. instruction }
  10986. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10987. RemoveInstruction(hp1);
  10988. Result := True;
  10989. Exit;
  10990. end
  10991. else
  10992. {$endif x86_64}
  10993. begin
  10994. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10995. taicpu(hp1).opcode := A_MOVZX;
  10996. {$ifdef x86_64}
  10997. case taicpu(hp1).opsize of
  10998. S_BQ:
  10999. begin
  11000. taicpu(hp1).opsize := S_BL;
  11001. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11002. end;
  11003. S_WQ:
  11004. begin
  11005. taicpu(hp1).opsize := S_WL;
  11006. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11007. end;
  11008. S_LQ:
  11009. begin
  11010. taicpu(hp1).opcode := A_MOV;
  11011. taicpu(hp1).opsize := S_L;
  11012. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11013. { In this instance, we need to break out because the
  11014. instruction is no longer MOVZX or MOVSXD }
  11015. Result := True;
  11016. Exit;
  11017. end;
  11018. else
  11019. ;
  11020. end;
  11021. {$endif x86_64}
  11022. Result := CompressInstructions;
  11023. Exit;
  11024. end;
  11025. end;
  11026. A_MOVZX:
  11027. begin
  11028. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11029. Break;
  11030. if (InstrMax = -1) then
  11031. begin
  11032. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11033. begin
  11034. { Optimise around i40003 }
  11035. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  11036. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11037. {$ifndef x86_64}
  11038. and (
  11039. (taicpu(p).oper[0]^.typ <> top_reg) or
  11040. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11041. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11042. )
  11043. {$endif not x86_64}
  11044. then
  11045. begin
  11046. if (taicpu(p).oper[0]^.typ = top_reg) then
  11047. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11048. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11049. taicpu(p).opsize := S_BL;
  11050. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11051. RemoveInstruction(hp1);
  11052. Result := True;
  11053. Exit;
  11054. end;
  11055. end
  11056. else
  11057. begin
  11058. { Will return false if the second parameter isn't ThisReg
  11059. (can happen on -O2 and under) }
  11060. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11061. begin
  11062. { The two MOVZX instructions are adjacent, so remove the first one }
  11063. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11064. RemoveCurrentP(p);
  11065. Result := True;
  11066. Exit;
  11067. end;
  11068. Break;
  11069. end;
  11070. end;
  11071. Result := CompressInstructions;
  11072. Exit;
  11073. end;
  11074. else
  11075. { This includes ADC, SBB and IDIV }
  11076. Break;
  11077. end;
  11078. if not CheckOverflowConditions then
  11079. Break;
  11080. { Contains highest index (so instruction count - 1) }
  11081. Inc(InstrMax);
  11082. if InstrMax > High(InstrList) then
  11083. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11084. InstrList[InstrMax] := taicpu(hp1);
  11085. end;
  11086. end;
  11087. {$pop}
  11088. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11089. var
  11090. hp1 : tai;
  11091. begin
  11092. Result:=false;
  11093. if (taicpu(p).ops >= 2) and
  11094. ((taicpu(p).oper[0]^.typ = top_const) or
  11095. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11096. (taicpu(p).oper[1]^.typ = top_reg) and
  11097. ((taicpu(p).ops = 2) or
  11098. ((taicpu(p).oper[2]^.typ = top_reg) and
  11099. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11100. GetLastInstruction(p,hp1) and
  11101. MatchInstruction(hp1,A_MOV,[]) and
  11102. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11103. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11104. begin
  11105. TransferUsedRegs(TmpUsedRegs);
  11106. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11107. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11108. { change
  11109. mov reg1,reg2
  11110. imul y,reg2 to imul y,reg1,reg2 }
  11111. begin
  11112. taicpu(p).ops := 3;
  11113. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11114. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11115. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11116. RemoveInstruction(hp1);
  11117. result:=true;
  11118. end;
  11119. end;
  11120. end;
  11121. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11122. var
  11123. ThisLabel: TAsmLabel;
  11124. begin
  11125. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11126. ThisLabel.decrefs;
  11127. taicpu(p).condition := C_None;
  11128. taicpu(p).opcode := A_RET;
  11129. taicpu(p).is_jmp := false;
  11130. taicpu(p).ops := taicpu(ret_p).ops;
  11131. case taicpu(ret_p).ops of
  11132. 0:
  11133. taicpu(p).clearop(0);
  11134. 1:
  11135. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11136. else
  11137. internalerror(2016041301);
  11138. end;
  11139. { If the original label is now dead, it might turn out that the label
  11140. immediately follows p. As a result, everything beyond it, which will
  11141. be just some final register configuration and a RET instruction, is
  11142. now dead code. [Kit] }
  11143. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11144. running RemoveDeadCodeAfterJump for each RET instruction, because
  11145. this optimisation rarely happens and most RETs appear at the end of
  11146. routines where there is nothing that can be stripped. [Kit] }
  11147. if not ThisLabel.is_used then
  11148. RemoveDeadCodeAfterJump(p);
  11149. end;
  11150. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11151. var
  11152. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11153. Unconditional, PotentialModified: Boolean;
  11154. OperPtr: POper;
  11155. NewRef: TReference;
  11156. InstrList: array of taicpu;
  11157. InstrMax, Index: Integer;
  11158. const
  11159. {$ifdef DEBUG_AOPTCPU}
  11160. SNoFlags: shortstring = ' so the flags aren''t modified';
  11161. {$else DEBUG_AOPTCPU}
  11162. SNoFlags = '';
  11163. {$endif DEBUG_AOPTCPU}
  11164. begin
  11165. Result:=false;
  11166. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11167. begin
  11168. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11169. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11170. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11171. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11172. GetNextInstruction(hp1, hp2) and
  11173. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11174. { Change from: To:
  11175. set(C) %reg j(~C) label
  11176. test %reg,%reg/cmp $0,%reg
  11177. je label
  11178. set(C) %reg j(C) label
  11179. test %reg,%reg/cmp $0,%reg
  11180. jne label
  11181. (Also do something similar with sete/setne instead of je/jne)
  11182. }
  11183. begin
  11184. { Before we do anything else, we need to check the instructions
  11185. in between SETcc and TEST to make sure they don't modify the
  11186. FLAGS register - if -O2 or under, there won't be any
  11187. instructions between SET and TEST }
  11188. TransferUsedRegs(TmpUsedRegs);
  11189. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11190. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11191. begin
  11192. next := p;
  11193. SetLength(InstrList, 0);
  11194. InstrMax := -1;
  11195. PotentialModified := False;
  11196. { Make a note of every instruction that modifies the FLAGS
  11197. register }
  11198. while GetNextInstruction(next, next) and (next <> hp1) do
  11199. begin
  11200. if next.typ <> ait_instruction then
  11201. { GetNextInstructionUsingReg should have returned False }
  11202. InternalError(2021051701);
  11203. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11204. begin
  11205. case taicpu(next).opcode of
  11206. A_SETcc,
  11207. A_CMOVcc,
  11208. A_Jcc:
  11209. begin
  11210. if PotentialModified then
  11211. { Not safe because the flags were modified earlier }
  11212. Exit
  11213. else
  11214. { Condition is the same as the initial SETcc, so this is safe
  11215. (don't add to instruction list though) }
  11216. Continue;
  11217. end;
  11218. A_ADD:
  11219. begin
  11220. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11221. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11222. (taicpu(next).oper[1]^.typ <> top_reg) or
  11223. { Must write to a register }
  11224. (taicpu(next).oper[0]^.typ = top_ref) then
  11225. { Require a constant or a register }
  11226. Exit;
  11227. PotentialModified := True;
  11228. end;
  11229. A_SUB:
  11230. begin
  11231. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11232. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11233. (taicpu(next).oper[1]^.typ <> top_reg) or
  11234. { Must write to a register }
  11235. (taicpu(next).oper[0]^.typ <> top_const) or
  11236. (taicpu(next).oper[0]^.val = $80000000) then
  11237. { Can't subtract a register with LEA - also
  11238. check that the value isn't -2^31, as this
  11239. can't be negated }
  11240. Exit;
  11241. PotentialModified := True;
  11242. end;
  11243. A_SAL,
  11244. A_SHL:
  11245. begin
  11246. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11247. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11248. (taicpu(next).oper[1]^.typ <> top_reg) or
  11249. { Must write to a register }
  11250. (taicpu(next).oper[0]^.typ <> top_const) or
  11251. (taicpu(next).oper[0]^.val < 0) or
  11252. (taicpu(next).oper[0]^.val > 3) then
  11253. Exit;
  11254. PotentialModified := True;
  11255. end;
  11256. A_IMUL:
  11257. begin
  11258. if (taicpu(next).ops <> 3) or
  11259. (taicpu(next).oper[1]^.typ <> top_reg) or
  11260. { Must write to a register }
  11261. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11262. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11263. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11264. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11265. Exit
  11266. else
  11267. PotentialModified := True;
  11268. end;
  11269. else
  11270. { Don't know how to change this, so abort }
  11271. Exit;
  11272. end;
  11273. { Contains highest index (so instruction count - 1) }
  11274. Inc(InstrMax);
  11275. if InstrMax > High(InstrList) then
  11276. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11277. InstrList[InstrMax] := taicpu(next);
  11278. end;
  11279. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11280. end;
  11281. if not Assigned(next) or (next <> hp1) then
  11282. { It should be equal to hp1 }
  11283. InternalError(2021051702);
  11284. { Cycle through each instruction and check to see if we can
  11285. change them to versions that don't modify the flags }
  11286. if (InstrMax >= 0) then
  11287. begin
  11288. for Index := 0 to InstrMax do
  11289. case InstrList[Index].opcode of
  11290. A_ADD:
  11291. begin
  11292. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11293. InstrList[Index].opcode := A_LEA;
  11294. reference_reset(NewRef, 1, []);
  11295. NewRef.base := InstrList[Index].oper[1]^.reg;
  11296. if InstrList[Index].oper[0]^.typ = top_reg then
  11297. begin
  11298. NewRef.index := InstrList[Index].oper[0]^.reg;
  11299. NewRef.scalefactor := 1;
  11300. end
  11301. else
  11302. NewRef.offset := InstrList[Index].oper[0]^.val;
  11303. InstrList[Index].loadref(0, NewRef);
  11304. end;
  11305. A_SUB:
  11306. begin
  11307. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11308. InstrList[Index].opcode := A_LEA;
  11309. reference_reset(NewRef, 1, []);
  11310. NewRef.base := InstrList[Index].oper[1]^.reg;
  11311. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11312. InstrList[Index].loadref(0, NewRef);
  11313. end;
  11314. A_SHL,
  11315. A_SAL:
  11316. begin
  11317. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11318. InstrList[Index].opcode := A_LEA;
  11319. reference_reset(NewRef, 1, []);
  11320. NewRef.index := InstrList[Index].oper[1]^.reg;
  11321. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11322. InstrList[Index].loadref(0, NewRef);
  11323. end;
  11324. A_IMUL:
  11325. begin
  11326. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11327. InstrList[Index].opcode := A_LEA;
  11328. reference_reset(NewRef, 1, []);
  11329. NewRef.index := InstrList[Index].oper[1]^.reg;
  11330. case InstrList[Index].oper[0]^.val of
  11331. 2, 4, 8:
  11332. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11333. else {3, 5 and 9}
  11334. begin
  11335. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11336. NewRef.base := InstrList[Index].oper[1]^.reg;
  11337. end;
  11338. end;
  11339. InstrList[Index].loadref(0, NewRef);
  11340. end;
  11341. else
  11342. InternalError(2021051710);
  11343. end;
  11344. end;
  11345. { Mark the FLAGS register as used across this whole block }
  11346. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11347. end;
  11348. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11349. JumpC := taicpu(hp2).condition;
  11350. Unconditional := False;
  11351. if conditions_equal(JumpC, C_E) then
  11352. SetC := inverse_cond(taicpu(p).condition)
  11353. else if conditions_equal(JumpC, C_NE) then
  11354. SetC := taicpu(p).condition
  11355. else
  11356. { We've got something weird here (and inefficent) }
  11357. begin
  11358. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11359. SetC := C_NONE;
  11360. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11361. if condition_in(C_AE, JumpC) then
  11362. Unconditional := True
  11363. else
  11364. { Not sure what to do with this jump - drop out }
  11365. Exit;
  11366. end;
  11367. RemoveInstruction(hp1);
  11368. if Unconditional then
  11369. MakeUnconditional(taicpu(hp2))
  11370. else
  11371. begin
  11372. if SetC = C_NONE then
  11373. InternalError(2018061402);
  11374. taicpu(hp2).SetCondition(SetC);
  11375. end;
  11376. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11377. TmpUsedRegs }
  11378. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11379. begin
  11380. RemoveCurrentp(p, hp2);
  11381. if taicpu(hp2).opcode = A_SETcc then
  11382. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11383. else
  11384. begin
  11385. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11386. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11387. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11388. end;
  11389. end
  11390. else
  11391. if taicpu(hp2).opcode = A_SETcc then
  11392. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11393. else
  11394. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11395. Result := True;
  11396. end
  11397. else if
  11398. { Make sure the instructions are adjacent }
  11399. (
  11400. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11401. GetNextInstruction(p, hp1)
  11402. ) and
  11403. MatchInstruction(hp1, A_MOV, [S_B]) and
  11404. { Writing to memory is allowed }
  11405. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11406. begin
  11407. {
  11408. Watch out for sequences such as:
  11409. set(c)b %regb
  11410. movb %regb,(ref)
  11411. movb $0,1(ref)
  11412. movb $0,2(ref)
  11413. movb $0,3(ref)
  11414. Much more efficient to turn it into:
  11415. movl $0,%regl
  11416. set(c)b %regb
  11417. movl %regl,(ref)
  11418. Or:
  11419. set(c)b %regb
  11420. movzbl %regb,%regl
  11421. movl %regl,(ref)
  11422. }
  11423. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11424. GetNextInstruction(hp1, hp2) and
  11425. MatchInstruction(hp2, A_MOV, [S_B]) and
  11426. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11427. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11428. begin
  11429. { Don't do anything else except set Result to True }
  11430. end
  11431. else
  11432. begin
  11433. if taicpu(p).oper[0]^.typ = top_reg then
  11434. begin
  11435. TransferUsedRegs(TmpUsedRegs);
  11436. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11437. end;
  11438. { If it's not a register, it's a memory address }
  11439. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11440. begin
  11441. { Even if the register is still in use, we can minimise the
  11442. pipeline stall by changing the MOV into another SETcc. }
  11443. taicpu(hp1).opcode := A_SETcc;
  11444. taicpu(hp1).condition := taicpu(p).condition;
  11445. if taicpu(hp1).oper[1]^.typ = top_ref then
  11446. begin
  11447. { Swapping the operand pointers like this is probably a
  11448. bit naughty, but it is far faster than using loadoper
  11449. to transfer the reference from oper[1] to oper[0] if
  11450. you take into account the extra procedure calls and
  11451. the memory allocation and deallocation required }
  11452. OperPtr := taicpu(hp1).oper[1];
  11453. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11454. taicpu(hp1).oper[0] := OperPtr;
  11455. end
  11456. else
  11457. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11458. taicpu(hp1).clearop(1);
  11459. taicpu(hp1).ops := 1;
  11460. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11461. end
  11462. else
  11463. begin
  11464. if taicpu(hp1).oper[1]^.typ = top_reg then
  11465. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11466. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11467. RemoveInstruction(hp1);
  11468. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11469. end
  11470. end;
  11471. Result := True;
  11472. end;
  11473. end;
  11474. end;
  11475. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11476. var
  11477. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11478. TargetReg: TRegister;
  11479. condition, inverted_condition: TAsmCond;
  11480. FoundMOV: Boolean;
  11481. begin
  11482. Result := False;
  11483. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11484. create the most optimial instructions possible due to limited
  11485. register availability, and there are situations where two
  11486. complementary "simple" CMOV blocks are created which, after the fact
  11487. can be merged into a "double" block. For example:
  11488. movw $257,%ax
  11489. movw $2,%r8w
  11490. xorl r9d,%r9d
  11491. testw $16,18(%rcx)
  11492. cmovew %ax,%dx
  11493. cmovew %r8w,%bx
  11494. cmovel %r9d,%r14d
  11495. movw $1283,%ax
  11496. movw $4,%r8w
  11497. movl $9,%r9d
  11498. cmovnew %ax,%dx
  11499. cmovnew %r8w,%bx
  11500. cmovnel %r9d,%r14d
  11501. The CMOVNE instructions at the end can be removed, and the
  11502. destination registers copied into the MOV instructions directly
  11503. above them, before finally being moved to before the first CMOVE
  11504. instructions, to produce:
  11505. movw $257,%ax
  11506. movw $2,%r8w
  11507. xorl r9d,%r9d
  11508. testw $16,18(%rcx)
  11509. movw $1283,%dx
  11510. movw $4,%bx
  11511. movl $9,%r14d
  11512. cmovew %ax,%dx
  11513. cmovew %r8w,%bx
  11514. cmovel %r9d,%r14d
  11515. Which can then be later optimised to:
  11516. movw $257,%ax
  11517. movw $2,%r8w
  11518. xorl r9d,%r9d
  11519. movw $1283,%dx
  11520. movw $4,%bx
  11521. movl $9,%r14d
  11522. testw $16,18(%rcx)
  11523. cmovew %ax,%dx
  11524. cmovew %r8w,%bx
  11525. cmovel %r9d,%r14d
  11526. }
  11527. TargetReg := taicpu(hp1).oper[1]^.reg;
  11528. condition := taicpu(hp1).condition;
  11529. inverted_condition := inverse_cond(condition);
  11530. pFirstMov := nil;
  11531. pLastMov := nil;
  11532. pCMOV := nil;
  11533. if (p.typ = ait_instruction) then
  11534. pCond := p
  11535. else if not GetNextInstruction(p, pCond) then
  11536. InternalError(2024012501);
  11537. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11538. { We should get the CMP or TEST instructeion }
  11539. InternalError(2024012502);
  11540. if (
  11541. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11542. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11543. ) then
  11544. begin
  11545. { We have to tread carefully here, hence why we're not using
  11546. GetNextInstructionUsingReg... we can only accept MOV and other
  11547. CMOV instructions. Anything else and we must drop out}
  11548. hp2 := hp1;
  11549. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11550. begin
  11551. if (hp2.typ <> ait_instruction) then
  11552. Exit;
  11553. case taicpu(hp2).opcode of
  11554. A_MOV:
  11555. begin
  11556. if not Assigned(pFirstMov) then
  11557. pFirstMov := hp2;
  11558. pLastMOV := hp2;
  11559. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11560. { Something different - drop out }
  11561. Exit;
  11562. { Otherwise, leave it for now }
  11563. end;
  11564. A_CMOVcc:
  11565. begin
  11566. if taicpu(hp2).condition = inverted_condition then
  11567. begin
  11568. { We found what we're looking for }
  11569. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11570. begin
  11571. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11572. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11573. begin
  11574. pCMOV := hp2;
  11575. Break;
  11576. end
  11577. else
  11578. { Unsafe reference - drop out }
  11579. Exit;
  11580. end;
  11581. end
  11582. else if taicpu(hp2).condition <> condition then
  11583. { Something weird - drop out }
  11584. Exit;
  11585. end;
  11586. else
  11587. { Invalid }
  11588. Exit;
  11589. end;
  11590. end;
  11591. if not Assigned(pCMOV) then
  11592. { No complementary CMOV found }
  11593. Exit;
  11594. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11595. begin
  11596. { Don't need to do anything special or search for a matching MOV }
  11597. Asml.Remove(pCMOV);
  11598. if RegInInstruction(TargetReg, pCond) then
  11599. { Make sure we don't overwrite the register if it's being used in the condition }
  11600. Asml.InsertAfter(pCMOV, pCond)
  11601. else
  11602. Asml.InsertBefore(pCMOV, pCond);
  11603. taicpu(pCMOV).opcode := A_MOV;
  11604. taicpu(pCMOV).condition := C_None;
  11605. { Don't need to worry about allocating new registers in these cases }
  11606. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11607. Result := True;
  11608. Exit;
  11609. end
  11610. else
  11611. begin
  11612. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11613. FoundMOV := False;
  11614. { Search for the MOV that sets the target register }
  11615. hp2 := pFirstMov;
  11616. repeat
  11617. if (taicpu(hp2).opcode = A_MOV) and
  11618. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11619. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11620. begin
  11621. { Change the destination }
  11622. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11623. if not FoundMOV then
  11624. begin
  11625. FoundMOV := True;
  11626. { Make sure the register is allocated }
  11627. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11628. end;
  11629. hp1 := tai(hp2.Previous);
  11630. Asml.Remove(hp2);
  11631. if RegInInstruction(TargetReg, pCond) then
  11632. { Make sure we don't overwrite the register if it's being used in the condition }
  11633. Asml.InsertAfter(hp2, pCond)
  11634. else
  11635. Asml.InsertBefore(hp2, pCond);
  11636. if (hp2 = pLastMov) then
  11637. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11638. Break;
  11639. hp2 := hp1;
  11640. end;
  11641. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11642. if FoundMOV then
  11643. { Delete the CMOV }
  11644. RemoveInstruction(pCMOV)
  11645. else
  11646. begin
  11647. { If no MOV was found, we have to actually move and transmute the CMOV }
  11648. Asml.Remove(pCMOV);
  11649. if RegInInstruction(TargetReg, pCond) then
  11650. { Make sure we don't overwrite the register if it's being used in the condition }
  11651. Asml.InsertAfter(pCMOV, pCond)
  11652. else
  11653. Asml.InsertBefore(pCMOV, pCond);
  11654. taicpu(pCMOV).opcode := A_MOV;
  11655. taicpu(pCMOV).condition := C_None;
  11656. end;
  11657. Result := True;
  11658. Exit;
  11659. end;
  11660. end;
  11661. end;
  11662. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11663. var
  11664. hp1, hp2, pCond: tai;
  11665. begin
  11666. Result := False;
  11667. { Search ahead for CMOV instructions }
  11668. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11669. begin
  11670. hp1 := p;
  11671. hp2 := p;
  11672. pCond := nil; { To prevent compiler warnings }
  11673. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11674. DEFAULTFLAGS }
  11675. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11676. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11677. pCond := p;
  11678. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11679. begin
  11680. if (hp1.typ <> ait_instruction) then
  11681. { Break out on markers and labels etc. }
  11682. Break;
  11683. case taicpu(hp1).opcode of
  11684. A_MOV:
  11685. { Ignore regular MOVs unless they are obviously not related
  11686. to a CMOV block }
  11687. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11688. Break;
  11689. A_CMOVcc:
  11690. if TryCmpCMovOpts(pCond, hp1) then
  11691. begin
  11692. hp1 := hp2;
  11693. { p itself isn't changed, and we're still inside a
  11694. while loop to catch subsequent CMOVs, so just flag
  11695. a new iteration }
  11696. Include(OptsToCheck, aoc_ForceNewIteration);
  11697. Continue;
  11698. end;
  11699. else
  11700. { Drop out if we find anything else }
  11701. Break;
  11702. end;
  11703. hp2 := hp1;
  11704. end;
  11705. end;
  11706. end;
  11707. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11708. var
  11709. hp1, hp2, pCond: tai;
  11710. SourceReg, TargetReg: TRegister;
  11711. begin
  11712. Result := False;
  11713. { In some situations, we end up with an inefficient arrangement of
  11714. instructions in the form of:
  11715. or %reg1,%reg2
  11716. (%reg1 deallocated)
  11717. test %reg2,%reg2
  11718. mov x,%reg2
  11719. we may be able to swap and rearrange the registers to produce:
  11720. or %reg2,%reg1
  11721. mov x,%reg2
  11722. test %reg1,%reg1
  11723. (%reg1 deallocated)
  11724. }
  11725. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11726. (taicpu(p).oper[1]^.typ = top_reg) and
  11727. (
  11728. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11729. MatchOperand(taicpu(p).oper[0]^, -1)
  11730. ) and
  11731. GetNextInstruction(p, hp1) and
  11732. MatchInstruction(hp1, A_MOV, []) and
  11733. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11734. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11735. begin
  11736. TargetReg := taicpu(p).oper[1]^.reg;
  11737. { Now look backwards to find a simple commutative operation: ADD,
  11738. IMUL (2-register version), OR, AND or XOR - whose destination
  11739. register is the same as TEST }
  11740. hp2 := p;
  11741. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11742. if RegInInstruction(TargetReg, hp2) then
  11743. begin
  11744. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11745. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11746. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11747. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11748. begin
  11749. SourceReg := taicpu(hp2).oper[0]^.reg;
  11750. if
  11751. { Make sure the MOV doesn't use the other register }
  11752. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11753. { And make sure the source register is not used afterwards }
  11754. not RegInUsedRegs(SourceReg, UsedRegs) then
  11755. begin
  11756. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11757. taicpu(hp2).oper[0]^.reg := TargetReg;
  11758. taicpu(hp2).oper[1]^.reg := SourceReg;
  11759. if taicpu(p).oper[0]^.typ = top_reg then
  11760. taicpu(p).oper[0]^.reg := SourceReg;
  11761. taicpu(p).oper[1]^.reg := SourceReg;
  11762. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11763. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11764. Include(OptsToCheck, aoc_ForceNewIteration);
  11765. { We can still check the following optimisations since
  11766. the instruction is still a TEST }
  11767. end;
  11768. end;
  11769. Break;
  11770. end;
  11771. end;
  11772. { Search ahead3 for CMOV instructions }
  11773. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11774. begin
  11775. hp1 := p;
  11776. hp2 := p;
  11777. pCond := nil; { To prevent compiler warnings }
  11778. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11779. DEFAULTFLAGS }
  11780. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11781. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11782. pCond := p;
  11783. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11784. begin
  11785. if (hp1.typ <> ait_instruction) then
  11786. { Break out on markers and labels etc. }
  11787. Break;
  11788. case taicpu(hp1).opcode of
  11789. A_MOV:
  11790. { Ignore regular MOVs unless they are obviously not related
  11791. to a CMOV block }
  11792. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11793. Break;
  11794. A_CMOVcc:
  11795. if TryCmpCMovOpts(pCond, hp1) then
  11796. begin
  11797. hp1 := hp2;
  11798. { p itself isn't changed, and we're still inside a
  11799. while loop to catch subsequent CMOVs, so just flag
  11800. a new iteration }
  11801. Include(OptsToCheck, aoc_ForceNewIteration);
  11802. Continue;
  11803. end;
  11804. else
  11805. { Drop out if we find anything else }
  11806. Break;
  11807. end;
  11808. hp2 := hp1;
  11809. end;
  11810. end;
  11811. end;
  11812. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11813. var
  11814. hp1: tai;
  11815. Count: Integer;
  11816. OrigLabel: TAsmLabel;
  11817. begin
  11818. result := False;
  11819. { Sometimes, the optimisations below can permit this }
  11820. RemoveDeadCodeAfterJump(p);
  11821. 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
  11822. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11823. begin
  11824. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11825. { Also a side-effect of optimisations }
  11826. if CollapseZeroDistJump(p, OrigLabel) then
  11827. begin
  11828. Result := True;
  11829. Exit;
  11830. end;
  11831. hp1 := GetLabelWithSym(OrigLabel);
  11832. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11833. begin
  11834. if taicpu(hp1).opcode = A_RET then
  11835. begin
  11836. {
  11837. change
  11838. jmp .L1
  11839. ...
  11840. .L1:
  11841. ret
  11842. into
  11843. ret
  11844. }
  11845. begin
  11846. ConvertJumpToRET(p, hp1);
  11847. result:=true;
  11848. end;
  11849. end
  11850. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11851. not (cs_opt_size in current_settings.optimizerswitches) and
  11852. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11853. begin
  11854. Result := True;
  11855. Exit;
  11856. end;
  11857. end;
  11858. end;
  11859. end;
  11860. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11861. begin
  11862. Result := assigned(p) and
  11863. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11864. (taicpu(p).oper[1]^.typ = top_reg) and
  11865. (
  11866. (taicpu(p).oper[0]^.typ = top_reg) or
  11867. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11868. it is not expected that this can cause a seg. violation }
  11869. (
  11870. (taicpu(p).oper[0]^.typ = top_ref) and
  11871. { TODO: Can we detect which references become constants at this
  11872. stage so we don't have to do a blanket ban? }
  11873. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11874. (
  11875. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11876. (
  11877. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11878. not RefModified and
  11879. { If the reference also appears in the condition, then we know it's safe, otherwise
  11880. any kind of access violation would have occurred already }
  11881. Assigned(cond_p) and
  11882. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11883. (cond_p.typ = ait_instruction) and
  11884. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11885. { Just consider 2-operand comparison instructions for now to be safe }
  11886. (taicpu(cond_p).ops = 2) and
  11887. (
  11888. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11889. (
  11890. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11891. { Don't risk identical registers but different offsets, as we may have constructs
  11892. such as buffer streams with things like length fields that indicate whether
  11893. any more data follows. And there are probably some contrived examples where
  11894. writing to offsets behind the one being read also lead to access violations }
  11895. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11896. (
  11897. { Check that we're not modifying a register that appears in the reference }
  11898. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11899. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11900. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11901. )
  11902. )
  11903. )
  11904. )
  11905. )
  11906. )
  11907. );
  11908. end;
  11909. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11910. begin
  11911. { Update integer registers, ignoring deallocations }
  11912. repeat
  11913. while assigned(p) and
  11914. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11915. (p.typ = ait_label) or
  11916. ((p.typ = ait_marker) and
  11917. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11918. p := tai(p.next);
  11919. while assigned(p) and
  11920. (p.typ=ait_RegAlloc) Do
  11921. begin
  11922. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11923. begin
  11924. case tai_regalloc(p).ratype of
  11925. ra_alloc :
  11926. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11927. else
  11928. ;
  11929. end;
  11930. end;
  11931. p := tai(p.next);
  11932. end;
  11933. until not(assigned(p)) or
  11934. (not(p.typ in SkipInstr) and
  11935. not((p.typ = ait_label) and
  11936. labelCanBeSkipped(tai_label(p))));
  11937. end;
  11938. {$ifndef 8086}
  11939. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11940. begin
  11941. Result := False;
  11942. EndJump := nil;
  11943. BlockStop := nil;
  11944. while (BlockStart <> fOptimizer.BlockEnd) and
  11945. { stop on labels }
  11946. (BlockStart.typ <> ait_label) do
  11947. begin
  11948. { Keep track of all integer registers that are used }
  11949. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11950. if BlockStart.typ = ait_instruction then
  11951. begin
  11952. if (taicpu(BlockStart).opcode = A_JMP) then
  11953. begin
  11954. if not IsJumpToLabel(taicpu(BlockStart)) or
  11955. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11956. Exit;
  11957. EndJump := BlockStart;
  11958. Break;
  11959. end
  11960. { Check to see if we have a valid MOV instruction instead }
  11961. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11962. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11963. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11964. begin
  11965. Exit;
  11966. end
  11967. else
  11968. { This will be a valid MOV }
  11969. fAllocationRange := BlockStart;
  11970. end;
  11971. OneBeforeBlock := BlockStart;
  11972. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11973. end;
  11974. if (BlockStart = fOptimizer.BlockEnd) then
  11975. Exit;
  11976. BlockStop := BlockStart;
  11977. Result := True;
  11978. end;
  11979. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11980. var
  11981. hp1: tai;
  11982. RefModified: Boolean;
  11983. begin
  11984. Result := 0;
  11985. hp1 := BlockStart;
  11986. RefModified := False; { As long as the condition is inverted, this can be reset }
  11987. while assigned(hp1) and
  11988. (hp1 <> BlockStop) do
  11989. begin
  11990. case hp1.typ of
  11991. ait_instruction:
  11992. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11993. begin
  11994. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11995. begin
  11996. Inc(Result);
  11997. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11998. Assigned(fCondition) and
  11999. { Will have 2 operands }
  12000. (
  12001. (
  12002. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12003. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12004. ) or
  12005. (
  12006. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12007. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12008. )
  12009. ) then
  12010. { It is no longer safe to use the reference in the condition.
  12011. this prevents problems such as:
  12012. mov (%reg),%reg
  12013. mov (%reg),...
  12014. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12015. (fixes #40165)
  12016. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12017. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12018. }
  12019. RefModified := True;
  12020. end
  12021. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12022. { CMOV with constants grows the code size }
  12023. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12024. begin
  12025. { Register was reserved by TryCMOVConst and
  12026. stored on ConstRegs }
  12027. end
  12028. else
  12029. begin
  12030. Result := -1;
  12031. Exit;
  12032. end;
  12033. end
  12034. else
  12035. begin
  12036. Result := -1;
  12037. Exit;
  12038. end;
  12039. else
  12040. { Most likely an align };
  12041. end;
  12042. fOptimizer.GetNextInstruction(hp1, hp1);
  12043. end;
  12044. end;
  12045. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12046. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12047. (this is done as a separate stage because the double types are extensions of the branching type,
  12048. but we can't discount the conditional jump until the last step) }
  12049. procedure EvaluateBranchingType;
  12050. begin
  12051. Inc(CMOVScore);
  12052. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12053. { Too many instructions to be worthwhile }
  12054. fState := tsInvalid;
  12055. end;
  12056. var
  12057. hp1: tai;
  12058. Count: Integer;
  12059. begin
  12060. { Table of valid CMOV block types
  12061. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12062. ---------- --------- --------- --------- --------- ---------
  12063. tsSimple X Yes X X X
  12064. tsDetour = 1st X X X X
  12065. tsBranching <> Mid Yes X X X
  12066. tsDouble End-label Yes * Yes X Yes
  12067. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12068. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12069. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12070. * Only one reference allowed
  12071. }
  12072. hp1 := nil; { To prevent compiler warnings }
  12073. Optimizer.CopyUsedRegs(RegisterTracking);
  12074. fOptimizer := Optimizer;
  12075. fLabel := AFirstLabel;
  12076. CMOVScore := 0;
  12077. ConstCount := 0;
  12078. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12079. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12080. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12081. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12082. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12083. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12084. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12085. fInsertionPoint := p_initialjump;
  12086. fCondition := nil;
  12087. fInitialJump := p_initialjump;
  12088. fFirstMovBlock := p_initialmov;
  12089. fFirstMovBlockStop := nil;
  12090. fSecondJump := nil;
  12091. fSecondMovBlock := nil;
  12092. fSecondMovBlockStop := nil;
  12093. fMidLabel := nil;
  12094. fSecondJump := nil;
  12095. fSecondMovBlock := nil;
  12096. fEndLabel := nil;
  12097. fAllocationRange := nil;
  12098. { Assume it all goes horribly wrong! }
  12099. fState := tsInvalid;
  12100. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12101. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12102. 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
  12103. begin
  12104. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12105. for Count := 0 to 1 do
  12106. with taicpu(fCondition).oper[Count]^ do
  12107. case typ of
  12108. top_reg:
  12109. if getregtype(reg) = R_INTREGISTER then
  12110. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12111. top_ref:
  12112. begin
  12113. if
  12114. {$ifdef x86_64}
  12115. (ref^.base <> NR_RIP) and
  12116. {$endif x86_64}
  12117. (ref^.base <> NR_NO) then
  12118. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12119. if (ref^.index <> NR_NO) then
  12120. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12121. end
  12122. else
  12123. ;
  12124. end;
  12125. { When inserting instructions before hp_prev, try to insert them
  12126. before the allocation of the FLAGS register }
  12127. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12128. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12129. { If not found, set it equal to the condition so it's something sensible }
  12130. fInsertionPoint := fCondition;
  12131. { When dealing with a comparison against zero, take note of the
  12132. instruction before it to see if we can move instructions further
  12133. back in order to benefit PostPeepholeOptTestOr.
  12134. }
  12135. if (
  12136. (
  12137. (taicpu(fCondition).opcode = A_CMP) and
  12138. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12139. ) or
  12140. (
  12141. (taicpu(fCondition).opcode = A_TEST) and
  12142. (
  12143. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12144. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12145. )
  12146. )
  12147. ) and
  12148. Optimizer.GetLastInstruction(fCondition, hp1) then
  12149. begin
  12150. { These instructions set the zero flag if the result is zero }
  12151. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12152. begin
  12153. fInsertionPoint := hp1;
  12154. { Also mark all the registers in this previous instruction
  12155. as 'in use', even if they've just been deallocated }
  12156. for Count := 0 to 1 do
  12157. with taicpu(hp1).oper[Count]^ do
  12158. case typ of
  12159. top_reg:
  12160. if getregtype(reg) = R_INTREGISTER then
  12161. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12162. top_ref:
  12163. begin
  12164. if
  12165. {$ifdef x86_64}
  12166. (ref^.base <> NR_RIP) and
  12167. {$endif x86_64}
  12168. (ref^.base <> NR_NO) then
  12169. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12170. if (ref^.index <> NR_NO) then
  12171. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12172. end
  12173. else
  12174. ;
  12175. end;
  12176. end;
  12177. end;
  12178. end
  12179. else
  12180. fCondition := nil;
  12181. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12182. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12183. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12184. { If not found, set it equal to p so it's something sensible }
  12185. fInsertionPoint := hp1;
  12186. hp1 := p_initialmov;
  12187. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12188. Exit;
  12189. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12190. if (hp1.typ <> ait_label) then { should be on a jump }
  12191. begin
  12192. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12193. { Need a label afterwards }
  12194. Exit;
  12195. end
  12196. else
  12197. fMidLabel := hp1;
  12198. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12199. { Not the correct label }
  12200. fMidLabel := nil;
  12201. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12202. { If there's neither a 2nd jump nor correct label, then it's invalid
  12203. (see above table) }
  12204. Exit;
  12205. { Analyse the first block of MOVs more closely }
  12206. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12207. if Assigned(fSecondJump) then
  12208. begin
  12209. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12210. begin
  12211. fState := tsDetour
  12212. end
  12213. else
  12214. begin
  12215. { Need the correct mid-label for this one }
  12216. if not Assigned(fMidLabel) then
  12217. Exit;
  12218. fState := tsBranching;
  12219. end;
  12220. end
  12221. else
  12222. { No jump. but mid-label is present }
  12223. fState := tsSimple;
  12224. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12225. begin
  12226. { Invalid or too many instructions to be worthwhile }
  12227. fState := tsInvalid;
  12228. Exit;
  12229. end;
  12230. { check further for
  12231. jCC xxx
  12232. <several movs 1>
  12233. jmp yyy
  12234. xxx:
  12235. <several movs 2>
  12236. yyy:
  12237. etc.
  12238. }
  12239. if (fState = tsBranching) and
  12240. { Estimate for required savings for extra jump }
  12241. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12242. { Only one reference is allowed for double blocks }
  12243. (AFirstLabel.getrefs = 1) then
  12244. begin
  12245. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12246. fSecondMovBlock := hp1;
  12247. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12248. begin
  12249. EvaluateBranchingType;
  12250. Exit;
  12251. end;
  12252. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12253. if (hp1.typ <> ait_label) then { should be on a jump }
  12254. begin
  12255. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12256. begin
  12257. { Need a label afterwards }
  12258. EvaluateBranchingType;
  12259. Exit;
  12260. end;
  12261. end
  12262. else
  12263. fEndLabel := hp1;
  12264. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12265. { Second jump doesn't go to the end }
  12266. fEndLabel := nil;
  12267. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12268. begin
  12269. { If there's neither a 3rd jump nor correct end label, then it's
  12270. not a invalid double block, but is a valid single branching
  12271. block (see above table) }
  12272. EvaluateBranchingType;
  12273. Exit;
  12274. end;
  12275. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12276. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12277. { Invalid or too many instructions to be worthwhile }
  12278. Exit;
  12279. Inc(CMOVScore, Count);
  12280. if Assigned(fThirdJump) then
  12281. begin
  12282. if not Assigned(fSecondJump) then
  12283. fState := tsDoubleSecondBranching
  12284. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12285. fState := tsDoubleBranchSame
  12286. else
  12287. fState := tsDoubleBranchDifferent;
  12288. end
  12289. else
  12290. fState := tsDouble;
  12291. end;
  12292. if fState = tsBranching then
  12293. EvaluateBranchingType;
  12294. end;
  12295. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12296. new register to store the constant }
  12297. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12298. var
  12299. RegSize: TSubRegister;
  12300. CurrentVal: TCGInt;
  12301. ANewReg: TRegister;
  12302. X: ShortInt;
  12303. begin
  12304. Result := False;
  12305. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12306. Exit;
  12307. if ConstCount >= MAX_CMOV_REGISTERS then
  12308. { Arrays are full }
  12309. Exit;
  12310. { Remember that CMOV can't encode 8-bit registers }
  12311. case taicpu(p).opsize of
  12312. S_W:
  12313. RegSize := R_SUBW;
  12314. S_L:
  12315. RegSize := R_SUBD;
  12316. {$ifdef x86_64}
  12317. S_Q:
  12318. RegSize := R_SUBQ;
  12319. {$endif x86_64}
  12320. else
  12321. InternalError(2021100401);
  12322. end;
  12323. { See if the value has already been reserved for another CMOV instruction }
  12324. CurrentVal := taicpu(p).oper[0]^.val;
  12325. for X := 0 to ConstCount - 1 do
  12326. if ConstVals[X] = CurrentVal then
  12327. begin
  12328. ConstRegs[ConstCount] := ConstRegs[X];
  12329. ConstSizes[ConstCount] := RegSize;
  12330. ConstVals[ConstCount] := CurrentVal;
  12331. Inc(ConstCount);
  12332. Inc(Count);
  12333. Result := True;
  12334. Exit;
  12335. end;
  12336. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12337. if ANewReg = NR_NO then
  12338. { No free registers }
  12339. Exit;
  12340. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12341. up vying for the same register }
  12342. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12343. ConstRegs[ConstCount] := ANewReg;
  12344. ConstSizes[ConstCount] := RegSize;
  12345. ConstVals[ConstCount] := CurrentVal;
  12346. Inc(ConstCount);
  12347. Inc(Count);
  12348. Result := True;
  12349. end;
  12350. destructor TCMOVTracking.Done;
  12351. begin
  12352. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12353. end;
  12354. procedure TCMOVTracking.Process(out new_p: tai);
  12355. var
  12356. Count, Writes: LongInt;
  12357. RegMatch: Boolean;
  12358. hp1, hp_new: tai;
  12359. inverted_condition, condition: TAsmCond;
  12360. begin
  12361. if (fState in [tsInvalid, tsProcessed]) then
  12362. InternalError(2023110701);
  12363. { Repurpose RegisterTracking to mark registers that we've defined }
  12364. RegisterTracking[R_INTREGISTER].Clear;
  12365. Count := 0;
  12366. Writes := 0;
  12367. condition := taicpu(fInitialJump).condition;
  12368. inverted_condition := inverse_cond(condition);
  12369. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12370. doesn't get CMOVs in this case }
  12371. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12372. begin
  12373. { Include the jump in the flag tracking }
  12374. if Assigned(fThirdJump) then
  12375. begin
  12376. if (fState = tsDoubleBranchSame) then
  12377. begin
  12378. { Will be an unconditional jump, so track to the instruction before it }
  12379. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12380. InternalError(2023110710);
  12381. end
  12382. else
  12383. hp1 := fThirdJump;
  12384. end
  12385. else
  12386. hp1 := fSecondMovBlockStop;
  12387. end
  12388. else
  12389. begin
  12390. { Include a conditional jump in the flag tracking }
  12391. if Assigned(fSecondJump) then
  12392. begin
  12393. if (fState = tsDetour) then
  12394. begin
  12395. { Will be an unconditional jump, so track to the instruction before it }
  12396. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12397. InternalError(2023110711);
  12398. end
  12399. else
  12400. hp1 := fSecondJump;
  12401. end
  12402. else
  12403. hp1 := fFirstMovBlockStop;
  12404. end;
  12405. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12406. { Process the second set of MOVs first, because if a destination
  12407. register is shared between the first and second MOV sets, it is more
  12408. efficient to turn the first one into a MOV instruction and place it
  12409. before the CMP if possible, but we won't know which registers are
  12410. shared until we've processed at least one list, so we might as well
  12411. make it the second one since that won't be modified again. }
  12412. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12413. begin
  12414. hp1 := fSecondMovBlock;
  12415. repeat
  12416. if not Assigned(hp1) then
  12417. InternalError(2018062902);
  12418. if (hp1.typ = ait_instruction) then
  12419. begin
  12420. { Extra safeguard }
  12421. if (taicpu(hp1).opcode <> A_MOV) then
  12422. InternalError(2018062903);
  12423. { Note: tsDoubleBranchDifferent is essentially identical to
  12424. tsBranching and the 2nd block is best left largely
  12425. untouched, but we need to evaluate which registers the MOVs
  12426. write to in order to track what would be complementary CMOV
  12427. pairs that can be further optimised. [Kit] }
  12428. if fState <> tsDoubleBranchDifferent then
  12429. begin
  12430. if taicpu(hp1).oper[0]^.typ = top_const then
  12431. begin
  12432. RegMatch := False;
  12433. for Count := 0 to ConstCount - 1 do
  12434. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12435. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12436. begin
  12437. RegMatch := True;
  12438. { If it's in RegisterTracking, then this register
  12439. is being used more than once and hence has
  12440. already had its value defined (it gets added to
  12441. UsedRegs through AllocRegBetween below) }
  12442. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12443. begin
  12444. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12445. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12446. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12447. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12448. ConstMovs[Count] := hp_new;
  12449. end
  12450. else
  12451. { We just need an instruction between hp_prev and hp1
  12452. where we know the register is marked as in use }
  12453. hp_new := fSecondMovBlock;
  12454. { Keep track of largest write for this register so it can be optimised later }
  12455. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12456. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12457. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12458. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12459. Break;
  12460. end;
  12461. if not RegMatch then
  12462. InternalError(2021100411);
  12463. end;
  12464. taicpu(hp1).opcode := A_CMOVcc;
  12465. taicpu(hp1).condition := condition;
  12466. end;
  12467. { Store these writes to search for duplicates later on }
  12468. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12469. Inc(Writes);
  12470. end;
  12471. fOptimizer.GetNextInstruction(hp1, hp1);
  12472. until (hp1 = fSecondMovBlockStop);
  12473. end;
  12474. { Now do the first set of MOVs }
  12475. hp1 := fFirstMovBlock;
  12476. repeat
  12477. if not Assigned(hp1) then
  12478. InternalError(2018062904);
  12479. if (hp1.typ = ait_instruction) then
  12480. begin
  12481. RegMatch := False;
  12482. { Extra safeguard }
  12483. if (taicpu(hp1).opcode <> A_MOV) then
  12484. InternalError(2018062905);
  12485. { Search through the RegWrites list to see if there are any
  12486. opposing CMOV pairs that write to the same register }
  12487. for Count := 0 to Writes - 1 do
  12488. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12489. begin
  12490. { We have a match. Keep this as a MOV }
  12491. { Move ahead in preparation }
  12492. fOptimizer.GetNextInstruction(hp1, hp1);
  12493. RegMatch := True;
  12494. Break;
  12495. end;
  12496. if RegMatch then
  12497. Continue;
  12498. if taicpu(hp1).oper[0]^.typ = top_const then
  12499. begin
  12500. for Count := 0 to ConstCount - 1 do
  12501. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12502. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12503. begin
  12504. RegMatch := True;
  12505. { If it's in RegisterTracking, then this register is
  12506. being used more than once and hence has already had
  12507. its value defined (it gets added to UsedRegs through
  12508. AllocRegBetween below) }
  12509. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12510. begin
  12511. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12512. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12513. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12514. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12515. ConstMovs[Count] := hp_new;
  12516. end
  12517. else
  12518. { We just need an instruction between hp_prev and hp1
  12519. where we know the register is marked as in use }
  12520. hp_new := fFirstMovBlock;
  12521. { Keep track of largest write for this register so it can be optimised later }
  12522. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12523. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12524. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12525. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12526. Break;
  12527. end;
  12528. if not RegMatch then
  12529. InternalError(2021100412);
  12530. end;
  12531. taicpu(hp1).opcode := A_CMOVcc;
  12532. taicpu(hp1).condition := inverted_condition;
  12533. if (fState = tsDoubleBranchDifferent) then
  12534. begin
  12535. { Store these writes to search for duplicates later on }
  12536. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12537. Inc(Writes);
  12538. end;
  12539. end;
  12540. fOptimizer.GetNextInstruction(hp1, hp1);
  12541. until (hp1 = fFirstMovBlockStop);
  12542. { Update initialisation MOVs to the smallest possible size }
  12543. for Count := 0 to ConstCount - 1 do
  12544. if Assigned(ConstMovs[Count]) then
  12545. begin
  12546. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12547. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12548. end;
  12549. case fState of
  12550. tsSimple:
  12551. begin
  12552. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12553. { No branch to delete }
  12554. end;
  12555. tsDetour:
  12556. begin
  12557. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12558. { Preserve jump }
  12559. end;
  12560. tsBranching, tsDoubleBranchDifferent:
  12561. begin
  12562. if (fState = tsBranching) then
  12563. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12564. else
  12565. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12566. taicpu(fSecondJump).opcode := A_JCC;
  12567. taicpu(fSecondJump).condition := inverted_condition;
  12568. end;
  12569. tsDouble, tsDoubleBranchSame:
  12570. begin
  12571. if (fState = tsDouble) then
  12572. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12573. else
  12574. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12575. { Delete second jump }
  12576. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12577. fOptimizer.RemoveInstruction(fSecondJump);
  12578. end;
  12579. tsDoubleSecondBranching:
  12580. begin
  12581. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12582. { Delete second jump, preserve third jump as conditional }
  12583. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12584. fOptimizer.RemoveInstruction(fSecondJump);
  12585. taicpu(fThirdJump).opcode := A_JCC;
  12586. taicpu(fThirdJump).condition := condition;
  12587. end;
  12588. else
  12589. InternalError(2023110720);
  12590. end;
  12591. { Now we can safely decrement the reference count }
  12592. tasmlabel(fLabel).decrefs;
  12593. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12594. { Remove the original jump }
  12595. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12596. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12597. fState := tsProcessed;
  12598. end;
  12599. {$endif 8086}
  12600. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12601. var
  12602. hp1,hp2: tai;
  12603. carryadd_opcode : TAsmOp;
  12604. symbol: TAsmSymbol;
  12605. increg, tmpreg: TRegister;
  12606. {$ifndef i8086}
  12607. CMOVTracking: PCMOVTracking;
  12608. hp3,hp4,hp5: tai;
  12609. {$endif i8086}
  12610. TempBool: Boolean;
  12611. begin
  12612. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12613. DoJumpOptimizations(p, TempBool) then
  12614. Exit(True);
  12615. result:=false;
  12616. if GetNextInstruction(p,hp1) then
  12617. begin
  12618. if (hp1.typ=ait_label) then
  12619. begin
  12620. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12621. Exit;
  12622. end
  12623. else if (hp1.typ<>ait_instruction) then
  12624. Exit;
  12625. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12626. if (
  12627. (
  12628. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12629. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12630. (Taicpu(hp1).oper[0]^.val=1)
  12631. ) or
  12632. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12633. ) and
  12634. GetNextInstruction(hp1,hp2) and
  12635. FindLabel(TAsmLabel(symbol), hp2) then
  12636. { jb @@1 cmc
  12637. inc/dec operand --> adc/sbb operand,0
  12638. @@1:
  12639. ... and ...
  12640. jnb @@1
  12641. inc/dec operand --> adc/sbb operand,0
  12642. @@1: }
  12643. begin
  12644. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12645. begin
  12646. case taicpu(hp1).opcode of
  12647. A_INC,
  12648. A_ADD:
  12649. carryadd_opcode:=A_ADC;
  12650. A_DEC,
  12651. A_SUB:
  12652. carryadd_opcode:=A_SBB;
  12653. else
  12654. InternalError(2021011001);
  12655. end;
  12656. Taicpu(p).clearop(0);
  12657. Taicpu(p).ops:=0;
  12658. Taicpu(p).is_jmp:=false;
  12659. Taicpu(p).opcode:=A_CMC;
  12660. Taicpu(p).condition:=C_NONE;
  12661. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12662. Taicpu(hp1).ops:=2;
  12663. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12664. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12665. else
  12666. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12667. Taicpu(hp1).loadconst(0,0);
  12668. Taicpu(hp1).opcode:=carryadd_opcode;
  12669. result:=true;
  12670. exit;
  12671. end
  12672. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12673. begin
  12674. case taicpu(hp1).opcode of
  12675. A_INC,
  12676. A_ADD:
  12677. carryadd_opcode:=A_ADC;
  12678. A_DEC,
  12679. A_SUB:
  12680. carryadd_opcode:=A_SBB;
  12681. else
  12682. InternalError(2021011002);
  12683. end;
  12684. Taicpu(hp1).ops:=2;
  12685. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12686. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12687. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12688. else
  12689. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12690. Taicpu(hp1).loadconst(0,0);
  12691. Taicpu(hp1).opcode:=carryadd_opcode;
  12692. RemoveCurrentP(p, hp1);
  12693. result:=true;
  12694. exit;
  12695. end
  12696. {
  12697. jcc @@1 setcc tmpreg
  12698. inc/dec/add/sub operand -> (movzx tmpreg)
  12699. @@1: add/sub tmpreg,operand
  12700. While this increases code size slightly, it makes the code much faster if the
  12701. jump is unpredictable
  12702. }
  12703. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12704. begin
  12705. { search for an available register which is volatile }
  12706. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12707. if increg <> NR_NO then
  12708. begin
  12709. { We don't need to check if tmpreg is in hp1 or not, because
  12710. it will be marked as in use at p (if not, this is
  12711. indictive of a compiler bug). }
  12712. TAsmLabel(symbol).decrefs;
  12713. Taicpu(p).clearop(0);
  12714. Taicpu(p).ops:=1;
  12715. Taicpu(p).is_jmp:=false;
  12716. Taicpu(p).opcode:=A_SETcc;
  12717. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12718. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12719. Taicpu(p).loadreg(0,increg);
  12720. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12721. begin
  12722. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12723. R_SUBW:
  12724. begin
  12725. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12726. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12727. end;
  12728. R_SUBD:
  12729. begin
  12730. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12731. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12732. end;
  12733. {$ifdef x86_64}
  12734. R_SUBQ:
  12735. begin
  12736. { MOVZX doesn't have a 64-bit variant, because
  12737. the 32-bit version implicitly zeroes the
  12738. upper 32-bits of the destination register }
  12739. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12740. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12741. setsubreg(tmpreg, R_SUBQ);
  12742. end;
  12743. {$endif x86_64}
  12744. else
  12745. Internalerror(2020030601);
  12746. end;
  12747. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12748. asml.InsertAfter(hp2,p);
  12749. end
  12750. else
  12751. tmpreg := increg;
  12752. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12753. begin
  12754. Taicpu(hp1).ops:=2;
  12755. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12756. end;
  12757. Taicpu(hp1).loadreg(0,tmpreg);
  12758. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12759. Result := True;
  12760. { p is no longer a Jcc instruction, so exit }
  12761. Exit;
  12762. end;
  12763. end;
  12764. end;
  12765. { Detect the following:
  12766. jmp<cond> @Lbl1
  12767. jmp @Lbl2
  12768. ...
  12769. @Lbl1:
  12770. ret
  12771. Change to:
  12772. jmp<inv_cond> @Lbl2
  12773. ret
  12774. }
  12775. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12776. begin
  12777. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12778. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12779. MatchInstruction(hp2,A_RET,[S_NO]) then
  12780. begin
  12781. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12782. { Change label address to that of the unconditional jump }
  12783. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12784. TAsmLabel(symbol).DecRefs;
  12785. taicpu(hp1).opcode := A_RET;
  12786. taicpu(hp1).is_jmp := false;
  12787. taicpu(hp1).ops := taicpu(hp2).ops;
  12788. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12789. case taicpu(hp2).ops of
  12790. 0:
  12791. taicpu(hp1).clearop(0);
  12792. 1:
  12793. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12794. else
  12795. internalerror(2016041302);
  12796. end;
  12797. end;
  12798. {$ifndef i8086}
  12799. end
  12800. {
  12801. convert
  12802. j<c> .L1
  12803. mov 1,reg
  12804. jmp .L2
  12805. .L1
  12806. mov 0,reg
  12807. .L2
  12808. into
  12809. mov 0,reg
  12810. set<not(c)> reg
  12811. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12812. would destroy the flag contents
  12813. }
  12814. else if MatchInstruction(hp1,A_MOV,[]) and
  12815. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12816. {$ifdef i386}
  12817. (
  12818. { Under i386, ESI, EDI, EBP and ESP
  12819. don't have an 8-bit representation }
  12820. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12821. ) and
  12822. {$endif i386}
  12823. (taicpu(hp1).oper[0]^.val=1) and
  12824. GetNextInstruction(hp1,hp2) and
  12825. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12826. GetNextInstruction(hp2,hp3) and
  12827. (hp3.typ=ait_label) and
  12828. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12829. (tai_label(hp3).labsym.getrefs=1) and
  12830. GetNextInstruction(hp3,hp4) and
  12831. MatchInstruction(hp4,A_MOV,[]) and
  12832. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12833. (taicpu(hp4).oper[0]^.val=0) and
  12834. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12835. GetNextInstruction(hp4,hp5) and
  12836. (hp5.typ=ait_label) and
  12837. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12838. (tai_label(hp5).labsym.getrefs=1) then
  12839. begin
  12840. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12841. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12842. { remove last label }
  12843. RemoveInstruction(hp5);
  12844. { remove second label }
  12845. RemoveInstruction(hp3);
  12846. { remove jmp }
  12847. RemoveInstruction(hp2);
  12848. if taicpu(hp1).opsize=S_B then
  12849. RemoveInstruction(hp1)
  12850. else
  12851. taicpu(hp1).loadconst(0,0);
  12852. taicpu(hp4).opcode:=A_SETcc;
  12853. taicpu(hp4).opsize:=S_B;
  12854. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12855. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12856. taicpu(hp4).opercnt:=1;
  12857. taicpu(hp4).ops:=1;
  12858. taicpu(hp4).freeop(1);
  12859. RemoveCurrentP(p);
  12860. Result:=true;
  12861. exit;
  12862. end
  12863. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12864. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12865. begin
  12866. { check for
  12867. jCC xxx
  12868. <several movs>
  12869. xxx:
  12870. Also spot:
  12871. Jcc xxx
  12872. <several movs>
  12873. jmp xxx
  12874. Change to:
  12875. <several cmovs with inverted condition>
  12876. jmp xxx (only for the 2nd case)
  12877. }
  12878. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12879. if CMOVTracking^.State <> tsInvalid then
  12880. begin
  12881. CMovTracking^.Process(p);
  12882. Result := True;
  12883. end;
  12884. CMOVTracking^.Done;
  12885. {$endif i8086}
  12886. end;
  12887. end;
  12888. end;
  12889. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12890. var
  12891. hp1,hp2,hp3: tai;
  12892. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12893. NewSize: TOpSize;
  12894. NewRegSize: TSubRegister;
  12895. Limit: TCgInt;
  12896. SwapOper: POper;
  12897. begin
  12898. result:=false;
  12899. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12900. GetNextInstruction(p,hp1) and
  12901. (hp1.typ = ait_instruction);
  12902. if reg_and_hp1_is_instr and
  12903. (
  12904. (taicpu(hp1).opcode <> A_LEA) or
  12905. { If the LEA instruction can be converted into an arithmetic instruction,
  12906. it may be possible to then fold it. }
  12907. (
  12908. { If the flags register is in use, don't change the instruction
  12909. to an ADD otherwise this will scramble the flags. [Kit] }
  12910. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12911. ConvertLEA(taicpu(hp1))
  12912. )
  12913. ) and
  12914. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12915. GetNextInstruction(hp1,hp2) and
  12916. MatchInstruction(hp2,A_MOV,[]) and
  12917. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12918. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12919. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12920. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12921. {$ifdef i386}
  12922. { not all registers have byte size sub registers on i386 }
  12923. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12924. {$endif i386}
  12925. (((taicpu(hp1).ops=2) and
  12926. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12927. ((taicpu(hp1).ops=1) and
  12928. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12929. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12930. begin
  12931. { change movsX/movzX reg/ref, reg2
  12932. add/sub/or/... reg3/$const, reg2
  12933. mov reg2 reg/ref
  12934. to add/sub/or/... reg3/$const, reg/ref }
  12935. { by example:
  12936. movswl %si,%eax movswl %si,%eax p
  12937. decl %eax addl %edx,%eax hp1
  12938. movw %ax,%si movw %ax,%si hp2
  12939. ->
  12940. movswl %si,%eax movswl %si,%eax p
  12941. decw %eax addw %edx,%eax hp1
  12942. movw %ax,%si movw %ax,%si hp2
  12943. }
  12944. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12945. {
  12946. ->
  12947. movswl %si,%eax movswl %si,%eax p
  12948. decw %si addw %dx,%si hp1
  12949. movw %ax,%si movw %ax,%si hp2
  12950. }
  12951. case taicpu(hp1).ops of
  12952. 1:
  12953. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12954. 2:
  12955. begin
  12956. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12957. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12958. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12959. end;
  12960. else
  12961. internalerror(2008042702);
  12962. end;
  12963. {
  12964. ->
  12965. decw %si addw %dx,%si p
  12966. }
  12967. DebugMsg(SPeepholeOptimization + 'var3',p);
  12968. RemoveCurrentP(p, hp1);
  12969. RemoveInstruction(hp2);
  12970. Result := True;
  12971. Exit;
  12972. end;
  12973. if reg_and_hp1_is_instr and
  12974. (taicpu(hp1).opcode = A_MOV) and
  12975. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12976. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12977. {$ifdef x86_64}
  12978. { check for implicit extension to 64 bit }
  12979. or
  12980. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12981. (taicpu(hp1).opsize=S_Q) and
  12982. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12983. )
  12984. {$endif x86_64}
  12985. )
  12986. then
  12987. begin
  12988. { change
  12989. movx %reg1,%reg2
  12990. mov %reg2,%reg3
  12991. dealloc %reg2
  12992. into
  12993. movx %reg,%reg3
  12994. }
  12995. TransferUsedRegs(TmpUsedRegs);
  12996. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12997. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12998. begin
  12999. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13000. {$ifdef x86_64}
  13001. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13002. (taicpu(hp1).opsize=S_Q) then
  13003. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13004. else
  13005. {$endif x86_64}
  13006. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13007. RemoveInstruction(hp1);
  13008. Result := True;
  13009. Exit;
  13010. end;
  13011. end;
  13012. if reg_and_hp1_is_instr and
  13013. ((taicpu(hp1).opcode=A_MOV) or
  13014. (taicpu(hp1).opcode=A_ADD) or
  13015. (taicpu(hp1).opcode=A_SUB) or
  13016. (taicpu(hp1).opcode=A_CMP) or
  13017. (taicpu(hp1).opcode=A_OR) or
  13018. (taicpu(hp1).opcode=A_XOR) or
  13019. (taicpu(hp1).opcode=A_AND)
  13020. ) and
  13021. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13022. begin
  13023. AndTest := (taicpu(hp1).opcode=A_AND) and
  13024. GetNextInstruction(hp1, hp2) and
  13025. (hp2.typ = ait_instruction) and
  13026. (
  13027. (
  13028. (taicpu(hp2).opcode=A_TEST) and
  13029. (
  13030. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13031. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13032. (
  13033. { If the AND and TEST instructions share a constant, this is also valid }
  13034. (taicpu(hp1).oper[0]^.typ = top_const) and
  13035. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13036. )
  13037. ) and
  13038. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13039. ) or
  13040. (
  13041. (taicpu(hp2).opcode=A_CMP) and
  13042. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13043. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13044. )
  13045. );
  13046. { change
  13047. movx (oper),%reg2
  13048. and $x,%reg2
  13049. test %reg2,%reg2
  13050. dealloc %reg2
  13051. into
  13052. op %reg1,%reg3
  13053. if the second op accesses only the bits stored in reg1
  13054. }
  13055. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13056. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13057. (taicpu(hp1).oper[0]^.typ = top_const) and
  13058. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13059. AndTest then
  13060. begin
  13061. { Check if the AND constant is in range }
  13062. case taicpu(p).opsize of
  13063. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13064. begin
  13065. NewSize := S_B;
  13066. Limit := $FF;
  13067. end;
  13068. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13069. begin
  13070. NewSize := S_W;
  13071. Limit := $FFFF;
  13072. end;
  13073. {$ifdef x86_64}
  13074. S_LQ:
  13075. begin
  13076. NewSize := S_L;
  13077. Limit := $FFFFFFFF;
  13078. end;
  13079. {$endif x86_64}
  13080. else
  13081. InternalError(2021120303);
  13082. end;
  13083. if (
  13084. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13085. { Check for negative operands }
  13086. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13087. ) and
  13088. GetNextInstruction(hp2,hp3) and
  13089. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13090. (taicpu(hp3).condition in [C_E,C_NE]) then
  13091. begin
  13092. TransferUsedRegs(TmpUsedRegs);
  13093. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13094. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13095. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13096. begin
  13097. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13098. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13099. taicpu(hp1).opcode := A_TEST;
  13100. taicpu(hp1).opsize := NewSize;
  13101. RemoveInstruction(hp2);
  13102. RemoveCurrentP(p, hp1);
  13103. Result:=true;
  13104. exit;
  13105. end;
  13106. end;
  13107. end;
  13108. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13109. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13110. (taicpu(hp1).opsize=S_B)) or
  13111. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13112. (taicpu(hp1).opsize=S_W))
  13113. {$ifdef x86_64}
  13114. or ((taicpu(p).opsize=S_LQ) and
  13115. (taicpu(hp1).opsize=S_L))
  13116. {$endif x86_64}
  13117. ) and
  13118. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13119. begin
  13120. { change
  13121. movx %reg1,%reg2
  13122. op %reg2,%reg3
  13123. dealloc %reg2
  13124. into
  13125. op %reg1,%reg3
  13126. if the second op accesses only the bits stored in reg1
  13127. }
  13128. TransferUsedRegs(TmpUsedRegs);
  13129. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13130. if AndTest then
  13131. begin
  13132. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13133. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13134. end
  13135. else
  13136. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13137. if not RegUsed then
  13138. begin
  13139. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13140. if taicpu(p).oper[0]^.typ=top_reg then
  13141. begin
  13142. case taicpu(hp1).opsize of
  13143. S_B:
  13144. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13145. S_W:
  13146. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13147. S_L:
  13148. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13149. else
  13150. Internalerror(2020102301);
  13151. end;
  13152. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13153. end
  13154. else
  13155. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13156. RemoveCurrentP(p);
  13157. if AndTest then
  13158. RemoveInstruction(hp2);
  13159. result:=true;
  13160. exit;
  13161. end;
  13162. end
  13163. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13164. (
  13165. { Bitwise operations only }
  13166. (taicpu(hp1).opcode=A_AND) or
  13167. (taicpu(hp1).opcode=A_TEST) or
  13168. (
  13169. (taicpu(hp1).oper[0]^.typ = top_const) and
  13170. (
  13171. (taicpu(hp1).opcode=A_OR) or
  13172. (taicpu(hp1).opcode=A_XOR)
  13173. )
  13174. )
  13175. ) and
  13176. (
  13177. (taicpu(hp1).oper[0]^.typ = top_const) or
  13178. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13179. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13180. ) then
  13181. begin
  13182. { change
  13183. movx %reg2,%reg2
  13184. op const,%reg2
  13185. into
  13186. op const,%reg2 (smaller version)
  13187. movx %reg2,%reg2
  13188. also change
  13189. movx %reg1,%reg2
  13190. and/test (oper),%reg2
  13191. dealloc %reg2
  13192. into
  13193. and/test (oper),%reg1
  13194. }
  13195. case taicpu(p).opsize of
  13196. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13197. begin
  13198. NewSize := S_B;
  13199. NewRegSize := R_SUBL;
  13200. Limit := $FF;
  13201. end;
  13202. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13203. begin
  13204. NewSize := S_W;
  13205. NewRegSize := R_SUBW;
  13206. Limit := $FFFF;
  13207. end;
  13208. {$ifdef x86_64}
  13209. S_LQ:
  13210. begin
  13211. NewSize := S_L;
  13212. NewRegSize := R_SUBD;
  13213. Limit := $FFFFFFFF;
  13214. end;
  13215. {$endif x86_64}
  13216. else
  13217. Internalerror(2021120302);
  13218. end;
  13219. TransferUsedRegs(TmpUsedRegs);
  13220. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13221. if AndTest then
  13222. begin
  13223. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13224. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13225. end
  13226. else
  13227. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13228. if
  13229. (
  13230. (taicpu(p).opcode = A_MOVZX) and
  13231. (
  13232. (taicpu(hp1).opcode=A_AND) or
  13233. (taicpu(hp1).opcode=A_TEST)
  13234. ) and
  13235. not (
  13236. { If both are references, then the final instruction will have
  13237. both operands as references, which is not allowed }
  13238. (taicpu(p).oper[0]^.typ = top_ref) and
  13239. (taicpu(hp1).oper[0]^.typ = top_ref)
  13240. ) and
  13241. not RegUsed
  13242. ) or
  13243. (
  13244. (
  13245. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13246. not RegUsed
  13247. ) and
  13248. (taicpu(p).oper[0]^.typ = top_reg) and
  13249. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13250. (taicpu(hp1).oper[0]^.typ = top_const) and
  13251. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13252. ) then
  13253. begin
  13254. {$if defined(i386) or defined(i8086)}
  13255. { If the target size is 8-bit, make sure we can actually encode it }
  13256. 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
  13257. Exit;
  13258. {$endif i386 or i8086}
  13259. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13260. taicpu(hp1).opsize := NewSize;
  13261. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13262. if AndTest then
  13263. begin
  13264. RemoveInstruction(hp2);
  13265. if not RegUsed then
  13266. begin
  13267. taicpu(hp1).opcode := A_TEST;
  13268. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13269. begin
  13270. { Make sure the reference is the second operand }
  13271. SwapOper := taicpu(hp1).oper[0];
  13272. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13273. taicpu(hp1).oper[1] := SwapOper;
  13274. end;
  13275. end;
  13276. end;
  13277. case taicpu(hp1).oper[0]^.typ of
  13278. top_reg:
  13279. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13280. top_const:
  13281. { For the AND/TEST case }
  13282. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13283. else
  13284. ;
  13285. end;
  13286. if RegUsed then
  13287. begin
  13288. AsmL.Remove(p);
  13289. AsmL.InsertAfter(p, hp1);
  13290. p := hp1;
  13291. end
  13292. else
  13293. RemoveCurrentP(p, hp1);
  13294. result:=true;
  13295. exit;
  13296. end;
  13297. end;
  13298. end;
  13299. if reg_and_hp1_is_instr and
  13300. (taicpu(p).oper[0]^.typ = top_reg) and
  13301. (
  13302. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13303. ) and
  13304. (taicpu(hp1).oper[0]^.typ = top_const) and
  13305. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13306. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13307. { Minimum shift value allowed is the bit difference between the sizes }
  13308. (taicpu(hp1).oper[0]^.val >=
  13309. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13310. 8 * (
  13311. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13312. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13313. )
  13314. ) then
  13315. begin
  13316. { For:
  13317. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13318. shl/sal ##, %reg1
  13319. Remove the movsx/movzx instruction if the shift overwrites the
  13320. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13321. }
  13322. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13323. RemoveCurrentP(p, hp1);
  13324. Result := True;
  13325. Exit;
  13326. end
  13327. else if reg_and_hp1_is_instr and
  13328. (taicpu(p).oper[0]^.typ = top_reg) and
  13329. (
  13330. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13331. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13332. ) and
  13333. (taicpu(hp1).oper[0]^.typ = top_const) and
  13334. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13335. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13336. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13337. (taicpu(hp1).oper[0]^.val <
  13338. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13339. 8 * (
  13340. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13341. )
  13342. ) then
  13343. begin
  13344. { For:
  13345. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13346. sar ##, %reg1 shr ##, %reg1
  13347. Move the shift to before the movx instruction if the shift value
  13348. is not too large.
  13349. }
  13350. asml.Remove(hp1);
  13351. asml.InsertBefore(hp1, p);
  13352. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13353. case taicpu(p).opsize of
  13354. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13355. taicpu(hp1).opsize := S_B;
  13356. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13357. taicpu(hp1).opsize := S_W;
  13358. {$ifdef x86_64}
  13359. S_LQ:
  13360. taicpu(hp1).opsize := S_L;
  13361. {$endif}
  13362. else
  13363. InternalError(2020112401);
  13364. end;
  13365. if (taicpu(hp1).opcode = A_SHR) then
  13366. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13367. else
  13368. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13369. Result := True;
  13370. end;
  13371. if reg_and_hp1_is_instr and
  13372. (taicpu(p).oper[0]^.typ = top_reg) and
  13373. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13374. (
  13375. (taicpu(hp1).opcode = taicpu(p).opcode)
  13376. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13377. {$ifdef x86_64}
  13378. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13379. {$endif x86_64}
  13380. ) then
  13381. begin
  13382. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13383. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13384. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13385. begin
  13386. {
  13387. For example:
  13388. movzbw %al,%ax
  13389. movzwl %ax,%eax
  13390. Compress into:
  13391. movzbl %al,%eax
  13392. }
  13393. RegUsed := False;
  13394. case taicpu(p).opsize of
  13395. S_BW:
  13396. case taicpu(hp1).opsize of
  13397. S_WL:
  13398. begin
  13399. taicpu(p).opsize := S_BL;
  13400. RegUsed := True;
  13401. end;
  13402. {$ifdef x86_64}
  13403. S_WQ:
  13404. begin
  13405. if taicpu(p).opcode = A_MOVZX then
  13406. begin
  13407. taicpu(p).opsize := S_BL;
  13408. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13409. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13410. end
  13411. else
  13412. taicpu(p).opsize := S_BQ;
  13413. RegUsed := True;
  13414. end;
  13415. {$endif x86_64}
  13416. else
  13417. ;
  13418. end;
  13419. {$ifdef x86_64}
  13420. S_BL:
  13421. case taicpu(hp1).opsize of
  13422. S_LQ:
  13423. begin
  13424. if taicpu(p).opcode = A_MOVZX then
  13425. begin
  13426. taicpu(p).opsize := S_BL;
  13427. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13428. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13429. end
  13430. else
  13431. taicpu(p).opsize := S_BQ;
  13432. RegUsed := True;
  13433. end;
  13434. else
  13435. ;
  13436. end;
  13437. S_WL:
  13438. case taicpu(hp1).opsize of
  13439. S_LQ:
  13440. begin
  13441. if taicpu(p).opcode = A_MOVZX then
  13442. begin
  13443. taicpu(p).opsize := S_WL;
  13444. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13445. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13446. end
  13447. else
  13448. taicpu(p).opsize := S_WQ;
  13449. RegUsed := True;
  13450. end;
  13451. else
  13452. ;
  13453. end;
  13454. {$endif x86_64}
  13455. else
  13456. ;
  13457. end;
  13458. if RegUsed then
  13459. begin
  13460. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13461. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13462. RemoveInstruction(hp1);
  13463. Result := True;
  13464. Exit;
  13465. end;
  13466. end;
  13467. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13468. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13469. GetNextInstruction(hp1, hp2) and
  13470. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13471. (
  13472. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13473. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13474. {$ifdef x86_64}
  13475. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13476. {$endif x86_64}
  13477. ) and
  13478. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13479. (
  13480. (
  13481. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13482. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13483. ) or
  13484. (
  13485. { Only allow the operands in reverse order for TEST instructions }
  13486. (taicpu(hp2).opcode = A_TEST) and
  13487. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13488. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13489. )
  13490. ) then
  13491. begin
  13492. {
  13493. For example:
  13494. movzbl %al,%eax
  13495. movzbl (ref),%edx
  13496. andl %edx,%eax
  13497. (%edx deallocated)
  13498. Change to:
  13499. andb (ref),%al
  13500. movzbl %al,%eax
  13501. Rules are:
  13502. - First two instructions have the same opcode and opsize
  13503. - First instruction's operands are the same super-register
  13504. - Second instruction operates on a different register
  13505. - Third instruction is AND, OR, XOR or TEST
  13506. - Third instruction's operands are the destination registers of the first two instructions
  13507. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13508. - Second instruction's destination register is deallocated afterwards
  13509. }
  13510. TransferUsedRegs(TmpUsedRegs);
  13511. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13512. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13513. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13514. begin
  13515. case taicpu(p).opsize of
  13516. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13517. NewSize := S_B;
  13518. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13519. NewSize := S_W;
  13520. {$ifdef x86_64}
  13521. S_LQ:
  13522. NewSize := S_L;
  13523. {$endif x86_64}
  13524. else
  13525. InternalError(2021120301);
  13526. end;
  13527. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13528. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13529. taicpu(hp2).opsize := NewSize;
  13530. RemoveInstruction(hp1);
  13531. { With TEST, it's best to keep the MOVX instruction at the top }
  13532. if (taicpu(hp2).opcode <> A_TEST) then
  13533. begin
  13534. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13535. asml.Remove(p);
  13536. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13537. asml.InsertAfter(p, hp2);
  13538. p := hp2;
  13539. end
  13540. else
  13541. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13542. Result := True;
  13543. Exit;
  13544. end;
  13545. end;
  13546. end;
  13547. if taicpu(p).opcode=A_MOVZX then
  13548. begin
  13549. { removes superfluous And's after movzx's }
  13550. if reg_and_hp1_is_instr and
  13551. (taicpu(hp1).opcode = A_AND) and
  13552. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13553. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13554. {$ifdef x86_64}
  13555. { check for implicit extension to 64 bit }
  13556. or
  13557. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13558. (taicpu(hp1).opsize=S_Q) and
  13559. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13560. )
  13561. {$endif x86_64}
  13562. )
  13563. then
  13564. begin
  13565. case taicpu(p).opsize Of
  13566. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13567. if (taicpu(hp1).oper[0]^.val = $ff) then
  13568. begin
  13569. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13570. RemoveInstruction(hp1);
  13571. Result:=true;
  13572. exit;
  13573. end;
  13574. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13575. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13576. begin
  13577. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13578. RemoveInstruction(hp1);
  13579. Result:=true;
  13580. exit;
  13581. end;
  13582. {$ifdef x86_64}
  13583. S_LQ:
  13584. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13585. begin
  13586. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13587. RemoveInstruction(hp1);
  13588. Result:=true;
  13589. exit;
  13590. end;
  13591. {$endif x86_64}
  13592. else
  13593. ;
  13594. end;
  13595. { we cannot get rid of the and, but can we get rid of the movz ?}
  13596. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13597. begin
  13598. case taicpu(p).opsize Of
  13599. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13600. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13601. begin
  13602. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13603. RemoveCurrentP(p,hp1);
  13604. Result:=true;
  13605. exit;
  13606. end;
  13607. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13608. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13609. begin
  13610. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13611. RemoveCurrentP(p,hp1);
  13612. Result:=true;
  13613. exit;
  13614. end;
  13615. {$ifdef x86_64}
  13616. S_LQ:
  13617. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13618. begin
  13619. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13620. RemoveCurrentP(p,hp1);
  13621. Result:=true;
  13622. exit;
  13623. end;
  13624. {$endif x86_64}
  13625. else
  13626. ;
  13627. end;
  13628. end;
  13629. end;
  13630. { changes some movzx constructs to faster synonyms (all examples
  13631. are given with eax/ax, but are also valid for other registers)}
  13632. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13633. begin
  13634. case taicpu(p).opsize of
  13635. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13636. (the machine code is equivalent to movzbl %al,%eax), but the
  13637. code generator still generates that assembler instruction and
  13638. it is silently converted. This should probably be checked.
  13639. [Kit] }
  13640. S_BW:
  13641. begin
  13642. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13643. (
  13644. not IsMOVZXAcceptable
  13645. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13646. or (
  13647. (cs_opt_size in current_settings.optimizerswitches) and
  13648. (taicpu(p).oper[1]^.reg = NR_AX)
  13649. )
  13650. ) then
  13651. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13652. begin
  13653. DebugMsg(SPeepholeOptimization + 'var7',p);
  13654. taicpu(p).opcode := A_AND;
  13655. taicpu(p).changeopsize(S_W);
  13656. taicpu(p).loadConst(0,$ff);
  13657. Result := True;
  13658. end
  13659. else if not IsMOVZXAcceptable and
  13660. GetNextInstruction(p, hp1) and
  13661. (tai(hp1).typ = ait_instruction) and
  13662. (taicpu(hp1).opcode = A_AND) and
  13663. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13664. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13665. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13666. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13667. begin
  13668. DebugMsg(SPeepholeOptimization + 'var8',p);
  13669. taicpu(p).opcode := A_MOV;
  13670. taicpu(p).changeopsize(S_W);
  13671. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13672. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13673. Result := True;
  13674. end;
  13675. end;
  13676. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13677. S_BL:
  13678. if not IsMOVZXAcceptable then
  13679. begin
  13680. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13681. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13682. begin
  13683. DebugMsg(SPeepholeOptimization + 'var9',p);
  13684. taicpu(p).opcode := A_AND;
  13685. taicpu(p).changeopsize(S_L);
  13686. taicpu(p).loadConst(0,$ff);
  13687. Result := True;
  13688. end
  13689. else if GetNextInstruction(p, hp1) and
  13690. (tai(hp1).typ = ait_instruction) and
  13691. (taicpu(hp1).opcode = A_AND) and
  13692. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13693. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13694. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13695. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13696. begin
  13697. DebugMsg(SPeepholeOptimization + 'var10',p);
  13698. taicpu(p).opcode := A_MOV;
  13699. taicpu(p).changeopsize(S_L);
  13700. { do not use R_SUBWHOLE
  13701. as movl %rdx,%eax
  13702. is invalid in assembler PM }
  13703. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13704. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13705. Result := True;
  13706. end;
  13707. end;
  13708. {$endif i8086}
  13709. S_WL:
  13710. if not IsMOVZXAcceptable then
  13711. begin
  13712. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13713. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13714. begin
  13715. DebugMsg(SPeepholeOptimization + 'var11',p);
  13716. taicpu(p).opcode := A_AND;
  13717. taicpu(p).changeopsize(S_L);
  13718. taicpu(p).loadConst(0,$ffff);
  13719. Result := True;
  13720. end
  13721. else if GetNextInstruction(p, hp1) and
  13722. (tai(hp1).typ = ait_instruction) and
  13723. (taicpu(hp1).opcode = A_AND) and
  13724. (taicpu(hp1).oper[0]^.typ = top_const) and
  13725. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13726. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13727. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13728. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13729. begin
  13730. DebugMsg(SPeepholeOptimization + 'var12',p);
  13731. taicpu(p).opcode := A_MOV;
  13732. taicpu(p).changeopsize(S_L);
  13733. { do not use R_SUBWHOLE
  13734. as movl %rdx,%eax
  13735. is invalid in assembler PM }
  13736. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13737. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13738. Result := True;
  13739. end;
  13740. end;
  13741. else
  13742. InternalError(2017050705);
  13743. end;
  13744. end
  13745. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13746. begin
  13747. if GetNextInstruction(p, hp1) and
  13748. (tai(hp1).typ = ait_instruction) and
  13749. (taicpu(hp1).opcode = A_AND) and
  13750. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13751. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13752. begin
  13753. case taicpu(p).opsize Of
  13754. S_BL:
  13755. if (taicpu(hp1).opsize <> S_L) or
  13756. (taicpu(hp1).oper[0]^.val > $FF) then
  13757. begin
  13758. DebugMsg(SPeepholeOptimization + 'var13',p);
  13759. taicpu(hp1).changeopsize(S_L);
  13760. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13761. Include(OptsToCheck, aoc_ForceNewIteration);
  13762. end;
  13763. S_WL:
  13764. if (taicpu(hp1).opsize <> S_L) or
  13765. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13766. begin
  13767. DebugMsg(SPeepholeOptimization + 'var14',p);
  13768. taicpu(hp1).changeopsize(S_L);
  13769. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13770. Include(OptsToCheck, aoc_ForceNewIteration);
  13771. end;
  13772. S_BW:
  13773. if (taicpu(hp1).opsize <> S_W) or
  13774. (taicpu(hp1).oper[0]^.val > $FF) then
  13775. begin
  13776. DebugMsg(SPeepholeOptimization + 'var15',p);
  13777. taicpu(hp1).changeopsize(S_W);
  13778. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13779. Include(OptsToCheck, aoc_ForceNewIteration);
  13780. end;
  13781. else
  13782. Internalerror(2017050704)
  13783. end;
  13784. end;
  13785. end;
  13786. end;
  13787. end;
  13788. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13789. var
  13790. hp1, hp2 : tai;
  13791. MaskLength : Cardinal;
  13792. MaskedBits : TCgInt;
  13793. ActiveReg : TRegister;
  13794. begin
  13795. Result:=false;
  13796. { There are no optimisations for reference targets }
  13797. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13798. Exit;
  13799. while GetNextInstruction(p, hp1) and
  13800. (hp1.typ = ait_instruction) do
  13801. begin
  13802. if (taicpu(p).oper[0]^.typ = top_const) then
  13803. begin
  13804. case taicpu(hp1).opcode of
  13805. A_AND:
  13806. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13807. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13808. { the second register must contain the first one, so compare their subreg types }
  13809. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13810. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13811. { change
  13812. and const1, reg
  13813. and const2, reg
  13814. to
  13815. and (const1 and const2), reg
  13816. }
  13817. begin
  13818. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13819. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13820. RemoveCurrentP(p, hp1);
  13821. Result:=true;
  13822. exit;
  13823. end;
  13824. A_CMP:
  13825. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13826. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13827. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13828. { Just check that the condition on the next instruction is compatible }
  13829. GetNextInstruction(hp1, hp2) and
  13830. (hp2.typ = ait_instruction) and
  13831. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13832. then
  13833. { change
  13834. and 2^n, reg
  13835. cmp 2^n, reg
  13836. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13837. to
  13838. and 2^n, reg
  13839. test reg, reg
  13840. j(~c) / set(~c) / cmov(~c)
  13841. }
  13842. begin
  13843. { Keep TEST instruction in, rather than remove it, because
  13844. it may trigger other optimisations such as MovAndTest2Test }
  13845. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13846. taicpu(hp1).opcode := A_TEST;
  13847. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13848. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13849. Result := True;
  13850. Exit;
  13851. end
  13852. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13853. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13854. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13855. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13856. { change
  13857. and $ff/$ff/$ffff, reg
  13858. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13859. dealloc reg
  13860. to
  13861. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13862. }
  13863. begin
  13864. TransferUsedRegs(TmpUsedRegs);
  13865. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13866. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13867. begin
  13868. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13869. case taicpu(p).oper[0]^.val of
  13870. $ff:
  13871. begin
  13872. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13873. taicpu(hp1).opsize:=S_B;
  13874. end;
  13875. $ffff:
  13876. begin
  13877. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13878. taicpu(hp1).opsize:=S_W;
  13879. end;
  13880. $ffffffff:
  13881. begin
  13882. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13883. taicpu(hp1).opsize:=S_L;
  13884. end;
  13885. else
  13886. Internalerror(2023030401);
  13887. end;
  13888. RemoveCurrentP(p);
  13889. Result := True;
  13890. Exit;
  13891. end;
  13892. end;
  13893. A_MOVZX:
  13894. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13895. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13896. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13897. (
  13898. (
  13899. (taicpu(p).opsize=S_W) and
  13900. (taicpu(hp1).opsize=S_BW)
  13901. ) or
  13902. (
  13903. (taicpu(p).opsize=S_L) and
  13904. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13905. )
  13906. {$ifdef x86_64}
  13907. or
  13908. (
  13909. (taicpu(p).opsize=S_Q) and
  13910. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13911. )
  13912. {$endif x86_64}
  13913. ) then
  13914. begin
  13915. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13916. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13917. ) or
  13918. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13919. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13920. then
  13921. begin
  13922. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13923. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13924. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13925. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13926. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13927. }
  13928. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13929. RemoveInstruction(hp1);
  13930. { See if there are other optimisations possible }
  13931. Continue;
  13932. end;
  13933. end;
  13934. A_SHL:
  13935. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13936. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13937. begin
  13938. {$ifopt R+}
  13939. {$define RANGE_WAS_ON}
  13940. {$R-}
  13941. {$endif}
  13942. { get length of potential and mask }
  13943. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13944. { really a mask? }
  13945. {$ifdef RANGE_WAS_ON}
  13946. {$R+}
  13947. {$endif}
  13948. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13949. { unmasked part shifted out? }
  13950. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13951. begin
  13952. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13953. RemoveCurrentP(p, hp1);
  13954. Result:=true;
  13955. exit;
  13956. end;
  13957. end;
  13958. A_SHR:
  13959. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13960. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13961. (taicpu(hp1).oper[0]^.val <= 63) then
  13962. begin
  13963. { Does SHR combined with the AND cover all the bits?
  13964. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13965. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13966. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13967. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13968. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13969. begin
  13970. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13971. RemoveCurrentP(p, hp1);
  13972. Result := True;
  13973. Exit;
  13974. end;
  13975. end;
  13976. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13977. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13978. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13979. begin
  13980. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13981. (
  13982. (
  13983. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13984. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13985. ) or (
  13986. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13987. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13988. {$ifdef x86_64}
  13989. ) or (
  13990. (taicpu(hp1).opsize = S_LQ) and
  13991. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13992. {$endif x86_64}
  13993. )
  13994. ) then
  13995. begin
  13996. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13997. begin
  13998. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13999. RemoveInstruction(hp1);
  14000. { See if there are other optimisations possible }
  14001. Continue;
  14002. end;
  14003. { The super-registers are the same though.
  14004. Note that this change by itself doesn't improve
  14005. code speed, but it opens up other optimisations. }
  14006. {$ifdef x86_64}
  14007. { Convert 64-bit register to 32-bit }
  14008. case taicpu(hp1).opsize of
  14009. S_BQ:
  14010. begin
  14011. taicpu(hp1).opsize := S_BL;
  14012. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14013. end;
  14014. S_WQ:
  14015. begin
  14016. taicpu(hp1).opsize := S_WL;
  14017. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14018. end
  14019. else
  14020. ;
  14021. end;
  14022. {$endif x86_64}
  14023. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14024. taicpu(hp1).opcode := A_MOVZX;
  14025. { See if there are other optimisations possible }
  14026. Continue;
  14027. end;
  14028. end;
  14029. else
  14030. ;
  14031. end;
  14032. end
  14033. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14034. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14035. begin
  14036. {$ifdef x86_64}
  14037. if (taicpu(p).opsize = S_Q) then
  14038. begin
  14039. { Never necessary }
  14040. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14041. RemoveCurrentP(p, hp1);
  14042. Result := True;
  14043. Exit;
  14044. end;
  14045. {$endif x86_64}
  14046. { Forward check to determine necessity of and %reg,%reg }
  14047. TransferUsedRegs(TmpUsedRegs);
  14048. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14049. { Saves on a bunch of dereferences }
  14050. ActiveReg := taicpu(p).oper[1]^.reg;
  14051. case taicpu(hp1).opcode of
  14052. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14053. if (
  14054. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14055. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14056. ) and
  14057. (
  14058. (taicpu(hp1).opcode <> A_MOV) or
  14059. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14060. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14061. ) and
  14062. not (
  14063. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14064. (taicpu(hp1).opcode = A_MOV) and
  14065. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14066. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14067. ) and
  14068. (
  14069. (
  14070. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14071. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14072. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14073. ) or
  14074. (
  14075. {$ifdef x86_64}
  14076. (
  14077. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14078. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14079. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14080. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14081. ) and
  14082. {$endif x86_64}
  14083. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14084. )
  14085. ) then
  14086. begin
  14087. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14088. RemoveCurrentP(p, hp1);
  14089. Result := True;
  14090. Exit;
  14091. end;
  14092. A_ADD,
  14093. A_AND,
  14094. A_BSF,
  14095. A_BSR,
  14096. A_BTC,
  14097. A_BTR,
  14098. A_BTS,
  14099. A_OR,
  14100. A_SUB,
  14101. A_XOR:
  14102. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14103. if (
  14104. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14105. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14106. ) and
  14107. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14108. begin
  14109. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14110. RemoveCurrentP(p, hp1);
  14111. Result := True;
  14112. Exit;
  14113. end;
  14114. A_CMP,
  14115. A_TEST:
  14116. if (
  14117. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14118. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14119. ) and
  14120. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14121. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14122. begin
  14123. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14124. RemoveCurrentP(p, hp1);
  14125. Result := True;
  14126. Exit;
  14127. end;
  14128. A_BSWAP,
  14129. A_NEG,
  14130. A_NOT:
  14131. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14132. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14133. begin
  14134. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14135. RemoveCurrentP(p, hp1);
  14136. Result := True;
  14137. Exit;
  14138. end;
  14139. else
  14140. ;
  14141. end;
  14142. end;
  14143. if (taicpu(hp1).is_jmp) and
  14144. (taicpu(hp1).opcode<>A_JMP) and
  14145. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14146. begin
  14147. { change
  14148. and x, reg
  14149. jxx
  14150. to
  14151. test x, reg
  14152. jxx
  14153. if reg is deallocated before the
  14154. jump, but only if it's a conditional jump (PFV)
  14155. }
  14156. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14157. taicpu(p).opcode := A_TEST;
  14158. Exit;
  14159. end;
  14160. Break;
  14161. end;
  14162. { Lone AND tests }
  14163. if (taicpu(p).oper[0]^.typ = top_const) then
  14164. begin
  14165. {
  14166. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14167. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14168. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14169. }
  14170. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14171. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14172. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14173. begin
  14174. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14175. if taicpu(p).opsize = S_L then
  14176. begin
  14177. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14178. Result := True;
  14179. end;
  14180. end;
  14181. end;
  14182. { Backward check to determine necessity of and %reg,%reg }
  14183. if (taicpu(p).oper[0]^.typ = top_reg) and
  14184. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14185. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14186. GetLastInstruction(p, hp2) and
  14187. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14188. { Check size of adjacent instruction to determine if the AND is
  14189. effectively a null operation }
  14190. (
  14191. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14192. { Note: Don't include S_Q }
  14193. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14194. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14195. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14196. ) then
  14197. begin
  14198. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14199. { If GetNextInstruction returned False, hp1 will be nil }
  14200. RemoveCurrentP(p, hp1);
  14201. Result := True;
  14202. Exit;
  14203. end;
  14204. end;
  14205. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14206. var
  14207. hp1, hp2: tai;
  14208. NewRef: TReference;
  14209. Distance: Cardinal;
  14210. TempTracking: TAllUsedRegs;
  14211. DoAddMov2Lea: Boolean;
  14212. { This entire nested function is used in an if-statement below, but we
  14213. want to avoid all the used reg transfers and GetNextInstruction calls
  14214. until we really have to check }
  14215. function MemRegisterNotUsedLater: Boolean; inline;
  14216. var
  14217. hp2: tai;
  14218. begin
  14219. TransferUsedRegs(TmpUsedRegs);
  14220. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14221. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14222. else
  14223. { p and hp1 will be adjacent }
  14224. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14225. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14226. end;
  14227. begin
  14228. Result := False;
  14229. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14230. (taicpu(p).oper[1]^.typ = top_reg) then
  14231. begin
  14232. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14233. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14234. (hp1.typ <> ait_instruction) or
  14235. not
  14236. (
  14237. (cs_opt_level3 in current_settings.optimizerswitches) or
  14238. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14239. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14240. ) then
  14241. Exit;
  14242. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14243. addq $x, %rax
  14244. movq %rax, %rdx
  14245. sarq $63, %rdx
  14246. (%rax still in use)
  14247. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14248. leaq $x(%rax),%rdx
  14249. addq $x, %rax
  14250. sarq $63, %rdx
  14251. ...which is okay since it breaks the dependency chain between
  14252. addq and movq, but if OptPass2MOV is called first:
  14253. addq $x, %rax
  14254. cqto
  14255. ...which is better in all ways, taking only 2 cycles to execute
  14256. and much smaller in code size.
  14257. }
  14258. { The extra register tracking is quite strenuous }
  14259. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14260. MatchInstruction(hp1, A_MOV, []) then
  14261. begin
  14262. { Update the register tracking to the MOV instruction }
  14263. CopyUsedRegs(TempTracking);
  14264. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14265. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14266. else
  14267. { p and hp1 will be adjacent }
  14268. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14269. hp2 := hp1;
  14270. if OptPass2MOV(hp1) then
  14271. Include(OptsToCheck, aoc_ForceNewIteration);
  14272. { Reset the tracking to the current instruction }
  14273. RestoreUsedRegs(TempTracking);
  14274. ReleaseUsedRegs(TempTracking);
  14275. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14276. OptPass2ADD get called again }
  14277. if (hp1 <> hp2) then
  14278. begin
  14279. Result := True;
  14280. Exit;
  14281. end;
  14282. end;
  14283. { Change:
  14284. add %reg2,%reg1
  14285. (%reg2 not modified in between)
  14286. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14287. To:
  14288. mov/s/z #(%reg1,%reg2),%reg1
  14289. }
  14290. if (taicpu(p).oper[0]^.typ = top_reg) and
  14291. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14292. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14293. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14294. (
  14295. (
  14296. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14297. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14298. { r/esp cannot be an index }
  14299. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14300. ) or (
  14301. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14302. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14303. )
  14304. ) and (
  14305. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14306. (
  14307. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14308. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14309. MemRegisterNotUsedLater
  14310. )
  14311. ) then
  14312. begin
  14313. if (
  14314. { Instructions are guaranteed to be adjacent on -O2 and under }
  14315. (cs_opt_level3 in current_settings.optimizerswitches) and
  14316. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14317. ) then
  14318. begin
  14319. { If the other register is used in between, move the MOV
  14320. instruction to right after the ADD instruction so a
  14321. saving can still be made }
  14322. Asml.Remove(hp1);
  14323. Asml.InsertAfter(hp1, p);
  14324. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14325. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14326. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14327. RemoveCurrentp(p, hp1);
  14328. end
  14329. else
  14330. begin
  14331. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14332. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14333. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14334. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14335. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14336. { hp1 may not be the immediate next instruction under -O3 }
  14337. RemoveCurrentp(p)
  14338. else
  14339. RemoveCurrentp(p, hp1);
  14340. end;
  14341. Result := True;
  14342. Exit;
  14343. end;
  14344. { Change:
  14345. addl/q $x,%reg1
  14346. movl/q %reg1,%reg2
  14347. To:
  14348. leal/q $x(%reg1),%reg2
  14349. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14350. Breaks the dependency chain.
  14351. }
  14352. if (taicpu(p).oper[0]^.typ = top_const) and
  14353. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14354. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14355. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14356. (
  14357. { Instructions are guaranteed to be adjacent on -O2 and under }
  14358. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14359. (
  14360. { If the flags are used, don't make the optimisation,
  14361. otherwise they will be scrambled. Fixes #41148 }
  14362. (
  14363. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14364. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14365. ) and
  14366. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14367. )
  14368. ) then
  14369. begin
  14370. TransferUsedRegs(TmpUsedRegs);
  14371. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14372. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14373. else
  14374. { p and hp1 will be adjacent }
  14375. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14376. if (
  14377. SetAndTest(
  14378. (
  14379. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14380. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14381. ),
  14382. DoAddMov2Lea
  14383. ) or
  14384. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14385. not (cs_opt_size in current_settings.optimizerswitches)
  14386. ) then
  14387. begin
  14388. { Change the MOV instruction to a LEA instruction, and update the
  14389. first operand }
  14390. reference_reset(NewRef, 1, []);
  14391. NewRef.base := taicpu(p).oper[1]^.reg;
  14392. NewRef.scalefactor := 1;
  14393. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14394. taicpu(hp1).opcode := A_LEA;
  14395. taicpu(hp1).loadref(0, NewRef);
  14396. if DoAddMov2Lea then
  14397. begin
  14398. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14399. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14400. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14401. { hp1 may not be the immediate next instruction under -O3 }
  14402. RemoveCurrentp(p)
  14403. else
  14404. RemoveCurrentp(p, hp1);
  14405. end
  14406. else
  14407. begin
  14408. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14409. { Move what is now the LEA instruction to before the ADD instruction }
  14410. Asml.Remove(hp1);
  14411. Asml.InsertBefore(hp1, p);
  14412. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14413. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14414. p := hp1;
  14415. end;
  14416. Result := True;
  14417. end;
  14418. end;
  14419. end;
  14420. end;
  14421. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14422. var
  14423. SubReg: TSubRegister;
  14424. hp1, hp2: tai;
  14425. CallJmp: Boolean;
  14426. begin
  14427. Result := False;
  14428. CallJmp := False;
  14429. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14430. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14431. with taicpu(p).oper[0]^.ref^ do
  14432. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14433. if (offset = 0) then
  14434. begin
  14435. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14436. begin
  14437. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14438. taicpu(p).opcode := A_ADD;
  14439. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14440. Result := True;
  14441. end
  14442. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14443. begin
  14444. if (base <> NR_NO) then
  14445. begin
  14446. if (scalefactor <= 1) then
  14447. begin
  14448. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14449. taicpu(p).opcode := A_ADD;
  14450. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14451. Result := True;
  14452. end;
  14453. end
  14454. else
  14455. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14456. if (scalefactor in [2, 4, 8]) then
  14457. begin
  14458. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14459. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14460. taicpu(p).opcode := A_SHL;
  14461. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14462. Result := True;
  14463. end;
  14464. end;
  14465. end
  14466. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14467. lot of latency, so break off the offset if %reg3 is used soon
  14468. afterwards }
  14469. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14470. { If 3-component addresses don't have additional latency, don't
  14471. perform this optimisation }
  14472. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14473. GetNextInstruction(p, hp1) and
  14474. (hp1.typ = ait_instruction) and
  14475. (
  14476. (
  14477. { Permit jumps and calls since they have a larger degree of overhead }
  14478. (
  14479. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14480. (
  14481. { ... unless the register specifies the location }
  14482. (taicpu(hp1).ops > 0) and
  14483. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14484. )
  14485. ) and
  14486. (
  14487. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14488. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14489. )
  14490. )
  14491. or
  14492. (
  14493. { Check up to two instructions ahead }
  14494. GetNextInstruction(hp1, hp2) and
  14495. (hp2.typ = ait_instruction) and
  14496. (
  14497. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14498. (
  14499. { Same as above }
  14500. (taicpu(hp2).ops > 0) and
  14501. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14502. )
  14503. ) and
  14504. (
  14505. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14506. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14507. )
  14508. )
  14509. ) then
  14510. begin
  14511. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14512. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14513. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14514. offset := 0;
  14515. if Assigned(symbol) or Assigned(relsymbol) then
  14516. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14517. else
  14518. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14519. { Inserting before the next instruction rather than after the
  14520. current instruction gives more accurate register tracking }
  14521. asml.InsertBefore(hp2, hp1);
  14522. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14523. Result := True;
  14524. end;
  14525. end;
  14526. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14527. var
  14528. hp1, hp2: tai;
  14529. NewRef: TReference;
  14530. Distance: Cardinal;
  14531. TempTracking: TAllUsedRegs;
  14532. DoSubMov2Lea: Boolean;
  14533. begin
  14534. Result := False;
  14535. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14536. MatchOpType(taicpu(p),top_const,top_reg) then
  14537. begin
  14538. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14539. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14540. (hp1.typ <> ait_instruction) or
  14541. not
  14542. (
  14543. (cs_opt_level3 in current_settings.optimizerswitches) or
  14544. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14545. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14546. ) then
  14547. Exit;
  14548. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14549. subq $x, %rax
  14550. movq %rax, %rdx
  14551. sarq $63, %rdx
  14552. (%rax still in use)
  14553. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14554. leaq $-x(%rax),%rdx
  14555. movq $x, %rax
  14556. sarq $63, %rdx
  14557. ...which is okay since it breaks the dependency chain between
  14558. subq and movq, but if OptPass2MOV is called first:
  14559. subq $x, %rax
  14560. cqto
  14561. ...which is better in all ways, taking only 2 cycles to execute
  14562. and much smaller in code size.
  14563. }
  14564. { The extra register tracking is quite strenuous }
  14565. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14566. MatchInstruction(hp1, A_MOV, []) then
  14567. begin
  14568. { Update the register tracking to the MOV instruction }
  14569. CopyUsedRegs(TempTracking);
  14570. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14571. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14572. else
  14573. { p and hp1 will be adjacent }
  14574. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14575. hp2 := hp1;
  14576. if OptPass2MOV(hp1) then
  14577. Include(OptsToCheck, aoc_ForceNewIteration);
  14578. { Reset the tracking to the current instruction }
  14579. RestoreUsedRegs(TempTracking);
  14580. ReleaseUsedRegs(TempTracking);
  14581. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14582. OptPass2SUB get called again }
  14583. if (hp1 <> hp2) then
  14584. begin
  14585. Result := True;
  14586. Exit;
  14587. end;
  14588. end;
  14589. { Change:
  14590. subl/q $x,%reg1
  14591. movl/q %reg1,%reg2
  14592. To:
  14593. leal/q $-x(%reg1),%reg2
  14594. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14595. Breaks the dependency chain and potentially permits the removal of
  14596. a CMP instruction if one follows.
  14597. }
  14598. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14599. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14600. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14601. (
  14602. { Instructions are guaranteed to be adjacent on -O2 and under }
  14603. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14604. (
  14605. { If the flags are used, don't make the optimisation,
  14606. otherwise they will be scrambled. Fixes #41148 }
  14607. (
  14608. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14609. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14610. ) and
  14611. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14612. )
  14613. ) then
  14614. begin
  14615. TransferUsedRegs(TmpUsedRegs);
  14616. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14617. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14618. else
  14619. { p and hp1 will be adjacent }
  14620. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14621. if (
  14622. SetAndTest(
  14623. (
  14624. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14625. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14626. ),
  14627. DoSubMov2Lea
  14628. ) or
  14629. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14630. not (cs_opt_size in current_settings.optimizerswitches)
  14631. ) then
  14632. begin
  14633. { Change the MOV instruction to a LEA instruction, and update the
  14634. first operand }
  14635. reference_reset(NewRef, 1, []);
  14636. NewRef.base := taicpu(p).oper[1]^.reg;
  14637. NewRef.scalefactor := 1;
  14638. NewRef.offset := -taicpu(p).oper[0]^.val;
  14639. taicpu(hp1).opcode := A_LEA;
  14640. taicpu(hp1).loadref(0, NewRef);
  14641. if DoSubMov2Lea then
  14642. begin
  14643. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14644. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14645. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14646. { hp1 may not be the immediate next instruction under -O3 }
  14647. RemoveCurrentp(p)
  14648. else
  14649. RemoveCurrentp(p, hp1);
  14650. end
  14651. else
  14652. begin
  14653. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14654. { Move what is now the LEA instruction to before the SUB instruction }
  14655. Asml.Remove(hp1);
  14656. Asml.InsertBefore(hp1, p);
  14657. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14658. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14659. p := hp1;
  14660. end;
  14661. Result := True;
  14662. end;
  14663. end;
  14664. end;
  14665. end;
  14666. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14667. begin
  14668. { we can skip all instructions not messing with the stack pointer }
  14669. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14670. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14671. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14672. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14673. ({(taicpu(hp1).ops=0) or }
  14674. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14675. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14676. ) and }
  14677. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14678. )
  14679. ) do
  14680. GetNextInstruction(hp1,hp1);
  14681. Result:=assigned(hp1);
  14682. end;
  14683. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14684. var
  14685. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14686. begin
  14687. Result:=false;
  14688. hp5:=nil;
  14689. hp6:=nil;
  14690. hp7:=nil;
  14691. hp8:=nil;
  14692. { replace
  14693. leal(q) x(<stackpointer>),<stackpointer>
  14694. <optional .seh_stackalloc ...>
  14695. <optional .seh_endprologue ...>
  14696. call procname
  14697. <optional NOP>
  14698. leal(q) -x(<stackpointer>),<stackpointer>
  14699. <optional VZEROUPPER>
  14700. ret
  14701. by
  14702. jmp procname
  14703. but do it only on level 4 because it destroys stack back traces
  14704. }
  14705. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14706. MatchOpType(taicpu(p),top_ref,top_reg) and
  14707. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14708. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14709. { the -8, -24, -40 are not required, but bail out early if possible,
  14710. higher values are unlikely }
  14711. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14712. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14713. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14714. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14715. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14716. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14717. GetNextInstruction(p, hp1) and
  14718. { Take a copy of hp1 }
  14719. SetAndTest(hp1, hp4) and
  14720. { trick to skip label }
  14721. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14722. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14723. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14724. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14725. SkipSimpleInstructions(hp1) and
  14726. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14727. GetNextInstruction(hp1, hp2) and
  14728. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14729. { skip nop instruction on win64 }
  14730. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14731. SetAndTest(hp2,hp6) and
  14732. GetNextInstruction(hp2,hp2) and
  14733. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14734. ) and
  14735. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14736. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14737. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14738. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14739. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14740. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14741. { Segment register will be NR_NO }
  14742. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14743. GetNextInstruction(hp2, hp3) and
  14744. { trick to skip label }
  14745. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14746. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14747. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14748. SetAndTest(hp3,hp5) and
  14749. GetNextInstruction(hp3,hp3) and
  14750. MatchInstruction(hp3,A_RET,[S_NO])
  14751. )
  14752. ) and
  14753. (taicpu(hp3).ops=0) then
  14754. begin
  14755. taicpu(hp1).opcode := A_JMP;
  14756. taicpu(hp1).is_jmp := true;
  14757. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14758. { search for the stackalloc directive and remove it }
  14759. hp7:=tai(p.next);
  14760. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14761. begin
  14762. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14763. begin
  14764. { sanity check }
  14765. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14766. Internalerror(2024012201);
  14767. hp8:=tai(hp7.next);
  14768. RemoveInstruction(tai(hp7));
  14769. hp7:=hp8;
  14770. break;
  14771. end
  14772. else
  14773. hp7:=tai(hp7.next);
  14774. end;
  14775. RemoveCurrentP(p, hp4);
  14776. RemoveInstruction(hp2);
  14777. RemoveInstruction(hp3);
  14778. { if there is a vzeroupper instruction then move it before the jmp }
  14779. if Assigned(hp5) then
  14780. begin
  14781. AsmL.Remove(hp5);
  14782. ASmL.InsertBefore(hp5,hp1)
  14783. end;
  14784. { remove nop on win64 }
  14785. if Assigned(hp6) then
  14786. RemoveInstruction(hp6);
  14787. Result:=true;
  14788. end;
  14789. end;
  14790. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14791. {$ifdef x86_64}
  14792. var
  14793. hp1, hp2, hp3, hp4, hp5: tai;
  14794. {$endif x86_64}
  14795. begin
  14796. Result:=false;
  14797. {$ifdef x86_64}
  14798. hp5:=nil;
  14799. { replace
  14800. push %rax
  14801. call procname
  14802. pop %rcx
  14803. ret
  14804. by
  14805. jmp procname
  14806. but do it only on level 4 because it destroys stack back traces
  14807. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14808. for all supported calling conventions
  14809. }
  14810. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14811. MatchOpType(taicpu(p),top_reg) and
  14812. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14813. GetNextInstruction(p, hp1) and
  14814. { Take a copy of hp1 }
  14815. SetAndTest(hp1, hp4) and
  14816. { trick to skip label }
  14817. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14818. SkipSimpleInstructions(hp1) and
  14819. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14820. GetNextInstruction(hp1, hp2) and
  14821. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14822. MatchOpType(taicpu(hp2),top_reg) and
  14823. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14824. GetNextInstruction(hp2, hp3) and
  14825. { trick to skip label }
  14826. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14827. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14828. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14829. SetAndTest(hp3,hp5) and
  14830. GetNextInstruction(hp3,hp3) and
  14831. MatchInstruction(hp3,A_RET,[S_NO])
  14832. )
  14833. ) and
  14834. (taicpu(hp3).ops=0) then
  14835. begin
  14836. taicpu(hp1).opcode := A_JMP;
  14837. taicpu(hp1).is_jmp := true;
  14838. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14839. RemoveCurrentP(p, hp4);
  14840. RemoveInstruction(hp2);
  14841. RemoveInstruction(hp3);
  14842. if Assigned(hp5) then
  14843. begin
  14844. AsmL.Remove(hp5);
  14845. ASmL.InsertBefore(hp5,hp1)
  14846. end;
  14847. Result:=true;
  14848. end;
  14849. {$endif x86_64}
  14850. end;
  14851. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14852. var
  14853. Value, RegName: string;
  14854. hp1: tai;
  14855. begin
  14856. Result:=false;
  14857. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14858. begin
  14859. case taicpu(p).oper[0]^.val of
  14860. 0:
  14861. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14862. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14863. (
  14864. { See if we can still convert the instruction }
  14865. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14866. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14867. ) then
  14868. begin
  14869. { change "mov $0,%reg" into "xor %reg,%reg" }
  14870. taicpu(p).opcode := A_XOR;
  14871. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14872. Result := True;
  14873. {$ifdef x86_64}
  14874. end
  14875. else if (taicpu(p).opsize = S_Q) then
  14876. begin
  14877. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14878. { The actual optimization }
  14879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14880. taicpu(p).changeopsize(S_L);
  14881. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14882. Result := True;
  14883. end;
  14884. $1..$FFFFFFFF:
  14885. begin
  14886. { Code size reduction by J. Gareth "Kit" Moreton }
  14887. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14888. case taicpu(p).opsize of
  14889. S_Q:
  14890. begin
  14891. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14892. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14893. { The actual optimization }
  14894. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14895. taicpu(p).changeopsize(S_L);
  14896. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14897. Result := True;
  14898. end;
  14899. else
  14900. { Do nothing };
  14901. end;
  14902. {$endif x86_64}
  14903. end;
  14904. -1:
  14905. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14906. if (cs_opt_size in current_settings.optimizerswitches) and
  14907. (taicpu(p).opsize <> S_B) and
  14908. (
  14909. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14910. (
  14911. { See if we can still convert the instruction }
  14912. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14913. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14914. )
  14915. ) then
  14916. begin
  14917. { change "mov $-1,%reg" into "or $-1,%reg" }
  14918. { NOTES:
  14919. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14920. - This operation creates a false dependency on the register, so only do it when optimising for size
  14921. - 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
  14922. }
  14923. taicpu(p).opcode := A_OR;
  14924. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14925. Result := True;
  14926. end;
  14927. else
  14928. { Do nothing };
  14929. end;
  14930. end;
  14931. end;
  14932. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14933. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14934. begin
  14935. Result := False;
  14936. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14937. Exit;
  14938. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14939. so don't bother optimising }
  14940. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14941. Exit;
  14942. if (taicpu(p).oper[0]^.typ <> top_const) or
  14943. { If the value can fit into an 8-bit signed integer, a smaller
  14944. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14945. falls within this range }
  14946. (
  14947. (taicpu(p).oper[0]^.val > -128) and
  14948. (taicpu(p).oper[0]^.val <= 127)
  14949. ) then
  14950. Exit;
  14951. { If we're optimising for size, this is acceptable }
  14952. if (cs_opt_size in current_settings.optimizerswitches) then
  14953. Exit(True);
  14954. if (taicpu(p).oper[1]^.typ = top_reg) and
  14955. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14956. Exit(True);
  14957. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14958. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14959. Exit(True);
  14960. end;
  14961. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14962. var
  14963. hp1: tai;
  14964. Value: TCGInt;
  14965. begin
  14966. Result := False;
  14967. if MatchOpType(taicpu(p), top_const, top_reg) then
  14968. begin
  14969. { Detect:
  14970. andw x, %ax (0 <= x < $8000)
  14971. ...
  14972. movzwl %ax,%eax
  14973. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14974. }
  14975. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14976. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14977. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14978. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14979. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14980. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14981. begin
  14982. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14983. taicpu(hp1).opcode := A_CWDE;
  14984. taicpu(hp1).clearop(0);
  14985. taicpu(hp1).clearop(1);
  14986. taicpu(hp1).ops := 0;
  14987. { A change was made, but not with p, so don't set Result, but
  14988. notify the compiler that a change was made }
  14989. Include(OptsToCheck, aoc_ForceNewIteration);
  14990. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14991. end;
  14992. end;
  14993. { If "not x" is a power of 2 (popcnt = 1), change:
  14994. and $x, %reg/ref
  14995. To:
  14996. btr lb(x), %reg/ref
  14997. }
  14998. if IsBTXAcceptable(p) and
  14999. (
  15000. { Make sure a TEST doesn't follow that plays with the register }
  15001. not GetNextInstruction(p, hp1) or
  15002. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15003. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15004. ) then
  15005. begin
  15006. {$push}{$R-}{$Q-}
  15007. { Value is a sign-extended 32-bit integer - just correct it
  15008. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15009. checks to see if this operand is an immediate. }
  15010. Value := not taicpu(p).oper[0]^.val;
  15011. {$pop}
  15012. {$ifdef x86_64}
  15013. if taicpu(p).opsize = S_L then
  15014. {$endif x86_64}
  15015. Value := Value and $FFFFFFFF;
  15016. if (PopCnt(QWord(Value)) = 1) then
  15017. begin
  15018. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15019. taicpu(p).opcode := A_BTR;
  15020. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15021. Result := True;
  15022. Exit;
  15023. end;
  15024. end;
  15025. end;
  15026. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15027. begin
  15028. Result := False;
  15029. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15030. Exit;
  15031. { Convert:
  15032. movswl %ax,%eax -> cwtl
  15033. movslq %eax,%rax -> cdqe
  15034. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15035. refer to the same opcode and depends only on the assembler's
  15036. current operand-size attribute. [Kit]
  15037. }
  15038. with taicpu(p) do
  15039. case opsize of
  15040. S_WL:
  15041. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15042. begin
  15043. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15044. opcode := A_CWDE;
  15045. clearop(0);
  15046. clearop(1);
  15047. ops := 0;
  15048. Result := True;
  15049. end;
  15050. {$ifdef x86_64}
  15051. S_LQ:
  15052. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15053. begin
  15054. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15055. opcode := A_CDQE;
  15056. clearop(0);
  15057. clearop(1);
  15058. ops := 0;
  15059. Result := True;
  15060. end;
  15061. {$endif x86_64}
  15062. else
  15063. ;
  15064. end;
  15065. end;
  15066. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15067. var
  15068. hp1: tai;
  15069. begin
  15070. Result := False;
  15071. { All these optimisations work on "shr const,%reg" }
  15072. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15073. Exit;
  15074. if HandleSHRMerge(p, True) then
  15075. begin
  15076. Result := True;
  15077. Exit;
  15078. end;
  15079. { Detect the following (looking backwards):
  15080. shr %cl,%reg
  15081. shr x, %reg
  15082. Swap the two SHR instructions to minimise a pipeline stall.
  15083. }
  15084. if GetLastInstruction(p, hp1) and
  15085. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15086. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15087. { First operand will be %cl }
  15088. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15089. { Just to be sure }
  15090. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15091. begin
  15092. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15093. { Moving the entries this way ensures the register tracking remains correct }
  15094. Asml.Remove(p);
  15095. Asml.InsertBefore(p, hp1);
  15096. p := hp1;
  15097. { Don't set Result to True because the current instruction is now
  15098. "shr %cl,%reg" and there's nothing more we can do with it }
  15099. end;
  15100. end;
  15101. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15102. var
  15103. hp1, hp2: tai;
  15104. Opposite, SecondOpposite: TAsmOp;
  15105. NewCond: TAsmCond;
  15106. begin
  15107. Result := False;
  15108. { Change:
  15109. add/sub 128,(dest)
  15110. To:
  15111. sub/add -128,(dest)
  15112. This generaally takes fewer bytes to encode because -128 can be stored
  15113. in a signed byte, whereas +128 cannot.
  15114. }
  15115. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15116. begin
  15117. if taicpu(p).opcode = A_ADD then
  15118. Opposite := A_SUB
  15119. else
  15120. Opposite := A_ADD;
  15121. { Be careful if the flags are in use, because the CF flag inverts
  15122. when changing from ADD to SUB and vice versa }
  15123. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15124. GetNextInstruction(p, hp1) then
  15125. begin
  15126. TransferUsedRegs(TmpUsedRegs);
  15127. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15128. hp2 := hp1;
  15129. { Scan ahead to check if everything's safe }
  15130. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15131. begin
  15132. if (hp1.typ <> ait_instruction) then
  15133. { Probably unsafe since the flags are still in use }
  15134. Exit;
  15135. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15136. { Stop searching at an unconditional jump }
  15137. Break;
  15138. if not
  15139. (
  15140. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15141. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15142. ) and
  15143. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15144. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15145. Exit;
  15146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15147. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15148. { Move to the next instruction }
  15149. GetNextInstruction(hp1, hp1);
  15150. end;
  15151. while Assigned(hp2) and (hp2 <> hp1) do
  15152. begin
  15153. NewCond := C_None;
  15154. case taicpu(hp2).condition of
  15155. C_A, C_NBE:
  15156. NewCond := C_BE;
  15157. C_B, C_C, C_NAE:
  15158. NewCond := C_AE;
  15159. C_AE, C_NB, C_NC:
  15160. NewCond := C_B;
  15161. C_BE, C_NA:
  15162. NewCond := C_A;
  15163. else
  15164. { No change needed };
  15165. end;
  15166. if NewCond <> C_None then
  15167. begin
  15168. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15169. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15170. taicpu(hp2).condition := NewCond;
  15171. end
  15172. else
  15173. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15174. begin
  15175. { Because of the flipping of the carry bit, to ensure
  15176. the operation remains equivalent, ADC becomes SBB
  15177. and vice versa, and the constant is not-inverted.
  15178. If multiple ADCs or SBBs appear in a row, each one
  15179. changed causes the carry bit to invert, so they all
  15180. need to be flipped }
  15181. if taicpu(hp2).opcode = A_ADC then
  15182. SecondOpposite := A_SBB
  15183. else
  15184. SecondOpposite := A_ADC;
  15185. if taicpu(hp2).oper[0]^.typ <> top_const then
  15186. { Should have broken out of this optimisation already }
  15187. InternalError(2021112901);
  15188. 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]^) + ' -> ' +
  15189. 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);
  15190. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15191. taicpu(hp2).opcode := SecondOpposite;
  15192. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15193. end;
  15194. { Move to the next instruction }
  15195. GetNextInstruction(hp2, hp2);
  15196. end;
  15197. if (hp2 <> hp1) then
  15198. InternalError(2021111501);
  15199. end;
  15200. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15201. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15202. taicpu(p).opcode := Opposite;
  15203. taicpu(p).oper[0]^.val := -128;
  15204. { No further optimisations can be made on this instruction, so move
  15205. onto the next one to save time }
  15206. p := tai(p.Next);
  15207. UpdateUsedRegs(p);
  15208. Result := True;
  15209. Exit;
  15210. end;
  15211. { Detect:
  15212. add/sub %reg2,(dest)
  15213. add/sub x, (dest)
  15214. (dest can be a register or a reference)
  15215. Swap the instructions to minimise a pipeline stall. This reverses the
  15216. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15217. optimisations could be made.
  15218. }
  15219. if (taicpu(p).oper[0]^.typ = top_reg) and
  15220. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15221. (
  15222. (
  15223. (taicpu(p).oper[1]^.typ = top_reg) and
  15224. { We can try searching further ahead if we're writing to a register }
  15225. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15226. ) or
  15227. (
  15228. (taicpu(p).oper[1]^.typ = top_ref) and
  15229. GetNextInstruction(p, hp1)
  15230. )
  15231. ) and
  15232. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15233. (taicpu(hp1).oper[0]^.typ = top_const) and
  15234. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15235. begin
  15236. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15237. TransferUsedRegs(TmpUsedRegs);
  15238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15239. hp2 := p;
  15240. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15241. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15242. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15243. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15244. begin
  15245. asml.remove(hp1);
  15246. asml.InsertBefore(hp1, p);
  15247. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15248. Result := True;
  15249. end;
  15250. end;
  15251. end;
  15252. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15253. var
  15254. hp1: tai;
  15255. begin
  15256. Result:=false;
  15257. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15258. while GetNextInstruction(p, hp1) and
  15259. TrySwapMovCmp(p, hp1) do
  15260. begin
  15261. if MatchInstruction(hp1, A_MOV, []) then
  15262. begin
  15263. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15264. begin
  15265. { A little hacky, but since CMP doesn't read the flags, only
  15266. modify them, it's safe if they get scrambled by MOV -> XOR }
  15267. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15268. Result := PostPeepholeOptMov(hp1);
  15269. {$ifdef x86_64}
  15270. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15271. { Used to shrink instruction size }
  15272. PostPeepholeOptXor(hp1);
  15273. {$endif x86_64}
  15274. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15275. end
  15276. else
  15277. begin
  15278. Result := PostPeepholeOptMov(hp1);
  15279. {$ifdef x86_64}
  15280. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15281. { Used to shrink instruction size }
  15282. PostPeepholeOptXor(hp1);
  15283. {$endif x86_64}
  15284. end;
  15285. end;
  15286. { Enabling this flag is actually a null operation, but it marks
  15287. the code as 'modified' during this pass }
  15288. Include(OptsToCheck, aoc_ForceNewIteration);
  15289. end;
  15290. { change "cmp $0, %reg" to "test %reg, %reg" }
  15291. if MatchOpType(taicpu(p),top_const,top_reg) and
  15292. (taicpu(p).oper[0]^.val = 0) then
  15293. begin
  15294. taicpu(p).opcode := A_TEST;
  15295. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15296. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15297. Result:=true;
  15298. end;
  15299. end;
  15300. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15301. var
  15302. IsTestConstX, IsValid : Boolean;
  15303. hp1,hp2 : tai;
  15304. begin
  15305. Result:=false;
  15306. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15307. if (taicpu(p).opcode = A_TEST) then
  15308. while GetNextInstruction(p, hp1) and
  15309. TrySwapMovCmp(p, hp1) do
  15310. begin
  15311. if MatchInstruction(hp1, A_MOV, []) then
  15312. begin
  15313. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15314. begin
  15315. { A little hacky, but since TEST doesn't read the flags, only
  15316. modify them, it's safe if they get scrambled by MOV -> XOR }
  15317. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15318. Result := PostPeepholeOptMov(hp1);
  15319. {$ifdef x86_64}
  15320. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15321. { Used to shrink instruction size }
  15322. PostPeepholeOptXor(hp1);
  15323. {$endif x86_64}
  15324. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15325. end
  15326. else
  15327. begin
  15328. Result := PostPeepholeOptMov(hp1);
  15329. {$ifdef x86_64}
  15330. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15331. { Used to shrink instruction size }
  15332. PostPeepholeOptXor(hp1);
  15333. {$endif x86_64}
  15334. end;
  15335. end;
  15336. { Enabling this flag is actually a null operation, but it marks
  15337. the code as 'modified' during this pass }
  15338. Include(OptsToCheck, aoc_ForceNewIteration);
  15339. end;
  15340. { If x is a power of 2 (popcnt = 1), change:
  15341. or $x, %reg/ref
  15342. To:
  15343. bts lb(x), %reg/ref
  15344. }
  15345. if (taicpu(p).opcode = A_OR) and
  15346. IsBTXAcceptable(p) and
  15347. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15348. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15349. (
  15350. { Don't optimise if a test instruction follows }
  15351. not GetNextInstruction(p, hp1) or
  15352. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15353. ) then
  15354. begin
  15355. 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);
  15356. taicpu(p).opcode := A_BTS;
  15357. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15358. Result := True;
  15359. Exit;
  15360. end;
  15361. { If x is a power of 2 (popcnt = 1), change:
  15362. test $x, %reg/ref
  15363. je / sete / cmove (or jne / setne)
  15364. To:
  15365. bt lb(x), %reg/ref
  15366. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15367. }
  15368. if (taicpu(p).opcode = A_TEST) and
  15369. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15370. (taicpu(p).oper[0]^.typ = top_const) and
  15371. (
  15372. (cs_opt_size in current_settings.optimizerswitches) or
  15373. (
  15374. (taicpu(p).oper[1]^.typ = top_reg) and
  15375. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15376. ) or
  15377. (
  15378. (taicpu(p).oper[1]^.typ <> top_reg) and
  15379. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15380. )
  15381. ) and
  15382. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15383. { For sizes less than S_L, the byte size is equal or larger with BT,
  15384. so don't bother optimising }
  15385. (taicpu(p).opsize >= S_L) then
  15386. begin
  15387. IsValid := True;
  15388. { Check the next set of instructions, watching the FLAGS register
  15389. and the conditions used }
  15390. TransferUsedRegs(TmpUsedRegs);
  15391. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15392. hp1 := p;
  15393. hp2 := nil;
  15394. while GetNextInstruction(hp1, hp1) do
  15395. begin
  15396. if not Assigned(hp2) then
  15397. { The first instruction after TEST }
  15398. hp2 := hp1;
  15399. if (hp1.typ <> ait_instruction) then
  15400. begin
  15401. { If the flags are no longer in use, everything is fine }
  15402. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15403. IsValid := False;
  15404. Break;
  15405. end;
  15406. case taicpu(hp1).condition of
  15407. C_None:
  15408. begin
  15409. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15410. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15411. { Something is not quite normal, so play safe and don't change }
  15412. IsValid := False;
  15413. Break;
  15414. end;
  15415. C_E, C_Z, C_NE, C_NZ:
  15416. { This is fine };
  15417. else
  15418. begin
  15419. { Unsupported condition }
  15420. IsValid := False;
  15421. Break;
  15422. end;
  15423. end;
  15424. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15425. end;
  15426. if IsValid then
  15427. begin
  15428. while hp2 <> hp1 do
  15429. begin
  15430. case taicpu(hp2).condition of
  15431. C_Z, C_E:
  15432. taicpu(hp2).condition := C_NC;
  15433. C_NZ, C_NE:
  15434. taicpu(hp2).condition := C_C;
  15435. else
  15436. { Should not get this by this point }
  15437. InternalError(2022110701);
  15438. end;
  15439. GetNextInstruction(hp2, hp2);
  15440. end;
  15441. 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);
  15442. taicpu(p).opcode := A_BT;
  15443. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15444. Result := True;
  15445. Exit;
  15446. end;
  15447. end;
  15448. { removes the line marked with (x) from the sequence
  15449. and/or/xor/add/sub/... $x, %y
  15450. test/or %y, %y | test $-1, %y (x)
  15451. j(n)z _Label
  15452. as the first instruction already adjusts the ZF
  15453. %y operand may also be a reference }
  15454. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15455. MatchOperand(taicpu(p).oper[0]^,-1);
  15456. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15457. GetLastInstruction(p, hp1) and
  15458. (tai(hp1).typ = ait_instruction) and
  15459. GetNextInstruction(p,hp2) and
  15460. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15461. case taicpu(hp1).opcode Of
  15462. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15463. { These two instructions set the zero flag if the result is zero }
  15464. A_POPCNT, A_LZCNT:
  15465. begin
  15466. if (
  15467. { With POPCNT, an input of zero will set the zero flag
  15468. because the population count of zero is zero }
  15469. (taicpu(hp1).opcode = A_POPCNT) and
  15470. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15471. (
  15472. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15473. { Faster than going through the second half of the 'or'
  15474. condition below }
  15475. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15476. )
  15477. ) or (
  15478. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15479. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15480. { and in case of carry for A(E)/B(E)/C/NC }
  15481. (
  15482. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15483. (
  15484. (taicpu(hp1).opcode <> A_ADD) and
  15485. (taicpu(hp1).opcode <> A_SUB) and
  15486. (taicpu(hp1).opcode <> A_LZCNT)
  15487. )
  15488. )
  15489. ) then
  15490. begin
  15491. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15492. RemoveCurrentP(p, hp2);
  15493. Result:=true;
  15494. Exit;
  15495. end;
  15496. end;
  15497. A_SHL, A_SAL, A_SHR, A_SAR:
  15498. begin
  15499. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15500. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15501. { therefore, it's only safe to do this optimization for }
  15502. { shifts by a (nonzero) constant }
  15503. (taicpu(hp1).oper[0]^.typ = top_const) and
  15504. (taicpu(hp1).oper[0]^.val <> 0) and
  15505. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15506. { and in case of carry for A(E)/B(E)/C/NC }
  15507. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15508. begin
  15509. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15510. RemoveCurrentP(p, hp2);
  15511. Result:=true;
  15512. Exit;
  15513. end;
  15514. end;
  15515. A_DEC, A_INC, A_NEG:
  15516. begin
  15517. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15518. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15519. { and in case of carry for A(E)/B(E)/C/NC }
  15520. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15521. begin
  15522. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15523. RemoveCurrentP(p, hp2);
  15524. Result:=true;
  15525. Exit;
  15526. end;
  15527. end;
  15528. A_ANDN, A_BZHI:
  15529. begin
  15530. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15531. { Only the zero and sign flags are consistent with what the result is }
  15532. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15533. begin
  15534. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15535. RemoveCurrentP(p, hp2);
  15536. Result:=true;
  15537. Exit;
  15538. end;
  15539. end;
  15540. A_BEXTR:
  15541. begin
  15542. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15543. { Only the zero flag is set }
  15544. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15545. begin
  15546. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15547. RemoveCurrentP(p, hp2);
  15548. Result:=true;
  15549. Exit;
  15550. end;
  15551. end;
  15552. else
  15553. ;
  15554. end; { case }
  15555. { change "test $-1,%reg" into "test %reg,%reg" }
  15556. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15557. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15558. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15559. if MatchInstruction(p, A_OR, []) and
  15560. { Can only match if they're both registers }
  15561. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15562. begin
  15563. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15564. taicpu(p).opcode := A_TEST;
  15565. { No need to set Result to True, as we've done all the optimisations we can }
  15566. end;
  15567. end;
  15568. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15569. var
  15570. hp1,hp3 : tai;
  15571. {$ifndef x86_64}
  15572. hp2 : taicpu;
  15573. {$endif x86_64}
  15574. begin
  15575. Result:=false;
  15576. hp3:=nil;
  15577. {$ifndef x86_64}
  15578. { don't do this on modern CPUs, this really hurts them due to
  15579. broken call/ret pairing }
  15580. if (current_settings.optimizecputype < cpu_Pentium2) and
  15581. not(cs_create_pic in current_settings.moduleswitches) and
  15582. GetNextInstruction(p, hp1) and
  15583. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15584. MatchOpType(taicpu(hp1),top_ref) and
  15585. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15586. begin
  15587. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15588. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15589. InsertLLItem(p.previous, p, hp2);
  15590. taicpu(p).opcode := A_JMP;
  15591. taicpu(p).is_jmp := true;
  15592. RemoveInstruction(hp1);
  15593. Result:=true;
  15594. end
  15595. else
  15596. {$endif x86_64}
  15597. { replace
  15598. call procname
  15599. ret
  15600. by
  15601. jmp procname
  15602. but do it only on level 4 because it destroys stack back traces
  15603. else if the subroutine is marked as no return, remove the ret
  15604. }
  15605. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15606. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15607. GetNextInstruction(p, hp1) and
  15608. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15609. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15610. SetAndTest(hp1,hp3) and
  15611. GetNextInstruction(hp1,hp1) and
  15612. MatchInstruction(hp1,A_RET,[S_NO])
  15613. )
  15614. ) and
  15615. (taicpu(hp1).ops=0) then
  15616. begin
  15617. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15618. { we might destroy stack alignment here if we do not do a call }
  15619. (target_info.stackalign<=sizeof(SizeUInt)) then
  15620. begin
  15621. taicpu(p).opcode := A_JMP;
  15622. taicpu(p).is_jmp := true;
  15623. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15624. end
  15625. else
  15626. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15627. RemoveInstruction(hp1);
  15628. if Assigned(hp3) then
  15629. begin
  15630. AsmL.Remove(hp3);
  15631. AsmL.InsertBefore(hp3,p)
  15632. end;
  15633. Result:=true;
  15634. end;
  15635. end;
  15636. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15637. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15638. begin
  15639. case OpSize of
  15640. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15641. Result := (Val <= $FF) and (Val >= -128);
  15642. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15643. Result := (Val <= $FFFF) and (Val >= -32768);
  15644. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15645. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15646. else
  15647. Result := True;
  15648. end;
  15649. end;
  15650. var
  15651. hp1, hp2 : tai;
  15652. SizeChange: Boolean;
  15653. PreMessage: string;
  15654. begin
  15655. Result := False;
  15656. if (taicpu(p).oper[0]^.typ = top_reg) and
  15657. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15658. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15659. begin
  15660. { Change (using movzbl %al,%eax as an example):
  15661. movzbl %al, %eax movzbl %al, %eax
  15662. cmpl x, %eax testl %eax,%eax
  15663. To:
  15664. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15665. movzbl %al, %eax movzbl %al, %eax
  15666. Smaller instruction and minimises pipeline stall as the CPU
  15667. doesn't have to wait for the register to get zero-extended. [Kit]
  15668. Also allow if the smaller of the two registers is being checked,
  15669. as this still removes the false dependency.
  15670. }
  15671. if
  15672. (
  15673. (
  15674. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15675. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15676. ) or (
  15677. { If MatchOperand returns True, they must both be registers }
  15678. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15679. )
  15680. ) and
  15681. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15682. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15683. begin
  15684. 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);
  15685. asml.Remove(hp1);
  15686. asml.InsertBefore(hp1, p);
  15687. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15688. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15689. begin
  15690. taicpu(hp1).opcode := A_TEST;
  15691. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15692. end;
  15693. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15694. case taicpu(p).opsize of
  15695. S_BW, S_BL:
  15696. begin
  15697. SizeChange := taicpu(hp1).opsize <> S_B;
  15698. taicpu(hp1).changeopsize(S_B);
  15699. end;
  15700. S_WL:
  15701. begin
  15702. SizeChange := taicpu(hp1).opsize <> S_W;
  15703. taicpu(hp1).changeopsize(S_W);
  15704. end
  15705. else
  15706. InternalError(2020112701);
  15707. end;
  15708. UpdateUsedRegs(tai(p.Next));
  15709. { Check if the register is used aferwards - if not, we can
  15710. remove the movzx instruction completely }
  15711. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15712. begin
  15713. { Hp1 is a better position than p for debugging purposes }
  15714. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15715. RemoveCurrentp(p, hp1);
  15716. Result := True;
  15717. end;
  15718. if SizeChange then
  15719. DebugMsg(SPeepholeOptimization + PreMessage +
  15720. 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)
  15721. else
  15722. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15723. Exit;
  15724. end;
  15725. { Change (using movzwl %ax,%eax as an example):
  15726. movzwl %ax, %eax
  15727. movb %al, (dest) (Register is smaller than read register in movz)
  15728. To:
  15729. movb %al, (dest) (Move one back to avoid a false dependency)
  15730. movzwl %ax, %eax
  15731. }
  15732. if (taicpu(hp1).opcode = A_MOV) and
  15733. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15734. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15735. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15736. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15737. begin
  15738. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15739. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15740. asml.Remove(hp1);
  15741. asml.InsertBefore(hp1, p);
  15742. if taicpu(hp1).oper[1]^.typ = top_reg then
  15743. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15744. { Check if the register is used aferwards - if not, we can
  15745. remove the movzx instruction completely }
  15746. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15747. begin
  15748. { Hp1 is a better position than p for debugging purposes }
  15749. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15750. RemoveCurrentp(p, hp1);
  15751. Result := True;
  15752. end;
  15753. Exit;
  15754. end;
  15755. end;
  15756. end;
  15757. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15758. var
  15759. hp1: tai;
  15760. {$ifdef x86_64}
  15761. PreMessage, RegName: string;
  15762. {$endif x86_64}
  15763. begin
  15764. Result := False;
  15765. { If x is a power of 2 (popcnt = 1), change:
  15766. xor $x, %reg/ref
  15767. To:
  15768. btc lb(x), %reg/ref
  15769. }
  15770. if IsBTXAcceptable(p) and
  15771. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15772. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15773. (
  15774. { Don't optimise if a test instruction follows }
  15775. not GetNextInstruction(p, hp1) or
  15776. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15777. ) then
  15778. begin
  15779. 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);
  15780. taicpu(p).opcode := A_BTC;
  15781. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15782. Result := True;
  15783. Exit;
  15784. end;
  15785. {$ifdef x86_64}
  15786. { Code size reduction by J. Gareth "Kit" Moreton }
  15787. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15788. as this removes the REX prefix }
  15789. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15790. Exit;
  15791. if taicpu(p).oper[0]^.typ <> top_reg then
  15792. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15793. InternalError(2018011500);
  15794. case taicpu(p).opsize of
  15795. S_Q:
  15796. begin
  15797. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15798. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15799. { The actual optimization }
  15800. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15801. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15802. taicpu(p).changeopsize(S_L);
  15803. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15804. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15805. end;
  15806. else
  15807. ;
  15808. end;
  15809. {$endif x86_64}
  15810. end;
  15811. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15812. var
  15813. XReg: TRegister;
  15814. begin
  15815. Result := False;
  15816. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15817. Smaller encoding and slightly faster on some platforms (also works for
  15818. ZMM-sized registers) }
  15819. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15820. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15821. begin
  15822. XReg := taicpu(p).oper[0]^.reg;
  15823. if (taicpu(p).oper[1]^.reg = XReg) then
  15824. begin
  15825. taicpu(p).changeopsize(S_XMM);
  15826. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15827. if (cs_opt_size in current_settings.optimizerswitches) then
  15828. begin
  15829. { Change input registers to %xmm0 to reduce size. Note that
  15830. there's a risk of a false dependency doing this, so only
  15831. optimise for size here }
  15832. XReg := NR_XMM0;
  15833. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15834. end
  15835. else
  15836. begin
  15837. setsubreg(XReg, R_SUBMMX);
  15838. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15839. end;
  15840. taicpu(p).oper[0]^.reg := XReg;
  15841. taicpu(p).oper[1]^.reg := XReg;
  15842. Result := True;
  15843. end;
  15844. end;
  15845. end;
  15846. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15847. var
  15848. hp1, p_new: tai;
  15849. begin
  15850. Result := False;
  15851. { Check for:
  15852. ret
  15853. .Lbl:
  15854. ret
  15855. Remove first 'ret'
  15856. }
  15857. if GetNextInstruction(p, hp1) and
  15858. { Remember where the label is }
  15859. SetAndTest(hp1, p_new) and
  15860. (hp1.typ in [ait_align, ait_label]) and
  15861. SkipLabels(hp1, hp1) and
  15862. MatchInstruction(hp1, A_RET, []) and
  15863. { To be safe, make sure the RET instructions are identical }
  15864. (taicpu(p).ops = taicpu(hp1).ops) and
  15865. (
  15866. (taicpu(p).ops = 0) or
  15867. (
  15868. (taicpu(p).ops = 1) and
  15869. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15870. )
  15871. ) then
  15872. begin
  15873. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15874. UpdateUsedRegs(tai(p.Next));
  15875. RemoveCurrentP(p, p_new);
  15876. Result := True;
  15877. Exit;
  15878. end;
  15879. end;
  15880. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15881. var
  15882. OperIdx: Integer;
  15883. begin
  15884. for OperIdx := 0 to p.ops - 1 do
  15885. if p.oper[OperIdx]^.typ = top_ref then
  15886. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15887. end;
  15888. end.