aoptx86.pas 702 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass2Movx(var p : tai): Boolean;
  147. function OptPass2MOV(var p : tai) : boolean;
  148. function OptPass2Imul(var p : tai) : boolean;
  149. function OptPass2Jmp(var p : tai) : boolean;
  150. function OptPass2Jcc(var p : tai) : boolean;
  151. function OptPass2Lea(var p: tai): Boolean;
  152. function OptPass2SUB(var p: tai): Boolean;
  153. function OptPass2ADD(var p : tai): Boolean;
  154. function OptPass2SETcc(var p : tai) : boolean;
  155. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  156. function PostPeepholeOptMov(var p : tai) : Boolean;
  157. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  158. function PostPeepholeOptXor(var p : tai) : Boolean;
  159. function PostPeepholeOptAnd(var p : tai) : boolean;
  160. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  161. function PostPeepholeOptCmp(var p : tai) : Boolean;
  162. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  163. function PostPeepholeOptCall(var p : tai) : Boolean;
  164. function PostPeepholeOptLea(var p : tai) : Boolean;
  165. function PostPeepholeOptPush(var p: tai): Boolean;
  166. function PostPeepholeOptShr(var p : tai) : boolean;
  167. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  168. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  169. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  170. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  171. function TrySwapMovOp(var p, hp1: tai): Boolean;
  172. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  173. { Processor-dependent reference optimisation }
  174. class procedure OptimizeRefs(var p: taicpu); static;
  175. end;
  176. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  179. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  180. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  181. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  182. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  183. {$if max_operands>2}
  184. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  185. {$endif max_operands>2}
  186. function RefsEqual(const r1, r2: treference): boolean;
  187. { Note that Result is set to True if the references COULD overlap but the
  188. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  189. might still overlap because %reg2 could be equal to %reg1-4 }
  190. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  191. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  192. { returns true, if ref is a reference using only the registers passed as base and index
  193. and having an offset }
  194. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  195. implementation
  196. uses
  197. cutils,verbose,
  198. systems,
  199. globals,
  200. cpuinfo,
  201. procinfo,
  202. paramgr,
  203. aasmbase,
  204. aoptbase,aoptutils,
  205. symconst,symsym,
  206. cgx86,
  207. itcpugas;
  208. {$ifdef DEBUG_AOPTCPU}
  209. const
  210. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  211. {$else DEBUG_AOPTCPU}
  212. { Empty strings help the optimizer to remove string concatenations that won't
  213. ever appear to the user on release builds. [Kit] }
  214. const
  215. SPeepholeOptimization = '';
  216. {$endif DEBUG_AOPTCPU}
  217. LIST_STEP_SIZE = 4;
  218. {$ifndef 8086}
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. {$endif 8086}
  222. type
  223. TJumpTrackingItem = class(TLinkedListItem)
  224. private
  225. FSymbol: TAsmSymbol;
  226. FRefs: LongInt;
  227. public
  228. constructor Create(ASymbol: TAsmSymbol);
  229. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  230. property Symbol: TAsmSymbol read FSymbol;
  231. property Refs: LongInt read FRefs;
  232. end;
  233. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  234. begin
  235. inherited Create;
  236. FSymbol := ASymbol;
  237. FRefs := 0;
  238. end;
  239. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  240. begin
  241. Inc(FRefs);
  242. end;
  243. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  244. begin
  245. result :=
  246. (instr.typ = ait_instruction) and
  247. (taicpu(instr).opcode = op) and
  248. ((opsize = []) or (taicpu(instr).opsize in opsize));
  249. end;
  250. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  251. begin
  252. result :=
  253. (instr.typ = ait_instruction) and
  254. ((taicpu(instr).opcode = op1) or
  255. (taicpu(instr).opcode = op2)
  256. ) and
  257. ((opsize = []) or (taicpu(instr).opsize in opsize));
  258. end;
  259. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  260. begin
  261. result :=
  262. (instr.typ = ait_instruction) and
  263. ((taicpu(instr).opcode = op1) or
  264. (taicpu(instr).opcode = op2) or
  265. (taicpu(instr).opcode = op3)
  266. ) and
  267. ((opsize = []) or (taicpu(instr).opsize in opsize));
  268. end;
  269. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  270. const opsize : topsizes) : boolean;
  271. var
  272. op : TAsmOp;
  273. begin
  274. result:=false;
  275. if (instr.typ <> ait_instruction) or
  276. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  277. exit;
  278. for op in ops do
  279. begin
  280. if taicpu(instr).opcode = op then
  281. begin
  282. result:=true;
  283. exit;
  284. end;
  285. end;
  286. end;
  287. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  288. begin
  289. result := (oper.typ = top_reg) and (oper.reg = reg);
  290. end;
  291. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  292. begin
  293. result := (oper.typ = top_const) and (oper.val = a);
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  296. begin
  297. result := oper1.typ = oper2.typ;
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=oper1.val = oper2.val;
  302. top_reg:
  303. Result:=oper1.reg = oper2.reg;
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  306. else
  307. internalerror(2013102801);
  308. end
  309. end;
  310. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  311. begin
  312. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  313. if result then
  314. case oper1.typ of
  315. top_const:
  316. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  317. top_reg:
  318. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  319. top_ref:
  320. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  321. else
  322. internalerror(2020052401);
  323. end
  324. end;
  325. function RefsEqual(const r1, r2: treference): boolean;
  326. begin
  327. RefsEqual :=
  328. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  329. (r1.relsymbol = r2.relsymbol) and
  330. (r1.segment = r2.segment) and (r1.base = r2.base) and
  331. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  332. (r1.offset = r2.offset) and
  333. (r1.volatility + r2.volatility = []);
  334. end;
  335. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  336. begin
  337. if (r1.symbol<>r2.symbol) then
  338. { If the index registers are different, there's a chance one could
  339. be set so it equals the other symbol }
  340. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  341. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  342. (r1.relsymbol = r2.relsymbol) and
  343. (r1.segment = r2.segment) and (r1.base = r2.base) and
  344. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  345. (r1.volatility + r2.volatility = []) then
  346. { In this case, it all depends on the offsets }
  347. Exit(abs(r1.offset - r2.offset) < Range);
  348. { There's a chance things MIGHT overlap, so take no chances }
  349. Result := True;
  350. end;
  351. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  352. begin
  353. Result:=(ref.offset=0) and
  354. (ref.scalefactor in [0,1]) and
  355. (ref.segment=NR_NO) and
  356. (ref.symbol=nil) and
  357. (ref.relsymbol=nil) and
  358. ((base=NR_INVALID) or
  359. (ref.base=base)) and
  360. ((index=NR_INVALID) or
  361. (ref.index=index)) and
  362. (ref.volatility=[]);
  363. end;
  364. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  365. begin
  366. Result:=(ref.scalefactor in [0,1]) and
  367. (ref.segment=NR_NO) and
  368. (ref.symbol=nil) and
  369. (ref.relsymbol=nil) and
  370. ((base=NR_INVALID) or
  371. (ref.base=base)) and
  372. ((index=NR_INVALID) or
  373. (ref.index=index)) and
  374. (ref.volatility=[]);
  375. end;
  376. function InstrReadsFlags(p: tai): boolean;
  377. begin
  378. InstrReadsFlags := true;
  379. case p.typ of
  380. ait_instruction:
  381. if InsProp[taicpu(p).opcode].Ch*
  382. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  383. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  384. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  385. exit;
  386. ait_label:
  387. exit;
  388. else
  389. ;
  390. end;
  391. InstrReadsFlags := false;
  392. end;
  393. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  394. begin
  395. Next:=Current;
  396. repeat
  397. Result:=GetNextInstruction(Next,Next);
  398. until not (Result) or
  399. not(cs_opt_level3 in current_settings.optimizerswitches) or
  400. (Next.typ<>ait_instruction) or
  401. RegInInstruction(reg,Next) or
  402. is_calljmp(taicpu(Next).opcode);
  403. end;
  404. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  405. var
  406. GetNextResult: Boolean;
  407. begin
  408. Result:=0;
  409. Next:=Current;
  410. repeat
  411. GetNextResult := GetNextInstruction(Next,Next);
  412. if GetNextResult then
  413. Inc(Result)
  414. else
  415. { Must return zero upon hitting the end of the linked list without a match }
  416. Result := 0;
  417. until not (GetNextResult) or
  418. not(cs_opt_level3 in current_settings.optimizerswitches) or
  419. (Next.typ<>ait_instruction) or
  420. RegInInstruction(reg,Next) or
  421. is_calljmp(taicpu(Next).opcode);
  422. end;
  423. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  424. procedure TrackJump(Symbol: TAsmSymbol);
  425. var
  426. Search: TJumpTrackingItem;
  427. begin
  428. { See if an entry already exists in our jump tracking list
  429. (faster to search backwards due to the higher chance of
  430. matching destinations) }
  431. Search := TJumpTrackingItem(JumpTracking.Last);
  432. while Assigned(Search) do
  433. begin
  434. if Search.Symbol = Symbol then
  435. begin
  436. { Found it - remove it so it can be pushed to the front }
  437. JumpTracking.Remove(Search);
  438. Break;
  439. end;
  440. Search := TJumpTrackingItem(Search.Previous);
  441. end;
  442. if not Assigned(Search) then
  443. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  444. JumpTracking.Concat(Search);
  445. Search.IncRefs;
  446. end;
  447. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  448. var
  449. Search: TJumpTrackingItem;
  450. begin
  451. Result := False;
  452. { See if this label appears in the tracking list }
  453. Search := TJumpTrackingItem(JumpTracking.Last);
  454. while Assigned(Search) do
  455. begin
  456. if Search.Symbol = Symbol then
  457. begin
  458. { Found it - let's see what we can discover }
  459. if Search.Symbol.getrefs = Search.Refs then
  460. begin
  461. { Success - all the references are accounted for }
  462. JumpTracking.Remove(Search);
  463. Search.Free;
  464. { It is logically impossible for CrossJump to be false here
  465. because we must have run into a conditional jump for
  466. this label at some point }
  467. if not CrossJump then
  468. InternalError(2022041710);
  469. if JumpTracking.First = nil then
  470. { Tracking list is now empty - no more cross jumps }
  471. CrossJump := False;
  472. Result := True;
  473. Exit;
  474. end;
  475. { If the references don't match, it's possible to enter
  476. this label through other means, so drop out }
  477. Exit;
  478. end;
  479. Search := TJumpTrackingItem(Search.Previous);
  480. end;
  481. end;
  482. var
  483. Next_Label: tai;
  484. begin
  485. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  486. Next := Current;
  487. repeat
  488. Result := GetNextInstruction(Next,Next);
  489. if not Result then
  490. Break;
  491. if Next.typ = ait_align then
  492. Result := SkipAligns(Next, Next);
  493. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  494. if is_calljmpuncondret(taicpu(Next).opcode) then
  495. begin
  496. if (taicpu(Next).opcode = A_JMP) and
  497. { Remove dead code now to save time }
  498. RemoveDeadCodeAfterJump(taicpu(Next)) then
  499. { A jump was removed, but not the current instruction, and
  500. Result doesn't necessarily translate into an optimisation
  501. routine's Result, so use the "Force New Iteration" flag so
  502. mark a new pass }
  503. Include(OptsToCheck, aoc_ForceNewIteration);
  504. if not Assigned(JumpTracking) then
  505. begin
  506. { Cross-label optimisations often causes other optimisations
  507. to perform worse because they're not given the chance to
  508. optimise locally. In this case, don't do the cross-label
  509. optimisations yet, but flag them as a potential possibility
  510. for the next iteration of Pass 1 }
  511. if not NotFirstIteration then
  512. Include(OptsToCheck, aoc_ForceNewIteration);
  513. end
  514. else if IsJumpToLabel(taicpu(Next)) and
  515. GetNextInstruction(Next, Next_Label) and
  516. SkipAligns(Next_Label, Next_Label) then
  517. begin
  518. { If we have JMP .lbl, and the label after it has all of its
  519. references tracked, then this is probably an if-else style of
  520. block and we can keep tracking. If the label for this jump
  521. then appears later and is fully tracked, then it's the end
  522. of the if-else blocks and the code paths converge (thus
  523. marking the end of the cross-jump) }
  524. if (Next_Label.typ = ait_label) then
  525. begin
  526. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  527. begin
  528. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  529. Next := Next_Label;
  530. { CrossJump gets set to false by LabelAccountedFor if the
  531. list is completely emptied (as it indicates that all
  532. code paths have converged). We could avoid this nuance
  533. by moving the TrackJump call to before the
  534. LabelAccountedFor call, but this is slower in situations
  535. where LabelAccountedFor would return False due to the
  536. creation of a new object that is not used and destroyed
  537. soon after. }
  538. CrossJump := True;
  539. Continue;
  540. end;
  541. end
  542. else if (Next_Label.typ <> ait_marker) then
  543. { We just did a RemoveDeadCodeAfterJump, so either we find
  544. a label, the end of the procedure or some kind of marker}
  545. InternalError(2022041720);
  546. end;
  547. Result := False;
  548. Exit;
  549. end
  550. else
  551. begin
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) then
  563. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  564. else
  565. { Conditional jumps should always be a jump to label }
  566. InternalError(2022041701);
  567. CrossJump := True;
  568. Continue;
  569. end;
  570. if Next.typ = ait_label then
  571. begin
  572. if not Assigned(JumpTracking) then
  573. begin
  574. { Cross-label optimisations often causes other optimisations
  575. to perform worse because they're not given the chance to
  576. optimise locally. In this case, don't do the cross-label
  577. optimisations yet, but flag them as a potential possibility
  578. for the next iteration of Pass 1 }
  579. if not NotFirstIteration then
  580. Include(OptsToCheck, aoc_ForceNewIteration);
  581. end
  582. else if LabelAccountedFor(tai_label(Next).labsym) then
  583. Continue;
  584. { If we reach here, we're at a label that hasn't been seen before
  585. (or JumpTracking was nil) }
  586. Break;
  587. end;
  588. until not Result or
  589. not (cs_opt_level3 in current_settings.optimizerswitches) or
  590. not (Next.typ in [ait_label, ait_instruction]) or
  591. RegInInstruction(reg,Next);
  592. end;
  593. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  594. begin
  595. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  596. begin
  597. Result:=GetNextInstruction(Current,Next);
  598. exit;
  599. end;
  600. Next:=tai(Current.Next);
  601. Result:=false;
  602. while assigned(Next) do
  603. begin
  604. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  605. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  606. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  607. exit
  608. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  609. begin
  610. Result:=true;
  611. exit;
  612. end;
  613. Next:=tai(Next.Next);
  614. end;
  615. end;
  616. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  617. begin
  618. Result:=RegReadByInstruction(reg,hp);
  619. end;
  620. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  621. var
  622. p: taicpu;
  623. opcount: longint;
  624. begin
  625. RegReadByInstruction := false;
  626. if hp.typ <> ait_instruction then
  627. exit;
  628. p := taicpu(hp);
  629. case p.opcode of
  630. A_CALL:
  631. regreadbyinstruction := true;
  632. A_IMUL:
  633. case p.ops of
  634. 1:
  635. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  636. (
  637. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  638. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  639. );
  640. 2,3:
  641. regReadByInstruction :=
  642. reginop(reg,p.oper[0]^) or
  643. reginop(reg,p.oper[1]^);
  644. else
  645. InternalError(2019112801);
  646. end;
  647. A_MUL:
  648. begin
  649. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  650. (
  651. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  652. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  653. );
  654. end;
  655. A_IDIV,A_DIV:
  656. begin
  657. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  658. (
  659. (getregtype(reg)=R_INTREGISTER) and
  660. (
  661. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  662. )
  663. );
  664. end;
  665. else
  666. begin
  667. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  668. begin
  669. RegReadByInstruction := false;
  670. exit;
  671. end;
  672. for opcount := 0 to p.ops-1 do
  673. if (p.oper[opCount]^.typ = top_ref) and
  674. RegInRef(reg,p.oper[opcount]^.ref^) then
  675. begin
  676. RegReadByInstruction := true;
  677. exit
  678. end;
  679. { special handling for SSE MOVSD }
  680. if (p.opcode=A_MOVSD) and (p.ops>0) then
  681. begin
  682. if p.ops<>2 then
  683. internalerror(2017042702);
  684. regReadByInstruction := reginop(reg,p.oper[0]^) or
  685. (
  686. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  687. );
  688. exit;
  689. end;
  690. with insprop[p.opcode] do
  691. begin
  692. case getregtype(reg) of
  693. R_INTREGISTER:
  694. begin
  695. case getsupreg(reg) of
  696. RS_EAX:
  697. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  698. begin
  699. RegReadByInstruction := true;
  700. exit
  701. end;
  702. RS_ECX:
  703. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  704. begin
  705. RegReadByInstruction := true;
  706. exit
  707. end;
  708. RS_EDX:
  709. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  710. begin
  711. RegReadByInstruction := true;
  712. exit
  713. end;
  714. RS_EBX:
  715. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  716. begin
  717. RegReadByInstruction := true;
  718. exit
  719. end;
  720. RS_ESP:
  721. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. RS_EBP:
  727. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  728. begin
  729. RegReadByInstruction := true;
  730. exit
  731. end;
  732. RS_ESI:
  733. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  734. begin
  735. RegReadByInstruction := true;
  736. exit
  737. end;
  738. RS_EDI:
  739. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. end;
  745. end;
  746. R_MMREGISTER:
  747. begin
  748. case getsupreg(reg) of
  749. RS_XMM0:
  750. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. end;
  756. end;
  757. else
  758. ;
  759. end;
  760. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  761. begin
  762. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  763. begin
  764. case p.condition of
  765. C_A,C_NBE, { CF=0 and ZF=0 }
  766. C_BE,C_NA: { CF=1 or ZF=1 }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  768. C_AE,C_NB,C_NC, { CF=0 }
  769. C_B,C_NAE,C_C: { CF=1 }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  771. C_NE,C_NZ, { ZF=0 }
  772. C_E,C_Z: { ZF=1 }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  774. C_G,C_NLE, { ZF=0 and SF=OF }
  775. C_LE,C_NG: { ZF=1 or SF<>OF }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  777. C_GE,C_NL, { SF=OF }
  778. C_L,C_NGE: { SF<>OF }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  780. C_NO, { OF=0 }
  781. C_O: { OF=1 }
  782. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  783. C_NP,C_PO, { PF=0 }
  784. C_P,C_PE: { PF=1 }
  785. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  786. C_NS, { SF=0 }
  787. C_S: { SF=1 }
  788. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  789. else
  790. internalerror(2017042701);
  791. end;
  792. if RegReadByInstruction then
  793. exit;
  794. end;
  795. case getsubreg(reg) of
  796. R_SUBW,R_SUBD,R_SUBQ:
  797. RegReadByInstruction :=
  798. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  799. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  800. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  801. R_SUBFLAGCARRY:
  802. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGPARITY:
  804. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGAUXILIARY:
  806. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGZERO:
  808. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. R_SUBFLAGSIGN:
  810. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  811. R_SUBFLAGOVERFLOW:
  812. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  813. R_SUBFLAGINTERRUPT:
  814. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  815. R_SUBFLAGDIRECTION:
  816. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  817. else
  818. internalerror(2017042601);
  819. end;
  820. exit;
  821. end;
  822. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  823. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  824. (p.oper[0]^.reg=p.oper[1]^.reg) then
  825. exit;
  826. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  827. begin
  828. RegReadByInstruction := true;
  829. exit
  830. end;
  831. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  832. begin
  833. RegReadByInstruction := true;
  834. exit
  835. end;
  836. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  837. begin
  838. RegReadByInstruction := true;
  839. exit
  840. end;
  841. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  842. begin
  843. RegReadByInstruction := true;
  844. exit
  845. end;
  846. end;
  847. end;
  848. end;
  849. end;
  850. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  851. begin
  852. result:=false;
  853. if p1.typ<>ait_instruction then
  854. exit;
  855. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  856. exit(true);
  857. if (getregtype(reg)=R_INTREGISTER) and
  858. { change information for xmm movsd are not correct }
  859. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  860. begin
  861. { Handle instructions that behave differently depending on the size and operand count }
  862. case taicpu(p1).opcode of
  863. A_MUL, A_DIV, A_IDIV:
  864. if taicpu(p1).opsize = S_B then
  865. Result := (getsupreg(Reg) = RS_EAX)
  866. else
  867. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  868. A_IMUL:
  869. if taicpu(p1).ops = 1 then
  870. begin
  871. if taicpu(p1).opsize = S_B then
  872. Result := (getsupreg(Reg) = RS_EAX)
  873. else
  874. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  875. end;
  876. { If ops are greater than 1, call inherited method }
  877. else
  878. case getsupreg(reg) of
  879. { RS_EAX = RS_RAX on x86-64 }
  880. RS_EAX:
  881. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  882. RS_ECX:
  883. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  884. RS_EDX:
  885. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  886. RS_EBX:
  887. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  888. RS_ESP:
  889. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  890. RS_EBP:
  891. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  892. RS_ESI:
  893. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  894. RS_EDI:
  895. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  896. else
  897. ;
  898. end;
  899. end;
  900. if result then
  901. exit;
  902. end
  903. else if getregtype(reg)=R_MMREGISTER then
  904. begin
  905. case getsupreg(reg) of
  906. RS_XMM0:
  907. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. else
  909. ;
  910. end;
  911. if result then
  912. exit;
  913. end
  914. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  915. begin
  916. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  917. exit(true);
  918. case getsubreg(reg) of
  919. R_SUBFLAGCARRY:
  920. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  921. R_SUBFLAGPARITY:
  922. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  923. R_SUBFLAGAUXILIARY:
  924. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  925. R_SUBFLAGZERO:
  926. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. R_SUBFLAGSIGN:
  928. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. R_SUBFLAGOVERFLOW:
  930. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. R_SUBFLAGINTERRUPT:
  932. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. R_SUBFLAGDIRECTION:
  934. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. R_SUBW,R_SUBD,R_SUBQ:
  936. { Everything except the direction bits }
  937. Result:=
  938. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  939. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  940. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  941. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  942. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  943. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  944. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. else
  946. ;
  947. end;
  948. if result then
  949. exit;
  950. end
  951. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  952. exit(true);
  953. Result:=inherited RegInInstruction(Reg, p1);
  954. end;
  955. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  956. const
  957. WriteOps: array[0..3] of set of TInsChange =
  958. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  959. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  960. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  961. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  962. var
  963. OperIdx: Integer;
  964. begin
  965. Result := False;
  966. if p1.typ <> ait_instruction then
  967. exit;
  968. with insprop[taicpu(p1).opcode] do
  969. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  970. begin
  971. case getsubreg(reg) of
  972. R_SUBW,R_SUBD,R_SUBQ:
  973. Result :=
  974. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  975. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  976. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  977. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  978. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  979. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  980. R_SUBFLAGCARRY:
  981. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  982. R_SUBFLAGPARITY:
  983. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  984. R_SUBFLAGAUXILIARY:
  985. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  986. R_SUBFLAGZERO:
  987. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  988. R_SUBFLAGSIGN:
  989. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  990. R_SUBFLAGOVERFLOW:
  991. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  992. R_SUBFLAGINTERRUPT:
  993. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  994. R_SUBFLAGDIRECTION:
  995. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  996. else
  997. internalerror(2017042602);
  998. end;
  999. exit;
  1000. end;
  1001. case taicpu(p1).opcode of
  1002. A_CALL:
  1003. { We could potentially set Result to False if the register in
  1004. question is non-volatile for the subroutine's calling convention,
  1005. but this would require detecting the calling convention in use and
  1006. also assuming that the routine doesn't contain malformed assembly
  1007. language, for example... so it could only be done under -O4 as it
  1008. would be considered a side-effect. [Kit] }
  1009. Result := True;
  1010. A_MOVSD:
  1011. { special handling for SSE MOVSD }
  1012. if (taicpu(p1).ops>0) then
  1013. begin
  1014. if taicpu(p1).ops<>2 then
  1015. internalerror(2017042703);
  1016. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1017. end;
  1018. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1019. so fix it here (FK)
  1020. }
  1021. A_VMOVSS,
  1022. A_VMOVSD:
  1023. begin
  1024. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1025. exit;
  1026. end;
  1027. A_MUL, A_DIV, A_IDIV:
  1028. begin
  1029. if taicpu(p1).opsize = S_B then
  1030. Result := (getsupreg(Reg) = RS_EAX)
  1031. else
  1032. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1033. end;
  1034. A_IMUL:
  1035. begin
  1036. if taicpu(p1).ops = 1 then
  1037. begin
  1038. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1039. end
  1040. else
  1041. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1042. Exit;
  1043. end;
  1044. else
  1045. ;
  1046. end;
  1047. if Result then
  1048. exit;
  1049. with insprop[taicpu(p1).opcode] do
  1050. begin
  1051. if getregtype(reg)=R_INTREGISTER then
  1052. begin
  1053. case getsupreg(reg) of
  1054. RS_EAX:
  1055. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1056. begin
  1057. Result := True;
  1058. exit
  1059. end;
  1060. RS_ECX:
  1061. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1062. begin
  1063. Result := True;
  1064. exit
  1065. end;
  1066. RS_EDX:
  1067. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1068. begin
  1069. Result := True;
  1070. exit
  1071. end;
  1072. RS_EBX:
  1073. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1074. begin
  1075. Result := True;
  1076. exit
  1077. end;
  1078. RS_ESP:
  1079. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1080. begin
  1081. Result := True;
  1082. exit
  1083. end;
  1084. RS_EBP:
  1085. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1086. begin
  1087. Result := True;
  1088. exit
  1089. end;
  1090. RS_ESI:
  1091. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1092. begin
  1093. Result := True;
  1094. exit
  1095. end;
  1096. RS_EDI:
  1097. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1098. begin
  1099. Result := True;
  1100. exit
  1101. end;
  1102. end;
  1103. end;
  1104. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1105. if (WriteOps[OperIdx]*Ch<>[]) and
  1106. { The register doesn't get modified inside a reference }
  1107. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1108. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1109. begin
  1110. Result := true;
  1111. exit
  1112. end;
  1113. end;
  1114. end;
  1115. {$ifdef DEBUG_AOPTCPU}
  1116. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1117. begin
  1118. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1119. end;
  1120. function debug_tostr(i: tcgint): string; inline;
  1121. begin
  1122. Result := tostr(i);
  1123. end;
  1124. function debug_hexstr(i: tcgint): string;
  1125. begin
  1126. Result := '0x';
  1127. case i of
  1128. 0..$FF:
  1129. Result := Result + hexstr(i, 2);
  1130. $100..$FFFF:
  1131. Result := Result + hexstr(i, 4);
  1132. $10000..$FFFFFF:
  1133. Result := Result + hexstr(i, 6);
  1134. $1000000..$FFFFFFFF:
  1135. Result := Result + hexstr(i, 8);
  1136. else
  1137. Result := Result + hexstr(i, 16);
  1138. end;
  1139. end;
  1140. function debug_regname(r: TRegister): string; inline;
  1141. begin
  1142. Result := '%' + std_regname(r);
  1143. end;
  1144. { Debug output function - creates a string representation of an operator }
  1145. function debug_operstr(oper: TOper): string;
  1146. begin
  1147. case oper.typ of
  1148. top_const:
  1149. Result := '$' + debug_tostr(oper.val);
  1150. top_reg:
  1151. Result := debug_regname(oper.reg);
  1152. top_ref:
  1153. begin
  1154. if oper.ref^.offset <> 0 then
  1155. Result := debug_tostr(oper.ref^.offset) + '('
  1156. else
  1157. Result := '(';
  1158. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1159. begin
  1160. Result := Result + debug_regname(oper.ref^.base);
  1161. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1162. Result := Result + ',' + debug_regname(oper.ref^.index);
  1163. end
  1164. else
  1165. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1166. Result := Result + debug_regname(oper.ref^.index);
  1167. if (oper.ref^.scalefactor > 1) then
  1168. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1169. else
  1170. Result := Result + ')';
  1171. end;
  1172. else
  1173. Result := '[UNKNOWN]';
  1174. end;
  1175. end;
  1176. function debug_op2str(opcode: tasmop): string; inline;
  1177. begin
  1178. Result := std_op2str[opcode];
  1179. end;
  1180. function debug_opsize2str(opsize: topsize): string; inline;
  1181. begin
  1182. Result := gas_opsize2str[opsize];
  1183. end;
  1184. {$else DEBUG_AOPTCPU}
  1185. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1186. begin
  1187. end;
  1188. function debug_tostr(i: tcgint): string; inline;
  1189. begin
  1190. Result := '';
  1191. end;
  1192. function debug_hexstr(i: tcgint): string; inline;
  1193. begin
  1194. Result := '';
  1195. end;
  1196. function debug_regname(r: TRegister): string; inline;
  1197. begin
  1198. Result := '';
  1199. end;
  1200. function debug_operstr(oper: TOper): string; inline;
  1201. begin
  1202. Result := '';
  1203. end;
  1204. function debug_op2str(opcode: tasmop): string; inline;
  1205. begin
  1206. Result := '';
  1207. end;
  1208. function debug_opsize2str(opsize: topsize): string; inline;
  1209. begin
  1210. Result := '';
  1211. end;
  1212. {$endif DEBUG_AOPTCPU}
  1213. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1214. begin
  1215. {$ifdef x86_64}
  1216. { Always fine on x86-64 }
  1217. Result := True;
  1218. {$else x86_64}
  1219. Result :=
  1220. {$ifdef i8086}
  1221. (current_settings.cputype >= cpu_386) and
  1222. {$endif i8086}
  1223. (
  1224. { Always accept if optimising for size }
  1225. (cs_opt_size in current_settings.optimizerswitches) or
  1226. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1227. (current_settings.optimizecputype >= cpu_Pentium2)
  1228. );
  1229. {$endif x86_64}
  1230. end;
  1231. { Attempts to allocate a volatile integer register for use between p and hp,
  1232. using AUsedRegs for the current register usage information. Returns NR_NO
  1233. if no free register could be found }
  1234. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1235. var
  1236. RegSet: TCPURegisterSet;
  1237. CurrentSuperReg: Integer;
  1238. CurrentReg: TRegister;
  1239. Currentp: tai;
  1240. Breakout: Boolean;
  1241. begin
  1242. Result := NR_NO;
  1243. RegSet :=
  1244. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1245. current_procinfo.saved_regs_int;
  1246. (*
  1247. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1248. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1249. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1250. *)
  1251. for CurrentSuperReg in RegSet do
  1252. begin
  1253. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1254. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1255. {$if defined(i386) or defined(i8086)}
  1256. { If the target size is 8-bit, make sure we can actually encode it }
  1257. and (
  1258. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1259. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1260. )
  1261. {$endif i386 or i8086}
  1262. then
  1263. begin
  1264. Currentp := p;
  1265. Breakout := False;
  1266. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1267. begin
  1268. case Currentp.typ of
  1269. ait_instruction:
  1270. begin
  1271. if RegInInstruction(CurrentReg, Currentp) then
  1272. begin
  1273. Breakout := True;
  1274. Break;
  1275. end;
  1276. { Cannot allocate across an unconditional jump }
  1277. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1278. Exit;
  1279. end;
  1280. ait_marker:
  1281. { Don't try anything more if a marker is hit }
  1282. Exit;
  1283. ait_regalloc:
  1284. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1285. begin
  1286. Breakout := True;
  1287. Break;
  1288. end;
  1289. else
  1290. ;
  1291. end;
  1292. end;
  1293. if Breakout then
  1294. { Try the next register }
  1295. Continue;
  1296. { We have a free register available }
  1297. Result := CurrentReg;
  1298. if not DontAlloc then
  1299. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1300. Exit;
  1301. end;
  1302. end;
  1303. end;
  1304. { Attempts to allocate a volatile MM register for use between p and hp,
  1305. using AUsedRegs for the current register usage information. Returns NR_NO
  1306. if no free register could be found }
  1307. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1308. var
  1309. RegSet: TCPURegisterSet;
  1310. CurrentSuperReg: Integer;
  1311. CurrentReg: TRegister;
  1312. Currentp: tai;
  1313. Breakout: Boolean;
  1314. begin
  1315. Result := NR_NO;
  1316. RegSet :=
  1317. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1318. current_procinfo.saved_regs_mm;
  1319. for CurrentSuperReg in RegSet do
  1320. begin
  1321. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1322. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1323. begin
  1324. Currentp := p;
  1325. Breakout := False;
  1326. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1327. begin
  1328. case Currentp.typ of
  1329. ait_instruction:
  1330. begin
  1331. if RegInInstruction(CurrentReg, Currentp) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. { Cannot allocate across an unconditional jump }
  1337. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1338. Exit;
  1339. end;
  1340. ait_marker:
  1341. { Don't try anything more if a marker is hit }
  1342. Exit;
  1343. ait_regalloc:
  1344. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1345. begin
  1346. Breakout := True;
  1347. Break;
  1348. end;
  1349. else
  1350. ;
  1351. end;
  1352. end;
  1353. if Breakout then
  1354. { Try the next register }
  1355. Continue;
  1356. { We have a free register available }
  1357. Result := CurrentReg;
  1358. if not DontAlloc then
  1359. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1360. Exit;
  1361. end;
  1362. end;
  1363. end;
  1364. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1365. begin
  1366. if not SuperRegistersEqual(reg1,reg2) then
  1367. exit(false);
  1368. if getregtype(reg1)<>R_INTREGISTER then
  1369. exit(true); {because SuperRegisterEqual is true}
  1370. case getsubreg(reg1) of
  1371. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1372. higher, it preserves the high bits, so the new value depends on
  1373. reg2's previous value. In other words, it is equivalent to doing:
  1374. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1375. R_SUBL:
  1376. exit(getsubreg(reg2)=R_SUBL);
  1377. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1378. higher, it actually does a:
  1379. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1380. R_SUBH:
  1381. exit(getsubreg(reg2)=R_SUBH);
  1382. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1383. bits of reg2:
  1384. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1385. R_SUBW:
  1386. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1387. { a write to R_SUBD always overwrites every other subregister,
  1388. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1389. R_SUBD,
  1390. R_SUBQ:
  1391. exit(true);
  1392. else
  1393. internalerror(2017042801);
  1394. end;
  1395. end;
  1396. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1397. begin
  1398. if not SuperRegistersEqual(reg1,reg2) then
  1399. exit(false);
  1400. if getregtype(reg1)<>R_INTREGISTER then
  1401. exit(true); {because SuperRegisterEqual is true}
  1402. case getsubreg(reg1) of
  1403. R_SUBL:
  1404. exit(getsubreg(reg2)<>R_SUBH);
  1405. R_SUBH:
  1406. exit(getsubreg(reg2)<>R_SUBL);
  1407. R_SUBW,
  1408. R_SUBD,
  1409. R_SUBQ:
  1410. exit(true);
  1411. else
  1412. internalerror(2017042802);
  1413. end;
  1414. end;
  1415. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1416. var
  1417. hp1 : tai;
  1418. l : TCGInt;
  1419. begin
  1420. result:=false;
  1421. if not(GetNextInstruction(p, hp1)) then
  1422. exit;
  1423. { changes the code sequence
  1424. shr/sar const1, x
  1425. shl const2, x
  1426. to
  1427. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1428. if (taicpu(p).oper[0]^.typ = top_const) and
  1429. MatchInstruction(hp1,A_SHL,[]) and
  1430. (taicpu(hp1).oper[0]^.typ = top_const) and
  1431. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1432. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1433. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1434. begin
  1435. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1436. not(cs_opt_size in current_settings.optimizerswitches) then
  1437. begin
  1438. { shr/sar const1, %reg
  1439. shl const2, %reg
  1440. with const1 > const2 }
  1441. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1442. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1443. taicpu(hp1).opcode := A_AND;
  1444. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1445. case taicpu(p).opsize Of
  1446. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1447. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1448. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1449. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1450. else
  1451. Internalerror(2017050703)
  1452. end;
  1453. end
  1454. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1455. not(cs_opt_size in current_settings.optimizerswitches) then
  1456. begin
  1457. { shr/sar const1, %reg
  1458. shl const2, %reg
  1459. with const1 < const2 }
  1460. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1462. taicpu(p).opcode := A_AND;
  1463. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1464. case taicpu(p).opsize Of
  1465. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1466. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1467. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1468. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1469. else
  1470. Internalerror(2017050702)
  1471. end;
  1472. end
  1473. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1474. begin
  1475. { shr/sar const1, %reg
  1476. shl const2, %reg
  1477. with const1 = const2 }
  1478. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1479. taicpu(p).opcode := A_AND;
  1480. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1481. case taicpu(p).opsize Of
  1482. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1483. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1484. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1485. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1486. else
  1487. Internalerror(2017050701)
  1488. end;
  1489. RemoveInstruction(hp1);
  1490. end;
  1491. end;
  1492. end;
  1493. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1494. var
  1495. opsize : topsize;
  1496. hp1, hp2 : tai;
  1497. tmpref : treference;
  1498. ShiftValue : Cardinal;
  1499. BaseValue : TCGInt;
  1500. begin
  1501. result:=false;
  1502. opsize:=taicpu(p).opsize;
  1503. { changes certain "imul const, %reg"'s to lea sequences }
  1504. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1505. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1506. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1507. if (taicpu(p).oper[0]^.val = 1) then
  1508. if (taicpu(p).ops = 2) then
  1509. { remove "imul $1, reg" }
  1510. begin
  1511. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1512. Result := RemoveCurrentP(p);
  1513. end
  1514. else
  1515. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1516. begin
  1517. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1518. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1519. asml.InsertAfter(hp1, p);
  1520. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1521. RemoveCurrentP(p, hp1);
  1522. Result := True;
  1523. end
  1524. else if ((taicpu(p).ops <= 2) or
  1525. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1526. not(cs_opt_size in current_settings.optimizerswitches) and
  1527. (not(GetNextInstruction(p, hp1)) or
  1528. not((tai(hp1).typ = ait_instruction) and
  1529. ((taicpu(hp1).opcode=A_Jcc) and
  1530. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1531. begin
  1532. {
  1533. imul X, reg1, reg2 to
  1534. lea (reg1,reg1,Y), reg2
  1535. shl ZZ,reg2
  1536. imul XX, reg1 to
  1537. lea (reg1,reg1,YY), reg1
  1538. shl ZZ,reg2
  1539. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1540. it does not exist as a separate optimization target in FPC though.
  1541. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1542. at most two zeros
  1543. }
  1544. reference_reset(tmpref,1,[]);
  1545. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1546. begin
  1547. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1548. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1549. TmpRef.base := taicpu(p).oper[1]^.reg;
  1550. TmpRef.index := taicpu(p).oper[1]^.reg;
  1551. if not(BaseValue in [3,5,9]) then
  1552. Internalerror(2018110101);
  1553. TmpRef.ScaleFactor := BaseValue-1;
  1554. if (taicpu(p).ops = 2) then
  1555. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1556. else
  1557. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1558. AsmL.InsertAfter(hp1,p);
  1559. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1560. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1561. RemoveCurrentP(p, hp1);
  1562. if ShiftValue>0 then
  1563. begin
  1564. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1565. AsmL.InsertAfter(hp2,hp1);
  1566. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1567. end;
  1568. Result := True;
  1569. end;
  1570. end;
  1571. end;
  1572. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1573. begin
  1574. Result := False;
  1575. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1576. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1577. begin
  1578. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1579. taicpu(p).opcode := A_MOV;
  1580. Result := True;
  1581. end;
  1582. end;
  1583. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1584. var
  1585. p: taicpu absolute hp; { Implicit typecast }
  1586. i: Integer;
  1587. begin
  1588. Result := False;
  1589. if not assigned(hp) or
  1590. (hp.typ <> ait_instruction) then
  1591. Exit;
  1592. Prefetch(insprop[p.opcode]);
  1593. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1594. with insprop[p.opcode] do
  1595. begin
  1596. case getsubreg(reg) of
  1597. R_SUBW,R_SUBD,R_SUBQ:
  1598. Result:=
  1599. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1600. uncommon flags are checked first }
  1601. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1602. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1606. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1607. R_SUBFLAGCARRY:
  1608. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1609. R_SUBFLAGPARITY:
  1610. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1611. R_SUBFLAGAUXILIARY:
  1612. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1613. R_SUBFLAGZERO:
  1614. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1615. R_SUBFLAGSIGN:
  1616. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1617. R_SUBFLAGOVERFLOW:
  1618. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1619. R_SUBFLAGINTERRUPT:
  1620. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1621. R_SUBFLAGDIRECTION:
  1622. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1623. else
  1624. internalerror(2017050501);
  1625. end;
  1626. exit;
  1627. end;
  1628. { Handle special cases first }
  1629. case p.opcode of
  1630. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1631. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1632. begin
  1633. Result :=
  1634. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1635. (p.oper[1]^.typ = top_reg) and
  1636. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1637. (
  1638. (p.oper[0]^.typ = top_const) or
  1639. (
  1640. (p.oper[0]^.typ = top_reg) and
  1641. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1642. ) or (
  1643. (p.oper[0]^.typ = top_ref) and
  1644. not RegInRef(reg,p.oper[0]^.ref^)
  1645. )
  1646. );
  1647. end;
  1648. A_MUL, A_IMUL:
  1649. Result :=
  1650. (
  1651. (p.ops=3) and { IMUL only }
  1652. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1653. (
  1654. (
  1655. (p.oper[1]^.typ=top_reg) and
  1656. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1657. ) or (
  1658. (p.oper[1]^.typ=top_ref) and
  1659. not RegInRef(reg,p.oper[1]^.ref^)
  1660. )
  1661. )
  1662. ) or (
  1663. (
  1664. (p.ops=1) and
  1665. (
  1666. (
  1667. (
  1668. (p.oper[0]^.typ=top_reg) and
  1669. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1670. )
  1671. ) or (
  1672. (p.oper[0]^.typ=top_ref) and
  1673. not RegInRef(reg,p.oper[0]^.ref^)
  1674. )
  1675. ) and (
  1676. (
  1677. (p.opsize=S_B) and
  1678. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1679. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1680. ) or (
  1681. (p.opsize=S_W) and
  1682. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1683. ) or (
  1684. (p.opsize=S_L) and
  1685. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1686. {$ifdef x86_64}
  1687. ) or (
  1688. (p.opsize=S_Q) and
  1689. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1690. {$endif x86_64}
  1691. )
  1692. )
  1693. )
  1694. );
  1695. A_CBW:
  1696. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1697. {$ifndef x86_64}
  1698. A_LDS:
  1699. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1700. A_LES:
  1701. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1702. {$endif not x86_64}
  1703. A_LFS:
  1704. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1705. A_LGS:
  1706. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1707. A_LSS:
  1708. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1709. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1710. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1711. A_LODSB:
  1712. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1713. A_LODSW:
  1714. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1715. {$ifdef x86_64}
  1716. A_LODSQ:
  1717. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1718. {$endif x86_64}
  1719. A_LODSD:
  1720. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1721. A_FSTSW, A_FNSTSW:
  1722. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1723. else
  1724. begin
  1725. with insprop[p.opcode] do
  1726. begin
  1727. if (
  1728. { xor %reg,%reg etc. is classed as a new value }
  1729. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1730. MatchOpType(p, top_reg, top_reg) and
  1731. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1732. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1733. ) then
  1734. begin
  1735. Result := True;
  1736. Exit;
  1737. end;
  1738. { Make sure the entire register is overwritten }
  1739. if (getregtype(reg) = R_INTREGISTER) then
  1740. begin
  1741. if (p.ops > 0) then
  1742. begin
  1743. if RegInOp(reg, p.oper[0]^) then
  1744. begin
  1745. if (p.oper[0]^.typ = top_ref) then
  1746. begin
  1747. if RegInRef(reg, p.oper[0]^.ref^) then
  1748. begin
  1749. Result := False;
  1750. Exit;
  1751. end;
  1752. end
  1753. else if (p.oper[0]^.typ = top_reg) then
  1754. begin
  1755. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1756. begin
  1757. Result := False;
  1758. Exit;
  1759. end
  1760. else if ([Ch_WOp1]*Ch<>[]) then
  1761. begin
  1762. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1763. Result := True
  1764. else
  1765. begin
  1766. Result := False;
  1767. Exit;
  1768. end;
  1769. end;
  1770. end;
  1771. end;
  1772. if (p.ops > 1) then
  1773. begin
  1774. if RegInOp(reg, p.oper[1]^) then
  1775. begin
  1776. if (p.oper[1]^.typ = top_ref) then
  1777. begin
  1778. if RegInRef(reg, p.oper[1]^.ref^) then
  1779. begin
  1780. Result := False;
  1781. Exit;
  1782. end;
  1783. end
  1784. else if (p.oper[1]^.typ = top_reg) then
  1785. begin
  1786. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1787. begin
  1788. Result := False;
  1789. Exit;
  1790. end
  1791. else if ([Ch_WOp2]*Ch<>[]) then
  1792. begin
  1793. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1794. Result := True
  1795. else
  1796. begin
  1797. Result := False;
  1798. Exit;
  1799. end;
  1800. end;
  1801. end;
  1802. end;
  1803. if (p.ops > 2) then
  1804. begin
  1805. if RegInOp(reg, p.oper[2]^) then
  1806. begin
  1807. if (p.oper[2]^.typ = top_ref) then
  1808. begin
  1809. if RegInRef(reg, p.oper[2]^.ref^) then
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end
  1815. else if (p.oper[2]^.typ = top_reg) then
  1816. begin
  1817. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1818. begin
  1819. Result := False;
  1820. Exit;
  1821. end
  1822. else if ([Ch_WOp3]*Ch<>[]) then
  1823. begin
  1824. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1825. Result := True
  1826. else
  1827. begin
  1828. Result := False;
  1829. Exit;
  1830. end;
  1831. end;
  1832. end;
  1833. end;
  1834. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1835. begin
  1836. if (p.oper[3]^.typ = top_ref) then
  1837. begin
  1838. if RegInRef(reg, p.oper[3]^.ref^) then
  1839. begin
  1840. Result := False;
  1841. Exit;
  1842. end;
  1843. end
  1844. else if (p.oper[3]^.typ = top_reg) then
  1845. begin
  1846. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1847. begin
  1848. Result := False;
  1849. Exit;
  1850. end
  1851. else if ([Ch_WOp4]*Ch<>[]) then
  1852. begin
  1853. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1854. Result := True
  1855. else
  1856. begin
  1857. Result := False;
  1858. Exit;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. end;
  1866. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1867. case getsupreg(reg) of
  1868. RS_EAX:
  1869. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1870. begin
  1871. Result := True;
  1872. Exit;
  1873. end;
  1874. RS_ECX:
  1875. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1876. begin
  1877. Result := True;
  1878. Exit;
  1879. end;
  1880. RS_EDX:
  1881. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1882. begin
  1883. Result := True;
  1884. Exit;
  1885. end;
  1886. RS_EBX:
  1887. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1888. begin
  1889. Result := True;
  1890. Exit;
  1891. end;
  1892. RS_ESP:
  1893. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1894. begin
  1895. Result := True;
  1896. Exit;
  1897. end;
  1898. RS_EBP:
  1899. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1900. begin
  1901. Result := True;
  1902. Exit;
  1903. end;
  1904. RS_ESI:
  1905. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1906. begin
  1907. Result := True;
  1908. Exit;
  1909. end;
  1910. RS_EDI:
  1911. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1912. begin
  1913. Result := True;
  1914. Exit;
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. end;
  1924. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1925. var
  1926. hp2,hp3 : tai;
  1927. begin
  1928. { some x86-64 issue a NOP before the real exit code }
  1929. if MatchInstruction(p,A_NOP,[]) then
  1930. GetNextInstruction(p,p);
  1931. result:=assigned(p) and (p.typ=ait_instruction) and
  1932. ((taicpu(p).opcode = A_RET) or
  1933. ((taicpu(p).opcode=A_LEAVE) and
  1934. GetNextInstruction(p,hp2) and
  1935. MatchInstruction(hp2,A_RET,[S_NO])
  1936. ) or
  1937. (((taicpu(p).opcode=A_LEA) and
  1938. MatchOpType(taicpu(p),top_ref,top_reg) and
  1939. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1940. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1941. ) and
  1942. GetNextInstruction(p,hp2) and
  1943. MatchInstruction(hp2,A_RET,[S_NO])
  1944. ) or
  1945. ((((taicpu(p).opcode=A_MOV) and
  1946. MatchOpType(taicpu(p),top_reg,top_reg) and
  1947. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1948. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1949. ((taicpu(p).opcode=A_LEA) and
  1950. MatchOpType(taicpu(p),top_ref,top_reg) and
  1951. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1952. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1953. )
  1954. ) and
  1955. GetNextInstruction(p,hp2) and
  1956. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1957. MatchOpType(taicpu(hp2),top_reg) and
  1958. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1959. GetNextInstruction(hp2,hp3) and
  1960. MatchInstruction(hp3,A_RET,[S_NO])
  1961. )
  1962. );
  1963. end;
  1964. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1965. begin
  1966. isFoldableArithOp := False;
  1967. case hp1.opcode of
  1968. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1969. isFoldableArithOp :=
  1970. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1971. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1972. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1973. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1974. (taicpu(hp1).oper[1]^.reg = reg);
  1975. A_INC,A_DEC,A_NEG,A_NOT:
  1976. isFoldableArithOp :=
  1977. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1978. (taicpu(hp1).oper[0]^.reg = reg);
  1979. else
  1980. ;
  1981. end;
  1982. end;
  1983. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1984. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1985. var
  1986. hp2: tai;
  1987. begin
  1988. hp2 := p;
  1989. repeat
  1990. hp2 := tai(hp2.previous);
  1991. if assigned(hp2) and
  1992. (hp2.typ = ait_regalloc) and
  1993. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1994. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1995. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1996. begin
  1997. RemoveInstruction(hp2);
  1998. break;
  1999. end;
  2000. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2001. end;
  2002. begin
  2003. case current_procinfo.procdef.returndef.typ of
  2004. arraydef,recorddef,pointerdef,
  2005. stringdef,enumdef,procdef,objectdef,errordef,
  2006. filedef,setdef,procvardef,
  2007. classrefdef,forwarddef:
  2008. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2009. orddef:
  2010. if current_procinfo.procdef.returndef.size <> 0 then
  2011. begin
  2012. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2013. { for int64/qword }
  2014. if current_procinfo.procdef.returndef.size = 8 then
  2015. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2016. end;
  2017. else
  2018. ;
  2019. end;
  2020. end;
  2021. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2022. var
  2023. hp1,hp2 : tai;
  2024. begin
  2025. result:=false;
  2026. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2027. begin
  2028. { vmova* reg1,reg1
  2029. =>
  2030. <nop> }
  2031. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2032. begin
  2033. RemoveCurrentP(p);
  2034. result:=true;
  2035. exit;
  2036. end;
  2037. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2038. (hp1.typ = ait_instruction) and
  2039. (
  2040. { Under -O2 and below, the instructions are always adjacent }
  2041. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2042. (taicpu(hp1).ops <= 1) or
  2043. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2044. { If reg1 = reg3, reg1 must not be modified in between }
  2045. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2046. ) then
  2047. begin
  2048. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2049. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2050. begin
  2051. { vmova* reg1,reg2
  2052. ...
  2053. vmova* reg2,reg3
  2054. dealloc reg2
  2055. =>
  2056. vmova* reg1,reg3 }
  2057. TransferUsedRegs(TmpUsedRegs);
  2058. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2059. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2060. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2061. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2062. begin
  2063. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2064. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2065. TransferUsedRegs(TmpUsedRegs);
  2066. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2067. RemoveInstruction(hp1);
  2068. result:=true;
  2069. exit;
  2070. end;
  2071. { special case:
  2072. vmova* reg1,<op>
  2073. ...
  2074. vmova* <op>,reg1
  2075. =>
  2076. vmova* reg1,<op> }
  2077. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2078. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2079. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2080. ) then
  2081. begin
  2082. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2083. RemoveInstruction(hp1);
  2084. result:=true;
  2085. exit;
  2086. end
  2087. end
  2088. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2089. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2090. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2091. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2092. ) and
  2093. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2094. begin
  2095. { vmova* reg1,reg2
  2096. ...
  2097. vmovs* reg2,<op>
  2098. dealloc reg2
  2099. =>
  2100. vmovs* reg1,<op> }
  2101. TransferUsedRegs(TmpUsedRegs);
  2102. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2103. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2104. begin
  2105. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2106. taicpu(p).opcode:=taicpu(hp1).opcode;
  2107. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2108. TransferUsedRegs(TmpUsedRegs);
  2109. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2110. RemoveInstruction(hp1);
  2111. result:=true;
  2112. exit;
  2113. end
  2114. end;
  2115. if MatchInstruction(hp1,[A_VFMADDPD,
  2116. A_VFMADD132PD,
  2117. A_VFMADD132PS,
  2118. A_VFMADD132SD,
  2119. A_VFMADD132SS,
  2120. A_VFMADD213PD,
  2121. A_VFMADD213PS,
  2122. A_VFMADD213SD,
  2123. A_VFMADD213SS,
  2124. A_VFMADD231PD,
  2125. A_VFMADD231PS,
  2126. A_VFMADD231SD,
  2127. A_VFMADD231SS,
  2128. A_VFMADDSUB132PD,
  2129. A_VFMADDSUB132PS,
  2130. A_VFMADDSUB213PD,
  2131. A_VFMADDSUB213PS,
  2132. A_VFMADDSUB231PD,
  2133. A_VFMADDSUB231PS,
  2134. A_VFMSUB132PD,
  2135. A_VFMSUB132PS,
  2136. A_VFMSUB132SD,
  2137. A_VFMSUB132SS,
  2138. A_VFMSUB213PD,
  2139. A_VFMSUB213PS,
  2140. A_VFMSUB213SD,
  2141. A_VFMSUB213SS,
  2142. A_VFMSUB231PD,
  2143. A_VFMSUB231PS,
  2144. A_VFMSUB231SD,
  2145. A_VFMSUB231SS,
  2146. A_VFMSUBADD132PD,
  2147. A_VFMSUBADD132PS,
  2148. A_VFMSUBADD213PD,
  2149. A_VFMSUBADD213PS,
  2150. A_VFMSUBADD231PD,
  2151. A_VFMSUBADD231PS,
  2152. A_VFNMADD132PD,
  2153. A_VFNMADD132PS,
  2154. A_VFNMADD132SD,
  2155. A_VFNMADD132SS,
  2156. A_VFNMADD213PD,
  2157. A_VFNMADD213PS,
  2158. A_VFNMADD213SD,
  2159. A_VFNMADD213SS,
  2160. A_VFNMADD231PD,
  2161. A_VFNMADD231PS,
  2162. A_VFNMADD231SD,
  2163. A_VFNMADD231SS,
  2164. A_VFNMSUB132PD,
  2165. A_VFNMSUB132PS,
  2166. A_VFNMSUB132SD,
  2167. A_VFNMSUB132SS,
  2168. A_VFNMSUB213PD,
  2169. A_VFNMSUB213PS,
  2170. A_VFNMSUB213SD,
  2171. A_VFNMSUB213SS,
  2172. A_VFNMSUB231PD,
  2173. A_VFNMSUB231PS,
  2174. A_VFNMSUB231SD,
  2175. A_VFNMSUB231SS],[S_NO]) and
  2176. { we mix single and double opperations here because we assume that the compiler
  2177. generates vmovapd only after double operations and vmovaps only after single operations }
  2178. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2179. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2180. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2181. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2182. begin
  2183. TransferUsedRegs(TmpUsedRegs);
  2184. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2185. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2186. begin
  2187. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2188. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2189. RemoveCurrentP(p)
  2190. else
  2191. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2192. RemoveInstruction(hp2);
  2193. end;
  2194. end
  2195. else if (hp1.typ = ait_instruction) and
  2196. (((taicpu(p).opcode=A_MOVAPS) and
  2197. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2198. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2199. ((taicpu(p).opcode=A_MOVAPD) and
  2200. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2201. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2202. ) and
  2203. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2204. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2205. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2206. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2207. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2208. { change
  2209. movapX reg,reg2
  2210. addsX/subsX/... reg3, reg2
  2211. movapX reg2,reg
  2212. to
  2213. addsX/subsX/... reg3,reg
  2214. }
  2215. begin
  2216. TransferUsedRegs(TmpUsedRegs);
  2217. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2218. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2219. begin
  2220. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2221. debug_op2str(taicpu(p).opcode)+' '+
  2222. debug_op2str(taicpu(hp1).opcode)+' '+
  2223. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2224. { we cannot eliminate the first move if
  2225. the operations uses the same register for source and dest }
  2226. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { Remember that hp1 is not necessarily the immediate
  2228. next instruction }
  2229. RemoveCurrentP(p);
  2230. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2231. RemoveInstruction(hp2);
  2232. result:=true;
  2233. end;
  2234. end
  2235. else if (hp1.typ = ait_instruction) and
  2236. (((taicpu(p).opcode=A_VMOVAPD) and
  2237. (taicpu(hp1).opcode=A_VCOMISD)) or
  2238. ((taicpu(p).opcode=A_VMOVAPS) and
  2239. ((taicpu(hp1).opcode=A_VCOMISS))
  2240. )
  2241. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2242. { change
  2243. movapX reg,reg1
  2244. vcomisX reg1,reg1
  2245. to
  2246. vcomisX reg,reg
  2247. }
  2248. begin
  2249. TransferUsedRegs(TmpUsedRegs);
  2250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2251. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2252. begin
  2253. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2254. debug_op2str(taicpu(p).opcode)+' '+
  2255. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2256. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2257. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2258. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2259. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2260. RemoveCurrentP(p);
  2261. result:=true;
  2262. exit;
  2263. end;
  2264. end
  2265. end;
  2266. end;
  2267. end;
  2268. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2269. var
  2270. hp1 : tai;
  2271. begin
  2272. result:=false;
  2273. { replace
  2274. V<Op>X %mreg1,%mreg2,%mreg3
  2275. VMovX %mreg3,%mreg4
  2276. dealloc %mreg3
  2277. by
  2278. V<Op>X %mreg1,%mreg2,%mreg4
  2279. ?
  2280. }
  2281. if GetNextInstruction(p,hp1) and
  2282. { we mix single and double operations here because we assume that the compiler
  2283. generates vmovapd only after double operations and vmovaps only after single operations }
  2284. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2285. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2286. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2287. begin
  2288. TransferUsedRegs(TmpUsedRegs);
  2289. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2290. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2291. begin
  2292. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2293. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2294. RemoveInstruction(hp1);
  2295. result:=true;
  2296. end;
  2297. end;
  2298. end;
  2299. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2300. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2301. begin
  2302. Result := False;
  2303. { For safety reasons, only check for exact register matches }
  2304. { Check base register }
  2305. if (ref.base = AOldReg) then
  2306. begin
  2307. ref.base := ANewReg;
  2308. Result := True;
  2309. end;
  2310. { Check index register }
  2311. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2312. begin
  2313. ref.index := ANewReg;
  2314. Result := True;
  2315. end;
  2316. end;
  2317. { Replaces all references to AOldReg in an operand to ANewReg }
  2318. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2319. var
  2320. OldSupReg, NewSupReg: TSuperRegister;
  2321. OldSubReg, NewSubReg: TSubRegister;
  2322. OldRegType: TRegisterType;
  2323. ThisOper: POper;
  2324. begin
  2325. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2326. Result := False;
  2327. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2328. InternalError(2020011801);
  2329. OldSupReg := getsupreg(AOldReg);
  2330. OldSubReg := getsubreg(AOldReg);
  2331. OldRegType := getregtype(AOldReg);
  2332. NewSupReg := getsupreg(ANewReg);
  2333. NewSubReg := getsubreg(ANewReg);
  2334. if OldRegType <> getregtype(ANewReg) then
  2335. InternalError(2020011802);
  2336. if OldSubReg <> NewSubReg then
  2337. InternalError(2020011803);
  2338. case ThisOper^.typ of
  2339. top_reg:
  2340. if (
  2341. (ThisOper^.reg = AOldReg) or
  2342. (
  2343. (OldRegType = R_INTREGISTER) and
  2344. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2345. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2346. (
  2347. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2348. {$ifndef x86_64}
  2349. and (
  2350. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2351. don't have an 8-bit representation }
  2352. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2353. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2354. )
  2355. {$endif x86_64}
  2356. )
  2357. )
  2358. ) then
  2359. begin
  2360. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2361. Result := True;
  2362. end;
  2363. top_ref:
  2364. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2365. Result := True;
  2366. else
  2367. ;
  2368. end;
  2369. end;
  2370. { Replaces all references to AOldReg in an instruction to ANewReg }
  2371. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2372. const
  2373. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2374. var
  2375. OperIdx: Integer;
  2376. begin
  2377. Result := False;
  2378. for OperIdx := 0 to p.ops - 1 do
  2379. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2380. begin
  2381. { The shift and rotate instructions can only use CL }
  2382. if not (
  2383. (OperIdx = 0) and
  2384. { This second condition just helps to avoid unnecessarily
  2385. calling MatchInstruction for 10 different opcodes }
  2386. (p.oper[0]^.reg = NR_CL) and
  2387. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2388. ) then
  2389. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2390. end
  2391. else if p.oper[OperIdx]^.typ = top_ref then
  2392. { It's okay to replace registers in references that get written to }
  2393. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2394. end;
  2395. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2396. begin
  2397. Result :=
  2398. (ref^.index = NR_NO) and
  2399. (
  2400. {$ifdef x86_64}
  2401. (
  2402. (ref^.base = NR_RIP) and
  2403. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2404. ) or
  2405. {$endif x86_64}
  2406. (ref^.refaddr = addr_full) or
  2407. (ref^.base = NR_STACK_POINTER_REG) or
  2408. (ref^.base = current_procinfo.framepointer)
  2409. );
  2410. end;
  2411. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2412. var
  2413. l: asizeint;
  2414. begin
  2415. Result := False;
  2416. { Should have been checked previously }
  2417. if p.opcode <> A_LEA then
  2418. InternalError(2020072501);
  2419. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2420. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2421. not(cs_opt_size in current_settings.optimizerswitches) then
  2422. exit;
  2423. with p.oper[0]^.ref^ do
  2424. begin
  2425. if (base <> p.oper[1]^.reg) or
  2426. (index <> NR_NO) or
  2427. assigned(symbol) then
  2428. exit;
  2429. l:=offset;
  2430. if (l=1) and UseIncDec then
  2431. begin
  2432. p.opcode:=A_INC;
  2433. p.loadreg(0,p.oper[1]^.reg);
  2434. p.ops:=1;
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2436. end
  2437. else if (l=-1) and UseIncDec then
  2438. begin
  2439. p.opcode:=A_DEC;
  2440. p.loadreg(0,p.oper[1]^.reg);
  2441. p.ops:=1;
  2442. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2443. end
  2444. else
  2445. begin
  2446. if (l<0) and (l<>-2147483648) then
  2447. begin
  2448. p.opcode:=A_SUB;
  2449. p.loadConst(0,-l);
  2450. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2451. end
  2452. else
  2453. begin
  2454. p.opcode:=A_ADD;
  2455. p.loadConst(0,l);
  2456. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2457. end;
  2458. end;
  2459. end;
  2460. Result := True;
  2461. end;
  2462. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2463. var
  2464. CurrentReg, ReplaceReg: TRegister;
  2465. begin
  2466. Result := False;
  2467. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2468. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2469. case hp.opcode of
  2470. A_FSTSW, A_FNSTSW,
  2471. A_IN, A_INS, A_OUT, A_OUTS,
  2472. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2473. { These routines have explicit operands, but they are restricted in
  2474. what they can be (e.g. IN and OUT can only read from AL, AX or
  2475. EAX. }
  2476. Exit;
  2477. A_IMUL:
  2478. begin
  2479. { The 1-operand version writes to implicit registers
  2480. The 2-operand version reads from the first operator, and reads
  2481. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2482. the 3-operand version reads from a register that it doesn't write to
  2483. }
  2484. case hp.ops of
  2485. 1:
  2486. if (
  2487. (
  2488. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2489. ) or
  2490. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2491. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2492. begin
  2493. Result := True;
  2494. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2495. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2496. end;
  2497. 2:
  2498. { Only modify the first parameter }
  2499. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2500. begin
  2501. Result := True;
  2502. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2503. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2504. end;
  2505. 3:
  2506. { Only modify the second parameter }
  2507. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2508. begin
  2509. Result := True;
  2510. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2511. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2512. end;
  2513. else
  2514. InternalError(2020012901);
  2515. end;
  2516. end;
  2517. else
  2518. if (hp.ops > 0) and
  2519. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2520. begin
  2521. Result := True;
  2522. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2523. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2524. end;
  2525. end;
  2526. end;
  2527. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2528. var
  2529. hp2: tai;
  2530. p_SourceReg, p_TargetReg: TRegister;
  2531. begin
  2532. Result := False;
  2533. { Backward optimisation. If we have:
  2534. func. %reg1,%reg2
  2535. mov %reg2,%reg3
  2536. (dealloc %reg2)
  2537. Change to:
  2538. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2539. Perform similar optimisations with 1, 3 and 4-operand instructions
  2540. that only have one output.
  2541. }
  2542. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2543. begin
  2544. p_SourceReg := taicpu(p).oper[0]^.reg;
  2545. p_TargetReg := taicpu(p).oper[1]^.reg;
  2546. TransferUsedRegs(TmpUsedRegs);
  2547. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2548. GetLastInstruction(p, hp2) and
  2549. (hp2.typ = ait_instruction) and
  2550. { Have to make sure it's an instruction that only reads from
  2551. the first operands and only writes (not reads or modifies) to
  2552. the last one; in essence, a pure function such as BSR, POPCNT
  2553. or ANDN }
  2554. (
  2555. (
  2556. (taicpu(hp2).ops = 1) and
  2557. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2558. ) or
  2559. (
  2560. (taicpu(hp2).ops = 2) and
  2561. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2562. ) or
  2563. (
  2564. (taicpu(hp2).ops = 3) and
  2565. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2566. ) or
  2567. (
  2568. (taicpu(hp2).ops = 4) and
  2569. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2570. )
  2571. ) and
  2572. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2573. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2574. begin
  2575. case taicpu(hp2).opcode of
  2576. A_FSTSW, A_FNSTSW,
  2577. A_IN, A_INS, A_OUT, A_OUTS,
  2578. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2579. { These routines have explicit operands, but they are restricted in
  2580. what they can be (e.g. IN and OUT can only read from AL, AX or
  2581. EAX. }
  2582. ;
  2583. else
  2584. begin
  2585. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2586. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2587. if not RegInInstruction(p_TargetReg, hp2) then
  2588. begin
  2589. { Since we're allocating from an earlier point, we
  2590. need to remove the register from the tracking }
  2591. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2592. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2593. end;
  2594. RemoveCurrentp(p, hp1);
  2595. { If the Func was another MOV instruction, we might get
  2596. "mov %reg,%reg" that doesn't get removed in Pass 2
  2597. otherwise, so deal with it here (also do something
  2598. similar with lea (%reg),%reg}
  2599. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2600. begin
  2601. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2602. if p = hp2 then
  2603. RemoveCurrentp(p)
  2604. else
  2605. RemoveInstruction(hp2);
  2606. end;
  2607. Result := True;
  2608. Exit;
  2609. end;
  2610. end;
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2615. begin
  2616. Result := False;
  2617. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2618. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2619. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2620. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2621. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2622. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2623. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2624. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2625. begin
  2626. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2627. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2628. Result := True;
  2629. end;
  2630. end;
  2631. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2632. var
  2633. hp1, hp2, hp3, hp4: tai;
  2634. DoOptimisation, TempBool: Boolean;
  2635. {$ifdef x86_64}
  2636. NewConst: TCGInt;
  2637. {$endif x86_64}
  2638. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2639. begin
  2640. if taicpu(hp1).opcode = signed_movop then
  2641. begin
  2642. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2643. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2644. end
  2645. else
  2646. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2647. end;
  2648. function TryConstMerge(var p1, p2: tai): Boolean;
  2649. var
  2650. ThisRef: TReference;
  2651. begin
  2652. Result := False;
  2653. ThisRef := taicpu(p2).oper[1]^.ref^;
  2654. { Only permit writes to the stack, since we can guarantee alignment with that }
  2655. if (ThisRef.index = NR_NO) and
  2656. (
  2657. (ThisRef.base = NR_STACK_POINTER_REG) or
  2658. (ThisRef.base = current_procinfo.framepointer)
  2659. ) then
  2660. begin
  2661. case taicpu(p).opsize of
  2662. S_B:
  2663. begin
  2664. { Word writes must be on a 2-byte boundary }
  2665. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2666. begin
  2667. { Reduce offset of second reference to see if it is sequential with the first }
  2668. Dec(ThisRef.offset, 1);
  2669. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2670. begin
  2671. { Make sure the constants aren't represented as a
  2672. negative number, as these won't merge properly }
  2673. taicpu(p1).opsize := S_W;
  2674. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2675. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2676. RemoveInstruction(p2);
  2677. Result := True;
  2678. end;
  2679. end;
  2680. end;
  2681. S_W:
  2682. begin
  2683. { Longword writes must be on a 4-byte boundary }
  2684. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2685. begin
  2686. { Reduce offset of second reference to see if it is sequential with the first }
  2687. Dec(ThisRef.offset, 2);
  2688. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2689. begin
  2690. { Make sure the constants aren't represented as a
  2691. negative number, as these won't merge properly }
  2692. taicpu(p1).opsize := S_L;
  2693. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2694. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2695. RemoveInstruction(p2);
  2696. Result := True;
  2697. end;
  2698. end;
  2699. end;
  2700. {$ifdef x86_64}
  2701. S_L:
  2702. begin
  2703. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2704. see if the constants can be encoded this way. }
  2705. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2706. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2707. { Quadword writes must be on an 8-byte boundary }
  2708. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2709. begin
  2710. { Reduce offset of second reference to see if it is sequential with the first }
  2711. Dec(ThisRef.offset, 4);
  2712. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2713. begin
  2714. { Make sure the constants aren't represented as a
  2715. negative number, as these won't merge properly }
  2716. taicpu(p1).opsize := S_Q;
  2717. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2718. taicpu(p1).oper[0]^.val := NewConst;
  2719. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2720. RemoveInstruction(p2);
  2721. Result := True;
  2722. end;
  2723. end;
  2724. end;
  2725. {$endif x86_64}
  2726. else
  2727. ;
  2728. end;
  2729. end;
  2730. end;
  2731. var
  2732. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2733. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2734. NewSize: topsize; NewOffset: asizeint;
  2735. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2736. SourceRef, TargetRef: TReference;
  2737. MovAligned, MovUnaligned: TAsmOp;
  2738. ThisRef: TReference;
  2739. JumpTracking: TLinkedList;
  2740. begin
  2741. Result:=false;
  2742. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2743. { remove mov reg1,reg1? }
  2744. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2745. then
  2746. begin
  2747. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2748. { take care of the register (de)allocs following p }
  2749. RemoveCurrentP(p, hp1);
  2750. Result:=true;
  2751. exit;
  2752. end;
  2753. { All the next optimisations require a next instruction }
  2754. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2755. Exit;
  2756. { Prevent compiler warnings }
  2757. p_TargetReg := NR_NO;
  2758. if taicpu(p).oper[1]^.typ = top_reg then
  2759. begin
  2760. { Saves on a large number of dereferences }
  2761. p_TargetReg := taicpu(p).oper[1]^.reg;
  2762. { Look for:
  2763. mov %reg1,%reg2
  2764. ??? %reg2,r/m
  2765. Change to:
  2766. mov %reg1,%reg2
  2767. ??? %reg1,r/m
  2768. }
  2769. if taicpu(p).oper[0]^.typ = top_reg then
  2770. begin
  2771. if RegReadByInstruction(p_TargetReg, hp1) and
  2772. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2773. begin
  2774. { A change has occurred, just not in p }
  2775. Result := True;
  2776. TransferUsedRegs(TmpUsedRegs);
  2777. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2778. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2779. { Just in case something didn't get modified (e.g. an
  2780. implicit register) }
  2781. not RegReadByInstruction(p_TargetReg, hp1) then
  2782. begin
  2783. { We can remove the original MOV }
  2784. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2785. RemoveCurrentp(p, hp1);
  2786. { UsedRegs got updated by RemoveCurrentp }
  2787. Result := True;
  2788. Exit;
  2789. end;
  2790. { If we know a MOV instruction has become a null operation, we might as well
  2791. get rid of it now to save time. }
  2792. if (taicpu(hp1).opcode = A_MOV) and
  2793. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2794. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2795. { Just being a register is enough to confirm it's a null operation }
  2796. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2797. begin
  2798. Result := True;
  2799. { Speed-up to reduce a pipeline stall... if we had something like...
  2800. movl %eax,%edx
  2801. movw %dx,%ax
  2802. ... the second instruction would change to movw %ax,%ax, but
  2803. given that it is now %ax that's active rather than %eax,
  2804. penalties might occur due to a partial register write, so instead,
  2805. change it to a MOVZX instruction when optimising for speed.
  2806. }
  2807. if not (cs_opt_size in current_settings.optimizerswitches) and
  2808. IsMOVZXAcceptable and
  2809. (taicpu(hp1).opsize < taicpu(p).opsize)
  2810. {$ifdef x86_64}
  2811. { operations already implicitly set the upper 64 bits to zero }
  2812. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2813. {$endif x86_64}
  2814. then
  2815. begin
  2816. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2817. case taicpu(p).opsize of
  2818. S_W:
  2819. if taicpu(hp1).opsize = S_B then
  2820. taicpu(hp1).opsize := S_BL
  2821. else
  2822. InternalError(2020012911);
  2823. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2824. case taicpu(hp1).opsize of
  2825. S_B:
  2826. taicpu(hp1).opsize := S_BL;
  2827. S_W:
  2828. taicpu(hp1).opsize := S_WL;
  2829. else
  2830. InternalError(2020012912);
  2831. end;
  2832. else
  2833. InternalError(2020012910);
  2834. end;
  2835. taicpu(hp1).opcode := A_MOVZX;
  2836. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2837. end
  2838. else
  2839. begin
  2840. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2841. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2842. RemoveInstruction(hp1);
  2843. { The instruction after what was hp1 is now the immediate next instruction,
  2844. so we can continue to make optimisations if it's present }
  2845. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2846. Exit;
  2847. hp1 := hp2;
  2848. end;
  2849. end;
  2850. end;
  2851. end;
  2852. end;
  2853. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2854. overwrites the original destination register. e.g.
  2855. movl ###,%reg2d
  2856. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2857. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2858. }
  2859. if (taicpu(p).oper[1]^.typ = top_reg) and
  2860. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2861. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2862. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2863. begin
  2864. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2865. begin
  2866. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2867. case taicpu(p).oper[0]^.typ of
  2868. top_const:
  2869. { We have something like:
  2870. movb $x, %regb
  2871. movzbl %regb,%regd
  2872. Change to:
  2873. movl $x, %regd
  2874. }
  2875. begin
  2876. case taicpu(hp1).opsize of
  2877. S_BW:
  2878. begin
  2879. convert_mov_value(A_MOVSX, $FF);
  2880. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2881. taicpu(p).opsize := S_W;
  2882. end;
  2883. S_BL:
  2884. begin
  2885. convert_mov_value(A_MOVSX, $FF);
  2886. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2887. taicpu(p).opsize := S_L;
  2888. end;
  2889. S_WL:
  2890. begin
  2891. convert_mov_value(A_MOVSX, $FFFF);
  2892. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2893. taicpu(p).opsize := S_L;
  2894. end;
  2895. {$ifdef x86_64}
  2896. S_BQ:
  2897. begin
  2898. convert_mov_value(A_MOVSX, $FF);
  2899. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2900. taicpu(p).opsize := S_Q;
  2901. end;
  2902. S_WQ:
  2903. begin
  2904. convert_mov_value(A_MOVSX, $FFFF);
  2905. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2906. taicpu(p).opsize := S_Q;
  2907. end;
  2908. S_LQ:
  2909. begin
  2910. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2911. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2912. taicpu(p).opsize := S_Q;
  2913. end;
  2914. {$endif x86_64}
  2915. else
  2916. { If hp1 was a MOV instruction, it should have been
  2917. optimised already }
  2918. InternalError(2020021001);
  2919. end;
  2920. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2921. RemoveInstruction(hp1);
  2922. Result := True;
  2923. Exit;
  2924. end;
  2925. top_ref:
  2926. begin
  2927. { We have something like:
  2928. movb mem, %regb
  2929. movzbl %regb,%regd
  2930. Change to:
  2931. movzbl mem, %regd
  2932. }
  2933. ThisRef := taicpu(p).oper[0]^.ref^;
  2934. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2935. begin
  2936. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2937. taicpu(hp1).loadref(0, ThisRef);
  2938. { Make sure any registers in the references are properly tracked }
  2939. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2940. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2941. if (ThisRef.index <> NR_NO) then
  2942. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2943. RemoveCurrentP(p, hp1);
  2944. Result := True;
  2945. Exit;
  2946. end;
  2947. end;
  2948. else
  2949. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2950. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2951. Exit;
  2952. end;
  2953. end
  2954. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2955. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2956. optimised }
  2957. else
  2958. begin
  2959. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2960. RemoveCurrentP(p, hp1);
  2961. Result := True;
  2962. Exit;
  2963. end;
  2964. end;
  2965. if (taicpu(hp1).opcode = A_AND) and
  2966. (taicpu(p).oper[1]^.typ = top_reg) and
  2967. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2968. begin
  2969. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2970. begin
  2971. case taicpu(p).opsize of
  2972. S_L:
  2973. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2974. begin
  2975. { Optimize out:
  2976. mov x, %reg
  2977. and ffffffffh, %reg
  2978. }
  2979. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2980. RemoveInstruction(hp1);
  2981. Result:=true;
  2982. exit;
  2983. end;
  2984. S_Q: { TODO: Confirm if this is even possible }
  2985. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2986. begin
  2987. { Optimize out:
  2988. mov x, %reg
  2989. and ffffffffffffffffh, %reg
  2990. }
  2991. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2992. RemoveInstruction(hp1);
  2993. Result:=true;
  2994. exit;
  2995. end;
  2996. else
  2997. ;
  2998. end;
  2999. if (
  3000. (taicpu(p).oper[0]^.typ=top_reg) or
  3001. (
  3002. (taicpu(p).oper[0]^.typ=top_ref) and
  3003. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3004. )
  3005. ) and
  3006. GetNextInstruction(hp1,hp2) and
  3007. MatchInstruction(hp2,A_TEST,[]) and
  3008. (
  3009. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3010. (
  3011. { If the register being tested is smaller than the one
  3012. that received a bitwise AND, permit it if the constant
  3013. fits into the smaller size }
  3014. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3015. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3016. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3017. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3018. (
  3019. (
  3020. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3021. (taicpu(hp1).oper[0]^.val <= $FF)
  3022. ) or
  3023. (
  3024. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3025. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3026. {$ifdef x86_64}
  3027. ) or
  3028. (
  3029. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3030. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3031. {$endif x86_64}
  3032. )
  3033. )
  3034. )
  3035. ) and
  3036. (
  3037. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3038. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3039. ) and
  3040. GetNextInstruction(hp2,hp3) and
  3041. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3042. (taicpu(hp3).condition in [C_E,C_NE]) then
  3043. begin
  3044. TransferUsedRegs(TmpUsedRegs);
  3045. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3046. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3047. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3048. begin
  3049. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3050. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3051. taicpu(hp1).opcode:=A_TEST;
  3052. { Shrink the TEST instruction down to the smallest possible size }
  3053. case taicpu(hp1).oper[0]^.val of
  3054. 0..255:
  3055. if (taicpu(hp1).opsize <> S_B)
  3056. {$ifndef x86_64}
  3057. and (
  3058. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3059. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3060. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3061. )
  3062. {$endif x86_64}
  3063. then
  3064. begin
  3065. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3066. { Only print debug message if the TEST instruction
  3067. is a different size before and after }
  3068. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3069. taicpu(hp1).opsize := S_B;
  3070. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3071. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3072. end;
  3073. 256..65535:
  3074. if (taicpu(hp1).opsize <> S_W) then
  3075. begin
  3076. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3077. { Only print debug message if the TEST instruction
  3078. is a different size before and after }
  3079. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3080. taicpu(hp1).opsize := S_W;
  3081. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3082. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3083. end;
  3084. {$ifdef x86_64}
  3085. 65536..$7FFFFFFF:
  3086. if (taicpu(hp1).opsize <> S_L) then
  3087. begin
  3088. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3089. { Only print debug message if the TEST instruction
  3090. is a different size before and after }
  3091. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3092. taicpu(hp1).opsize := S_L;
  3093. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3094. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3095. end;
  3096. {$endif x86_64}
  3097. else
  3098. ;
  3099. end;
  3100. RemoveInstruction(hp2);
  3101. RemoveCurrentP(p, hp1);
  3102. Result:=true;
  3103. exit;
  3104. end;
  3105. end;
  3106. end
  3107. else if IsMOVZXAcceptable and
  3108. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3109. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3110. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3111. then
  3112. begin
  3113. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3114. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3115. case taicpu(p).opsize of
  3116. S_B:
  3117. if (taicpu(hp1).oper[0]^.val = $ff) then
  3118. begin
  3119. { Convert:
  3120. movb x, %regl movb x, %regl
  3121. andw ffh, %regw andl ffh, %regd
  3122. To:
  3123. movzbw x, %regd movzbl x, %regd
  3124. (Identical registers, just different sizes)
  3125. }
  3126. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3127. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3128. case taicpu(hp1).opsize of
  3129. S_W: NewSize := S_BW;
  3130. S_L: NewSize := S_BL;
  3131. {$ifdef x86_64}
  3132. S_Q: NewSize := S_BQ;
  3133. {$endif x86_64}
  3134. else
  3135. InternalError(2018011510);
  3136. end;
  3137. end
  3138. else
  3139. NewSize := S_NO;
  3140. S_W:
  3141. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3142. begin
  3143. { Convert:
  3144. movw x, %regw
  3145. andl ffffh, %regd
  3146. To:
  3147. movzwl x, %regd
  3148. (Identical registers, just different sizes)
  3149. }
  3150. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3151. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3152. case taicpu(hp1).opsize of
  3153. S_L: NewSize := S_WL;
  3154. {$ifdef x86_64}
  3155. S_Q: NewSize := S_WQ;
  3156. {$endif x86_64}
  3157. else
  3158. InternalError(2018011511);
  3159. end;
  3160. end
  3161. else
  3162. NewSize := S_NO;
  3163. else
  3164. NewSize := S_NO;
  3165. end;
  3166. if NewSize <> S_NO then
  3167. begin
  3168. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3169. { The actual optimization }
  3170. taicpu(p).opcode := A_MOVZX;
  3171. taicpu(p).changeopsize(NewSize);
  3172. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3173. { Safeguard if "and" is followed by a conditional command }
  3174. TransferUsedRegs(TmpUsedRegs);
  3175. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3176. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3177. begin
  3178. { At this point, the "and" command is effectively equivalent to
  3179. "test %reg,%reg". This will be handled separately by the
  3180. Peephole Optimizer. [Kit] }
  3181. DebugMsg(SPeepholeOptimization + PreMessage +
  3182. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3183. end
  3184. else
  3185. begin
  3186. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3187. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3188. RemoveInstruction(hp1);
  3189. end;
  3190. Result := True;
  3191. Exit;
  3192. end;
  3193. end;
  3194. end;
  3195. if (taicpu(hp1).opcode = A_OR) and
  3196. (taicpu(p).oper[1]^.typ = top_reg) and
  3197. MatchOperand(taicpu(p).oper[0]^, 0) and
  3198. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3199. begin
  3200. { mov 0, %reg
  3201. or ###,%reg
  3202. Change to (only if the flags are not used):
  3203. mov ###,%reg
  3204. }
  3205. TransferUsedRegs(TmpUsedRegs);
  3206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3207. DoOptimisation := True;
  3208. { Even if the flags are used, we might be able to do the optimisation
  3209. if the conditions are predictable }
  3210. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3211. begin
  3212. { Only perform if ### = %reg (the same register) or equal to 0,
  3213. so %reg is guaranteed to still have a value of zero }
  3214. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3215. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3216. begin
  3217. hp2 := hp1;
  3218. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3219. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3220. GetNextInstruction(hp2, hp3) do
  3221. begin
  3222. { Don't continue modifying if the flags state is getting changed }
  3223. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3224. Break;
  3225. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3226. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3227. begin
  3228. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3229. begin
  3230. { Condition is always true }
  3231. case taicpu(hp3).opcode of
  3232. A_Jcc:
  3233. begin
  3234. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3235. { Check for jump shortcuts before we destroy the condition }
  3236. DoJumpOptimizations(hp3, TempBool);
  3237. MakeUnconditional(taicpu(hp3));
  3238. Result := True;
  3239. end;
  3240. A_CMOVcc:
  3241. begin
  3242. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3243. taicpu(hp3).opcode := A_MOV;
  3244. taicpu(hp3).condition := C_None;
  3245. Result := True;
  3246. end;
  3247. A_SETcc:
  3248. begin
  3249. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3250. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3251. taicpu(hp3).opcode := A_MOV;
  3252. taicpu(hp3).ops := 2;
  3253. taicpu(hp3).condition := C_None;
  3254. taicpu(hp3).opsize := S_B;
  3255. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3256. taicpu(hp3).loadconst(0, 1);
  3257. Result := True;
  3258. end;
  3259. else
  3260. InternalError(2021090701);
  3261. end;
  3262. end
  3263. 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
  3264. begin
  3265. { Condition is always false }
  3266. case taicpu(hp3).opcode of
  3267. A_Jcc:
  3268. begin
  3269. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3270. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3271. RemoveInstruction(hp3);
  3272. Result := True;
  3273. { Since hp3 was deleted, hp2 must not be updated }
  3274. Continue;
  3275. end;
  3276. A_CMOVcc:
  3277. begin
  3278. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3279. RemoveInstruction(hp3);
  3280. Result := True;
  3281. { Since hp3 was deleted, hp2 must not be updated }
  3282. Continue;
  3283. end;
  3284. A_SETcc:
  3285. begin
  3286. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3287. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3288. taicpu(hp3).opcode := A_MOV;
  3289. taicpu(hp3).ops := 2;
  3290. taicpu(hp3).condition := C_None;
  3291. taicpu(hp3).opsize := S_B;
  3292. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3293. taicpu(hp3).loadconst(0, 0);
  3294. Result := True;
  3295. end;
  3296. else
  3297. InternalError(2021090702);
  3298. end;
  3299. end
  3300. else
  3301. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3302. DoOptimisation := False;
  3303. end;
  3304. hp2 := hp3;
  3305. end;
  3306. { Flags are still in use - don't optimise }
  3307. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3308. DoOptimisation := False;
  3309. end
  3310. else
  3311. DoOptimisation := False;
  3312. end;
  3313. if DoOptimisation then
  3314. begin
  3315. {$ifdef x86_64}
  3316. { OR only supports 32-bit sign-extended constants for 64-bit
  3317. instructions, so compensate for this if the constant is
  3318. encoded as a value greater than or equal to 2^31 }
  3319. if (taicpu(hp1).opsize = S_Q) and
  3320. (taicpu(hp1).oper[0]^.typ = top_const) and
  3321. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3322. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3323. {$endif x86_64}
  3324. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3325. taicpu(hp1).opcode := A_MOV;
  3326. RemoveCurrentP(p, hp1);
  3327. Result := True;
  3328. Exit;
  3329. end;
  3330. end;
  3331. { Next instruction is also a MOV ? }
  3332. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3333. begin
  3334. if MatchOpType(taicpu(p), top_const, top_ref) and
  3335. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3336. TryConstMerge(p, hp1) then
  3337. begin
  3338. Result := True;
  3339. { In case we have four byte writes in a row, check for 2 more
  3340. right now so we don't have to wait for another iteration of
  3341. pass 1
  3342. }
  3343. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3344. case taicpu(p).opsize of
  3345. S_W:
  3346. begin
  3347. if GetNextInstruction(p, hp1) and
  3348. MatchInstruction(hp1, A_MOV, [S_B]) and
  3349. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3350. GetNextInstruction(hp1, hp2) and
  3351. MatchInstruction(hp2, A_MOV, [S_B]) and
  3352. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3353. { Try to merge the two bytes }
  3354. TryConstMerge(hp1, hp2) then
  3355. { Now try to merge the two words (hp2 will get deleted) }
  3356. TryConstMerge(p, hp1);
  3357. end;
  3358. S_L:
  3359. begin
  3360. { Though this only really benefits x86_64 and not i386, it
  3361. gets a potential optimisation done faster and hence
  3362. reduces the number of times OptPass1MOV is entered }
  3363. if GetNextInstruction(p, hp1) and
  3364. MatchInstruction(hp1, A_MOV, [S_W]) and
  3365. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3366. GetNextInstruction(hp1, hp2) and
  3367. MatchInstruction(hp2, A_MOV, [S_W]) and
  3368. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3369. { Try to merge the two words }
  3370. TryConstMerge(hp1, hp2) then
  3371. { This will always fail on i386, so don't bother
  3372. calling it unless we're doing x86_64 }
  3373. {$ifdef x86_64}
  3374. { Now try to merge the two longwords (hp2 will get deleted) }
  3375. TryConstMerge(p, hp1)
  3376. {$endif x86_64}
  3377. ;
  3378. end;
  3379. else
  3380. ;
  3381. end;
  3382. Exit;
  3383. end;
  3384. if (taicpu(p).oper[1]^.typ = top_reg) and
  3385. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3386. begin
  3387. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3388. TransferUsedRegs(TmpUsedRegs);
  3389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3390. { we have
  3391. mov x, %treg
  3392. mov %treg, y
  3393. }
  3394. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3395. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3396. { we've got
  3397. mov x, %treg
  3398. mov %treg, y
  3399. with %treg is not used after }
  3400. case taicpu(p).oper[0]^.typ Of
  3401. { top_reg is covered by DeepMOVOpt }
  3402. top_const:
  3403. begin
  3404. { change
  3405. mov const, %treg
  3406. mov %treg, y
  3407. to
  3408. mov const, y
  3409. }
  3410. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3411. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3412. begin
  3413. if taicpu(hp1).oper[1]^.typ=top_reg then
  3414. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3415. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3416. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3417. RemoveInstruction(hp1);
  3418. Result:=true;
  3419. Exit;
  3420. end;
  3421. end;
  3422. top_ref:
  3423. case taicpu(hp1).oper[1]^.typ of
  3424. top_reg:
  3425. begin
  3426. { change
  3427. mov mem, %treg
  3428. mov %treg, %reg
  3429. to
  3430. mov mem, %reg"
  3431. }
  3432. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3433. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3435. RemoveInstruction(hp1);
  3436. Result:=true;
  3437. Exit;
  3438. end;
  3439. top_ref:
  3440. begin
  3441. {$ifdef x86_64}
  3442. { Look for the following to simplify:
  3443. mov x(mem1), %reg
  3444. mov %reg, y(mem2)
  3445. mov x+8(mem1), %reg
  3446. mov %reg, y+8(mem2)
  3447. Change to:
  3448. movdqu x(mem1), %xmmreg
  3449. movdqu %xmmreg, y(mem2)
  3450. ...but only as long as the memory blocks don't overlap
  3451. }
  3452. SourceRef := taicpu(p).oper[0]^.ref^;
  3453. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3454. if (taicpu(p).opsize = S_Q) and
  3455. GetNextInstruction(hp1, hp2) and
  3456. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3457. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3458. begin
  3459. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3460. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3461. Inc(SourceRef.offset, 8);
  3462. if UseAVX then
  3463. begin
  3464. MovAligned := A_VMOVDQA;
  3465. MovUnaligned := A_VMOVDQU;
  3466. end
  3467. else
  3468. begin
  3469. MovAligned := A_MOVDQA;
  3470. MovUnaligned := A_MOVDQU;
  3471. end;
  3472. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3473. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3474. begin
  3475. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3476. Inc(TargetRef.offset, 8);
  3477. if GetNextInstruction(hp2, hp3) and
  3478. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3479. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3480. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3481. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3482. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3483. begin
  3484. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3485. if NewMMReg <> NR_NO then
  3486. begin
  3487. { Remember that the offsets are 8 ahead }
  3488. if ((SourceRef.offset mod 16) = 8) and
  3489. (
  3490. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3491. (SourceRef.base = current_procinfo.framepointer) or
  3492. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3493. ) then
  3494. taicpu(p).opcode := MovAligned
  3495. else
  3496. taicpu(p).opcode := MovUnaligned;
  3497. taicpu(p).opsize := S_XMM;
  3498. taicpu(p).oper[1]^.reg := NewMMReg;
  3499. if ((TargetRef.offset mod 16) = 8) and
  3500. (
  3501. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3502. (TargetRef.base = current_procinfo.framepointer) or
  3503. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3504. ) then
  3505. taicpu(hp1).opcode := MovAligned
  3506. else
  3507. taicpu(hp1).opcode := MovUnaligned;
  3508. taicpu(hp1).opsize := S_XMM;
  3509. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3510. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3511. RemoveInstruction(hp2);
  3512. RemoveInstruction(hp3);
  3513. Result := True;
  3514. Exit;
  3515. end;
  3516. end;
  3517. end
  3518. else
  3519. begin
  3520. { See if the next references are 8 less rather than 8 greater }
  3521. Dec(SourceRef.offset, 16); { -8 the other way }
  3522. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3523. begin
  3524. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3525. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3526. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3527. GetNextInstruction(hp2, hp3) and
  3528. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3529. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3530. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3531. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3532. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3533. begin
  3534. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3535. if NewMMReg <> NR_NO then
  3536. begin
  3537. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3538. if ((SourceRef.offset mod 16) = 0) and
  3539. (
  3540. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3541. (SourceRef.base = current_procinfo.framepointer) or
  3542. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3543. ) then
  3544. taicpu(hp2).opcode := MovAligned
  3545. else
  3546. taicpu(hp2).opcode := MovUnaligned;
  3547. taicpu(hp2).opsize := S_XMM;
  3548. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3549. if ((TargetRef.offset mod 16) = 0) and
  3550. (
  3551. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3552. (TargetRef.base = current_procinfo.framepointer) or
  3553. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3554. ) then
  3555. taicpu(hp3).opcode := MovAligned
  3556. else
  3557. taicpu(hp3).opcode := MovUnaligned;
  3558. taicpu(hp3).opsize := S_XMM;
  3559. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3561. RemoveInstruction(hp1);
  3562. RemoveCurrentP(p, hp2);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. end;
  3568. end;
  3569. end;
  3570. {$endif x86_64}
  3571. end;
  3572. else
  3573. { The write target should be a reg or a ref }
  3574. InternalError(2021091601);
  3575. end;
  3576. else
  3577. ;
  3578. end
  3579. else
  3580. { %treg is used afterwards, but all eventualities
  3581. other than the first MOV instruction being a constant
  3582. are covered by DeepMOVOpt, so only check for that }
  3583. if (taicpu(p).oper[0]^.typ = top_const) and
  3584. (
  3585. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3586. not (cs_opt_size in current_settings.optimizerswitches) or
  3587. (taicpu(hp1).opsize = S_B)
  3588. ) and
  3589. (
  3590. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3591. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3592. ) then
  3593. begin
  3594. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3595. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3596. end;
  3597. end;
  3598. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3599. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3600. { mov reg1, mem1 or mov mem1, reg1
  3601. mov mem2, reg2 mov reg2, mem2}
  3602. begin
  3603. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3604. { mov reg1, mem1 or mov mem1, reg1
  3605. mov mem2, reg1 mov reg2, mem1}
  3606. begin
  3607. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3608. { Removes the second statement from
  3609. mov reg1, mem1/reg2
  3610. mov mem1/reg2, reg1 }
  3611. begin
  3612. if taicpu(p).oper[0]^.typ=top_reg then
  3613. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3614. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3615. RemoveInstruction(hp1);
  3616. Result:=true;
  3617. exit;
  3618. end
  3619. else
  3620. begin
  3621. TransferUsedRegs(TmpUsedRegs);
  3622. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3623. if (taicpu(p).oper[1]^.typ = top_ref) and
  3624. { mov reg1, mem1
  3625. mov mem2, reg1 }
  3626. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3627. GetNextInstruction(hp1, hp2) and
  3628. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3629. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3630. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3631. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3632. { change to
  3633. mov reg1, mem1 mov reg1, mem1
  3634. mov mem2, reg1 cmp reg1, mem2
  3635. cmp mem1, reg1
  3636. }
  3637. begin
  3638. RemoveInstruction(hp2);
  3639. taicpu(hp1).opcode := A_CMP;
  3640. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3641. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3642. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3643. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3644. end;
  3645. end;
  3646. end
  3647. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3648. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3649. begin
  3650. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3651. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3652. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3653. end
  3654. else
  3655. begin
  3656. TransferUsedRegs(TmpUsedRegs);
  3657. if GetNextInstruction(hp1, hp2) and
  3658. MatchOpType(taicpu(p),top_ref,top_reg) and
  3659. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3660. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3661. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3662. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3663. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3664. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3665. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3666. { mov mem1, %reg1
  3667. mov %reg1, mem2
  3668. mov mem2, reg2
  3669. to:
  3670. mov mem1, reg2
  3671. mov reg2, mem2}
  3672. begin
  3673. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3674. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3675. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3676. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3677. RemoveInstruction(hp2);
  3678. Result := True;
  3679. end
  3680. {$ifdef i386}
  3681. { this is enabled for i386 only, as the rules to create the reg sets below
  3682. are too complicated for x86-64, so this makes this code too error prone
  3683. on x86-64
  3684. }
  3685. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3686. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3687. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3688. { mov mem1, reg1 mov mem1, reg1
  3689. mov reg1, mem2 mov reg1, mem2
  3690. mov mem2, reg2 mov mem2, reg1
  3691. to: to:
  3692. mov mem1, reg1 mov mem1, reg1
  3693. mov mem1, reg2 mov reg1, mem2
  3694. mov reg1, mem2
  3695. or (if mem1 depends on reg1
  3696. and/or if mem2 depends on reg2)
  3697. to:
  3698. mov mem1, reg1
  3699. mov reg1, mem2
  3700. mov reg1, reg2
  3701. }
  3702. begin
  3703. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3704. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3705. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3706. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3707. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3708. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3709. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3710. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3711. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3712. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3713. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3714. end
  3715. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3716. begin
  3717. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3718. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3719. end
  3720. else
  3721. begin
  3722. RemoveInstruction(hp2);
  3723. end
  3724. {$endif i386}
  3725. ;
  3726. end;
  3727. end
  3728. { movl [mem1],reg1
  3729. movl [mem1],reg2
  3730. to
  3731. movl [mem1],reg1
  3732. movl reg1,reg2
  3733. }
  3734. else if not CheckMovMov2MovMov2(p, hp1) and
  3735. { movl const1,[mem1]
  3736. movl [mem1],reg1
  3737. to
  3738. movl const1,reg1
  3739. movl reg1,[mem1]
  3740. }
  3741. MatchOpType(Taicpu(p),top_const,top_ref) and
  3742. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3743. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3744. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3745. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3746. begin
  3747. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3748. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3749. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3750. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3751. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3752. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3753. Result:=true;
  3754. exit;
  3755. end;
  3756. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3757. { Change:
  3758. movl %reg1,%reg2
  3759. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3760. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3761. To:
  3762. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3763. movl x(%reg1),%reg1
  3764. movl %reg1,%regX
  3765. }
  3766. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3767. begin
  3768. p_SourceReg := taicpu(p).oper[0]^.reg;
  3769. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3770. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3771. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3772. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3773. GetNextInstruction(hp1, hp2) and
  3774. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3775. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3776. begin
  3777. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3778. if RegInRef(p_TargetReg, SourceRef) and
  3779. { If %reg1 also appears in the second reference, then it will
  3780. not refer to the same memory block as the first reference }
  3781. not RegInRef(p_SourceReg, SourceRef) then
  3782. begin
  3783. { Check to see if the references match if %reg2 is changed to %reg1 }
  3784. if SourceRef.base = p_TargetReg then
  3785. SourceRef.base := p_SourceReg;
  3786. if SourceRef.index = p_TargetReg then
  3787. SourceRef.index := p_SourceReg;
  3788. { RefsEqual also checks to ensure both references are non-volatile }
  3789. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3790. begin
  3791. taicpu(hp2).loadreg(0, p_SourceReg);
  3792. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3793. Result := True;
  3794. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3795. begin
  3796. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3797. RemoveCurrentP(p, hp1);
  3798. Exit;
  3799. end
  3800. else
  3801. begin
  3802. { Check to see if %reg2 is no longer in use }
  3803. TransferUsedRegs(TmpUsedRegs);
  3804. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3805. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3806. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3807. begin
  3808. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3809. RemoveCurrentP(p, hp1);
  3810. Exit;
  3811. end;
  3812. end;
  3813. { If we reach this point, p and hp1 weren't actually modified,
  3814. so we can do a bit more work on this pass }
  3815. end;
  3816. end;
  3817. end;
  3818. end;
  3819. end;
  3820. {$ifdef x86_64}
  3821. { Change:
  3822. movl %reg1l,%reg2l
  3823. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3824. To:
  3825. movl %reg1l,%reg2l
  3826. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3827. If %reg1 = %reg3, convert to:
  3828. movl %reg1l,%reg2l
  3829. andl %reg1l,%reg1l
  3830. }
  3831. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3832. MatchOpType(taicpu(p), top_reg, top_reg) and
  3833. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3834. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3835. begin
  3836. TransferUsedRegs(TmpUsedRegs);
  3837. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3838. taicpu(hp1).opsize := S_L;
  3839. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3840. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3841. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3842. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3843. begin
  3844. { %reg1 = %reg3 }
  3845. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3846. taicpu(hp1).opcode := A_AND;
  3847. end
  3848. else
  3849. begin
  3850. { %reg1 <> %reg3 }
  3851. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3852. end;
  3853. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3854. begin
  3855. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3856. RemoveCurrentP(p, hp1);
  3857. Result := True;
  3858. Exit;
  3859. end
  3860. else
  3861. begin
  3862. { Initial instruction wasn't actually changed }
  3863. Include(OptsToCheck, aoc_ForceNewIteration);
  3864. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3865. appears below since %reg1 has technically changed }
  3866. if taicpu(hp1).opcode = A_AND then
  3867. Exit;
  3868. end;
  3869. end;
  3870. {$endif x86_64}
  3871. { search further than the next instruction for a mov (as long as it's not a jump) }
  3872. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3873. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3874. (taicpu(p).oper[1]^.typ = top_reg) and
  3875. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3876. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3877. begin
  3878. { we work with hp2 here, so hp1 can be still used later on when
  3879. checking for GetNextInstruction_p }
  3880. hp3 := hp1;
  3881. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3882. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3883. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3884. TransferUsedRegs(TmpUsedRegs);
  3885. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3886. if NotFirstIteration then
  3887. JumpTracking := TLinkedList.Create
  3888. else
  3889. JumpTracking := nil;
  3890. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3891. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3892. (hp2.typ=ait_instruction) do
  3893. begin
  3894. case taicpu(hp2).opcode of
  3895. A_POP:
  3896. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3897. begin
  3898. if not CrossJump and
  3899. not RegUsedBetween(p_TargetReg, p, hp2) then
  3900. begin
  3901. { We can remove the original MOV since the register
  3902. wasn't used between it and its popping from the stack }
  3903. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3904. RemoveCurrentp(p, hp1);
  3905. Result := True;
  3906. JumpTracking.Free;
  3907. Exit;
  3908. end;
  3909. { Can't go any further }
  3910. Break;
  3911. end;
  3912. A_MOV:
  3913. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3914. ((taicpu(p).oper[0]^.typ=top_const) or
  3915. ((taicpu(p).oper[0]^.typ=top_reg) and
  3916. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3917. )
  3918. ) then
  3919. begin
  3920. { we have
  3921. mov x, %treg
  3922. mov %treg, y
  3923. }
  3924. { We don't need to call UpdateUsedRegs for every instruction between
  3925. p and hp2 because the register we're concerned about will not
  3926. become deallocated (otherwise GetNextInstructionUsingReg would
  3927. have stopped at an earlier instruction). [Kit] }
  3928. TempRegUsed :=
  3929. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3930. RegReadByInstruction(p_TargetReg, hp3) or
  3931. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3932. case taicpu(p).oper[0]^.typ Of
  3933. top_reg:
  3934. begin
  3935. { change
  3936. mov %reg, %treg
  3937. mov %treg, y
  3938. to
  3939. mov %reg, y
  3940. }
  3941. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3942. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3943. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3944. begin
  3945. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3946. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3947. if TempRegUsed then
  3948. begin
  3949. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3950. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3951. { Set the start of the next GetNextInstructionUsingRegCond search
  3952. to start at the entry right before hp2 (which is about to be removed) }
  3953. hp3 := tai(hp2.Previous);
  3954. RemoveInstruction(hp2);
  3955. Include(OptsToCheck, aoc_ForceNewIteration);
  3956. { See if there's more we can optimise }
  3957. Continue;
  3958. end
  3959. else
  3960. begin
  3961. RemoveInstruction(hp2);
  3962. { We can remove the original MOV too }
  3963. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3964. RemoveCurrentP(p, hp1);
  3965. Result:=true;
  3966. JumpTracking.Free;
  3967. Exit;
  3968. end;
  3969. end
  3970. else
  3971. begin
  3972. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3973. taicpu(hp2).loadReg(0, p_SourceReg);
  3974. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3975. { Check to see if the register also appears in the reference }
  3976. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3977. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3978. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3979. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3980. begin
  3981. { Don't remove the first instruction if the temporary register is in use }
  3982. if not TempRegUsed then
  3983. begin
  3984. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3985. RemoveCurrentP(p, hp1);
  3986. Result:=true;
  3987. JumpTracking.Free;
  3988. Exit;
  3989. end;
  3990. { No need to set Result to True here. If there's another instruction later
  3991. on that can be optimised, it will be detected when the main Pass 1 loop
  3992. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3993. hp3 := hp2;
  3994. Continue;
  3995. end;
  3996. end;
  3997. end;
  3998. top_const:
  3999. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4000. begin
  4001. { change
  4002. mov const, %treg
  4003. mov %treg, y
  4004. to
  4005. mov const, y
  4006. }
  4007. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4008. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4009. begin
  4010. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4011. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4012. if TempRegUsed then
  4013. begin
  4014. { Don't remove the first instruction if the temporary register is in use }
  4015. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4016. { No need to set Result to True. If there's another instruction later on
  4017. that can be optimised, it will be detected when the main Pass 1 loop
  4018. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4019. end
  4020. else
  4021. begin
  4022. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4023. RemoveCurrentP(p, hp1);
  4024. Result:=true;
  4025. Exit;
  4026. end;
  4027. end;
  4028. end;
  4029. else
  4030. Internalerror(2019103001);
  4031. end;
  4032. end
  4033. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4034. begin
  4035. if not CrossJump and
  4036. not RegUsedBetween(p_TargetReg, p, hp2) and
  4037. not RegReadByInstruction(p_TargetReg, hp2) then
  4038. begin
  4039. { Register is not used before it is overwritten }
  4040. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4041. RemoveCurrentp(p, hp1);
  4042. Result := True;
  4043. Exit;
  4044. end;
  4045. if (taicpu(p).oper[0]^.typ = top_const) and
  4046. (taicpu(hp2).oper[0]^.typ = top_const) then
  4047. begin
  4048. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4049. begin
  4050. { Same value - register hasn't changed }
  4051. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4052. RemoveInstruction(hp2);
  4053. Include(OptsToCheck, aoc_ForceNewIteration);
  4054. { See if there's more we can optimise }
  4055. Continue;
  4056. end;
  4057. end;
  4058. {$ifdef x86_64}
  4059. end
  4060. { Change:
  4061. movl %reg1l,%reg2l
  4062. ...
  4063. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4064. To:
  4065. movl %reg1l,%reg2l
  4066. ...
  4067. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4068. If %reg1 = %reg3, convert to:
  4069. movl %reg1l,%reg2l
  4070. ...
  4071. andl %reg1l,%reg1l
  4072. }
  4073. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4074. (taicpu(p).oper[0]^.typ = top_reg) and
  4075. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4076. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4077. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4078. begin
  4079. TempRegUsed :=
  4080. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4081. RegReadByInstruction(p_TargetReg, hp3) or
  4082. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4083. taicpu(hp2).opsize := S_L;
  4084. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4085. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4086. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4087. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4088. begin
  4089. { %reg1 = %reg3 }
  4090. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4091. taicpu(hp2).opcode := A_AND;
  4092. end
  4093. else
  4094. begin
  4095. { %reg1 <> %reg3 }
  4096. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4097. end;
  4098. if not TempRegUsed then
  4099. begin
  4100. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4101. RemoveCurrentP(p, hp1);
  4102. Result := True;
  4103. Exit;
  4104. end
  4105. else
  4106. begin
  4107. { Initial instruction wasn't actually changed }
  4108. Include(OptsToCheck, aoc_ForceNewIteration);
  4109. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4110. appears below since %reg1 has technically changed }
  4111. if taicpu(hp2).opcode = A_AND then
  4112. Break;
  4113. end;
  4114. {$endif x86_64}
  4115. end
  4116. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4117. GetNextInstruction(hp2, hp4) and
  4118. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4119. { Optimise the following first:
  4120. movl [mem1],reg1
  4121. movl [mem1],reg2
  4122. to
  4123. movl [mem1],reg1
  4124. movl reg1,reg2
  4125. If [mem1] contains the target register and reg1 is the
  4126. the source register, this optimisation will get missed
  4127. and produce less efficient code later on.
  4128. }
  4129. if CheckMovMov2MovMov2(hp2, hp4) then
  4130. { Initial instruction wasn't actually changed }
  4131. Include(OptsToCheck, aoc_ForceNewIteration);
  4132. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4133. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4134. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4135. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4136. begin
  4137. {
  4138. Change from:
  4139. mov ###, %reg
  4140. ...
  4141. movs/z %reg,%reg (Same register, just different sizes)
  4142. To:
  4143. movs/z ###, %reg (Longer version)
  4144. ...
  4145. (remove)
  4146. }
  4147. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4148. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4149. { Keep the first instruction as mov if ### is a constant }
  4150. if taicpu(p).oper[0]^.typ = top_const then
  4151. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4152. else
  4153. begin
  4154. taicpu(p).opcode := taicpu(hp2).opcode;
  4155. taicpu(p).opsize := taicpu(hp2).opsize;
  4156. end;
  4157. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4158. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4159. RemoveInstruction(hp2);
  4160. Result := True;
  4161. JumpTracking.Free;
  4162. Exit;
  4163. end;
  4164. else
  4165. { Move down to the if-block below };
  4166. end;
  4167. { Also catches MOV/S/Z instructions that aren't modified }
  4168. if taicpu(p).oper[0]^.typ = top_reg then
  4169. begin
  4170. p_SourceReg := taicpu(p).oper[0]^.reg;
  4171. if
  4172. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4173. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4174. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4175. begin
  4176. Result := True;
  4177. { Just in case something didn't get modified (e.g. an
  4178. implicit register). Also, if it does read from this
  4179. register, then there's no longer an advantage to
  4180. changing the register on subsequent instructions.}
  4181. if not RegReadByInstruction(p_TargetReg, hp2) then
  4182. begin
  4183. { If a conditional jump was crossed, do not delete
  4184. the original MOV no matter what }
  4185. if not CrossJump and
  4186. { RegEndOfLife returns True if the register is
  4187. deallocated before the next instruction or has
  4188. been loaded with a new value }
  4189. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4190. begin
  4191. { We can remove the original MOV }
  4192. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4193. RemoveCurrentp(p, hp1);
  4194. JumpTracking.Free;
  4195. Result := True;
  4196. Exit;
  4197. end;
  4198. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4199. begin
  4200. { See if there's more we can optimise }
  4201. hp3 := hp2;
  4202. Continue;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. { Break out of the while loop under normal circumstances }
  4208. Break;
  4209. end;
  4210. JumpTracking.Free;
  4211. end;
  4212. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4213. (taicpu(p).oper[1]^.typ = top_reg) and
  4214. (taicpu(p).opsize = S_L) and
  4215. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4216. (hp2.typ = ait_instruction) and
  4217. (taicpu(hp2).opcode = A_AND) and
  4218. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4219. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4220. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4221. ) then
  4222. begin
  4223. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4224. begin
  4225. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4226. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4227. begin
  4228. { Optimize out:
  4229. mov x, %reg
  4230. and ffffffffh, %reg
  4231. }
  4232. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4233. RemoveInstruction(hp2);
  4234. Result:=true;
  4235. exit;
  4236. end;
  4237. end;
  4238. end;
  4239. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4240. x >= RetOffset) as it doesn't do anything (it writes either to a
  4241. parameter or to the temporary storage room for the function
  4242. result)
  4243. }
  4244. if IsExitCode(hp1) and
  4245. (taicpu(p).oper[1]^.typ = top_ref) and
  4246. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4247. (
  4248. (
  4249. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4250. not (
  4251. assigned(current_procinfo.procdef.funcretsym) and
  4252. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4253. )
  4254. ) or
  4255. { Also discard writes to the stack that are below the base pointer,
  4256. as this is temporary storage rather than a function result on the
  4257. stack, say. }
  4258. (
  4259. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4260. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4261. )
  4262. ) then
  4263. begin
  4264. RemoveCurrentp(p, hp1);
  4265. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4266. RemoveLastDeallocForFuncRes(p);
  4267. Result:=true;
  4268. exit;
  4269. end;
  4270. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4271. begin
  4272. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4273. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4274. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4275. begin
  4276. { change
  4277. mov reg1, mem1
  4278. test/cmp x, mem1
  4279. to
  4280. mov reg1, mem1
  4281. test/cmp x, reg1
  4282. }
  4283. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4284. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4285. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4286. Result := True;
  4287. Exit;
  4288. end;
  4289. if DoMovCmpMemOpt(p, hp1) then
  4290. begin
  4291. Result := True;
  4292. Exit;
  4293. end;
  4294. end;
  4295. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4296. { If the flags register is in use, don't change the instruction to an
  4297. ADD otherwise this will scramble the flags. [Kit] }
  4298. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4299. begin
  4300. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4301. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4302. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4303. ) or
  4304. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4305. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4306. )
  4307. ) then
  4308. { mov reg1,ref
  4309. lea reg2,[reg1,reg2]
  4310. to
  4311. add reg2,ref}
  4312. begin
  4313. TransferUsedRegs(TmpUsedRegs);
  4314. { reg1 may not be used afterwards }
  4315. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4316. begin
  4317. Taicpu(hp1).opcode:=A_ADD;
  4318. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4319. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4320. RemoveCurrentp(p, hp1);
  4321. result:=true;
  4322. exit;
  4323. end;
  4324. end;
  4325. { If the LEA instruction can be converted into an arithmetic instruction,
  4326. it may be possible to then fold it in the next optimisation, otherwise
  4327. there's nothing more that can be optimised here. }
  4328. if not ConvertLEA(taicpu(hp1)) then
  4329. Exit;
  4330. end;
  4331. if (taicpu(p).oper[1]^.typ = top_reg) and
  4332. (hp1.typ = ait_instruction) and
  4333. GetNextInstruction(hp1, hp2) and
  4334. MatchInstruction(hp2,A_MOV,[]) and
  4335. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4336. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4337. (
  4338. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4339. {$ifdef x86_64}
  4340. or
  4341. (
  4342. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4343. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4344. )
  4345. {$endif x86_64}
  4346. ) then
  4347. begin
  4348. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4349. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4350. { change movsX/movzX reg/ref, reg2
  4351. add/sub/or/... reg3/$const, reg2
  4352. mov reg2 reg/ref
  4353. dealloc reg2
  4354. to
  4355. add/sub/or/... reg3/$const, reg/ref }
  4356. begin
  4357. TransferUsedRegs(TmpUsedRegs);
  4358. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4359. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4360. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4361. begin
  4362. { by example:
  4363. movswl %si,%eax movswl %si,%eax p
  4364. decl %eax addl %edx,%eax hp1
  4365. movw %ax,%si movw %ax,%si hp2
  4366. ->
  4367. movswl %si,%eax movswl %si,%eax p
  4368. decw %eax addw %edx,%eax hp1
  4369. movw %ax,%si movw %ax,%si hp2
  4370. }
  4371. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4372. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4373. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4374. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4375. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4376. {
  4377. ->
  4378. movswl %si,%eax movswl %si,%eax p
  4379. decw %si addw %dx,%si hp1
  4380. movw %ax,%si movw %ax,%si hp2
  4381. }
  4382. case taicpu(hp1).ops of
  4383. 1:
  4384. begin
  4385. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4386. if taicpu(hp1).oper[0]^.typ=top_reg then
  4387. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4388. end;
  4389. 2:
  4390. begin
  4391. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4392. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4393. (taicpu(hp1).opcode<>A_SHL) and
  4394. (taicpu(hp1).opcode<>A_SHR) and
  4395. (taicpu(hp1).opcode<>A_SAR) then
  4396. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4397. end;
  4398. else
  4399. internalerror(2008042701);
  4400. end;
  4401. {
  4402. ->
  4403. decw %si addw %dx,%si p
  4404. }
  4405. RemoveInstruction(hp2);
  4406. RemoveCurrentP(p, hp1);
  4407. Result:=True;
  4408. Exit;
  4409. end;
  4410. end;
  4411. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4412. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4413. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4414. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4415. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4416. )
  4417. {$ifdef i386}
  4418. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4419. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4420. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4421. {$endif i386}
  4422. then
  4423. { change movsX/movzX reg/ref, reg2
  4424. add/sub/or/... regX/$const, reg2
  4425. mov reg2, reg3
  4426. dealloc reg2
  4427. to
  4428. movsX/movzX reg/ref, reg3
  4429. add/sub/or/... reg3/$const, reg3
  4430. }
  4431. begin
  4432. TransferUsedRegs(TmpUsedRegs);
  4433. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4434. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4435. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4436. begin
  4437. { by example:
  4438. movswl %si,%eax movswl %si,%eax p
  4439. decl %eax addl %edx,%eax hp1
  4440. movw %ax,%si movw %ax,%si hp2
  4441. ->
  4442. movswl %si,%eax movswl %si,%eax p
  4443. decw %eax addw %edx,%eax hp1
  4444. movw %ax,%si movw %ax,%si hp2
  4445. }
  4446. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4447. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4448. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4449. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4450. { limit size of constants as well to avoid assembler errors, but
  4451. check opsize to avoid overflow when left shifting the 1 }
  4452. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4453. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4454. {$ifdef x86_64}
  4455. { Be careful of, for example:
  4456. movl %reg1,%reg2
  4457. addl %reg3,%reg2
  4458. movq %reg2,%reg4
  4459. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4460. }
  4461. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4462. begin
  4463. taicpu(hp2).changeopsize(S_L);
  4464. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4465. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4466. end;
  4467. {$endif x86_64}
  4468. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4469. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4470. if taicpu(p).oper[0]^.typ=top_reg then
  4471. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4472. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4473. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4474. {
  4475. ->
  4476. movswl %si,%eax movswl %si,%eax p
  4477. decw %si addw %dx,%si hp1
  4478. movw %ax,%si movw %ax,%si hp2
  4479. }
  4480. case taicpu(hp1).ops of
  4481. 1:
  4482. begin
  4483. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4484. if taicpu(hp1).oper[0]^.typ=top_reg then
  4485. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4486. end;
  4487. 2:
  4488. begin
  4489. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4490. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4491. (taicpu(hp1).opcode<>A_SHL) and
  4492. (taicpu(hp1).opcode<>A_SHR) and
  4493. (taicpu(hp1).opcode<>A_SAR) then
  4494. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4495. end;
  4496. else
  4497. internalerror(2018111801);
  4498. end;
  4499. {
  4500. ->
  4501. decw %si addw %dx,%si p
  4502. }
  4503. RemoveInstruction(hp2);
  4504. end;
  4505. end;
  4506. end;
  4507. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4508. GetNextInstruction(hp1, hp2) and
  4509. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4510. MatchOperand(Taicpu(p).oper[0]^,0) and
  4511. (Taicpu(p).oper[1]^.typ = top_reg) and
  4512. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4513. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4514. { mov reg1,0
  4515. bts reg1,operand1 --> mov reg1,operand2
  4516. or reg1,operand2 bts reg1,operand1}
  4517. begin
  4518. Taicpu(hp2).opcode:=A_MOV;
  4519. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4520. asml.remove(hp1);
  4521. insertllitem(hp2,hp2.next,hp1);
  4522. RemoveCurrentp(p, hp1);
  4523. Result:=true;
  4524. exit;
  4525. end;
  4526. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4527. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4528. GetNextInstruction(hp1, hp2) and
  4529. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4530. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4531. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4532. { change
  4533. mov reg1,reg2
  4534. sub reg3,reg2
  4535. cmp reg3,reg1
  4536. into
  4537. mov reg1,reg2
  4538. sub reg3,reg2
  4539. }
  4540. begin
  4541. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4542. RemoveInstruction(hp2);
  4543. Result:=true;
  4544. exit;
  4545. end;
  4546. {
  4547. mov ref,reg0
  4548. <op> reg0,reg1
  4549. dealloc reg0
  4550. to
  4551. <op> ref,reg1
  4552. }
  4553. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4554. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4555. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4556. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4557. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4558. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4559. begin
  4560. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4561. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4562. RemoveCurrentp(p, hp1);
  4563. Result:=true;
  4564. exit;
  4565. end;
  4566. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4567. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4568. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4569. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4570. begin
  4571. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4572. {$ifdef x86_64}
  4573. { Convert:
  4574. movq x(ref),%reg64
  4575. shrq y,%reg64
  4576. To:
  4577. movl x+4(ref),%reg32
  4578. shrl y-32,%reg32 (Remove if y = 32)
  4579. }
  4580. if (taicpu(p).opsize = S_Q) and
  4581. (taicpu(hp1).opcode = A_SHR) and
  4582. (taicpu(hp1).oper[0]^.val >= 32) then
  4583. begin
  4584. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4585. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4586. { Convert to 32-bit }
  4587. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4588. taicpu(p).opsize := S_L;
  4589. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4590. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4591. if (taicpu(hp1).oper[0]^.val = 32) then
  4592. begin
  4593. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4594. RemoveInstruction(hp1);
  4595. end
  4596. else
  4597. begin
  4598. { This will potentially open up more arithmetic operations since
  4599. the peephole optimizer now has a big hint that only the lower
  4600. 32 bits are currently in use (and opcodes are smaller in size) }
  4601. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4602. taicpu(hp1).opsize := S_L;
  4603. Dec(taicpu(hp1).oper[0]^.val, 32);
  4604. DebugMsg(SPeepholeOptimization + PreMessage +
  4605. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4606. end;
  4607. Result := True;
  4608. Exit;
  4609. end;
  4610. {$endif x86_64}
  4611. { Convert:
  4612. movl x(ref),%reg
  4613. shrl $24,%reg
  4614. To:
  4615. movzbl x+3(ref),%reg
  4616. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4617. Also accept sar instead of shr, but convert to movsx instead of movzx
  4618. }
  4619. if taicpu(hp1).opcode = A_SHR then
  4620. MovUnaligned := A_MOVZX
  4621. else
  4622. MovUnaligned := A_MOVSX;
  4623. NewSize := S_NO;
  4624. NewOffset := 0;
  4625. case taicpu(p).opsize of
  4626. S_B:
  4627. { No valid combinations };
  4628. S_W:
  4629. if (taicpu(hp1).oper[0]^.val = 8) then
  4630. begin
  4631. NewSize := S_BW;
  4632. NewOffset := 1;
  4633. end;
  4634. S_L:
  4635. case taicpu(hp1).oper[0]^.val of
  4636. 16:
  4637. begin
  4638. NewSize := S_WL;
  4639. NewOffset := 2;
  4640. end;
  4641. 24:
  4642. begin
  4643. NewSize := S_BL;
  4644. NewOffset := 3;
  4645. end;
  4646. else
  4647. ;
  4648. end;
  4649. {$ifdef x86_64}
  4650. S_Q:
  4651. case taicpu(hp1).oper[0]^.val of
  4652. 32:
  4653. begin
  4654. if taicpu(hp1).opcode = A_SAR then
  4655. begin
  4656. { 32-bit to 64-bit is a distinct instruction }
  4657. MovUnaligned := A_MOVSXD;
  4658. NewSize := S_LQ;
  4659. NewOffset := 4;
  4660. end
  4661. else
  4662. { Should have been handled by MovShr2Mov above }
  4663. InternalError(2022081811);
  4664. end;
  4665. 48:
  4666. begin
  4667. NewSize := S_WQ;
  4668. NewOffset := 6;
  4669. end;
  4670. 56:
  4671. begin
  4672. NewSize := S_BQ;
  4673. NewOffset := 7;
  4674. end;
  4675. else
  4676. ;
  4677. end;
  4678. {$endif x86_64}
  4679. else
  4680. InternalError(2022081810);
  4681. end;
  4682. if (NewSize <> S_NO) and
  4683. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4684. begin
  4685. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4686. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4687. debug_op2str(MovUnaligned);
  4688. {$ifdef x86_64}
  4689. if MovUnaligned <> A_MOVSXD then
  4690. { Don't add size suffix for MOVSXD }
  4691. {$endif x86_64}
  4692. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4693. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4694. taicpu(p).opcode := MovUnaligned;
  4695. taicpu(p).opsize := NewSize;
  4696. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4697. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4698. RemoveInstruction(hp1);
  4699. Result := True;
  4700. Exit;
  4701. end;
  4702. end;
  4703. { Backward optimisation shared with OptPass2MOV }
  4704. if FuncMov2Func(p, hp1) then
  4705. begin
  4706. Result := True;
  4707. Exit;
  4708. end;
  4709. end;
  4710. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4711. var
  4712. hp1 : tai;
  4713. begin
  4714. Result:=false;
  4715. if taicpu(p).ops <> 2 then
  4716. exit;
  4717. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4718. GetNextInstruction(p,hp1) then
  4719. begin
  4720. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4721. (taicpu(hp1).ops = 2) then
  4722. begin
  4723. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4724. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4725. { movXX reg1, mem1 or movXX mem1, reg1
  4726. movXX mem2, reg2 movXX reg2, mem2}
  4727. begin
  4728. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4729. { movXX reg1, mem1 or movXX mem1, reg1
  4730. movXX mem2, reg1 movXX reg2, mem1}
  4731. begin
  4732. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4733. begin
  4734. { Removes the second statement from
  4735. movXX reg1, mem1/reg2
  4736. movXX mem1/reg2, reg1
  4737. }
  4738. if taicpu(p).oper[0]^.typ=top_reg then
  4739. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4740. { Removes the second statement from
  4741. movXX mem1/reg1, reg2
  4742. movXX reg2, mem1/reg1
  4743. }
  4744. if (taicpu(p).oper[1]^.typ=top_reg) and
  4745. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4746. begin
  4747. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4748. RemoveInstruction(hp1);
  4749. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4750. Result:=true;
  4751. exit;
  4752. end
  4753. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4754. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4755. begin
  4756. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4757. RemoveInstruction(hp1);
  4758. Result:=true;
  4759. exit;
  4760. end;
  4761. end
  4762. end;
  4763. end;
  4764. end;
  4765. end;
  4766. end;
  4767. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4768. var
  4769. hp1 : tai;
  4770. begin
  4771. result:=false;
  4772. { replace
  4773. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4774. MovX %mreg2,%mreg1
  4775. dealloc %mreg2
  4776. by
  4777. <Op>X %mreg2,%mreg1
  4778. ?
  4779. }
  4780. if GetNextInstruction(p,hp1) and
  4781. { we mix single and double opperations here because we assume that the compiler
  4782. generates vmovapd only after double operations and vmovaps only after single operations }
  4783. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4784. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4785. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4786. (taicpu(p).oper[0]^.typ=top_reg) then
  4787. begin
  4788. TransferUsedRegs(TmpUsedRegs);
  4789. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4790. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4791. begin
  4792. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4793. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4794. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4795. RemoveInstruction(hp1);
  4796. result:=true;
  4797. end;
  4798. end;
  4799. end;
  4800. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4801. var
  4802. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4803. JumpLabel, JumpLabel_dist: TAsmLabel;
  4804. FirstValue, SecondValue: TCGInt;
  4805. function OptimizeJump(var InputP: tai): Boolean;
  4806. var
  4807. TempBool: Boolean;
  4808. begin
  4809. Result := False;
  4810. TempBool := True;
  4811. if DoJumpOptimizations(InputP, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(InputP) then
  4816. begin
  4817. { CollapseZeroDistJump will be set to the label or an align
  4818. before it after the jump if it optimises, whether or not
  4819. the label is live or dead }
  4820. if (InputP.typ = ait_align) or
  4821. (
  4822. (InputP.typ = ait_label) and
  4823. not (tai_label(InputP).labsym.is_used)
  4824. ) then
  4825. GetNextInstruction(InputP, InputP);
  4826. end;
  4827. Exit;
  4828. end;
  4829. end;
  4830. begin
  4831. Result := False;
  4832. if (taicpu(p).oper[0]^.typ = top_const) and
  4833. (taicpu(p).oper[0]^.val <> -1) then
  4834. begin
  4835. { Convert unsigned maximum constants to -1 to aid optimisation }
  4836. case taicpu(p).opsize of
  4837. S_B:
  4838. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4839. begin
  4840. taicpu(p).oper[0]^.val := -1;
  4841. Result := True;
  4842. Exit;
  4843. end;
  4844. S_W:
  4845. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4846. begin
  4847. taicpu(p).oper[0]^.val := -1;
  4848. Result := True;
  4849. Exit;
  4850. end;
  4851. S_L:
  4852. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4853. begin
  4854. taicpu(p).oper[0]^.val := -1;
  4855. Result := True;
  4856. Exit;
  4857. end;
  4858. {$ifdef x86_64}
  4859. S_Q:
  4860. { Storing anything greater than $7FFFFFFF is not possible so do
  4861. nothing };
  4862. {$endif x86_64}
  4863. else
  4864. InternalError(2021121001);
  4865. end;
  4866. end;
  4867. if GetNextInstruction(p, hp1) and
  4868. TrySwapMovCmp(p, hp1) then
  4869. begin
  4870. Result := True;
  4871. Exit;
  4872. end;
  4873. p_label := nil;
  4874. JumpLabel := nil;
  4875. if MatchInstruction(hp1, A_Jcc, []) then
  4876. begin
  4877. if OptimizeJump(hp1) then
  4878. begin
  4879. Result := True;
  4880. if Assigned(hp1) then
  4881. begin
  4882. { CollapseZeroDistJump will be set to the label or an align
  4883. before it after the jump if it optimises, whether or not
  4884. the label is live or dead }
  4885. if (hp1.typ = ait_align) or
  4886. (
  4887. (hp1.typ = ait_label) and
  4888. not (tai_label(hp1).labsym.is_used)
  4889. ) then
  4890. GetNextInstruction(hp1, hp1);
  4891. end;
  4892. TransferUsedRegs(TmpUsedRegs);
  4893. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4894. if not Assigned(hp1) or
  4895. (
  4896. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4897. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4898. ) then
  4899. begin
  4900. { No more conditional jumps; conditional statement is no longer required }
  4901. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4902. RemoveCurrentP(p);
  4903. end;
  4904. Exit;
  4905. end;
  4906. if IsJumpToLabel(taicpu(hp1)) then
  4907. begin
  4908. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4909. if Assigned(JumpLabel) then
  4910. p_label := getlabelwithsym(JumpLabel);
  4911. end;
  4912. end;
  4913. { Search for:
  4914. test $x,(reg/ref)
  4915. jne @lbl1
  4916. test $y,(reg/ref) (same register or reference)
  4917. jne @lbl1
  4918. Change to:
  4919. test $(x or y),(reg/ref)
  4920. jne @lbl1
  4921. (Note, this doesn't work with je instead of jne)
  4922. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4923. Also search for:
  4924. test $x,(reg/ref)
  4925. je @lbl1
  4926. ...
  4927. test $y,(reg/ref)
  4928. je/jne @lbl2
  4929. If (x or y) = x, then the second jump is deterministic
  4930. }
  4931. if (
  4932. (
  4933. (taicpu(p).oper[0]^.typ = top_const) or
  4934. (
  4935. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4936. (taicpu(p).oper[0]^.typ = top_reg) and
  4937. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4938. )
  4939. ) and
  4940. MatchInstruction(hp1, A_JCC, [])
  4941. ) then
  4942. begin
  4943. if (taicpu(p).oper[0]^.typ = top_reg) and
  4944. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4945. FirstValue := -1
  4946. else
  4947. FirstValue := taicpu(p).oper[0]^.val;
  4948. { If we have several test/jne's in a row, it might be the case that
  4949. the second label doesn't go to the same location, but the one
  4950. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4951. so accommodate for this with a while loop.
  4952. }
  4953. hp1_last := hp1;
  4954. while (
  4955. (
  4956. (taicpu(p).oper[1]^.typ = top_reg) and
  4957. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4958. ) or GetNextInstruction(hp1_last, p_dist)
  4959. ) and (p_dist.typ = ait_instruction) do
  4960. begin
  4961. if (
  4962. (
  4963. (taicpu(p_dist).opcode = A_TEST) and
  4964. (
  4965. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4966. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4967. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4968. )
  4969. ) or
  4970. (
  4971. { cmp 0,%reg = test %reg,%reg }
  4972. (taicpu(p_dist).opcode = A_CMP) and
  4973. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4974. )
  4975. ) and
  4976. { Make sure the destination operands are actually the same }
  4977. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4978. GetNextInstruction(p_dist, hp1_dist) and
  4979. MatchInstruction(hp1_dist, A_JCC, []) then
  4980. begin
  4981. if OptimizeJump(hp1_dist) then
  4982. begin
  4983. Result := True;
  4984. Exit;
  4985. end;
  4986. if
  4987. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4988. (
  4989. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4990. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4991. ) then
  4992. SecondValue := -1
  4993. else
  4994. SecondValue := taicpu(p_dist).oper[0]^.val;
  4995. { If both of the TEST constants are identical, delete the
  4996. second TEST that is unnecessary (be careful though, just
  4997. in case the flags are modified in between) }
  4998. if (FirstValue = SecondValue) then
  4999. begin
  5000. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5001. begin
  5002. { Since the second jump's condition is a subset of the first, we
  5003. know it will never branch because the first jump dominates it.
  5004. Get it out of the way now rather than wait for the jump
  5005. optimisations for a speed boost. }
  5006. if IsJumpToLabel(taicpu(hp1_dist)) then
  5007. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5008. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5009. RemoveInstruction(hp1_dist);
  5010. Result := True;
  5011. end
  5012. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5013. begin
  5014. { If the inverse of the first condition is a subset of the second,
  5015. the second one will definitely branch if the first one doesn't }
  5016. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5017. { We can remove the TEST instruction too }
  5018. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5019. RemoveInstruction(p_dist);
  5020. MakeUnconditional(taicpu(hp1_dist));
  5021. RemoveDeadCodeAfterJump(hp1_dist);
  5022. { Since the jump is now unconditional, we can't
  5023. continue any further with this particular
  5024. optimisation. The original TEST is still intact
  5025. though, so there might be something else we can
  5026. do }
  5027. Include(OptsToCheck, aoc_ForceNewIteration);
  5028. Break;
  5029. end;
  5030. if Result or
  5031. { If a jump wasn't removed or made unconditional, only
  5032. remove the identical TEST instruction if the flags
  5033. weren't modified }
  5034. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5035. begin
  5036. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5037. RemoveInstruction(p_dist);
  5038. { If the jump was removed or made unconditional, we
  5039. don't need to allocate NR_DEFAULTFLAGS over the
  5040. entire range }
  5041. if not Result then
  5042. begin
  5043. { Mark the flags as 'in use' over the entire range }
  5044. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5045. { Speed gain - continue search from the Jcc instruction }
  5046. hp1_last := hp1_dist;
  5047. { Only the TEST instruction was removed, and the
  5048. original was unchanged, so we can safely do
  5049. another iteration of the while loop }
  5050. Include(OptsToCheck, aoc_ForceNewIteration);
  5051. Continue;
  5052. end;
  5053. Exit;
  5054. end;
  5055. end;
  5056. hp1_last := nil;
  5057. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5058. (
  5059. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5060. { Always adjacent under -O2 and under }
  5061. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5062. (
  5063. GetNextInstruction(hp1, hp1_last) and
  5064. (hp1_last = p_dist)
  5065. )
  5066. ) and
  5067. (
  5068. (
  5069. { Test the following variant:
  5070. test $x,(reg/ref)
  5071. jne @lbl1
  5072. test $y,(reg/ref)
  5073. je @lbl2
  5074. @lbl1:
  5075. Becomes:
  5076. test $(x or y),(reg/ref)
  5077. je @lbl2
  5078. @lbl1: (may become a dead label)
  5079. }
  5080. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5081. GetNextInstruction(hp1_dist, hp1_last) and
  5082. (hp1_last = p_label)
  5083. ) or
  5084. (
  5085. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5086. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5087. then the second jump will never branch, so it can also be
  5088. removed regardless of where it goes }
  5089. (
  5090. (FirstValue = -1) or
  5091. (SecondValue = -1) or
  5092. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5093. )
  5094. )
  5095. ) then
  5096. begin
  5097. { Same jump location... can be a register since nothing's changed }
  5098. { If any of the entries are equivalent to test %reg,%reg, then the
  5099. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5100. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5101. if (hp1_last = p_label) then
  5102. begin
  5103. { Variant }
  5104. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5105. RemoveInstruction(p_dist);
  5106. if Assigned(JumpLabel) then
  5107. JumpLabel.decrefs;
  5108. RemoveInstruction(hp1);
  5109. end
  5110. else
  5111. begin
  5112. { Only remove the second test if no jumps or other conditional instructions follow }
  5113. TransferUsedRegs(TmpUsedRegs);
  5114. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5115. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5116. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5117. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5118. begin
  5119. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5120. RemoveInstruction(p_dist);
  5121. { Remove the first jump, not the second, to keep
  5122. any register deallocations between the second
  5123. TEST/JNE pair in the same place. Aids future
  5124. optimisation. }
  5125. if Assigned(JumpLabel) then
  5126. JumpLabel.decrefs;
  5127. RemoveInstruction(hp1);
  5128. end
  5129. else
  5130. begin
  5131. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5132. if IsJumpToLabel(taicpu(hp1_dist)) then
  5133. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5134. { Remove second jump in this instance }
  5135. RemoveInstruction(hp1_dist);
  5136. end;
  5137. end;
  5138. Result := True;
  5139. Exit;
  5140. end;
  5141. end;
  5142. if { If -O2 and under, it may stop on any old instruction }
  5143. (cs_opt_level3 in current_settings.optimizerswitches) and
  5144. (taicpu(p).oper[1]^.typ = top_reg) and
  5145. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5146. begin
  5147. hp1_last := p_dist;
  5148. Continue;
  5149. end;
  5150. Break;
  5151. end;
  5152. end;
  5153. { Search for:
  5154. test %reg,%reg
  5155. j(c1) @lbl1
  5156. ...
  5157. @lbl:
  5158. test %reg,%reg (same register)
  5159. j(c2) @lbl2
  5160. If c2 is a subset of c1, change to:
  5161. test %reg,%reg
  5162. j(c1) @lbl2
  5163. (@lbl1 may become a dead label as a result)
  5164. }
  5165. if (taicpu(p).oper[1]^.typ = top_reg) and
  5166. (taicpu(p).oper[0]^.typ = top_reg) and
  5167. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5168. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5169. Assigned(p_label) and
  5170. GetNextInstruction(p_label, p_dist) and
  5171. MatchInstruction(p_dist, A_TEST, []) and
  5172. { It's fine if the second test uses smaller sub-registers }
  5173. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5174. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5175. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5176. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5177. GetNextInstruction(p_dist, hp1_dist) and
  5178. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5179. begin
  5180. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5181. if JumpLabel = JumpLabel_dist then
  5182. { This is an infinite loop }
  5183. Exit;
  5184. { Best optimisation when the first condition is a subset (or equal) of the second }
  5185. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5186. begin
  5187. { Any registers used here will already be allocated }
  5188. if Assigned(JumpLabel) then
  5189. JumpLabel.DecRefs;
  5190. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5191. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5192. Result := True;
  5193. Exit;
  5194. end;
  5195. end;
  5196. end;
  5197. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5198. var
  5199. hp1, hp2: tai;
  5200. ActiveReg: TRegister;
  5201. OldOffset: asizeint;
  5202. ThisConst: TCGInt;
  5203. function RegDeallocated: Boolean;
  5204. begin
  5205. TransferUsedRegs(TmpUsedRegs);
  5206. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5207. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5208. end;
  5209. begin
  5210. result:=false;
  5211. hp1 := nil;
  5212. { replace
  5213. addX const,%reg1
  5214. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5215. dealloc %reg1
  5216. by
  5217. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5218. }
  5219. if MatchOpType(taicpu(p),top_const,top_reg) then
  5220. begin
  5221. ActiveReg := taicpu(p).oper[1]^.reg;
  5222. { Ensures the entire register was updated }
  5223. if (taicpu(p).opsize >= S_L) and
  5224. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5225. MatchInstruction(hp1,A_LEA,[]) and
  5226. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5227. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5228. (
  5229. { Cover the case where the register in the reference is also the destination register }
  5230. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5231. (
  5232. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5233. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5234. RegDeallocated
  5235. )
  5236. ) then
  5237. begin
  5238. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5239. {$push}
  5240. {$R-}{$Q-}
  5241. { Explicitly disable overflow checking for these offset calculation
  5242. as those do not matter for the final result }
  5243. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5244. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5245. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5246. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5247. {$pop}
  5248. {$ifdef x86_64}
  5249. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5250. begin
  5251. { Overflow; abort }
  5252. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5253. end
  5254. else
  5255. {$endif x86_64}
  5256. begin
  5257. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5258. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5259. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5260. RemoveCurrentP(p, hp1)
  5261. else
  5262. RemoveCurrentP(p);
  5263. result:=true;
  5264. Exit;
  5265. end;
  5266. end;
  5267. if (
  5268. { Save calling GetNextInstructionUsingReg again }
  5269. Assigned(hp1) or
  5270. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5271. ) and
  5272. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5273. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5274. begin
  5275. if taicpu(hp1).oper[0]^.typ = top_const then
  5276. begin
  5277. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5278. if taicpu(hp1).opcode = A_ADD then
  5279. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5280. else
  5281. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5282. Result := True;
  5283. { Handle any overflows }
  5284. case taicpu(p).opsize of
  5285. S_B:
  5286. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5287. S_W:
  5288. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5289. S_L:
  5290. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5291. {$ifdef x86_64}
  5292. S_Q:
  5293. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5294. { Overflow; abort }
  5295. Result := False
  5296. else
  5297. taicpu(p).oper[0]^.val := ThisConst;
  5298. {$endif x86_64}
  5299. else
  5300. InternalError(2021102610);
  5301. end;
  5302. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5303. if Result then
  5304. begin
  5305. if (taicpu(p).oper[0]^.val < 0) and
  5306. (
  5307. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5308. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5309. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5310. ) then
  5311. begin
  5312. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5313. taicpu(p).opcode := A_SUB;
  5314. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5315. end
  5316. else
  5317. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5318. RemoveInstruction(hp1);
  5319. end;
  5320. end
  5321. else
  5322. begin
  5323. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5324. TransferUsedRegs(TmpUsedRegs);
  5325. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5326. hp2 := p;
  5327. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5328. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5329. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5330. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5331. begin
  5332. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5333. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5334. Asml.Remove(p);
  5335. Asml.InsertAfter(p, hp1);
  5336. p := hp1;
  5337. Result := True;
  5338. Exit;
  5339. end;
  5340. end;
  5341. end;
  5342. if DoArithCombineOpt(p) then
  5343. Result:=true;
  5344. end;
  5345. end;
  5346. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5347. var
  5348. hp1, hp2: tai;
  5349. ref: Integer;
  5350. saveref: treference;
  5351. offsetcalc: Int64;
  5352. TempReg: TRegister;
  5353. Multiple: TCGInt;
  5354. Adjacent, IntermediateRegDiscarded: Boolean;
  5355. begin
  5356. Result:=false;
  5357. { play save and throw an error if LEA uses a seg register prefix,
  5358. this is most likely an error somewhere else }
  5359. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5360. internalerror(2022022001);
  5361. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5362. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5363. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5364. (
  5365. { do not mess with leas accessing the stack pointer
  5366. unless it's a null operation }
  5367. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5368. (
  5369. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5370. (taicpu(p).oper[0]^.ref^.offset = 0)
  5371. )
  5372. ) and
  5373. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5374. begin
  5375. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5376. begin
  5377. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5378. begin
  5379. taicpu(p).opcode := A_MOV;
  5380. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5381. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5382. end
  5383. else
  5384. begin
  5385. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5386. RemoveCurrentP(p);
  5387. end;
  5388. Result:=true;
  5389. exit;
  5390. end
  5391. else if (
  5392. { continue to use lea to adjust the stack pointer,
  5393. it is the recommended way, but only if not optimizing for size }
  5394. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5395. (cs_opt_size in current_settings.optimizerswitches)
  5396. ) and
  5397. { If the flags register is in use, don't change the instruction
  5398. to an ADD otherwise this will scramble the flags. [Kit] }
  5399. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5400. ConvertLEA(taicpu(p)) then
  5401. begin
  5402. Result:=true;
  5403. exit;
  5404. end;
  5405. end;
  5406. { Don't optimise if the stack or frame pointer is the destination register }
  5407. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5408. Exit;
  5409. if GetNextInstruction(p,hp1) and
  5410. (hp1.typ=ait_instruction) then
  5411. begin
  5412. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5413. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5414. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5415. begin
  5416. TransferUsedRegs(TmpUsedRegs);
  5417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5418. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5419. begin
  5420. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5421. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5422. RemoveInstruction(hp1);
  5423. result:=true;
  5424. exit;
  5425. end;
  5426. end;
  5427. { changes
  5428. lea <ref1>, reg1
  5429. <op> ...,<ref. with reg1>,...
  5430. to
  5431. <op> ...,<ref1>,... }
  5432. { find a reference which uses reg1 }
  5433. 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
  5434. ref:=0
  5435. 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
  5436. ref:=1
  5437. else
  5438. ref:=-1;
  5439. if (ref<>-1) and
  5440. { reg1 must be either the base or the index }
  5441. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5442. begin
  5443. { reg1 can be removed from the reference }
  5444. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5445. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5446. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5447. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5448. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5449. else
  5450. Internalerror(2019111201);
  5451. { check if the can insert all data of the lea into the second instruction }
  5452. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5453. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5454. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5455. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5456. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5457. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5458. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5459. {$ifdef x86_64}
  5460. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5461. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5462. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5463. )
  5464. {$endif x86_64}
  5465. then
  5466. begin
  5467. { reg1 might not used by the second instruction after it is remove from the reference }
  5468. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5469. begin
  5470. TransferUsedRegs(TmpUsedRegs);
  5471. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5472. { reg1 is not updated so it might not be used afterwards }
  5473. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5474. begin
  5475. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5476. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5477. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5478. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5479. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5480. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5481. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5482. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5483. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5484. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5485. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5486. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5487. RemoveCurrentP(p, hp1);
  5488. result:=true;
  5489. exit;
  5490. end
  5491. end;
  5492. end;
  5493. { recover }
  5494. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5495. end;
  5496. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5497. if Adjacent or
  5498. { Check further ahead (up to 2 instructions ahead for -O2) }
  5499. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5500. begin
  5501. { Check common LEA/LEA conditions }
  5502. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5503. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5504. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5505. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5506. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5507. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5508. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5509. (
  5510. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5511. calling it (since it calls GetNextInstruction) }
  5512. Adjacent or
  5513. (
  5514. (
  5515. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5516. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5517. ) and (
  5518. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5519. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5520. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5521. )
  5522. )
  5523. ) then
  5524. begin
  5525. TransferUsedRegs(TmpUsedRegs);
  5526. hp2 := p;
  5527. repeat
  5528. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5529. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5530. IntermediateRegDiscarded :=
  5531. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5532. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5533. { changes
  5534. lea offset1(regX,scale), reg1
  5535. lea offset2(reg1,reg1), reg2
  5536. to
  5537. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5538. and
  5539. lea offset1(regX,scale1), reg1
  5540. lea offset2(reg1,scale2), reg2
  5541. to
  5542. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5543. and
  5544. lea offset1(regX,scale1), reg1
  5545. lea offset2(reg3,reg1,scale2), reg2
  5546. to
  5547. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5548. ... so long as the final scale does not exceed 8
  5549. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5550. }
  5551. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5552. (
  5553. { Don't optimise if size is a concern and the intermediate register remains in use }
  5554. IntermediateRegDiscarded or
  5555. not (cs_opt_size in current_settings.optimizerswitches)
  5556. ) and
  5557. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5558. (
  5559. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5560. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5561. ) and (
  5562. (
  5563. { lea (reg1,scale2), reg2 variant }
  5564. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5565. (
  5566. Adjacent or
  5567. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5568. ) and
  5569. (
  5570. (
  5571. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5572. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5573. ) or (
  5574. { lea (regX,regX), reg1 variant }
  5575. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5576. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5577. )
  5578. )
  5579. ) or (
  5580. { lea (reg1,reg1), reg1 variant }
  5581. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5582. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5583. )
  5584. ) then
  5585. begin
  5586. { Make everything homogeneous to make calculations easier }
  5587. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5588. begin
  5589. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5590. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5591. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5592. else
  5593. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5594. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5595. end;
  5596. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5597. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5598. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5599. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5600. begin
  5601. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5602. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5603. begin
  5604. { Put the register to change in the index register }
  5605. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5606. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5607. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5608. end;
  5609. { Change lea (reg,reg) to lea(,reg,2) }
  5610. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5611. begin
  5612. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5613. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5614. end;
  5615. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5616. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5617. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5618. { Just to prevent miscalculations }
  5619. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5620. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5621. else
  5622. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5623. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5624. if IntermediateRegDiscarded then
  5625. begin
  5626. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5627. RemoveCurrentP(p);
  5628. end
  5629. else
  5630. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5631. result:=true;
  5632. exit;
  5633. end;
  5634. end;
  5635. { changes
  5636. lea offset1(regX), reg1
  5637. lea offset2(reg1), reg2
  5638. to
  5639. lea offset1+offset2(regX), reg2 }
  5640. if (
  5641. { Don't optimise if size is a concern and the intermediate register remains in use }
  5642. IntermediateRegDiscarded or
  5643. not (cs_opt_size in current_settings.optimizerswitches)
  5644. ) and
  5645. (
  5646. (
  5647. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5648. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5649. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5650. ) or (
  5651. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5652. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5653. (
  5654. (
  5655. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5656. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5657. ) or (
  5658. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5659. (
  5660. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5661. (
  5662. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5663. (
  5664. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5665. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5666. )
  5667. )
  5668. )
  5669. )
  5670. )
  5671. )
  5672. ) then
  5673. begin
  5674. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5675. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5676. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5677. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5678. begin
  5679. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5680. begin
  5681. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5682. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5683. { if the register is used as index and base, we have to increase for base as well
  5684. and adapt base }
  5685. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5686. begin
  5687. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5688. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5689. end;
  5690. end
  5691. else
  5692. begin
  5693. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5694. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5695. end;
  5696. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5697. begin
  5698. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5699. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5700. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5701. end;
  5702. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5703. if IntermediateRegDiscarded then
  5704. begin
  5705. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5706. RemoveCurrentP(p);
  5707. end
  5708. else
  5709. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5710. result:=true;
  5711. exit;
  5712. end;
  5713. end;
  5714. end;
  5715. { Change:
  5716. leal/q $x(%reg1),%reg2
  5717. ...
  5718. shll/q $y,%reg2
  5719. To:
  5720. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5721. }
  5722. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5723. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5724. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5725. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5726. (taicpu(hp1).oper[0]^.val <= 3) then
  5727. begin
  5728. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5729. TransferUsedRegs(TmpUsedRegs);
  5730. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5731. if
  5732. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5733. (this works even if scalefactor is zero) }
  5734. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5735. { Ensure offset doesn't go out of bounds }
  5736. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5737. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5738. (
  5739. (
  5740. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5741. (
  5742. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5743. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5744. (
  5745. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5746. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5747. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5748. )
  5749. )
  5750. ) or (
  5751. (
  5752. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5753. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5754. ) and
  5755. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5756. )
  5757. ) then
  5758. begin
  5759. repeat
  5760. with taicpu(p).oper[0]^.ref^ do
  5761. begin
  5762. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5763. if index = base then
  5764. begin
  5765. if Multiple > 4 then
  5766. { Optimisation will no longer work because resultant
  5767. scale factor will exceed 8 }
  5768. Break;
  5769. base := NR_NO;
  5770. scalefactor := 2;
  5771. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5772. end
  5773. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5774. begin
  5775. { Scale factor only works on the index register }
  5776. index := base;
  5777. base := NR_NO;
  5778. end;
  5779. { For safety }
  5780. if scalefactor <= 1 then
  5781. begin
  5782. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5783. scalefactor := Multiple;
  5784. end
  5785. else
  5786. begin
  5787. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5788. scalefactor := scalefactor * Multiple;
  5789. end;
  5790. offset := offset * Multiple;
  5791. end;
  5792. RemoveInstruction(hp1);
  5793. Result := True;
  5794. Exit;
  5795. { This repeat..until loop exists for the benefit of Break }
  5796. until True;
  5797. end;
  5798. end;
  5799. end;
  5800. end;
  5801. end;
  5802. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5803. var
  5804. hp1 : tai;
  5805. SubInstr: Boolean;
  5806. ThisConst: TCGInt;
  5807. const
  5808. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5809. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5810. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5811. begin
  5812. Result := False;
  5813. if taicpu(p).oper[0]^.typ <> top_const then
  5814. { Should have been confirmed before calling }
  5815. InternalError(2021102601);
  5816. SubInstr := (taicpu(p).opcode = A_SUB);
  5817. if GetLastInstruction(p, hp1) and
  5818. (hp1.typ = ait_instruction) and
  5819. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5820. begin
  5821. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5822. { Bad size }
  5823. InternalError(2022042001);
  5824. case taicpu(hp1).opcode Of
  5825. A_INC:
  5826. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5827. begin
  5828. if SubInstr then
  5829. ThisConst := taicpu(p).oper[0]^.val - 1
  5830. else
  5831. ThisConst := taicpu(p).oper[0]^.val + 1;
  5832. end
  5833. else
  5834. Exit;
  5835. A_DEC:
  5836. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5837. begin
  5838. if SubInstr then
  5839. ThisConst := taicpu(p).oper[0]^.val + 1
  5840. else
  5841. ThisConst := taicpu(p).oper[0]^.val - 1;
  5842. end
  5843. else
  5844. Exit;
  5845. A_SUB:
  5846. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5847. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5848. begin
  5849. if SubInstr then
  5850. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5851. else
  5852. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5853. end
  5854. else
  5855. Exit;
  5856. A_ADD:
  5857. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5858. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5859. begin
  5860. if SubInstr then
  5861. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5862. else
  5863. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5864. end
  5865. else
  5866. Exit;
  5867. else
  5868. Exit;
  5869. end;
  5870. { Check that the values are in range }
  5871. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5872. { Overflow; abort }
  5873. Exit;
  5874. if (ThisConst = 0) then
  5875. begin
  5876. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5877. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5878. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5879. RemoveInstruction(hp1);
  5880. hp1 := tai(p.next);
  5881. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5882. if not GetLastInstruction(hp1, p) then
  5883. p := hp1;
  5884. end
  5885. else
  5886. begin
  5887. if taicpu(hp1).opercnt=1 then
  5888. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5889. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5890. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5891. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5892. else
  5893. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5894. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5895. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5896. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5897. RemoveInstruction(hp1);
  5898. taicpu(p).loadconst(0, ThisConst);
  5899. end;
  5900. Result := True;
  5901. end;
  5902. end;
  5903. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5904. begin
  5905. Result := False;
  5906. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5907. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5908. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5909. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5910. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5911. (
  5912. (
  5913. (taicpu(hp1).opcode = A_TEST)
  5914. ) or (
  5915. (taicpu(hp1).opcode = A_CMP) and
  5916. { A sanity check more than anything }
  5917. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5918. )
  5919. ) then
  5920. begin
  5921. { change
  5922. mov mem, %reg
  5923. ...
  5924. cmp/test x, %reg / test %reg,%reg
  5925. (reg deallocated)
  5926. to
  5927. cmp/test x, mem / cmp 0, mem
  5928. }
  5929. TransferUsedRegs(TmpUsedRegs);
  5930. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5931. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5932. begin
  5933. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5934. if (taicpu(hp1).opcode = A_TEST) and
  5935. (
  5936. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5937. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5938. ) then
  5939. begin
  5940. taicpu(hp1).opcode := A_CMP;
  5941. taicpu(hp1).loadconst(0, 0);
  5942. end;
  5943. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5944. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5945. RemoveCurrentP(p);
  5946. if (p <> hp1) then
  5947. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5948. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5949. { Make sure the flags are allocated across the CMP instruction }
  5950. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5951. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5952. Result := True;
  5953. Exit;
  5954. end;
  5955. end;
  5956. end;
  5957. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5958. var
  5959. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5960. ThisReg, SecondReg: TRegister;
  5961. JumpLoc: TAsmLabel;
  5962. NewSize: TOpSize;
  5963. begin
  5964. Result := False;
  5965. {
  5966. Convert:
  5967. j<c> .L1
  5968. .L2:
  5969. mov 1,reg
  5970. jmp .L3 (or ret, although it might not be a RET yet)
  5971. .L1:
  5972. mov 0,reg
  5973. jmp .L3 (or ret)
  5974. ( As long as .L3 <> .L1 or .L2)
  5975. To:
  5976. mov 0,reg
  5977. set<not(c)> reg
  5978. jmp .L3 (or ret)
  5979. .L2:
  5980. mov 1,reg
  5981. jmp .L3 (or ret)
  5982. .L1:
  5983. mov 0,reg
  5984. jmp .L3 (or ret)
  5985. }
  5986. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5987. Exit;
  5988. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5989. if GetNextInstruction(hp_label, hp2) and
  5990. MatchInstruction(hp2,A_MOV,[]) and
  5991. (taicpu(hp2).oper[0]^.typ = top_const) and
  5992. (
  5993. (
  5994. (taicpu(hp2).oper[1]^.typ = top_reg)
  5995. {$ifdef i386}
  5996. { Under i386, ESI, EDI, EBP and ESP
  5997. don't have an 8-bit representation }
  5998. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5999. {$endif i386}
  6000. ) or (
  6001. {$ifdef i386}
  6002. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6003. {$endif i386}
  6004. (taicpu(hp2).opsize = S_B)
  6005. )
  6006. ) and
  6007. GetNextInstruction(hp2, hp3) and
  6008. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6009. (
  6010. (taicpu(hp3).opcode=A_RET) or
  6011. (
  6012. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6013. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6014. )
  6015. ) and
  6016. GetNextInstruction(hp3, hp4) and
  6017. SkipAligns(hp4, hp4) and
  6018. (hp4.typ=ait_label) and
  6019. (tai_label(hp4).labsym=JumpLoc) and
  6020. (
  6021. not (cs_opt_size in current_settings.optimizerswitches) or
  6022. { If the initial jump is the label's only reference, then it will
  6023. become a dead label if the other conditions are met and hence
  6024. remove at least 2 instructions, including a jump }
  6025. (JumpLoc.getrefs = 1)
  6026. ) and
  6027. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6028. that will be optimised out }
  6029. GetNextInstruction(hp4, hp5) and
  6030. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6031. (taicpu(hp5).oper[0]^.typ = top_const) and
  6032. (
  6033. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6034. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6035. ) and
  6036. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6037. GetNextInstruction(hp5,hp6) and
  6038. (
  6039. (hp6.typ<>ait_label) or
  6040. SkipLabels(hp6, hp6)
  6041. ) and
  6042. (hp6.typ=ait_instruction) then
  6043. begin
  6044. { First, let's look at the two jumps that are hp3 and hp6 }
  6045. if not
  6046. (
  6047. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6048. (
  6049. (taicpu(hp6).opcode=A_RET) or
  6050. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6051. )
  6052. ) then
  6053. { If condition is False, then the JMP/RET instructions matched conventionally }
  6054. begin
  6055. { See if one of the jumps can be instantly converted into a RET }
  6056. if (taicpu(hp3).opcode=A_JMP) then
  6057. begin
  6058. { Reuse hp5 }
  6059. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6060. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6061. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6062. Exit;
  6063. if MatchInstruction(hp5, A_RET, []) then
  6064. begin
  6065. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6066. ConvertJumpToRET(hp3, hp5);
  6067. Result := True;
  6068. end
  6069. else
  6070. Exit;
  6071. end;
  6072. if (taicpu(hp6).opcode=A_JMP) then
  6073. begin
  6074. { Reuse hp5 }
  6075. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6076. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6077. Exit;
  6078. if MatchInstruction(hp5, A_RET, []) then
  6079. begin
  6080. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6081. ConvertJumpToRET(hp6, hp5);
  6082. Result := True;
  6083. end
  6084. else
  6085. Exit;
  6086. end;
  6087. if not
  6088. (
  6089. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6090. (
  6091. (taicpu(hp6).opcode=A_RET) or
  6092. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6093. )
  6094. ) then
  6095. { Still doesn't match }
  6096. Exit;
  6097. end;
  6098. if (taicpu(hp2).oper[0]^.val = 1) then
  6099. begin
  6100. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6101. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6102. end
  6103. else
  6104. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6105. if taicpu(hp2).opsize=S_B then
  6106. begin
  6107. if taicpu(hp2).oper[1]^.typ = top_reg then
  6108. begin
  6109. SecondReg := taicpu(hp2).oper[1]^.reg;
  6110. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6111. end
  6112. else
  6113. begin
  6114. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6115. SecondReg := NR_NO;
  6116. end;
  6117. hp_pos := p;
  6118. hp_allocstart := hp4;
  6119. end
  6120. else
  6121. begin
  6122. { Will be a register because the size can't be S_B otherwise }
  6123. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6124. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6125. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6126. if (cs_opt_size in current_settings.optimizerswitches) then
  6127. begin
  6128. { Favour using MOVZX when optimising for size }
  6129. case taicpu(hp2).opsize of
  6130. S_W:
  6131. NewSize := S_BW;
  6132. S_L:
  6133. NewSize := S_BL;
  6134. {$ifdef x86_64}
  6135. S_Q:
  6136. begin
  6137. NewSize := S_BL;
  6138. { Will implicitly zero-extend to 64-bit }
  6139. setsubreg(SecondReg, R_SUBD);
  6140. end;
  6141. {$endif x86_64}
  6142. else
  6143. InternalError(2022101301);
  6144. end;
  6145. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6146. { Inserting it right before p will guarantee that the flags are also tracked }
  6147. Asml.InsertBefore(hp5, p);
  6148. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6149. hp_pos := hp5;
  6150. hp_allocstart := hp4;
  6151. end
  6152. else
  6153. begin
  6154. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6155. { Inserting it right before p will guarantee that the flags are also tracked }
  6156. Asml.InsertBefore(hp5, p);
  6157. hp_pos := p;
  6158. hp_allocstart := hp5;
  6159. end;
  6160. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6161. end;
  6162. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6163. taicpu(hp4).condition := taicpu(p).condition;
  6164. asml.InsertBefore(hp4, hp_pos);
  6165. if taicpu(hp3).is_jmp then
  6166. begin
  6167. JumpLoc.decrefs;
  6168. MakeUnconditional(taicpu(p));
  6169. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6170. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6171. end
  6172. else
  6173. ConvertJumpToRET(p, hp3);
  6174. if SecondReg <> NR_NO then
  6175. { Ensure the destination register is allocated over this region }
  6176. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6177. if (JumpLoc.getrefs = 0) then
  6178. RemoveDeadCodeAfterJump(hp3);
  6179. Result:=true;
  6180. exit;
  6181. end;
  6182. end;
  6183. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6184. var
  6185. hp1, hp2: tai;
  6186. ActiveReg: TRegister;
  6187. OldOffset: asizeint;
  6188. ThisConst: TCGInt;
  6189. function RegDeallocated: Boolean;
  6190. begin
  6191. TransferUsedRegs(TmpUsedRegs);
  6192. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6193. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6194. end;
  6195. begin
  6196. Result:=false;
  6197. hp1 := nil;
  6198. { replace
  6199. subX const,%reg1
  6200. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6201. dealloc %reg1
  6202. by
  6203. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6204. }
  6205. if MatchOpType(taicpu(p),top_const,top_reg) then
  6206. begin
  6207. ActiveReg := taicpu(p).oper[1]^.reg;
  6208. { Ensures the entire register was updated }
  6209. if (taicpu(p).opsize >= S_L) and
  6210. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6211. MatchInstruction(hp1,A_LEA,[]) and
  6212. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6213. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6214. (
  6215. { Cover the case where the register in the reference is also the destination register }
  6216. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6217. (
  6218. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6219. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6220. RegDeallocated
  6221. )
  6222. ) then
  6223. begin
  6224. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6225. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6226. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6227. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6228. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6229. {$ifdef x86_64}
  6230. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6231. begin
  6232. { Overflow; abort }
  6233. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6234. end
  6235. else
  6236. {$endif x86_64}
  6237. begin
  6238. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6239. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6240. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6241. RemoveCurrentP(p, hp1)
  6242. else
  6243. RemoveCurrentP(p);
  6244. result:=true;
  6245. Exit;
  6246. end;
  6247. end;
  6248. if (
  6249. { Save calling GetNextInstructionUsingReg again }
  6250. Assigned(hp1) or
  6251. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6252. ) and
  6253. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6254. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6255. begin
  6256. if taicpu(hp1).oper[0]^.typ = top_const then
  6257. begin
  6258. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6259. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6260. Result := True;
  6261. { Handle any overflows }
  6262. case taicpu(p).opsize of
  6263. S_B:
  6264. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6265. S_W:
  6266. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6267. S_L:
  6268. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6269. {$ifdef x86_64}
  6270. S_Q:
  6271. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6272. { Overflow; abort }
  6273. Result := False
  6274. else
  6275. taicpu(p).oper[0]^.val := ThisConst;
  6276. {$endif x86_64}
  6277. else
  6278. InternalError(2021102611);
  6279. end;
  6280. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6281. if Result then
  6282. begin
  6283. if (taicpu(p).oper[0]^.val < 0) and
  6284. (
  6285. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6286. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6287. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6288. ) then
  6289. begin
  6290. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6291. taicpu(p).opcode := A_SUB;
  6292. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6293. end
  6294. else
  6295. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6296. RemoveInstruction(hp1);
  6297. end;
  6298. end
  6299. else
  6300. begin
  6301. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6302. TransferUsedRegs(TmpUsedRegs);
  6303. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6304. hp2 := p;
  6305. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6306. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6307. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6308. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6309. begin
  6310. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6311. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6312. Asml.Remove(p);
  6313. Asml.InsertAfter(p, hp1);
  6314. p := hp1;
  6315. Result := True;
  6316. Exit;
  6317. end;
  6318. end;
  6319. end;
  6320. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6321. { * change "sub/add const1, reg" or "dec reg" followed by
  6322. "sub const2, reg" to one "sub ..., reg" }
  6323. {$ifdef i386}
  6324. if (taicpu(p).oper[0]^.val = 2) and
  6325. (ActiveReg = NR_ESP) and
  6326. { Don't do the sub/push optimization if the sub }
  6327. { comes from setting up the stack frame (JM) }
  6328. (not(GetLastInstruction(p,hp1)) or
  6329. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6330. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6331. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6332. begin
  6333. hp1 := tai(p.next);
  6334. while Assigned(hp1) and
  6335. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6336. not RegReadByInstruction(NR_ESP,hp1) and
  6337. not RegModifiedByInstruction(NR_ESP,hp1) do
  6338. hp1 := tai(hp1.next);
  6339. if Assigned(hp1) and
  6340. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6341. begin
  6342. taicpu(hp1).changeopsize(S_L);
  6343. if taicpu(hp1).oper[0]^.typ=top_reg then
  6344. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6345. hp1 := tai(p.next);
  6346. RemoveCurrentp(p, hp1);
  6347. Result:=true;
  6348. exit;
  6349. end;
  6350. end;
  6351. {$endif i386}
  6352. if DoArithCombineOpt(p) then
  6353. Result:=true;
  6354. end;
  6355. end;
  6356. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6357. var
  6358. TmpBool1,TmpBool2 : Boolean;
  6359. tmpref : treference;
  6360. hp1,hp2: tai;
  6361. mask, shiftval: tcgint;
  6362. begin
  6363. Result:=false;
  6364. { All these optimisations work on "shl/sal const,%reg" }
  6365. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6366. Exit;
  6367. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6368. (taicpu(p).oper[0]^.val <= 3) then
  6369. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6370. begin
  6371. { should we check the next instruction? }
  6372. TmpBool1 := True;
  6373. { have we found an add/sub which could be
  6374. integrated in the lea? }
  6375. TmpBool2 := False;
  6376. reference_reset(tmpref,2,[]);
  6377. TmpRef.index := taicpu(p).oper[1]^.reg;
  6378. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6379. while TmpBool1 and
  6380. GetNextInstruction(p, hp1) and
  6381. (tai(hp1).typ = ait_instruction) and
  6382. ((((taicpu(hp1).opcode = A_ADD) or
  6383. (taicpu(hp1).opcode = A_SUB)) and
  6384. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6385. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6386. (((taicpu(hp1).opcode = A_INC) or
  6387. (taicpu(hp1).opcode = A_DEC)) and
  6388. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6389. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6390. ((taicpu(hp1).opcode = A_LEA) and
  6391. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6392. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6393. (not GetNextInstruction(hp1,hp2) or
  6394. not instrReadsFlags(hp2)) Do
  6395. begin
  6396. TmpBool1 := False;
  6397. if taicpu(hp1).opcode=A_LEA then
  6398. begin
  6399. if (TmpRef.base = NR_NO) and
  6400. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6401. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6402. { Segment register isn't a concern here }
  6403. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6404. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6405. begin
  6406. TmpBool1 := True;
  6407. TmpBool2 := True;
  6408. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6409. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6410. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6411. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6412. RemoveInstruction(hp1);
  6413. end
  6414. end
  6415. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6416. begin
  6417. TmpBool1 := True;
  6418. TmpBool2 := True;
  6419. case taicpu(hp1).opcode of
  6420. A_ADD:
  6421. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6422. A_SUB:
  6423. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6424. else
  6425. internalerror(2019050536);
  6426. end;
  6427. RemoveInstruction(hp1);
  6428. end
  6429. else
  6430. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6431. (((taicpu(hp1).opcode = A_ADD) and
  6432. (TmpRef.base = NR_NO)) or
  6433. (taicpu(hp1).opcode = A_INC) or
  6434. (taicpu(hp1).opcode = A_DEC)) then
  6435. begin
  6436. TmpBool1 := True;
  6437. TmpBool2 := True;
  6438. case taicpu(hp1).opcode of
  6439. A_ADD:
  6440. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6441. A_INC:
  6442. inc(TmpRef.offset);
  6443. A_DEC:
  6444. dec(TmpRef.offset);
  6445. else
  6446. internalerror(2019050535);
  6447. end;
  6448. RemoveInstruction(hp1);
  6449. end;
  6450. end;
  6451. if TmpBool2
  6452. {$ifndef x86_64}
  6453. or
  6454. ((current_settings.optimizecputype < cpu_Pentium2) and
  6455. (taicpu(p).oper[0]^.val <= 3) and
  6456. not(cs_opt_size in current_settings.optimizerswitches))
  6457. {$endif x86_64}
  6458. then
  6459. begin
  6460. if not(TmpBool2) and
  6461. (taicpu(p).oper[0]^.val=1) then
  6462. begin
  6463. taicpu(p).opcode := A_ADD;
  6464. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6465. end
  6466. else
  6467. begin
  6468. taicpu(p).opcode := A_LEA;
  6469. taicpu(p).loadref(0, TmpRef);
  6470. end;
  6471. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6472. Result := True;
  6473. end;
  6474. end
  6475. {$ifndef x86_64}
  6476. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6477. begin
  6478. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6479. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6480. (unlike shl, which is only Tairable in the U pipe) }
  6481. if taicpu(p).oper[0]^.val=1 then
  6482. begin
  6483. taicpu(p).opcode := A_ADD;
  6484. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6485. Result := True;
  6486. end
  6487. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6488. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6489. else if (taicpu(p).opsize = S_L) and
  6490. (taicpu(p).oper[0]^.val<= 3) then
  6491. begin
  6492. reference_reset(tmpref,2,[]);
  6493. TmpRef.index := taicpu(p).oper[1]^.reg;
  6494. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6495. taicpu(p).opcode := A_LEA;
  6496. taicpu(p).loadref(0, TmpRef);
  6497. Result := True;
  6498. end;
  6499. end
  6500. {$endif x86_64}
  6501. else if
  6502. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6503. (
  6504. (
  6505. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6506. SetAndTest(hp1, hp2)
  6507. {$ifdef x86_64}
  6508. ) or
  6509. (
  6510. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6511. GetNextInstruction(hp1, hp2) and
  6512. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6513. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6514. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6515. {$endif x86_64}
  6516. )
  6517. ) and
  6518. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6519. begin
  6520. { Change:
  6521. shl x, %reg1
  6522. mov -(1<<x), %reg2
  6523. and %reg2, %reg1
  6524. Or:
  6525. shl x, %reg1
  6526. and -(1<<x), %reg1
  6527. To just:
  6528. shl x, %reg1
  6529. Since the and operation only zeroes bits that are already zero from the shl operation
  6530. }
  6531. case taicpu(p).oper[0]^.val of
  6532. 8:
  6533. mask:=$FFFFFFFFFFFFFF00;
  6534. 16:
  6535. mask:=$FFFFFFFFFFFF0000;
  6536. 32:
  6537. mask:=$FFFFFFFF00000000;
  6538. 63:
  6539. { Constant pre-calculated to prevent overflow errors with Int64 }
  6540. mask:=$8000000000000000;
  6541. else
  6542. begin
  6543. if taicpu(p).oper[0]^.val >= 64 then
  6544. { Shouldn't happen realistically, since the register
  6545. is guaranteed to be set to zero at this point }
  6546. mask := 0
  6547. else
  6548. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6549. end;
  6550. end;
  6551. if taicpu(hp1).oper[0]^.val = mask then
  6552. begin
  6553. { Everything checks out, perform the optimisation, as long as
  6554. the FLAGS register isn't being used}
  6555. TransferUsedRegs(TmpUsedRegs);
  6556. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6557. {$ifdef x86_64}
  6558. if (hp1 <> hp2) then
  6559. begin
  6560. { "shl/mov/and" version }
  6561. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6562. { Don't do the optimisation if the FLAGS register is in use }
  6563. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6564. begin
  6565. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6566. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6567. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6568. begin
  6569. RemoveInstruction(hp1);
  6570. Result := True;
  6571. end;
  6572. { Only set Result to True if the 'mov' instruction was removed }
  6573. RemoveInstruction(hp2);
  6574. end;
  6575. end
  6576. else
  6577. {$endif x86_64}
  6578. begin
  6579. { "shl/and" version }
  6580. { Don't do the optimisation if the FLAGS register is in use }
  6581. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6582. begin
  6583. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6584. RemoveInstruction(hp1);
  6585. Result := True;
  6586. end;
  6587. end;
  6588. Exit;
  6589. end
  6590. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6591. begin
  6592. { Even if the mask doesn't allow for its removal, we might be
  6593. able to optimise the mask for the "shl/and" version, which
  6594. may permit other peephole optimisations }
  6595. {$ifdef DEBUG_AOPTCPU}
  6596. mask := taicpu(hp1).oper[0]^.val and mask;
  6597. if taicpu(hp1).oper[0]^.val <> mask then
  6598. begin
  6599. DebugMsg(
  6600. SPeepholeOptimization +
  6601. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6602. ' to $' + debug_tostr(mask) +
  6603. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6604. taicpu(hp1).oper[0]^.val := mask;
  6605. end;
  6606. {$else DEBUG_AOPTCPU}
  6607. { If debugging is off, just set the operand even if it's the same }
  6608. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6609. {$endif DEBUG_AOPTCPU}
  6610. end;
  6611. end;
  6612. {
  6613. change
  6614. shl/sal const,reg
  6615. <op> ...(...,reg,1),...
  6616. into
  6617. <op> ...(...,reg,1 shl const),...
  6618. if const in 1..3
  6619. }
  6620. if MatchOpType(taicpu(p), top_const, top_reg) and
  6621. (taicpu(p).oper[0]^.val in [1..3]) and
  6622. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6623. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6624. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6625. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6626. MatchOpType(taicpu(hp1),top_ref))
  6627. ) and
  6628. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6629. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6630. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6631. begin
  6632. TransferUsedRegs(TmpUsedRegs);
  6633. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6634. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6635. begin
  6636. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6637. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6638. RemoveCurrentP(p);
  6639. Result:=true;
  6640. exit;
  6641. end;
  6642. end;
  6643. if MatchOpType(taicpu(p), top_const, top_reg) and
  6644. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6645. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6646. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6647. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6648. begin
  6649. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6650. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6651. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6652. {$ifdef x86_64}
  6653. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6654. {$endif x86_64}
  6655. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6656. begin
  6657. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6658. taicpu(hp1).opcode:=A_MOV;
  6659. taicpu(hp1).oper[0]^.val:=0;
  6660. end
  6661. else
  6662. begin
  6663. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6664. taicpu(hp1).oper[0]^.val:=shiftval;
  6665. end;
  6666. RemoveCurrentP(p);
  6667. Result:=true;
  6668. exit;
  6669. end;
  6670. end;
  6671. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6672. begin
  6673. case shr_size of
  6674. S_B:
  6675. { No valid combinations }
  6676. Result := False;
  6677. S_W:
  6678. Result := (Shift >= 8) and (movz_size = S_BW);
  6679. S_L:
  6680. Result :=
  6681. (Shift >= 24) { Any opsize is valid for this shift } or
  6682. ((Shift >= 16) and (movz_size = S_WL));
  6683. {$ifdef x86_64}
  6684. S_Q:
  6685. Result :=
  6686. (Shift >= 56) { Any opsize is valid for this shift } or
  6687. ((Shift >= 48) and (movz_size = S_WL));
  6688. {$endif x86_64}
  6689. else
  6690. InternalError(2022081510);
  6691. end;
  6692. end;
  6693. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6694. var
  6695. hp1, hp2: tai;
  6696. Shift: TCGInt;
  6697. LimitSize: Topsize;
  6698. DoNotMerge: Boolean;
  6699. begin
  6700. Result := False;
  6701. { All these optimisations work on "shr const,%reg" }
  6702. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6703. Exit;
  6704. DoNotMerge := False;
  6705. Shift := taicpu(p).oper[0]^.val;
  6706. LimitSize := taicpu(p).opsize;
  6707. hp1 := p;
  6708. repeat
  6709. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6710. Exit;
  6711. case taicpu(hp1).opcode of
  6712. A_TEST, A_CMP, A_Jcc:
  6713. { Skip over conditional jumps and relevant comparisons }
  6714. Continue;
  6715. A_MOVZX:
  6716. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6717. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6718. begin
  6719. { Since the original register is being read as is, subsequent
  6720. SHRs must not be merged at this point }
  6721. DoNotMerge := True;
  6722. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6723. begin
  6724. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6725. begin
  6726. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6727. taicpu(hp1).opcode := A_MOV;
  6728. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6729. case taicpu(hp1).opsize of
  6730. S_BW:
  6731. taicpu(hp1).opsize := S_W;
  6732. S_BL, S_WL:
  6733. taicpu(hp1).opsize := S_L;
  6734. else
  6735. InternalError(2022081503);
  6736. end;
  6737. { p itself hasn't changed, so no need to set Result to True }
  6738. Include(OptsToCheck, aoc_ForceNewIteration);
  6739. { See if there's anything afterwards that can be
  6740. optimised, since the input register hasn't changed }
  6741. Continue;
  6742. end;
  6743. { NOTE: If the MOVZX instruction reads and writes the same
  6744. register, defer this to the post-peephole optimisation stage }
  6745. Exit;
  6746. end;
  6747. end;
  6748. A_SHL, A_SAL, A_SHR:
  6749. if (taicpu(hp1).opsize <= LimitSize) and
  6750. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6751. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6752. begin
  6753. { Make sure the sizes don't exceed the register size limit
  6754. (measured by the shift value falling below the limit) }
  6755. if taicpu(hp1).opsize < LimitSize then
  6756. LimitSize := taicpu(hp1).opsize;
  6757. if taicpu(hp1).opcode = A_SHR then
  6758. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6759. else
  6760. begin
  6761. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6762. DoNotMerge := True;
  6763. end;
  6764. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6765. Exit;
  6766. { Since we've established that the combined shift is within
  6767. limits, we can actually combine the adjacent SHR
  6768. instructions even if they're different sizes }
  6769. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6770. begin
  6771. hp2 := tai(hp1.Previous);
  6772. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6773. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6774. RemoveInstruction(hp1);
  6775. hp1 := hp2;
  6776. { Though p has changed, only the constant has, and its
  6777. effects can still be detected on the next iteration of
  6778. the repeat..until loop }
  6779. Include(OptsToCheck, aoc_ForceNewIteration);
  6780. end;
  6781. { Move onto the next instruction }
  6782. Continue;
  6783. end;
  6784. else
  6785. ;
  6786. end;
  6787. Break;
  6788. until False;
  6789. end;
  6790. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6791. var
  6792. CurrentRef: TReference;
  6793. FullReg: TRegister;
  6794. hp1, hp2: tai;
  6795. begin
  6796. Result := False;
  6797. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6798. Exit;
  6799. { We assume you've checked if the operand is actually a reference by
  6800. this point. If it isn't, you'll most likely get an access violation }
  6801. CurrentRef := first_mov.oper[1]^.ref^;
  6802. { Memory must be aligned }
  6803. if (CurrentRef.offset mod 4) <> 0 then
  6804. Exit;
  6805. Inc(CurrentRef.offset);
  6806. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6807. if MatchOperand(second_mov.oper[0]^, 0) and
  6808. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6809. GetNextInstruction(second_mov, hp1) and
  6810. (hp1.typ = ait_instruction) and
  6811. (taicpu(hp1).opcode = A_MOV) and
  6812. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6813. (taicpu(hp1).oper[0]^.val = 0) then
  6814. begin
  6815. Inc(CurrentRef.offset);
  6816. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6817. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6818. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6819. begin
  6820. case taicpu(hp1).opsize of
  6821. S_B:
  6822. if GetNextInstruction(hp1, hp2) and
  6823. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6824. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6825. (taicpu(hp2).oper[0]^.val = 0) then
  6826. begin
  6827. Inc(CurrentRef.offset);
  6828. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6829. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6830. (taicpu(hp2).opsize = S_B) then
  6831. begin
  6832. RemoveInstruction(hp1);
  6833. RemoveInstruction(hp2);
  6834. first_mov.opsize := S_L;
  6835. if first_mov.oper[0]^.typ = top_reg then
  6836. begin
  6837. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6838. { Reuse second_mov as a MOVZX instruction }
  6839. second_mov.opcode := A_MOVZX;
  6840. second_mov.opsize := S_BL;
  6841. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6842. second_mov.loadreg(1, FullReg);
  6843. first_mov.oper[0]^.reg := FullReg;
  6844. asml.Remove(second_mov);
  6845. asml.InsertBefore(second_mov, first_mov);
  6846. end
  6847. else
  6848. { It's a value }
  6849. begin
  6850. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6851. RemoveInstruction(second_mov);
  6852. end;
  6853. Result := True;
  6854. Exit;
  6855. end;
  6856. end;
  6857. S_W:
  6858. begin
  6859. RemoveInstruction(hp1);
  6860. first_mov.opsize := S_L;
  6861. if first_mov.oper[0]^.typ = top_reg then
  6862. begin
  6863. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6864. { Reuse second_mov as a MOVZX instruction }
  6865. second_mov.opcode := A_MOVZX;
  6866. second_mov.opsize := S_BL;
  6867. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6868. second_mov.loadreg(1, FullReg);
  6869. first_mov.oper[0]^.reg := FullReg;
  6870. asml.Remove(second_mov);
  6871. asml.InsertBefore(second_mov, first_mov);
  6872. end
  6873. else
  6874. { It's a value }
  6875. begin
  6876. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6877. RemoveInstruction(second_mov);
  6878. end;
  6879. Result := True;
  6880. Exit;
  6881. end;
  6882. else
  6883. ;
  6884. end;
  6885. end;
  6886. end;
  6887. end;
  6888. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6889. { returns true if a "continue" should be done after this optimization }
  6890. var
  6891. hp1, hp2, hp3: tai;
  6892. begin
  6893. Result := false;
  6894. hp3 := nil;
  6895. if MatchOpType(taicpu(p),top_ref) and
  6896. GetNextInstruction(p, hp1) and
  6897. (hp1.typ = ait_instruction) and
  6898. (((taicpu(hp1).opcode = A_FLD) and
  6899. (taicpu(p).opcode = A_FSTP)) or
  6900. ((taicpu(p).opcode = A_FISTP) and
  6901. (taicpu(hp1).opcode = A_FILD))) and
  6902. MatchOpType(taicpu(hp1),top_ref) and
  6903. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6904. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6905. begin
  6906. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6907. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6908. GetNextInstruction(hp1, hp2) and
  6909. (((hp2.typ = ait_instruction) and
  6910. IsExitCode(hp2) and
  6911. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6912. not(assigned(current_procinfo.procdef.funcretsym) and
  6913. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6914. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6915. { fstp <temp>
  6916. fld <temp>
  6917. <dealloc> <temp>
  6918. }
  6919. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6920. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6921. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6922. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6923. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6924. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6925. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6926. )
  6927. )
  6928. ) then
  6929. begin
  6930. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6931. RemoveInstruction(hp1);
  6932. RemoveCurrentP(p, hp2);
  6933. { first case: exit code }
  6934. if hp2.typ = ait_instruction then
  6935. RemoveLastDeallocForFuncRes(p);
  6936. Result := true;
  6937. end
  6938. else
  6939. { we can do this only in fast math mode as fstp is rounding ...
  6940. ... still disabled as it breaks the compiler and/or rtl }
  6941. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6942. { ... or if another fstp equal to the first one follows }
  6943. GetNextInstruction(hp1,hp2) and
  6944. (hp2.typ = ait_instruction) and
  6945. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6946. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6947. begin
  6948. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6949. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6950. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6951. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6952. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6953. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6954. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6955. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6956. ) then
  6957. begin
  6958. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6959. RemoveCurrentP(p,hp2);
  6960. RemoveInstruction(hp1);
  6961. Result := true;
  6962. end
  6963. else if { fst can't store an extended/comp value }
  6964. (taicpu(p).opsize <> S_FX) and
  6965. (taicpu(p).opsize <> S_IQ) then
  6966. begin
  6967. if (taicpu(p).opcode = A_FSTP) then
  6968. taicpu(p).opcode := A_FST
  6969. else
  6970. taicpu(p).opcode := A_FIST;
  6971. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6972. RemoveInstruction(hp1);
  6973. Result := true;
  6974. end;
  6975. end;
  6976. end;
  6977. end;
  6978. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6979. var
  6980. hp1, hp2, hp3: tai;
  6981. begin
  6982. result:=false;
  6983. if MatchOpType(taicpu(p),top_reg) and
  6984. GetNextInstruction(p, hp1) and
  6985. (hp1.typ = Ait_Instruction) and
  6986. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6987. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6988. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6989. { change to
  6990. fld reg fxxx reg,st
  6991. fxxxp st, st1 (hp1)
  6992. Remark: non commutative operations must be reversed!
  6993. }
  6994. begin
  6995. case taicpu(hp1).opcode Of
  6996. A_FMULP,A_FADDP,
  6997. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6998. begin
  6999. case taicpu(hp1).opcode Of
  7000. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7001. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7002. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7003. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7004. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7005. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7006. else
  7007. internalerror(2019050534);
  7008. end;
  7009. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7010. taicpu(hp1).oper[1]^.reg := NR_ST;
  7011. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7012. RemoveCurrentP(p, hp1);
  7013. Result:=true;
  7014. exit;
  7015. end;
  7016. else
  7017. ;
  7018. end;
  7019. end
  7020. else
  7021. if MatchOpType(taicpu(p),top_ref) and
  7022. GetNextInstruction(p, hp2) and
  7023. (hp2.typ = Ait_Instruction) and
  7024. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7025. (taicpu(p).opsize in [S_FS, S_FL]) and
  7026. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7027. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7028. if GetLastInstruction(p, hp1) and
  7029. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7030. MatchOpType(taicpu(hp1),top_ref) and
  7031. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7032. if ((taicpu(hp2).opcode = A_FMULP) or
  7033. (taicpu(hp2).opcode = A_FADDP)) then
  7034. { change to
  7035. fld/fst mem1 (hp1) fld/fst mem1
  7036. fld mem1 (p) fadd/
  7037. faddp/ fmul st, st
  7038. fmulp st, st1 (hp2) }
  7039. begin
  7040. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7041. RemoveCurrentP(p, hp1);
  7042. if (taicpu(hp2).opcode = A_FADDP) then
  7043. taicpu(hp2).opcode := A_FADD
  7044. else
  7045. taicpu(hp2).opcode := A_FMUL;
  7046. taicpu(hp2).oper[1]^.reg := NR_ST;
  7047. end
  7048. else
  7049. { change to
  7050. fld/fst mem1 (hp1) fld/fst mem1
  7051. fld mem1 (p) fld st
  7052. }
  7053. begin
  7054. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7055. taicpu(p).changeopsize(S_FL);
  7056. taicpu(p).loadreg(0,NR_ST);
  7057. end
  7058. else
  7059. begin
  7060. case taicpu(hp2).opcode Of
  7061. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7062. { change to
  7063. fld/fst mem1 (hp1) fld/fst mem1
  7064. fld mem2 (p) fxxx mem2
  7065. fxxxp st, st1 (hp2) }
  7066. begin
  7067. case taicpu(hp2).opcode Of
  7068. A_FADDP: taicpu(p).opcode := A_FADD;
  7069. A_FMULP: taicpu(p).opcode := A_FMUL;
  7070. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7071. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7072. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7073. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7074. else
  7075. internalerror(2019050533);
  7076. end;
  7077. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7078. RemoveInstruction(hp2);
  7079. end
  7080. else
  7081. ;
  7082. end
  7083. end
  7084. end;
  7085. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7086. begin
  7087. Result := condition_in(cond1, cond2) or
  7088. { Not strictly subsets due to the actual flags checked, but because we're
  7089. comparing integers, E is a subset of AE and GE and their aliases }
  7090. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7091. end;
  7092. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7093. var
  7094. v: TCGInt;
  7095. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7096. FirstMatch, TempBool: Boolean;
  7097. NewReg: TRegister;
  7098. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7099. begin
  7100. Result:=false;
  7101. { All these optimisations need a next instruction }
  7102. if not GetNextInstruction(p, hp1) then
  7103. Exit;
  7104. { Search for:
  7105. cmp ###,###
  7106. j(c1) @lbl1
  7107. ...
  7108. @lbl:
  7109. cmp ###,### (same comparison as above)
  7110. j(c2) @lbl2
  7111. If c1 is a subset of c2, change to:
  7112. cmp ###,###
  7113. j(c1) @lbl2
  7114. (@lbl1 may become a dead label as a result)
  7115. }
  7116. { Also handle cases where there are multiple jumps in a row }
  7117. p_jump := hp1;
  7118. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7119. begin
  7120. if IsJumpToLabel(taicpu(p_jump)) then
  7121. begin
  7122. { Do jump optimisations first in case the condition becomes
  7123. unnecessary }
  7124. TempBool := True;
  7125. if DoJumpOptimizations(p_jump, TempBool) or
  7126. not TempBool then
  7127. begin
  7128. if Assigned(p_jump) then
  7129. begin
  7130. hp1 := p_jump;
  7131. if (p_jump.typ in [ait_align]) then
  7132. SkipAligns(p_jump, p_jump);
  7133. { CollapseZeroDistJump will be set to the label after the
  7134. jump if it optimises, whether or not it's live or dead }
  7135. if (p_jump.typ in [ait_label]) and
  7136. not (tai_label(p_jump).labsym.is_used) then
  7137. GetNextInstruction(p_jump, p_jump);
  7138. end;
  7139. TransferUsedRegs(TmpUsedRegs);
  7140. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7141. if not Assigned(p_jump) or
  7142. (
  7143. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7144. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7145. ) then
  7146. begin
  7147. { No more conditional jumps; conditional statement is no longer required }
  7148. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7149. RemoveCurrentP(p);
  7150. Result := True;
  7151. Exit;
  7152. end;
  7153. hp1 := p_jump;
  7154. Include(OptsToCheck, aoc_ForceNewIteration);
  7155. Continue;
  7156. end;
  7157. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7158. if GetNextInstruction(p_jump, hp2) and
  7159. (
  7160. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7161. not TempBool
  7162. ) then
  7163. begin
  7164. hp1 := p_jump;
  7165. Include(OptsToCheck, aoc_ForceNewIteration);
  7166. Continue;
  7167. end;
  7168. p_label := nil;
  7169. if Assigned(JumpLabel) then
  7170. p_label := getlabelwithsym(JumpLabel);
  7171. if Assigned(p_label) and
  7172. GetNextInstruction(p_label, p_dist) and
  7173. MatchInstruction(p_dist, A_CMP, []) and
  7174. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7175. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7176. GetNextInstruction(p_dist, hp1_dist) and
  7177. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7178. begin
  7179. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7180. if JumpLabel = JumpLabel_dist then
  7181. { This is an infinite loop }
  7182. Exit;
  7183. { Best optimisation when the first condition is a subset (or equal) of the second }
  7184. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7185. begin
  7186. { Any registers used here will already be allocated }
  7187. if Assigned(JumpLabel) then
  7188. JumpLabel.DecRefs;
  7189. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7190. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7191. Result := True;
  7192. { Don't exit yet. Since p and p_jump haven't actually been
  7193. removed, we can check for more on this iteration }
  7194. end
  7195. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7196. GetNextInstruction(hp1_dist, hp1_label) and
  7197. SkipAligns(hp1_label, hp1_label) and
  7198. (hp1_label.typ = ait_label) then
  7199. begin
  7200. JumpLabel_far := tai_label(hp1_label).labsym;
  7201. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7202. { This is an infinite loop }
  7203. Exit;
  7204. if Assigned(JumpLabel_far) then
  7205. begin
  7206. { In this situation, if the first jump branches, the second one will never,
  7207. branch so change the destination label to after the second jump }
  7208. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7209. if Assigned(JumpLabel) then
  7210. JumpLabel.DecRefs;
  7211. JumpLabel_far.IncRefs;
  7212. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7213. Result := True;
  7214. { Don't exit yet. Since p and p_jump haven't actually been
  7215. removed, we can check for more on this iteration }
  7216. Continue;
  7217. end;
  7218. end;
  7219. end;
  7220. end;
  7221. { Search for:
  7222. cmp ###,###
  7223. j(c1) @lbl1
  7224. cmp ###,### (same as first)
  7225. Remove second cmp
  7226. }
  7227. if GetNextInstruction(p_jump, hp2) and
  7228. (
  7229. (
  7230. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7231. (
  7232. (
  7233. MatchOpType(taicpu(p), top_const, top_reg) and
  7234. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7235. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7236. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7237. ) or (
  7238. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7239. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7240. )
  7241. )
  7242. ) or (
  7243. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7244. MatchOperand(taicpu(p).oper[0]^, 0) and
  7245. (taicpu(p).oper[1]^.typ = top_reg) and
  7246. MatchInstruction(hp2, A_TEST, []) and
  7247. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7248. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7249. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7250. )
  7251. ) then
  7252. begin
  7253. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7254. RemoveInstruction(hp2);
  7255. Result := True;
  7256. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7257. end;
  7258. GetNextInstruction(p_jump, p_jump);
  7259. end;
  7260. if (
  7261. { Don't call GetNextInstruction again if we already have it }
  7262. (hp1 = p_jump) or
  7263. GetNextInstruction(p, hp1)
  7264. ) and
  7265. MatchInstruction(hp1, A_Jcc, []) and
  7266. IsJumpToLabel(taicpu(hp1)) and
  7267. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7268. GetNextInstruction(hp1, hp2) then
  7269. begin
  7270. {
  7271. cmp x, y (or "cmp y, x")
  7272. je @lbl
  7273. mov x, y
  7274. @lbl:
  7275. (x and y can be constants, registers or references)
  7276. Change to:
  7277. mov x, y (x and y will always be equal in the end)
  7278. @lbl: (may beceome a dead label)
  7279. Also:
  7280. cmp x, y (or "cmp y, x")
  7281. jne @lbl
  7282. mov x, y
  7283. @lbl:
  7284. (x and y can be constants, registers or references)
  7285. Change to:
  7286. Absolutely nothing! (Except @lbl if it's still live)
  7287. }
  7288. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7289. (
  7290. (
  7291. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7292. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7293. ) or (
  7294. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7295. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7296. )
  7297. ) and
  7298. GetNextInstruction(hp2, hp1_label) and
  7299. SkipAligns(hp1_label, hp1_label) and
  7300. (hp1_label.typ = ait_label) and
  7301. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7302. begin
  7303. tai_label(hp1_label).labsym.DecRefs;
  7304. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7305. begin
  7306. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7307. RemoveInstruction(hp2);
  7308. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7309. end
  7310. else
  7311. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7312. RemoveInstruction(hp1);
  7313. RemoveCurrentp(p, hp2);
  7314. Result := True;
  7315. Exit;
  7316. end;
  7317. {
  7318. Try to optimise the following:
  7319. cmp $x,### ($x and $y can be registers or constants)
  7320. je @lbl1 (only reference)
  7321. cmp $y,### (### are identical)
  7322. @Lbl:
  7323. sete %reg1
  7324. Change to:
  7325. cmp $x,###
  7326. sete %reg2 (allocate new %reg2)
  7327. cmp $y,###
  7328. sete %reg1
  7329. orb %reg2,%reg1
  7330. (dealloc %reg2)
  7331. This adds an instruction (so don't perform under -Os), but it removes
  7332. a conditional branch.
  7333. }
  7334. if not (cs_opt_size in current_settings.optimizerswitches) and
  7335. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7336. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7337. { The first operand of CMP instructions can only be a register or
  7338. immediate anyway, so no need to check }
  7339. GetNextInstruction(hp2, p_label) and
  7340. (p_label.typ = ait_label) and
  7341. (tai_label(p_label).labsym.getrefs = 1) and
  7342. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7343. GetNextInstruction(p_label, p_dist) and
  7344. MatchInstruction(p_dist, A_SETcc, []) and
  7345. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7346. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7347. begin
  7348. TransferUsedRegs(TmpUsedRegs);
  7349. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7350. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7351. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7352. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7353. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7354. { Get the instruction after the SETcc instruction so we can
  7355. allocate a new register over the entire range }
  7356. GetNextInstruction(p_dist, hp1_dist) then
  7357. begin
  7358. { Register can appear in p if it's not used afterwards, so only
  7359. allocate between hp1 and hp1_dist }
  7360. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7361. if NewReg <> NR_NO then
  7362. begin
  7363. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7364. { Change the jump instruction into a SETcc instruction }
  7365. taicpu(hp1).opcode := A_SETcc;
  7366. taicpu(hp1).opsize := S_B;
  7367. taicpu(hp1).loadreg(0, NewReg);
  7368. { This is now a dead label }
  7369. tai_label(p_label).labsym.decrefs;
  7370. { Prefer adding before the next instruction so the FLAGS
  7371. register is deallicated first }
  7372. AsmL.InsertBefore(
  7373. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7374. hp1_dist
  7375. );
  7376. Result := True;
  7377. { Don't exit yet, as p wasn't changed and hp1, while
  7378. modified, is still intact and might be optimised by the
  7379. SETcc optimisation below }
  7380. end;
  7381. end;
  7382. end;
  7383. end;
  7384. if taicpu(p).oper[0]^.typ = top_const then
  7385. begin
  7386. if (taicpu(p).oper[0]^.val = 0) and
  7387. (taicpu(p).oper[1]^.typ = top_reg) and
  7388. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7389. begin
  7390. hp2 := p;
  7391. FirstMatch := True;
  7392. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7393. anything meaningful once it's converted to "test %reg,%reg";
  7394. additionally, some jumps will always (or never) branch, so
  7395. evaluate every jump immediately following the
  7396. comparison, optimising the conditions if possible.
  7397. Similarly with SETcc... those that are always set to 0 or 1
  7398. are changed to MOV instructions }
  7399. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7400. (
  7401. GetNextInstruction(hp2, hp1) and
  7402. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7403. ) do
  7404. begin
  7405. FirstMatch := False;
  7406. case taicpu(hp1).condition of
  7407. C_B, C_C, C_NAE, C_O:
  7408. { For B/NAE:
  7409. Will never branch since an unsigned integer can never be below zero
  7410. For C/O:
  7411. Result cannot overflow because 0 is being subtracted
  7412. }
  7413. begin
  7414. if taicpu(hp1).opcode = A_Jcc then
  7415. begin
  7416. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7417. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7418. RemoveInstruction(hp1);
  7419. { Since hp1 was deleted, hp2 must not be updated }
  7420. Continue;
  7421. end
  7422. else
  7423. begin
  7424. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7425. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7426. taicpu(hp1).opcode := A_MOV;
  7427. taicpu(hp1).ops := 2;
  7428. taicpu(hp1).condition := C_None;
  7429. taicpu(hp1).opsize := S_B;
  7430. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7431. taicpu(hp1).loadconst(0, 0);
  7432. end;
  7433. end;
  7434. C_BE, C_NA:
  7435. begin
  7436. { Will only branch if equal to zero }
  7437. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7438. taicpu(hp1).condition := C_E;
  7439. end;
  7440. C_A, C_NBE:
  7441. begin
  7442. { Will only branch if not equal to zero }
  7443. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7444. taicpu(hp1).condition := C_NE;
  7445. end;
  7446. C_AE, C_NB, C_NC, C_NO:
  7447. begin
  7448. { Will always branch }
  7449. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7450. if taicpu(hp1).opcode = A_Jcc then
  7451. begin
  7452. MakeUnconditional(taicpu(hp1));
  7453. { Any jumps/set that follow will now be dead code }
  7454. RemoveDeadCodeAfterJump(taicpu(hp1));
  7455. Break;
  7456. end
  7457. else
  7458. begin
  7459. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7460. taicpu(hp1).opcode := A_MOV;
  7461. taicpu(hp1).ops := 2;
  7462. taicpu(hp1).condition := C_None;
  7463. taicpu(hp1).opsize := S_B;
  7464. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7465. taicpu(hp1).loadconst(0, 1);
  7466. end;
  7467. end;
  7468. C_None:
  7469. InternalError(2020012201);
  7470. C_P, C_PE, C_NP, C_PO:
  7471. { We can't handle parity checks and they should never be generated
  7472. after a general-purpose CMP (it's used in some floating-point
  7473. comparisons that don't use CMP) }
  7474. InternalError(2020012202);
  7475. else
  7476. { Zero/Equality, Sign, their complements and all of the
  7477. signed comparisons do not need to be converted };
  7478. end;
  7479. hp2 := hp1;
  7480. end;
  7481. { Convert the instruction to a TEST }
  7482. taicpu(p).opcode := A_TEST;
  7483. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7484. Result := True;
  7485. Exit;
  7486. end
  7487. else if (taicpu(p).oper[0]^.val = 1) and
  7488. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7489. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7490. begin
  7491. { Convert; To:
  7492. cmp $1,r/m cmp $0,r/m
  7493. jl @lbl jle @lbl
  7494. (Also do inverted conditions)
  7495. }
  7496. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7497. taicpu(p).oper[0]^.val := 0;
  7498. if taicpu(hp1).condition in [C_L, C_NGE] then
  7499. taicpu(hp1).condition := C_LE
  7500. else
  7501. taicpu(hp1).condition := C_NLE;
  7502. { If the instruction is now "cmp $0,%reg", convert it to a
  7503. TEST (and effectively do the work of the "cmp $0,%reg" in
  7504. the block above)
  7505. }
  7506. if (taicpu(p).oper[1]^.typ = top_reg) then
  7507. begin
  7508. taicpu(p).opcode := A_TEST;
  7509. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7510. end;
  7511. Result := True;
  7512. Exit;
  7513. end
  7514. else if (taicpu(p).oper[1]^.typ = top_reg)
  7515. {$ifdef x86_64}
  7516. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7517. {$endif x86_64}
  7518. then
  7519. begin
  7520. { cmp register,$8000 neg register
  7521. je target --> jo target
  7522. .... only if register is deallocated before jump.}
  7523. case Taicpu(p).opsize of
  7524. S_B: v:=$80;
  7525. S_W: v:=$8000;
  7526. S_L: v:=qword($80000000);
  7527. else
  7528. internalerror(2013112905);
  7529. end;
  7530. if (taicpu(p).oper[0]^.val=v) and
  7531. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7532. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7533. begin
  7534. TransferUsedRegs(TmpUsedRegs);
  7535. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7536. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7537. begin
  7538. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7539. Taicpu(p).opcode:=A_NEG;
  7540. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7541. Taicpu(p).clearop(1);
  7542. Taicpu(p).ops:=1;
  7543. if Taicpu(hp1).condition=C_E then
  7544. Taicpu(hp1).condition:=C_O
  7545. else
  7546. Taicpu(hp1).condition:=C_NO;
  7547. Result:=true;
  7548. exit;
  7549. end;
  7550. end;
  7551. end;
  7552. end;
  7553. if TrySwapMovCmp(p, hp1) then
  7554. begin
  7555. Result := True;
  7556. Exit;
  7557. end;
  7558. end;
  7559. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7560. var
  7561. hp1: tai;
  7562. begin
  7563. {
  7564. remove the second (v)pxor from
  7565. pxor reg,reg
  7566. ...
  7567. pxor reg,reg
  7568. }
  7569. Result:=false;
  7570. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7571. MatchOpType(taicpu(p),top_reg,top_reg) and
  7572. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7573. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7574. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7575. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7576. begin
  7577. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7578. RemoveInstruction(hp1);
  7579. Result:=true;
  7580. Exit;
  7581. end
  7582. {
  7583. replace
  7584. pxor reg1,reg1
  7585. movapd/s reg1,reg2
  7586. dealloc reg1
  7587. by
  7588. pxor reg2,reg2
  7589. }
  7590. else if GetNextInstruction(p,hp1) and
  7591. { we mix single and double opperations here because we assume that the compiler
  7592. generates vmovapd only after double operations and vmovaps only after single operations }
  7593. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7594. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7595. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7596. (taicpu(p).oper[0]^.typ=top_reg) then
  7597. begin
  7598. TransferUsedRegs(TmpUsedRegs);
  7599. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7600. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7601. begin
  7602. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7603. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7604. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7605. RemoveInstruction(hp1);
  7606. result:=true;
  7607. end;
  7608. end;
  7609. end;
  7610. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7611. var
  7612. hp1: tai;
  7613. begin
  7614. {
  7615. remove the second (v)pxor from
  7616. (v)pxor reg,reg
  7617. ...
  7618. (v)pxor reg,reg
  7619. }
  7620. Result:=false;
  7621. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7622. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7623. begin
  7624. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7625. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7626. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7627. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7628. begin
  7629. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7630. RemoveInstruction(hp1);
  7631. Result:=true;
  7632. Exit;
  7633. end;
  7634. {$ifdef x86_64}
  7635. {
  7636. replace
  7637. vpxor reg1,reg1,reg1
  7638. vmov reg,mem
  7639. by
  7640. movq $0,mem
  7641. }
  7642. if GetNextInstruction(p,hp1) and
  7643. MatchInstruction(hp1,A_VMOVSD,[]) and
  7644. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7645. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7646. begin
  7647. TransferUsedRegs(TmpUsedRegs);
  7648. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7649. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7650. begin
  7651. taicpu(hp1).loadconst(0,0);
  7652. taicpu(hp1).opcode:=A_MOV;
  7653. taicpu(hp1).opsize:=S_Q;
  7654. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7655. RemoveCurrentP(p);
  7656. result:=true;
  7657. Exit;
  7658. end;
  7659. end;
  7660. {$endif x86_64}
  7661. end
  7662. {
  7663. replace
  7664. vpxor reg1,reg1,reg2
  7665. by
  7666. vpxor reg2,reg2,reg2
  7667. to avoid unncessary data dependencies
  7668. }
  7669. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7670. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7671. begin
  7672. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7673. { avoid unncessary data dependency }
  7674. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7675. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7676. result:=true;
  7677. exit;
  7678. end;
  7679. Result:=OptPass1VOP(p);
  7680. end;
  7681. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7682. var
  7683. hp1 : tai;
  7684. begin
  7685. result:=false;
  7686. { replace
  7687. IMul const,%mreg1,%mreg2
  7688. Mov %reg2,%mreg3
  7689. dealloc %mreg3
  7690. by
  7691. Imul const,%mreg1,%mreg23
  7692. }
  7693. if (taicpu(p).ops=3) and
  7694. GetNextInstruction(p,hp1) and
  7695. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7696. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7697. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7698. begin
  7699. TransferUsedRegs(TmpUsedRegs);
  7700. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7701. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7702. begin
  7703. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7704. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7705. RemoveInstruction(hp1);
  7706. result:=true;
  7707. end;
  7708. end;
  7709. end;
  7710. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7711. var
  7712. hp1 : tai;
  7713. begin
  7714. result:=false;
  7715. { replace
  7716. IMul %reg0,%reg1,%reg2
  7717. Mov %reg2,%reg3
  7718. dealloc %reg2
  7719. by
  7720. Imul %reg0,%reg1,%reg3
  7721. }
  7722. if GetNextInstruction(p,hp1) and
  7723. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7724. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7725. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7726. begin
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7729. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7730. begin
  7731. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7732. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7733. RemoveInstruction(hp1);
  7734. result:=true;
  7735. end;
  7736. end;
  7737. end;
  7738. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7739. var
  7740. hp1: tai;
  7741. begin
  7742. Result:=false;
  7743. { get rid of
  7744. (v)cvtss2sd reg0,<reg1,>reg2
  7745. (v)cvtss2sd reg2,<reg2,>reg0
  7746. }
  7747. if GetNextInstruction(p,hp1) and
  7748. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7749. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7750. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7751. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7752. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7753. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7754. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7755. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7756. )
  7757. ) then
  7758. begin
  7759. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7760. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7761. begin
  7762. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7763. RemoveCurrentP(p);
  7764. RemoveInstruction(hp1);
  7765. end
  7766. else
  7767. begin
  7768. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7769. if taicpu(hp1).opcode=A_CVTSD2SS then
  7770. begin
  7771. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7772. taicpu(p).opcode:=A_MOVAPS;
  7773. end
  7774. else
  7775. begin
  7776. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7777. taicpu(p).opcode:=A_VMOVAPS;
  7778. end;
  7779. taicpu(p).ops:=2;
  7780. RemoveInstruction(hp1);
  7781. end;
  7782. Result:=true;
  7783. Exit;
  7784. end;
  7785. end;
  7786. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7787. var
  7788. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7789. ThisReg: TRegister;
  7790. begin
  7791. Result := False;
  7792. if not GetNextInstruction(p,hp1) then
  7793. Exit;
  7794. {
  7795. convert
  7796. j<c> .L1
  7797. mov 1,reg
  7798. jmp .L2
  7799. .L1
  7800. mov 0,reg
  7801. .L2
  7802. into
  7803. mov 0,reg
  7804. set<not(c)> reg
  7805. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7806. would destroy the flag contents
  7807. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7808. executed at the same time as a previous comparison.
  7809. set<not(c)> reg
  7810. movzx reg, reg
  7811. }
  7812. if MatchInstruction(hp1,A_MOV,[]) and
  7813. (taicpu(hp1).oper[0]^.typ = top_const) and
  7814. (
  7815. (
  7816. (taicpu(hp1).oper[1]^.typ = top_reg)
  7817. {$ifdef i386}
  7818. { Under i386, ESI, EDI, EBP and ESP
  7819. don't have an 8-bit representation }
  7820. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7821. {$endif i386}
  7822. ) or (
  7823. {$ifdef i386}
  7824. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7825. {$endif i386}
  7826. (taicpu(hp1).opsize = S_B)
  7827. )
  7828. ) and
  7829. GetNextInstruction(hp1,hp2) and
  7830. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7831. GetNextInstruction(hp2,hp3) and
  7832. SkipAligns(hp3, hp3) and
  7833. (hp3.typ=ait_label) and
  7834. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7835. GetNextInstruction(hp3,hp4) and
  7836. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7837. (taicpu(hp4).oper[0]^.typ = top_const) and
  7838. (
  7839. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7840. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7841. ) and
  7842. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7843. GetNextInstruction(hp4,hp5) and
  7844. SkipAligns(hp5, hp5) and
  7845. (hp5.typ=ait_label) and
  7846. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7847. begin
  7848. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7849. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7850. tai_label(hp3).labsym.DecRefs;
  7851. { If this isn't the only reference to the middle label, we can
  7852. still make a saving - only that the first jump and everything
  7853. that follows will remain. }
  7854. if (tai_label(hp3).labsym.getrefs = 0) then
  7855. begin
  7856. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7857. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7858. else
  7859. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7860. { remove jump, first label and second MOV (also catching any aligns) }
  7861. repeat
  7862. if not GetNextInstruction(hp2, hp3) then
  7863. InternalError(2021040810);
  7864. RemoveInstruction(hp2);
  7865. hp2 := hp3;
  7866. until hp2 = hp5;
  7867. { Don't decrement reference count before the removal loop
  7868. above, otherwise GetNextInstruction won't stop on the
  7869. the label }
  7870. tai_label(hp5).labsym.DecRefs;
  7871. end
  7872. else
  7873. begin
  7874. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7875. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7876. else
  7877. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7878. end;
  7879. taicpu(p).opcode:=A_SETcc;
  7880. taicpu(p).opsize:=S_B;
  7881. taicpu(p).is_jmp:=False;
  7882. if taicpu(hp1).opsize=S_B then
  7883. begin
  7884. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7885. if taicpu(hp1).oper[1]^.typ = top_reg then
  7886. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7887. RemoveInstruction(hp1);
  7888. end
  7889. else
  7890. begin
  7891. { Will be a register because the size can't be S_B otherwise }
  7892. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7893. taicpu(p).loadreg(0, ThisReg);
  7894. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7895. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7896. begin
  7897. case taicpu(hp1).opsize of
  7898. S_W:
  7899. taicpu(hp1).opsize := S_BW;
  7900. S_L:
  7901. taicpu(hp1).opsize := S_BL;
  7902. {$ifdef x86_64}
  7903. S_Q:
  7904. begin
  7905. taicpu(hp1).opsize := S_BL;
  7906. { Change the destination register to 32-bit }
  7907. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7908. end;
  7909. {$endif x86_64}
  7910. else
  7911. InternalError(2021040820);
  7912. end;
  7913. taicpu(hp1).opcode := A_MOVZX;
  7914. taicpu(hp1).loadreg(0, ThisReg);
  7915. end
  7916. else
  7917. begin
  7918. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7919. { hp1 is already a MOV instruction with the correct register }
  7920. taicpu(hp1).loadconst(0, 0);
  7921. { Inserting it right before p will guarantee that the flags are also tracked }
  7922. asml.Remove(hp1);
  7923. asml.InsertBefore(hp1, p);
  7924. end;
  7925. end;
  7926. Result:=true;
  7927. exit;
  7928. end
  7929. else if (hp1.typ = ait_label) then
  7930. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7931. end;
  7932. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7933. var
  7934. hp1, hp2, hp3: tai;
  7935. SourceRef, TargetRef: TReference;
  7936. CurrentReg: TRegister;
  7937. begin
  7938. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7939. if not UseAVX then
  7940. InternalError(2021100501);
  7941. Result := False;
  7942. { Look for the following to simplify:
  7943. vmovdqa/u x(mem1), %xmmreg
  7944. vmovdqa/u %xmmreg, y(mem2)
  7945. vmovdqa/u x+16(mem1), %xmmreg
  7946. vmovdqa/u %xmmreg, y+16(mem2)
  7947. Change to:
  7948. vmovdqa/u x(mem1), %ymmreg
  7949. vmovdqa/u %ymmreg, y(mem2)
  7950. vpxor %ymmreg, %ymmreg, %ymmreg
  7951. ( The VPXOR instruction is to zero the upper half, thus removing the
  7952. need to call the potentially expensive VZEROUPPER instruction. Other
  7953. peephole optimisations can remove VPXOR if it's unnecessary )
  7954. }
  7955. TransferUsedRegs(TmpUsedRegs);
  7956. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7957. { NOTE: In the optimisations below, if the references dictate that an
  7958. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7959. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7960. if (taicpu(p).opsize = S_XMM) and
  7961. MatchOpType(taicpu(p), top_ref, top_reg) and
  7962. GetNextInstruction(p, hp1) and
  7963. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7964. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7965. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7966. begin
  7967. SourceRef := taicpu(p).oper[0]^.ref^;
  7968. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7969. if GetNextInstruction(hp1, hp2) and
  7970. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7971. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7972. begin
  7973. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7974. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7975. Inc(SourceRef.offset, 16);
  7976. { Reuse the register in the first block move }
  7977. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7978. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7979. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7980. begin
  7981. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7982. Inc(TargetRef.offset, 16);
  7983. if GetNextInstruction(hp2, hp3) and
  7984. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7985. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7986. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7987. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7988. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7989. begin
  7990. { Update the register tracking to the new size }
  7991. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7992. { Remember that the offsets are 16 ahead }
  7993. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7994. if not (
  7995. ((SourceRef.offset mod 32) = 16) and
  7996. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7997. ) then
  7998. taicpu(p).opcode := A_VMOVDQU;
  7999. taicpu(p).opsize := S_YMM;
  8000. taicpu(p).oper[1]^.reg := CurrentReg;
  8001. if not (
  8002. ((TargetRef.offset mod 32) = 16) and
  8003. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8004. ) then
  8005. taicpu(hp1).opcode := A_VMOVDQU;
  8006. taicpu(hp1).opsize := S_YMM;
  8007. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8008. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8009. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8010. if (pi_uses_ymm in current_procinfo.flags) then
  8011. RemoveInstruction(hp2)
  8012. else
  8013. begin
  8014. taicpu(hp2).opcode := A_VPXOR;
  8015. taicpu(hp2).opsize := S_YMM;
  8016. taicpu(hp2).loadreg(0, CurrentReg);
  8017. taicpu(hp2).loadreg(1, CurrentReg);
  8018. taicpu(hp2).loadreg(2, CurrentReg);
  8019. taicpu(hp2).ops := 3;
  8020. end;
  8021. RemoveInstruction(hp3);
  8022. Result := True;
  8023. Exit;
  8024. end;
  8025. end
  8026. else
  8027. begin
  8028. { See if the next references are 16 less rather than 16 greater }
  8029. Dec(SourceRef.offset, 32); { -16 the other way }
  8030. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8031. begin
  8032. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8033. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8034. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8035. GetNextInstruction(hp2, hp3) and
  8036. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8037. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8038. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8039. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8040. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8041. begin
  8042. { Update the register tracking to the new size }
  8043. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8044. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8045. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8046. if not(
  8047. ((SourceRef.offset mod 32) = 0) and
  8048. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8049. ) then
  8050. taicpu(hp2).opcode := A_VMOVDQU;
  8051. taicpu(hp2).opsize := S_YMM;
  8052. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8053. if not (
  8054. ((TargetRef.offset mod 32) = 0) and
  8055. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8056. ) then
  8057. taicpu(hp3).opcode := A_VMOVDQU;
  8058. taicpu(hp3).opsize := S_YMM;
  8059. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8060. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8061. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8062. if (pi_uses_ymm in current_procinfo.flags) then
  8063. RemoveInstruction(hp1)
  8064. else
  8065. begin
  8066. taicpu(hp1).opcode := A_VPXOR;
  8067. taicpu(hp1).opsize := S_YMM;
  8068. taicpu(hp1).loadreg(0, CurrentReg);
  8069. taicpu(hp1).loadreg(1, CurrentReg);
  8070. taicpu(hp1).loadreg(2, CurrentReg);
  8071. taicpu(hp1).ops := 3;
  8072. Asml.Remove(hp1);
  8073. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8074. end;
  8075. RemoveCurrentP(p, hp2);
  8076. Result := True;
  8077. Exit;
  8078. end;
  8079. end;
  8080. end;
  8081. end;
  8082. end;
  8083. end;
  8084. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8085. var
  8086. hp2, hp3, first_assignment: tai;
  8087. IncCount, OperIdx: Integer;
  8088. OrigLabel: TAsmLabel;
  8089. begin
  8090. Count := 0;
  8091. Result := False;
  8092. first_assignment := nil;
  8093. if (LoopCount >= 20) then
  8094. begin
  8095. { Guard against infinite loops }
  8096. Exit;
  8097. end;
  8098. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8099. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8100. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8101. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8102. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8103. Exit;
  8104. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8105. {
  8106. change
  8107. jmp .L1
  8108. ...
  8109. .L1:
  8110. mov ##, ## ( multiple movs possible )
  8111. jmp/ret
  8112. into
  8113. mov ##, ##
  8114. jmp/ret
  8115. }
  8116. if not Assigned(hp1) then
  8117. begin
  8118. hp1 := GetLabelWithSym(OrigLabel);
  8119. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8120. Exit;
  8121. end;
  8122. hp2 := hp1;
  8123. while Assigned(hp2) do
  8124. begin
  8125. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8126. SkipLabels(hp2,hp2);
  8127. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8128. Break;
  8129. case taicpu(hp2).opcode of
  8130. A_MOVSD:
  8131. begin
  8132. if taicpu(hp2).ops = 0 then
  8133. { Wrong MOVSD }
  8134. Break;
  8135. Inc(Count);
  8136. if Count >= 5 then
  8137. { Too many to be worthwhile }
  8138. Break;
  8139. GetNextInstruction(hp2, hp2);
  8140. Continue;
  8141. end;
  8142. A_MOV,
  8143. A_MOVD,
  8144. A_MOVQ,
  8145. A_MOVSX,
  8146. {$ifdef x86_64}
  8147. A_MOVSXD,
  8148. {$endif x86_64}
  8149. A_MOVZX,
  8150. A_MOVAPS,
  8151. A_MOVUPS,
  8152. A_MOVSS,
  8153. A_MOVAPD,
  8154. A_MOVUPD,
  8155. A_MOVDQA,
  8156. A_MOVDQU,
  8157. A_VMOVSS,
  8158. A_VMOVAPS,
  8159. A_VMOVUPS,
  8160. A_VMOVSD,
  8161. A_VMOVAPD,
  8162. A_VMOVUPD,
  8163. A_VMOVDQA,
  8164. A_VMOVDQU:
  8165. begin
  8166. Inc(Count);
  8167. if Count >= 5 then
  8168. { Too many to be worthwhile }
  8169. Break;
  8170. GetNextInstruction(hp2, hp2);
  8171. Continue;
  8172. end;
  8173. A_JMP:
  8174. begin
  8175. { Guard against infinite loops }
  8176. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8177. Exit;
  8178. { Analyse this jump first in case it also duplicates assignments }
  8179. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8180. begin
  8181. { Something did change! }
  8182. Result := True;
  8183. Inc(Count, IncCount);
  8184. if Count >= 5 then
  8185. begin
  8186. { Too many to be worthwhile }
  8187. Exit;
  8188. end;
  8189. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8190. Break;
  8191. end;
  8192. Result := True;
  8193. Break;
  8194. end;
  8195. A_RET:
  8196. begin
  8197. Result := True;
  8198. Break;
  8199. end;
  8200. else
  8201. Break;
  8202. end;
  8203. end;
  8204. if Result then
  8205. begin
  8206. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8207. if Count = 0 then
  8208. begin
  8209. Result := False;
  8210. Exit;
  8211. end;
  8212. hp3 := p;
  8213. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8214. while True do
  8215. begin
  8216. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8217. SkipLabels(hp1,hp1);
  8218. if (hp1.typ <> ait_instruction) then
  8219. InternalError(2021040720);
  8220. case taicpu(hp1).opcode of
  8221. A_JMP:
  8222. begin
  8223. { Change the original jump to the new destination }
  8224. OrigLabel.decrefs;
  8225. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8226. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8227. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8228. if not Assigned(first_assignment) then
  8229. InternalError(2021040810)
  8230. else
  8231. p := first_assignment;
  8232. Exit;
  8233. end;
  8234. A_RET:
  8235. begin
  8236. { Now change the jump into a RET instruction }
  8237. ConvertJumpToRET(p, hp1);
  8238. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8239. if not Assigned(first_assignment) then
  8240. InternalError(2021040811)
  8241. else
  8242. p := first_assignment;
  8243. Exit;
  8244. end;
  8245. else
  8246. begin
  8247. { Duplicate the MOV instruction }
  8248. hp3:=tai(hp1.getcopy);
  8249. if first_assignment = nil then
  8250. first_assignment := hp3;
  8251. asml.InsertBefore(hp3, p);
  8252. { Make sure the compiler knows about any final registers written here }
  8253. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8254. with taicpu(hp3).oper[OperIdx]^ do
  8255. begin
  8256. case typ of
  8257. top_ref:
  8258. begin
  8259. if (ref^.base <> NR_NO) and
  8260. (getsupreg(ref^.base) <> RS_ESP) and
  8261. (getsupreg(ref^.base) <> RS_EBP)
  8262. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8263. then
  8264. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8265. if (ref^.index <> NR_NO) and
  8266. (getsupreg(ref^.index) <> RS_ESP) and
  8267. (getsupreg(ref^.index) <> RS_EBP)
  8268. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8269. (ref^.index <> ref^.base) then
  8270. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8271. end;
  8272. top_reg:
  8273. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8274. else
  8275. ;
  8276. end;
  8277. end;
  8278. end;
  8279. end;
  8280. if not GetNextInstruction(hp1, hp1) then
  8281. { Should have dropped out earlier }
  8282. InternalError(2021040710);
  8283. end;
  8284. end;
  8285. end;
  8286. const
  8287. WriteOp: array[0..3] of set of TInsChange = (
  8288. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8289. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8290. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8291. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8292. RegWriteFlags: array[0..7] of set of TInsChange = (
  8293. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8294. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8295. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8296. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8297. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8298. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8299. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8300. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8301. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8302. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8303. var
  8304. hp2: tai;
  8305. X: Integer;
  8306. begin
  8307. { If we have something like:
  8308. op ###,###
  8309. mov ###,###
  8310. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8311. interfere in regards to what they write to.
  8312. NOTE: p must be a 2-operand instruction
  8313. }
  8314. Result := False;
  8315. if (hp1.typ <> ait_instruction) or
  8316. taicpu(hp1).is_jmp or
  8317. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8318. Exit;
  8319. { NOP is a pipeline fence, likely marking the beginning of the function
  8320. epilogue, so drop out. Similarly, drop out if POP or RET are
  8321. encountered }
  8322. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8323. Exit;
  8324. if (taicpu(hp1).opcode = A_MOVSD) and
  8325. (taicpu(hp1).ops = 0) then
  8326. { Wrong MOVSD }
  8327. Exit;
  8328. { Check for writes to specific registers first }
  8329. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8330. for X := 0 to 7 do
  8331. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8332. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8333. Exit;
  8334. for X := 0 to taicpu(hp1).ops - 1 do
  8335. begin
  8336. { Check to see if this operand writes to something }
  8337. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8338. { And matches something in the CMP/TEST instruction }
  8339. (
  8340. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8341. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8342. (
  8343. { If it's a register, make sure the register written to doesn't
  8344. appear in the cmp instruction as part of a reference }
  8345. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8346. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8347. )
  8348. ) then
  8349. Exit;
  8350. end;
  8351. { Check p to make sure it doesn't write to something that affects hp1 }
  8352. { Check for writes to specific registers first }
  8353. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8354. for X := 0 to 7 do
  8355. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8356. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8357. Exit;
  8358. for X := 0 to taicpu(p).ops - 1 do
  8359. begin
  8360. { Check to see if this operand writes to something }
  8361. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8362. { And matches something in hp1 }
  8363. (taicpu(p).oper[X]^.typ = top_reg) and
  8364. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8365. Exit;
  8366. end;
  8367. { The instruction can be safely moved }
  8368. asml.Remove(hp1);
  8369. { Try to insert after the last instructions where the FLAGS register is not
  8370. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8371. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8372. asml.InsertBefore(hp1, hp2)
  8373. { Failing that, try to insert after the last instructions where the
  8374. FLAGS register is not yet in use }
  8375. else if GetLastInstruction(p, hp2) and
  8376. (
  8377. (hp2.typ <> ait_instruction) or
  8378. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8379. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8380. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8381. ) then
  8382. asml.InsertAfter(hp1, hp2)
  8383. else
  8384. { Note, if p.Previous is nil (even if it should logically never be the
  8385. case), FindRegAllocBackward immediately exits with False and so we
  8386. safely land here (we can't just pass p because FindRegAllocBackward
  8387. immediately exits on an instruction). [Kit] }
  8388. asml.InsertBefore(hp1, p);
  8389. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8390. { We can't trust UsedRegs because we're looking backwards, although we
  8391. know the registers are allocated after p at the very least, so manually
  8392. create tai_regalloc objects if needed }
  8393. for X := 0 to taicpu(hp1).ops - 1 do
  8394. case taicpu(hp1).oper[X]^.typ of
  8395. top_reg:
  8396. begin
  8397. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8398. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8399. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8400. end;
  8401. top_ref:
  8402. begin
  8403. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8404. begin
  8405. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8406. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8407. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8408. end;
  8409. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8410. begin
  8411. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8412. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8413. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8414. end;
  8415. end;
  8416. else
  8417. ;
  8418. end;
  8419. Result := True;
  8420. end;
  8421. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8422. var
  8423. hp2: tai;
  8424. X: Integer;
  8425. begin
  8426. { If we have something like:
  8427. cmp ###,%reg1
  8428. mov 0,%reg2
  8429. And no modified registers are shared, move the instruction to before
  8430. the comparison as this means it can be optimised without worrying
  8431. about the FLAGS register. (CMP/MOV is generated by
  8432. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8433. As long as the second instruction doesn't use the flags or one of the
  8434. registers used by CMP or TEST (also check any references that use the
  8435. registers), then it can be moved prior to the comparison.
  8436. }
  8437. Result := False;
  8438. if not TrySwapMovOp(p, hp1) then
  8439. Exit;
  8440. if taicpu(hp1).opcode = A_LEA then
  8441. { The flags will be overwritten by the CMP/TEST instruction }
  8442. ConvertLEA(taicpu(hp1));
  8443. Result := True;
  8444. { Can we move it one further back? }
  8445. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8446. { Check to see if CMP/TEST is a comparison against zero }
  8447. (
  8448. (
  8449. (taicpu(p).opcode = A_CMP) and
  8450. MatchOperand(taicpu(p).oper[0]^, 0)
  8451. ) or
  8452. (
  8453. (taicpu(p).opcode = A_TEST) and
  8454. (
  8455. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8456. MatchOperand(taicpu(p).oper[0]^, -1)
  8457. )
  8458. )
  8459. ) and
  8460. { These instructions set the zero flag if the result is zero }
  8461. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8462. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8463. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8464. TrySwapMovOp(hp2, hp1);
  8465. end;
  8466. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8467. function IsXCHGAcceptable: Boolean; inline;
  8468. begin
  8469. { Always accept if optimising for size }
  8470. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8471. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8472. than 3, so it becomes a saving compared to three MOVs with two of
  8473. them able to execute simultaneously. [Kit] }
  8474. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8475. end;
  8476. var
  8477. NewRef: TReference;
  8478. hp1, hp2, hp3, hp4: Tai;
  8479. {$ifndef x86_64}
  8480. OperIdx: Integer;
  8481. {$endif x86_64}
  8482. NewInstr : Taicpu;
  8483. NewAligh : Tai_align;
  8484. DestLabel: TAsmLabel;
  8485. TempTracking: TAllUsedRegs;
  8486. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8487. var
  8488. NextInstr: tai;
  8489. begin
  8490. Result := False;
  8491. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8492. if not GetNextInstruction(InputInstr, NextInstr) or
  8493. (
  8494. { The FLAGS register isn't always tracked properly, so do not
  8495. perform this optimisation if a conditional statement follows }
  8496. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8497. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8498. ) then
  8499. begin
  8500. reference_reset(NewRef, 1, []);
  8501. NewRef.base := taicpu(p).oper[0]^.reg;
  8502. NewRef.scalefactor := 1;
  8503. if taicpu(InputInstr).opcode = A_ADD then
  8504. begin
  8505. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8506. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8507. end
  8508. else
  8509. begin
  8510. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8511. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8512. end;
  8513. taicpu(p).opcode := A_LEA;
  8514. taicpu(p).loadref(0, NewRef);
  8515. RemoveInstruction(InputInstr);
  8516. Result := True;
  8517. end;
  8518. end;
  8519. begin
  8520. Result:=false;
  8521. { This optimisation adds an instruction, so only do it for speed }
  8522. if not (cs_opt_size in current_settings.optimizerswitches) and
  8523. MatchOpType(taicpu(p), top_const, top_reg) and
  8524. (taicpu(p).oper[0]^.val = 0) then
  8525. begin
  8526. { To avoid compiler warning }
  8527. DestLabel := nil;
  8528. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8529. InternalError(2021040750);
  8530. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8531. Exit;
  8532. case hp1.typ of
  8533. ait_align,
  8534. ait_label:
  8535. begin
  8536. { Change:
  8537. mov $0,%reg mov $0,%reg
  8538. @Lbl1: @Lbl1:
  8539. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8540. je @Lbl2 jne @Lbl2
  8541. To: To:
  8542. mov $0,%reg mov $0,%reg
  8543. jmp @Lbl2 jmp @Lbl3
  8544. (align) (align)
  8545. @Lbl1: @Lbl1:
  8546. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8547. je @Lbl2 je @Lbl2
  8548. @Lbl3: <-- Only if label exists
  8549. (Not if it's optimised for size)
  8550. }
  8551. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8552. Exit;
  8553. if (hp2.typ = ait_instruction) and
  8554. (
  8555. { Register sizes must exactly match }
  8556. (
  8557. (taicpu(hp2).opcode = A_CMP) and
  8558. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8559. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8560. ) or (
  8561. (taicpu(hp2).opcode = A_TEST) and
  8562. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8563. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8564. )
  8565. ) and GetNextInstruction(hp2, hp3) and
  8566. (hp3.typ = ait_instruction) and
  8567. (taicpu(hp3).opcode = A_JCC) and
  8568. (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
  8569. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8570. begin
  8571. { Check condition of jump }
  8572. { Always true? }
  8573. if condition_in(C_E, taicpu(hp3).condition) then
  8574. begin
  8575. { Copy label symbol and obtain matching label entry for the
  8576. conditional jump, as this will be our destination}
  8577. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8578. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8579. Result := True;
  8580. end
  8581. { Always false? }
  8582. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8583. begin
  8584. { This is only worth it if there's a jump to take }
  8585. case hp2.typ of
  8586. ait_instruction:
  8587. begin
  8588. if taicpu(hp2).opcode = A_JMP then
  8589. begin
  8590. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8591. { An unconditional jump follows the conditional jump which will always be false,
  8592. so use this jump's destination for the new jump }
  8593. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8594. Result := True;
  8595. end
  8596. else if taicpu(hp2).opcode = A_JCC then
  8597. begin
  8598. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8599. if condition_in(C_E, taicpu(hp2).condition) then
  8600. begin
  8601. { A second conditional jump follows the conditional jump which will always be false,
  8602. while the second jump is always True, so use this jump's destination for the new jump }
  8603. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8604. Result := True;
  8605. end;
  8606. { Don't risk it if the jump isn't always true (Result remains False) }
  8607. end;
  8608. end;
  8609. else
  8610. { If anything else don't optimise };
  8611. end;
  8612. end;
  8613. if Result then
  8614. begin
  8615. { Just so we have something to insert as a paremeter}
  8616. reference_reset(NewRef, 1, []);
  8617. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8618. { Now actually load the correct parameter (this also
  8619. increases the reference count) }
  8620. NewInstr.loadsymbol(0, DestLabel, 0);
  8621. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8622. begin
  8623. { Get instruction before original label (may not be p under -O3) }
  8624. if not GetLastInstruction(hp1, hp2) then
  8625. { Shouldn't fail here }
  8626. InternalError(2021040701);
  8627. { Before the aligns too }
  8628. while (hp2.typ = ait_align) do
  8629. if not GetLastInstruction(hp2, hp2) then
  8630. { Shouldn't fail here }
  8631. InternalError(2021040702);
  8632. end
  8633. else
  8634. hp2 := p;
  8635. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8636. AsmL.InsertAfter(NewInstr, hp2);
  8637. { Add new alignment field }
  8638. (* AsmL.InsertAfter(
  8639. cai_align.create_max(
  8640. current_settings.alignment.jumpalign,
  8641. current_settings.alignment.jumpalignskipmax
  8642. ),
  8643. NewInstr
  8644. ); *)
  8645. end;
  8646. Exit;
  8647. end;
  8648. end;
  8649. else
  8650. ;
  8651. end;
  8652. end;
  8653. if not GetNextInstruction(p, hp1) then
  8654. Exit;
  8655. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8656. and DoMovCmpMemOpt(p, hp1) then
  8657. begin
  8658. Result := True;
  8659. Exit;
  8660. end
  8661. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8662. begin
  8663. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8664. further, but we can't just put this jump optimisation in pass 1
  8665. because it tends to perform worse when conditional jumps are
  8666. nearby (e.g. when converting CMOV instructions). [Kit] }
  8667. CopyUsedRegs(TempTracking);
  8668. UpdateUsedRegs(tai(p.Next));
  8669. if OptPass2JMP(hp1) then
  8670. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8671. Result := OptPass1MOV(p);
  8672. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8673. returned True and the instruction is still a MOV, thus checking
  8674. the optimisations below }
  8675. { If OptPass2JMP returned False, no optimisations were done to
  8676. the jump and there are no further optimisations that can be done
  8677. to the MOV instruction on this pass }
  8678. { Restore register state }
  8679. RestoreUsedRegs(TempTracking);
  8680. ReleaseUsedRegs(TempTracking);
  8681. end
  8682. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8683. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8684. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8685. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8686. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8687. begin
  8688. { Change:
  8689. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8690. addl/q $x,%reg2 subl/q $x,%reg2
  8691. To:
  8692. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8693. }
  8694. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8695. { be lazy, checking separately for sub would be slightly better }
  8696. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8697. begin
  8698. TransferUsedRegs(TmpUsedRegs);
  8699. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8700. if TryMovArith2Lea(hp1) then
  8701. begin
  8702. Result := True;
  8703. Exit;
  8704. end
  8705. end
  8706. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8707. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8708. { Same as above, but also adds or subtracts to %reg2 in between.
  8709. It's still valid as long as the flags aren't in use }
  8710. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8711. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8712. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8713. { be lazy, checking separately for sub would be slightly better }
  8714. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8715. begin
  8716. TransferUsedRegs(TmpUsedRegs);
  8717. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8718. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8719. if TryMovArith2Lea(hp2) then
  8720. begin
  8721. Result := True;
  8722. Exit;
  8723. end;
  8724. end;
  8725. end
  8726. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8727. {$ifdef x86_64}
  8728. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8729. {$else x86_64}
  8730. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8731. {$endif x86_64}
  8732. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8733. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8734. { mov reg1, reg2 mov reg1, reg2
  8735. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8736. begin
  8737. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8738. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8739. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8740. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8741. TransferUsedRegs(TmpUsedRegs);
  8742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8743. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8744. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8745. then
  8746. begin
  8747. RemoveCurrentP(p, hp1);
  8748. Result:=true;
  8749. end;
  8750. exit;
  8751. end
  8752. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8753. IsXCHGAcceptable and
  8754. { XCHG doesn't support 8-byte registers }
  8755. (taicpu(p).opsize <> S_B) and
  8756. MatchInstruction(hp1, A_MOV, []) and
  8757. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8758. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8759. GetNextInstruction(hp1, hp2) and
  8760. MatchInstruction(hp2, A_MOV, []) and
  8761. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8762. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8763. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8764. begin
  8765. { mov %reg1,%reg2
  8766. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8767. mov %reg2,%reg3
  8768. (%reg2 not used afterwards)
  8769. Note that xchg takes 3 cycles to execute, and generally mov's take
  8770. only one cycle apiece, but the first two mov's can be executed in
  8771. parallel, only taking 2 cycles overall. Older processors should
  8772. therefore only optimise for size. [Kit]
  8773. }
  8774. TransferUsedRegs(TmpUsedRegs);
  8775. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8776. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8777. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8778. begin
  8779. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8780. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8781. taicpu(hp1).opcode := A_XCHG;
  8782. RemoveCurrentP(p, hp1);
  8783. RemoveInstruction(hp2);
  8784. Result := True;
  8785. Exit;
  8786. end;
  8787. end
  8788. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8789. MatchInstruction(hp1, A_SAR, []) then
  8790. begin
  8791. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8792. begin
  8793. { the use of %edx also covers the opsize being S_L }
  8794. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8795. begin
  8796. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8797. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8798. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8799. begin
  8800. { Change:
  8801. movl %eax,%edx
  8802. sarl $31,%edx
  8803. To:
  8804. cltd
  8805. }
  8806. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8807. RemoveInstruction(hp1);
  8808. taicpu(p).opcode := A_CDQ;
  8809. taicpu(p).opsize := S_NO;
  8810. taicpu(p).clearop(1);
  8811. taicpu(p).clearop(0);
  8812. taicpu(p).ops:=0;
  8813. Result := True;
  8814. end
  8815. else if (cs_opt_size in current_settings.optimizerswitches) and
  8816. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8817. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8818. begin
  8819. { Change:
  8820. movl %edx,%eax
  8821. sarl $31,%edx
  8822. To:
  8823. movl %edx,%eax
  8824. cltd
  8825. Note that this creates a dependency between the two instructions,
  8826. so only perform if optimising for size.
  8827. }
  8828. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8829. taicpu(hp1).opcode := A_CDQ;
  8830. taicpu(hp1).opsize := S_NO;
  8831. taicpu(hp1).clearop(1);
  8832. taicpu(hp1).clearop(0);
  8833. taicpu(hp1).ops:=0;
  8834. end;
  8835. {$ifndef x86_64}
  8836. end
  8837. { Don't bother if CMOV is supported, because a more optimal
  8838. sequence would have been generated for the Abs() intrinsic }
  8839. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8840. { the use of %eax also covers the opsize being S_L }
  8841. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8842. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8843. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8844. GetNextInstruction(hp1, hp2) and
  8845. MatchInstruction(hp2, A_XOR, [S_L]) and
  8846. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8847. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8848. GetNextInstruction(hp2, hp3) and
  8849. MatchInstruction(hp3, A_SUB, [S_L]) and
  8850. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8851. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8852. begin
  8853. { Change:
  8854. movl %eax,%edx
  8855. sarl $31,%eax
  8856. xorl %eax,%edx
  8857. subl %eax,%edx
  8858. (Instruction that uses %edx)
  8859. (%eax deallocated)
  8860. (%edx deallocated)
  8861. To:
  8862. cltd
  8863. xorl %edx,%eax <-- Note the registers have swapped
  8864. subl %edx,%eax
  8865. (Instruction that uses %eax) <-- %eax rather than %edx
  8866. }
  8867. TransferUsedRegs(TmpUsedRegs);
  8868. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8869. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8870. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8871. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8872. begin
  8873. if GetNextInstruction(hp3, hp4) and
  8874. not RegModifiedByInstruction(NR_EDX, hp4) and
  8875. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8876. begin
  8877. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8878. taicpu(p).opcode := A_CDQ;
  8879. taicpu(p).clearop(1);
  8880. taicpu(p).clearop(0);
  8881. taicpu(p).ops:=0;
  8882. RemoveInstruction(hp1);
  8883. taicpu(hp2).loadreg(0, NR_EDX);
  8884. taicpu(hp2).loadreg(1, NR_EAX);
  8885. taicpu(hp3).loadreg(0, NR_EDX);
  8886. taicpu(hp3).loadreg(1, NR_EAX);
  8887. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8888. { Convert references in the following instruction (hp4) from %edx to %eax }
  8889. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8890. with taicpu(hp4).oper[OperIdx]^ do
  8891. case typ of
  8892. top_reg:
  8893. if getsupreg(reg) = RS_EDX then
  8894. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8895. top_ref:
  8896. begin
  8897. if getsupreg(reg) = RS_EDX then
  8898. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8899. if getsupreg(reg) = RS_EDX then
  8900. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8901. end;
  8902. else
  8903. ;
  8904. end;
  8905. end;
  8906. end;
  8907. {$else x86_64}
  8908. end;
  8909. end
  8910. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8911. { the use of %rdx also covers the opsize being S_Q }
  8912. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8913. begin
  8914. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8915. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8916. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8917. begin
  8918. { Change:
  8919. movq %rax,%rdx
  8920. sarq $63,%rdx
  8921. To:
  8922. cqto
  8923. }
  8924. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8925. RemoveInstruction(hp1);
  8926. taicpu(p).opcode := A_CQO;
  8927. taicpu(p).opsize := S_NO;
  8928. taicpu(p).clearop(1);
  8929. taicpu(p).clearop(0);
  8930. taicpu(p).ops:=0;
  8931. Result := True;
  8932. end
  8933. else if (cs_opt_size in current_settings.optimizerswitches) and
  8934. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8935. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8936. begin
  8937. { Change:
  8938. movq %rdx,%rax
  8939. sarq $63,%rdx
  8940. To:
  8941. movq %rdx,%rax
  8942. cqto
  8943. Note that this creates a dependency between the two instructions,
  8944. so only perform if optimising for size.
  8945. }
  8946. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8947. taicpu(hp1).opcode := A_CQO;
  8948. taicpu(hp1).opsize := S_NO;
  8949. taicpu(hp1).clearop(1);
  8950. taicpu(hp1).clearop(0);
  8951. taicpu(hp1).ops:=0;
  8952. {$endif x86_64}
  8953. end;
  8954. end;
  8955. end
  8956. else if MatchInstruction(hp1, A_MOV, []) and
  8957. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8958. { Though "GetNextInstruction" could be factored out, along with
  8959. the instructions that depend on hp2, it is an expensive call that
  8960. should be delayed for as long as possible, hence we do cheaper
  8961. checks first that are likely to be False. [Kit] }
  8962. begin
  8963. if (
  8964. (
  8965. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8966. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8967. (
  8968. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8969. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8970. )
  8971. ) or
  8972. (
  8973. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8974. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8975. (
  8976. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8977. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8978. )
  8979. )
  8980. ) and
  8981. GetNextInstruction(hp1, hp2) and
  8982. MatchInstruction(hp2, A_SAR, []) and
  8983. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8984. begin
  8985. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8986. begin
  8987. { Change:
  8988. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8989. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8990. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8991. To:
  8992. movl r/m,%eax <- Note the change in register
  8993. cltd
  8994. }
  8995. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8996. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8997. taicpu(p).loadreg(1, NR_EAX);
  8998. taicpu(hp1).opcode := A_CDQ;
  8999. taicpu(hp1).clearop(1);
  9000. taicpu(hp1).clearop(0);
  9001. taicpu(hp1).ops:=0;
  9002. RemoveInstruction(hp2);
  9003. (*
  9004. {$ifdef x86_64}
  9005. end
  9006. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9007. { This code sequence does not get generated - however it might become useful
  9008. if and when 128-bit signed integer types make an appearance, so the code
  9009. is kept here for when it is eventually needed. [Kit] }
  9010. (
  9011. (
  9012. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9013. (
  9014. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9015. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9016. )
  9017. ) or
  9018. (
  9019. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9020. (
  9021. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9022. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9023. )
  9024. )
  9025. ) and
  9026. GetNextInstruction(hp1, hp2) and
  9027. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9028. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9029. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9030. begin
  9031. { Change:
  9032. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9033. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9034. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9035. To:
  9036. movq r/m,%rax <- Note the change in register
  9037. cqto
  9038. }
  9039. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9040. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9041. taicpu(p).loadreg(1, NR_RAX);
  9042. taicpu(hp1).opcode := A_CQO;
  9043. taicpu(hp1).clearop(1);
  9044. taicpu(hp1).clearop(0);
  9045. taicpu(hp1).ops:=0;
  9046. RemoveInstruction(hp2);
  9047. {$endif x86_64}
  9048. *)
  9049. end;
  9050. end;
  9051. {$ifdef x86_64}
  9052. end
  9053. else if (taicpu(p).opsize = S_L) and
  9054. (taicpu(p).oper[1]^.typ = top_reg) and
  9055. (
  9056. MatchInstruction(hp1, A_MOV,[]) and
  9057. (taicpu(hp1).opsize = S_L) and
  9058. (taicpu(hp1).oper[1]^.typ = top_reg)
  9059. ) and (
  9060. GetNextInstruction(hp1, hp2) and
  9061. (tai(hp2).typ=ait_instruction) and
  9062. (taicpu(hp2).opsize = S_Q) and
  9063. (
  9064. (
  9065. MatchInstruction(hp2, A_ADD,[]) and
  9066. (taicpu(hp2).opsize = S_Q) and
  9067. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9068. (
  9069. (
  9070. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9071. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9072. ) or (
  9073. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9074. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9075. )
  9076. )
  9077. ) or (
  9078. MatchInstruction(hp2, A_LEA,[]) and
  9079. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9080. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9081. (
  9082. (
  9083. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9084. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9085. ) or (
  9086. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9087. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9088. )
  9089. ) and (
  9090. (
  9091. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9092. ) or (
  9093. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9094. )
  9095. )
  9096. )
  9097. )
  9098. ) and (
  9099. GetNextInstruction(hp2, hp3) and
  9100. MatchInstruction(hp3, A_SHR,[]) and
  9101. (taicpu(hp3).opsize = S_Q) and
  9102. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9103. (taicpu(hp3).oper[0]^.val = 1) and
  9104. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9105. ) then
  9106. begin
  9107. { Change movl x, reg1d movl x, reg1d
  9108. movl y, reg2d movl y, reg2d
  9109. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9110. shrq $1, reg1q shrq $1, reg1q
  9111. ( reg1d and reg2d can be switched around in the first two instructions )
  9112. To movl x, reg1d
  9113. addl y, reg1d
  9114. rcrl $1, reg1d
  9115. This corresponds to the common expression (x + y) shr 1, where
  9116. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9117. smaller code, but won't account for x + y causing an overflow). [Kit]
  9118. }
  9119. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9120. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9121. { Change first MOV command to have the same register as the final output }
  9122. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9123. else
  9124. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9125. { Change second MOV command to an ADD command. This is easier than
  9126. converting the existing command because it means we don't have to
  9127. touch 'y', which might be a complicated reference, and also the
  9128. fact that the third command might either be ADD or LEA. [Kit] }
  9129. taicpu(hp1).opcode := A_ADD;
  9130. { Delete old ADD/LEA instruction }
  9131. RemoveInstruction(hp2);
  9132. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9133. taicpu(hp3).opcode := A_RCR;
  9134. taicpu(hp3).changeopsize(S_L);
  9135. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9136. {$endif x86_64}
  9137. end;
  9138. if FuncMov2Func(p, hp1) then
  9139. begin
  9140. Result := True;
  9141. Exit;
  9142. end;
  9143. end;
  9144. {$push}
  9145. {$q-}{$r-}
  9146. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9147. var
  9148. ThisReg: TRegister;
  9149. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9150. TargetSubReg: TSubRegister;
  9151. hp1, hp2: tai;
  9152. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9153. { Store list of found instructions so we don't have to call
  9154. GetNextInstructionUsingReg multiple times }
  9155. InstrList: array of taicpu;
  9156. InstrMax, Index: Integer;
  9157. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9158. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9159. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9160. WorkingValue: TCgInt;
  9161. PreMessage: string;
  9162. { Data flow analysis }
  9163. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9164. BitwiseOnly, OrXorUsed,
  9165. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9166. function CheckOverflowConditions: Boolean;
  9167. begin
  9168. Result := True;
  9169. if (TestValSignedMax > SignedUpperLimit) then
  9170. UpperSignedOverflow := True;
  9171. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9172. LowerSignedOverflow := True;
  9173. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9174. LowerUnsignedOverflow := True;
  9175. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9176. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9177. begin
  9178. { Absolute overflow }
  9179. Result := False;
  9180. Exit;
  9181. end;
  9182. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9183. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9184. ShiftDownOverflow := True;
  9185. if (TestValMin < 0) or (TestValMax < 0) then
  9186. begin
  9187. LowerUnsignedOverflow := True;
  9188. UpperUnsignedOverflow := True;
  9189. end;
  9190. end;
  9191. function AdjustInitialLoadAndSize: Boolean;
  9192. begin
  9193. Result := False;
  9194. if not p_removed then
  9195. begin
  9196. if TargetSize = MinSize then
  9197. begin
  9198. { Convert the input MOVZX to a MOV }
  9199. if (taicpu(p).oper[0]^.typ = top_reg) and
  9200. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9201. begin
  9202. { Or remove it completely! }
  9203. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9204. RemoveCurrentP(p);
  9205. p_removed := True;
  9206. end
  9207. else
  9208. begin
  9209. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9210. taicpu(p).opcode := A_MOV;
  9211. taicpu(p).oper[1]^.reg := ThisReg;
  9212. taicpu(p).opsize := TargetSize;
  9213. end;
  9214. Result := True;
  9215. end
  9216. else if TargetSize <> MaxSize then
  9217. begin
  9218. case MaxSize of
  9219. S_L:
  9220. if TargetSize = S_W then
  9221. begin
  9222. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9223. taicpu(p).opsize := S_BW;
  9224. taicpu(p).oper[1]^.reg := ThisReg;
  9225. Result := True;
  9226. end
  9227. else
  9228. InternalError(2020112341);
  9229. S_W:
  9230. if TargetSize = S_L then
  9231. begin
  9232. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9233. taicpu(p).opsize := S_BL;
  9234. taicpu(p).oper[1]^.reg := ThisReg;
  9235. Result := True;
  9236. end
  9237. else
  9238. InternalError(2020112342);
  9239. else
  9240. ;
  9241. end;
  9242. end
  9243. else if not hp1_removed and not RegInUse then
  9244. begin
  9245. { If we have something like:
  9246. movzbl (oper),%regd
  9247. add x, %regd
  9248. movzbl %regb, %regd
  9249. We can reduce the register size to the input of the final
  9250. movzbl instruction. Overflows won't have any effect.
  9251. }
  9252. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9253. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9254. begin
  9255. TargetSize := S_B;
  9256. setsubreg(ThisReg, R_SUBL);
  9257. Result := True;
  9258. end
  9259. else if (taicpu(p).opsize = S_WL) and
  9260. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9261. begin
  9262. TargetSize := S_W;
  9263. setsubreg(ThisReg, R_SUBW);
  9264. Result := True;
  9265. end;
  9266. if Result then
  9267. begin
  9268. { Convert the input MOVZX to a MOV }
  9269. if (taicpu(p).oper[0]^.typ = top_reg) and
  9270. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9271. begin
  9272. { Or remove it completely! }
  9273. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9274. RemoveCurrentP(p);
  9275. p_removed := True;
  9276. end
  9277. else
  9278. begin
  9279. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9280. taicpu(p).opcode := A_MOV;
  9281. taicpu(p).oper[1]^.reg := ThisReg;
  9282. taicpu(p).opsize := TargetSize;
  9283. end;
  9284. end;
  9285. end;
  9286. end;
  9287. end;
  9288. procedure AdjustFinalLoad;
  9289. begin
  9290. if not LowerUnsignedOverflow then
  9291. begin
  9292. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9293. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9294. begin
  9295. { Convert the output MOVZX to a MOV }
  9296. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9297. begin
  9298. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9299. if (MinSize = S_B) or
  9300. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9301. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9302. begin
  9303. { Remove it completely! }
  9304. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9305. { Be careful; if p = hp1 and p was also removed, p
  9306. will become a dangling pointer }
  9307. if p = hp1 then
  9308. begin
  9309. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9310. p_removed := True;
  9311. end
  9312. else
  9313. RemoveInstruction(hp1);
  9314. hp1_removed := True;
  9315. end;
  9316. end
  9317. else
  9318. begin
  9319. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9320. taicpu(hp1).opcode := A_MOV;
  9321. taicpu(hp1).oper[0]^.reg := ThisReg;
  9322. taicpu(hp1).opsize := TargetSize;
  9323. end;
  9324. end
  9325. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9326. begin
  9327. { Need to change the size of the output }
  9328. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9329. taicpu(hp1).oper[0]^.reg := ThisReg;
  9330. taicpu(hp1).opsize := S_BL;
  9331. end;
  9332. end;
  9333. end;
  9334. function CompressInstructions: Boolean;
  9335. var
  9336. LocalIndex: Integer;
  9337. begin
  9338. Result := False;
  9339. { The objective here is to try to find a combination that
  9340. removes one of the MOV/Z instructions. }
  9341. if (
  9342. (taicpu(p).oper[0]^.typ <> top_reg) or
  9343. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9344. ) and
  9345. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9346. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9347. begin
  9348. { Make a preference to remove the second MOVZX instruction }
  9349. case taicpu(hp1).opsize of
  9350. S_BL, S_WL:
  9351. begin
  9352. TargetSize := S_L;
  9353. TargetSubReg := R_SUBD;
  9354. end;
  9355. S_BW:
  9356. begin
  9357. TargetSize := S_W;
  9358. TargetSubReg := R_SUBW;
  9359. end;
  9360. else
  9361. InternalError(2020112302);
  9362. end;
  9363. end
  9364. else
  9365. begin
  9366. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9367. begin
  9368. { Exceeded lower bound but not upper bound }
  9369. TargetSize := MaxSize;
  9370. end
  9371. else if not LowerUnsignedOverflow then
  9372. begin
  9373. { Size didn't exceed lower bound }
  9374. TargetSize := MinSize;
  9375. end
  9376. else
  9377. Exit;
  9378. end;
  9379. case TargetSize of
  9380. S_B:
  9381. TargetSubReg := R_SUBL;
  9382. S_W:
  9383. TargetSubReg := R_SUBW;
  9384. S_L:
  9385. TargetSubReg := R_SUBD;
  9386. else
  9387. InternalError(2020112350);
  9388. end;
  9389. { Update the register to its new size }
  9390. setsubreg(ThisReg, TargetSubReg);
  9391. RegInUse := False;
  9392. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9393. begin
  9394. { Check to see if the active register is used afterwards;
  9395. if not, we can change it and make a saving. }
  9396. TransferUsedRegs(TmpUsedRegs);
  9397. { The target register may be marked as in use to cross
  9398. a jump to a distant label, so exclude it }
  9399. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9400. hp2 := p;
  9401. repeat
  9402. { Explicitly check for the excluded register (don't include the first
  9403. instruction as it may be reading from here }
  9404. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9405. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9406. begin
  9407. RegInUse := True;
  9408. Break;
  9409. end;
  9410. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9411. if not GetNextInstruction(hp2, hp2) then
  9412. InternalError(2020112340);
  9413. until (hp2 = hp1);
  9414. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9415. { We might still be able to get away with this }
  9416. RegInUse := not
  9417. (
  9418. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9419. (hp2.typ = ait_instruction) and
  9420. (
  9421. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9422. instruction that doesn't actually contain ThisReg }
  9423. (cs_opt_level3 in current_settings.optimizerswitches) or
  9424. RegInInstruction(ThisReg, hp2)
  9425. ) and
  9426. RegLoadedWithNewValue(ThisReg, hp2)
  9427. );
  9428. if not RegInUse then
  9429. begin
  9430. { Force the register size to the same as this instruction so it can be removed}
  9431. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9432. begin
  9433. TargetSize := S_L;
  9434. TargetSubReg := R_SUBD;
  9435. end
  9436. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9437. begin
  9438. TargetSize := S_W;
  9439. TargetSubReg := R_SUBW;
  9440. end;
  9441. ThisReg := taicpu(hp1).oper[1]^.reg;
  9442. setsubreg(ThisReg, TargetSubReg);
  9443. RegChanged := True;
  9444. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9445. TransferUsedRegs(TmpUsedRegs);
  9446. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9447. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9448. if p = hp1 then
  9449. begin
  9450. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9451. p_removed := True;
  9452. end
  9453. else
  9454. RemoveInstruction(hp1);
  9455. hp1_removed := True;
  9456. { Instruction will become "mov %reg,%reg" }
  9457. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9458. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9459. begin
  9460. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9461. RemoveCurrentP(p);
  9462. p_removed := True;
  9463. end
  9464. else
  9465. taicpu(p).oper[1]^.reg := ThisReg;
  9466. Result := True;
  9467. end
  9468. else
  9469. begin
  9470. if TargetSize <> MaxSize then
  9471. begin
  9472. { Since the register is in use, we have to force it to
  9473. MaxSize otherwise part of it may become undefined later on }
  9474. TargetSize := MaxSize;
  9475. case TargetSize of
  9476. S_B:
  9477. TargetSubReg := R_SUBL;
  9478. S_W:
  9479. TargetSubReg := R_SUBW;
  9480. S_L:
  9481. TargetSubReg := R_SUBD;
  9482. else
  9483. InternalError(2020112351);
  9484. end;
  9485. setsubreg(ThisReg, TargetSubReg);
  9486. end;
  9487. AdjustFinalLoad;
  9488. end;
  9489. end
  9490. else
  9491. AdjustFinalLoad;
  9492. Result := AdjustInitialLoadAndSize or Result;
  9493. { Now go through every instruction we found and change the
  9494. size. If TargetSize = MaxSize, then almost no changes are
  9495. needed and Result can remain False if it hasn't been set
  9496. yet.
  9497. If RegChanged is True, then the register requires changing
  9498. and so the point about TargetSize = MaxSize doesn't apply. }
  9499. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9500. begin
  9501. for LocalIndex := 0 to InstrMax do
  9502. begin
  9503. { If p_removed is true, then the original MOV/Z was removed
  9504. and removing the AND instruction may not be safe if it
  9505. appears first }
  9506. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9507. InternalError(2020112310);
  9508. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9509. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9510. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9511. InstrList[LocalIndex].opsize := TargetSize;
  9512. end;
  9513. Result := True;
  9514. end;
  9515. end;
  9516. begin
  9517. Result := False;
  9518. p_removed := False;
  9519. hp1_removed := False;
  9520. ThisReg := taicpu(p).oper[1]^.reg;
  9521. { Check for:
  9522. movs/z ###,%ecx (or %cx or %rcx)
  9523. ...
  9524. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9525. (dealloc %ecx)
  9526. Change to:
  9527. mov ###,%cl (if ### = %cl, then remove completely)
  9528. ...
  9529. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9530. }
  9531. if (getsupreg(ThisReg) = RS_ECX) and
  9532. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9533. (hp1.typ = ait_instruction) and
  9534. (
  9535. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9536. instruction that doesn't actually contain ECX }
  9537. (cs_opt_level3 in current_settings.optimizerswitches) or
  9538. RegInInstruction(NR_ECX, hp1) or
  9539. (
  9540. { It's common for the shift/rotate's read/write register to be
  9541. initialised in between, so under -O2 and under, search ahead
  9542. one more instruction
  9543. }
  9544. GetNextInstruction(hp1, hp1) and
  9545. (hp1.typ = ait_instruction) and
  9546. RegInInstruction(NR_ECX, hp1)
  9547. )
  9548. ) and
  9549. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9550. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9551. begin
  9552. TransferUsedRegs(TmpUsedRegs);
  9553. hp2 := p;
  9554. repeat
  9555. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9556. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9557. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9558. begin
  9559. case taicpu(p).opsize of
  9560. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9561. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9562. begin
  9563. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9564. RemoveCurrentP(p);
  9565. end
  9566. else
  9567. begin
  9568. taicpu(p).opcode := A_MOV;
  9569. taicpu(p).opsize := S_B;
  9570. taicpu(p).oper[1]^.reg := NR_CL;
  9571. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9572. end;
  9573. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9574. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9575. begin
  9576. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9577. RemoveCurrentP(p);
  9578. end
  9579. else
  9580. begin
  9581. taicpu(p).opcode := A_MOV;
  9582. taicpu(p).opsize := S_W;
  9583. taicpu(p).oper[1]^.reg := NR_CX;
  9584. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9585. end;
  9586. {$ifdef x86_64}
  9587. S_LQ:
  9588. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9589. begin
  9590. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9591. RemoveCurrentP(p);
  9592. end
  9593. else
  9594. begin
  9595. taicpu(p).opcode := A_MOV;
  9596. taicpu(p).opsize := S_L;
  9597. taicpu(p).oper[1]^.reg := NR_ECX;
  9598. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9599. end;
  9600. {$endif x86_64}
  9601. else
  9602. InternalError(2021120401);
  9603. end;
  9604. Result := True;
  9605. Exit;
  9606. end;
  9607. end;
  9608. { This is anything but quick! }
  9609. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9610. Exit;
  9611. SetLength(InstrList, 0);
  9612. InstrMax := -1;
  9613. case taicpu(p).opsize of
  9614. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9615. begin
  9616. {$if defined(i386) or defined(i8086)}
  9617. { If the target size is 8-bit, make sure we can actually encode it }
  9618. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9619. Exit;
  9620. {$endif i386 or i8086}
  9621. LowerLimit := $FF;
  9622. SignedLowerLimit := $7F;
  9623. SignedLowerLimitBottom := -128;
  9624. MinSize := S_B;
  9625. if taicpu(p).opsize = S_BW then
  9626. begin
  9627. MaxSize := S_W;
  9628. UpperLimit := $FFFF;
  9629. SignedUpperLimit := $7FFF;
  9630. SignedUpperLimitBottom := -32768;
  9631. end
  9632. else
  9633. begin
  9634. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9635. MaxSize := S_L;
  9636. UpperLimit := $FFFFFFFF;
  9637. SignedUpperLimit := $7FFFFFFF;
  9638. SignedUpperLimitBottom := -2147483648;
  9639. end;
  9640. end;
  9641. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9642. begin
  9643. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9644. LowerLimit := $FFFF;
  9645. SignedLowerLimit := $7FFF;
  9646. SignedLowerLimitBottom := -32768;
  9647. UpperLimit := $FFFFFFFF;
  9648. SignedUpperLimit := $7FFFFFFF;
  9649. SignedUpperLimitBottom := -2147483648;
  9650. MinSize := S_W;
  9651. MaxSize := S_L;
  9652. end;
  9653. {$ifdef x86_64}
  9654. S_LQ:
  9655. begin
  9656. { Both the lower and upper limits are set to 32-bit. If a limit
  9657. is breached, then optimisation is impossible }
  9658. LowerLimit := $FFFFFFFF;
  9659. SignedLowerLimit := $7FFFFFFF;
  9660. SignedLowerLimitBottom := -2147483648;
  9661. UpperLimit := $FFFFFFFF;
  9662. SignedUpperLimit := $7FFFFFFF;
  9663. SignedUpperLimitBottom := -2147483648;
  9664. MinSize := S_L;
  9665. MaxSize := S_L;
  9666. end;
  9667. {$endif x86_64}
  9668. else
  9669. InternalError(2020112301);
  9670. end;
  9671. TestValMin := 0;
  9672. TestValMax := LowerLimit;
  9673. TestValSignedMax := SignedLowerLimit;
  9674. TryShiftDownLimit := LowerLimit;
  9675. TryShiftDown := S_NO;
  9676. ShiftDownOverflow := False;
  9677. RegChanged := False;
  9678. BitwiseOnly := True;
  9679. OrXorUsed := False;
  9680. UpperSignedOverflow := False;
  9681. LowerSignedOverflow := False;
  9682. UpperUnsignedOverflow := False;
  9683. LowerUnsignedOverflow := False;
  9684. hp1 := p;
  9685. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9686. (hp1.typ = ait_instruction) and
  9687. (
  9688. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9689. instruction that doesn't actually contain ThisReg }
  9690. (cs_opt_level3 in current_settings.optimizerswitches) or
  9691. { This allows this Movx optimisation to work through the SETcc instructions
  9692. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9693. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9694. skip over these SETcc instructions). }
  9695. (taicpu(hp1).opcode = A_SETcc) or
  9696. RegInInstruction(ThisReg, hp1)
  9697. ) do
  9698. begin
  9699. case taicpu(hp1).opcode of
  9700. A_INC,A_DEC:
  9701. begin
  9702. { Has to be an exact match on the register }
  9703. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9704. Break;
  9705. if taicpu(hp1).opcode = A_INC then
  9706. begin
  9707. Inc(TestValMin);
  9708. Inc(TestValMax);
  9709. Inc(TestValSignedMax);
  9710. end
  9711. else
  9712. begin
  9713. Dec(TestValMin);
  9714. Dec(TestValMax);
  9715. Dec(TestValSignedMax);
  9716. end;
  9717. end;
  9718. A_TEST, A_CMP:
  9719. begin
  9720. if (
  9721. { Too high a risk of non-linear behaviour that breaks DFA
  9722. here, unless it's cmp $0,%reg, which is equivalent to
  9723. test %reg,%reg }
  9724. OrXorUsed and
  9725. (taicpu(hp1).opcode = A_CMP) and
  9726. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9727. ) or
  9728. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9729. { Has to be an exact match on the register }
  9730. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9731. (
  9732. { Permit "test %reg,%reg" }
  9733. (taicpu(hp1).opcode = A_TEST) and
  9734. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9735. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9736. ) or
  9737. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9738. { Make sure the comparison value is not smaller than the
  9739. smallest allowed signed value for the minimum size (e.g.
  9740. -128 for 8-bit) }
  9741. not (
  9742. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9743. { Is it in the negative range? }
  9744. (
  9745. (taicpu(hp1).oper[0]^.val < 0) and
  9746. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9747. )
  9748. ) then
  9749. Break;
  9750. { Check to see if the active register is used afterwards }
  9751. TransferUsedRegs(TmpUsedRegs);
  9752. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9753. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9754. begin
  9755. { Make sure the comparison or any previous instructions
  9756. hasn't pushed the test values outside of the range of
  9757. MinSize }
  9758. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9759. begin
  9760. { Exceeded lower bound but not upper bound }
  9761. Exit;
  9762. end
  9763. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9764. begin
  9765. { Size didn't exceed lower bound }
  9766. TargetSize := MinSize;
  9767. end
  9768. else
  9769. Break;
  9770. case TargetSize of
  9771. S_B:
  9772. TargetSubReg := R_SUBL;
  9773. S_W:
  9774. TargetSubReg := R_SUBW;
  9775. S_L:
  9776. TargetSubReg := R_SUBD;
  9777. else
  9778. InternalError(2021051002);
  9779. end;
  9780. if TargetSize <> MaxSize then
  9781. begin
  9782. { Update the register to its new size }
  9783. setsubreg(ThisReg, TargetSubReg);
  9784. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9785. taicpu(hp1).oper[1]^.reg := ThisReg;
  9786. taicpu(hp1).opsize := TargetSize;
  9787. { Convert the input MOVZX to a MOV if necessary }
  9788. AdjustInitialLoadAndSize;
  9789. if (InstrMax >= 0) then
  9790. begin
  9791. for Index := 0 to InstrMax do
  9792. begin
  9793. { If p_removed is true, then the original MOV/Z was removed
  9794. and removing the AND instruction may not be safe if it
  9795. appears first }
  9796. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9797. InternalError(2020112311);
  9798. if InstrList[Index].oper[0]^.typ = top_reg then
  9799. InstrList[Index].oper[0]^.reg := ThisReg;
  9800. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9801. InstrList[Index].opsize := MinSize;
  9802. end;
  9803. end;
  9804. Result := True;
  9805. end;
  9806. Exit;
  9807. end;
  9808. end;
  9809. A_SETcc:
  9810. begin
  9811. { This allows this Movx optimisation to work through the SETcc instructions
  9812. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9813. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9814. skip over these SETcc instructions). }
  9815. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9816. { Of course, break out if the current register is used }
  9817. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9818. Break
  9819. else
  9820. { We must use Continue so the instruction doesn't get added
  9821. to InstrList }
  9822. Continue;
  9823. end;
  9824. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9825. begin
  9826. if
  9827. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9828. { Has to be an exact match on the register }
  9829. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9830. (
  9831. (
  9832. (taicpu(hp1).oper[0]^.typ = top_const) and
  9833. (
  9834. (
  9835. (taicpu(hp1).opcode = A_SHL) and
  9836. (
  9837. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9838. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9839. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9840. )
  9841. ) or (
  9842. (taicpu(hp1).opcode <> A_SHL) and
  9843. (
  9844. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9845. { Is it in the negative range? }
  9846. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9847. )
  9848. )
  9849. )
  9850. ) or (
  9851. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9852. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9853. )
  9854. ) then
  9855. Break;
  9856. { Only process OR and XOR if there are only bitwise operations,
  9857. since otherwise they can too easily fool the data flow
  9858. analysis (they can cause non-linear behaviour) }
  9859. case taicpu(hp1).opcode of
  9860. A_ADD:
  9861. begin
  9862. if OrXorUsed then
  9863. { Too high a risk of non-linear behaviour that breaks DFA here }
  9864. Break
  9865. else
  9866. BitwiseOnly := False;
  9867. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9868. begin
  9869. TestValMin := TestValMin * 2;
  9870. TestValMax := TestValMax * 2;
  9871. TestValSignedMax := TestValSignedMax * 2;
  9872. end
  9873. else
  9874. begin
  9875. WorkingValue := taicpu(hp1).oper[0]^.val;
  9876. TestValMin := TestValMin + WorkingValue;
  9877. TestValMax := TestValMax + WorkingValue;
  9878. TestValSignedMax := TestValSignedMax + WorkingValue;
  9879. end;
  9880. end;
  9881. A_SUB:
  9882. begin
  9883. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9884. begin
  9885. TestValMin := 0;
  9886. TestValMax := 0;
  9887. TestValSignedMax := 0;
  9888. end
  9889. else
  9890. begin
  9891. if OrXorUsed then
  9892. { Too high a risk of non-linear behaviour that breaks DFA here }
  9893. Break
  9894. else
  9895. BitwiseOnly := False;
  9896. WorkingValue := taicpu(hp1).oper[0]^.val;
  9897. TestValMin := TestValMin - WorkingValue;
  9898. TestValMax := TestValMax - WorkingValue;
  9899. TestValSignedMax := TestValSignedMax - WorkingValue;
  9900. end;
  9901. end;
  9902. A_AND:
  9903. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9904. begin
  9905. { we might be able to go smaller if AND appears first }
  9906. if InstrMax = -1 then
  9907. case MinSize of
  9908. S_B:
  9909. ;
  9910. S_W:
  9911. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9912. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9913. begin
  9914. TryShiftDown := S_B;
  9915. TryShiftDownLimit := $FF;
  9916. end;
  9917. S_L:
  9918. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9919. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9920. begin
  9921. TryShiftDown := S_B;
  9922. TryShiftDownLimit := $FF;
  9923. end
  9924. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9925. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9926. begin
  9927. TryShiftDown := S_W;
  9928. TryShiftDownLimit := $FFFF;
  9929. end;
  9930. else
  9931. InternalError(2020112320);
  9932. end;
  9933. WorkingValue := taicpu(hp1).oper[0]^.val;
  9934. TestValMin := TestValMin and WorkingValue;
  9935. TestValMax := TestValMax and WorkingValue;
  9936. TestValSignedMax := TestValSignedMax and WorkingValue;
  9937. end;
  9938. A_OR:
  9939. begin
  9940. if not BitwiseOnly then
  9941. Break;
  9942. OrXorUsed := True;
  9943. WorkingValue := taicpu(hp1).oper[0]^.val;
  9944. TestValMin := TestValMin or WorkingValue;
  9945. TestValMax := TestValMax or WorkingValue;
  9946. TestValSignedMax := TestValSignedMax or WorkingValue;
  9947. end;
  9948. A_XOR:
  9949. begin
  9950. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9951. begin
  9952. TestValMin := 0;
  9953. TestValMax := 0;
  9954. TestValSignedMax := 0;
  9955. end
  9956. else
  9957. begin
  9958. if not BitwiseOnly then
  9959. Break;
  9960. OrXorUsed := True;
  9961. WorkingValue := taicpu(hp1).oper[0]^.val;
  9962. TestValMin := TestValMin xor WorkingValue;
  9963. TestValMax := TestValMax xor WorkingValue;
  9964. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9965. end;
  9966. end;
  9967. A_SHL:
  9968. begin
  9969. BitwiseOnly := False;
  9970. WorkingValue := taicpu(hp1).oper[0]^.val;
  9971. TestValMin := TestValMin shl WorkingValue;
  9972. TestValMax := TestValMax shl WorkingValue;
  9973. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9974. end;
  9975. A_SHR,
  9976. { The first instruction was MOVZX, so the value won't be negative }
  9977. A_SAR:
  9978. begin
  9979. if InstrMax <> -1 then
  9980. BitwiseOnly := False
  9981. else
  9982. { we might be able to go smaller if SHR appears first }
  9983. case MinSize of
  9984. S_B:
  9985. ;
  9986. S_W:
  9987. if (taicpu(hp1).oper[0]^.val >= 8) then
  9988. begin
  9989. TryShiftDown := S_B;
  9990. TryShiftDownLimit := $FF;
  9991. TryShiftDownSignedLimit := $7F;
  9992. TryShiftDownSignedLimitLower := -128;
  9993. end;
  9994. S_L:
  9995. if (taicpu(hp1).oper[0]^.val >= 24) then
  9996. begin
  9997. TryShiftDown := S_B;
  9998. TryShiftDownLimit := $FF;
  9999. TryShiftDownSignedLimit := $7F;
  10000. TryShiftDownSignedLimitLower := -128;
  10001. end
  10002. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10003. begin
  10004. TryShiftDown := S_W;
  10005. TryShiftDownLimit := $FFFF;
  10006. TryShiftDownSignedLimit := $7FFF;
  10007. TryShiftDownSignedLimitLower := -32768;
  10008. end;
  10009. else
  10010. InternalError(2020112321);
  10011. end;
  10012. WorkingValue := taicpu(hp1).oper[0]^.val;
  10013. if taicpu(hp1).opcode = A_SAR then
  10014. begin
  10015. TestValMin := SarInt64(TestValMin, WorkingValue);
  10016. TestValMax := SarInt64(TestValMax, WorkingValue);
  10017. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10018. end
  10019. else
  10020. begin
  10021. TestValMin := TestValMin shr WorkingValue;
  10022. TestValMax := TestValMax shr WorkingValue;
  10023. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10024. end;
  10025. end;
  10026. else
  10027. InternalError(2020112303);
  10028. end;
  10029. end;
  10030. (*
  10031. A_IMUL:
  10032. case taicpu(hp1).ops of
  10033. 2:
  10034. begin
  10035. if not MatchOpType(hp1, top_reg, top_reg) or
  10036. { Has to be an exact match on the register }
  10037. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10038. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10039. Break;
  10040. TestValMin := TestValMin * TestValMin;
  10041. TestValMax := TestValMax * TestValMax;
  10042. TestValSignedMax := TestValSignedMax * TestValMax;
  10043. end;
  10044. 3:
  10045. begin
  10046. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10047. { Has to be an exact match on the register }
  10048. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10049. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10050. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10051. { Is it in the negative range? }
  10052. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10053. Break;
  10054. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10055. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10056. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10057. end;
  10058. else
  10059. Break;
  10060. end;
  10061. A_IDIV:
  10062. case taicpu(hp1).ops of
  10063. 3:
  10064. begin
  10065. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10066. { Has to be an exact match on the register }
  10067. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10068. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10069. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10070. { Is it in the negative range? }
  10071. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10072. Break;
  10073. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10074. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10075. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10076. end;
  10077. else
  10078. Break;
  10079. end;
  10080. *)
  10081. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10082. begin
  10083. { If there are no instructions in between, then we might be able to make a saving }
  10084. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10085. Break;
  10086. { We have something like:
  10087. movzbw %dl,%dx
  10088. ...
  10089. movswl %dx,%edx
  10090. Change the latter to a zero-extension then enter the
  10091. A_MOVZX case branch.
  10092. }
  10093. {$ifdef x86_64}
  10094. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10095. begin
  10096. { this becomes a zero extension from 32-bit to 64-bit, but
  10097. the upper 32 bits are already zero, so just delete the
  10098. instruction }
  10099. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10100. RemoveInstruction(hp1);
  10101. Result := True;
  10102. Exit;
  10103. end
  10104. else
  10105. {$endif x86_64}
  10106. begin
  10107. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10108. taicpu(hp1).opcode := A_MOVZX;
  10109. {$ifdef x86_64}
  10110. case taicpu(hp1).opsize of
  10111. S_BQ:
  10112. begin
  10113. taicpu(hp1).opsize := S_BL;
  10114. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10115. end;
  10116. S_WQ:
  10117. begin
  10118. taicpu(hp1).opsize := S_WL;
  10119. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10120. end;
  10121. S_LQ:
  10122. begin
  10123. taicpu(hp1).opcode := A_MOV;
  10124. taicpu(hp1).opsize := S_L;
  10125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10126. { In this instance, we need to break out because the
  10127. instruction is no longer MOVZX or MOVSXD }
  10128. Result := True;
  10129. Exit;
  10130. end;
  10131. else
  10132. ;
  10133. end;
  10134. {$endif x86_64}
  10135. Result := CompressInstructions;
  10136. Exit;
  10137. end;
  10138. end;
  10139. A_MOVZX:
  10140. begin
  10141. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10142. Break;
  10143. if (InstrMax = -1) then
  10144. begin
  10145. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10146. begin
  10147. { Optimise around i40003 }
  10148. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10149. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10150. {$ifndef x86_64}
  10151. and (
  10152. (taicpu(p).oper[0]^.typ <> top_reg) or
  10153. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10154. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10155. )
  10156. {$endif not x86_64}
  10157. then
  10158. begin
  10159. if (taicpu(p).oper[0]^.typ = top_reg) then
  10160. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10161. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10162. taicpu(p).opsize := S_BL;
  10163. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10164. RemoveInstruction(hp1);
  10165. Result := True;
  10166. Exit;
  10167. end;
  10168. end
  10169. else
  10170. begin
  10171. { Will return false if the second parameter isn't ThisReg
  10172. (can happen on -O2 and under) }
  10173. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10174. begin
  10175. { The two MOVZX instructions are adjacent, so remove the first one }
  10176. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10177. RemoveCurrentP(p);
  10178. Result := True;
  10179. Exit;
  10180. end;
  10181. Break;
  10182. end;
  10183. end;
  10184. Result := CompressInstructions;
  10185. Exit;
  10186. end;
  10187. else
  10188. { This includes ADC, SBB and IDIV }
  10189. Break;
  10190. end;
  10191. if not CheckOverflowConditions then
  10192. Break;
  10193. { Contains highest index (so instruction count - 1) }
  10194. Inc(InstrMax);
  10195. if InstrMax > High(InstrList) then
  10196. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10197. InstrList[InstrMax] := taicpu(hp1);
  10198. end;
  10199. end;
  10200. {$pop}
  10201. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10202. var
  10203. hp1 : tai;
  10204. begin
  10205. Result:=false;
  10206. if (taicpu(p).ops >= 2) and
  10207. ((taicpu(p).oper[0]^.typ = top_const) or
  10208. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10209. (taicpu(p).oper[1]^.typ = top_reg) and
  10210. ((taicpu(p).ops = 2) or
  10211. ((taicpu(p).oper[2]^.typ = top_reg) and
  10212. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10213. GetLastInstruction(p,hp1) and
  10214. MatchInstruction(hp1,A_MOV,[]) and
  10215. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10216. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10217. begin
  10218. TransferUsedRegs(TmpUsedRegs);
  10219. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10220. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10221. { change
  10222. mov reg1,reg2
  10223. imul y,reg2 to imul y,reg1,reg2 }
  10224. begin
  10225. taicpu(p).ops := 3;
  10226. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10227. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10228. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10229. RemoveInstruction(hp1);
  10230. result:=true;
  10231. end;
  10232. end;
  10233. end;
  10234. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10235. var
  10236. ThisLabel: TAsmLabel;
  10237. begin
  10238. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10239. ThisLabel.decrefs;
  10240. taicpu(p).condition := C_None;
  10241. taicpu(p).opcode := A_RET;
  10242. taicpu(p).is_jmp := false;
  10243. taicpu(p).ops := taicpu(ret_p).ops;
  10244. case taicpu(ret_p).ops of
  10245. 0:
  10246. taicpu(p).clearop(0);
  10247. 1:
  10248. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10249. else
  10250. internalerror(2016041301);
  10251. end;
  10252. { If the original label is now dead, it might turn out that the label
  10253. immediately follows p. As a result, everything beyond it, which will
  10254. be just some final register configuration and a RET instruction, is
  10255. now dead code. [Kit] }
  10256. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10257. running RemoveDeadCodeAfterJump for each RET instruction, because
  10258. this optimisation rarely happens and most RETs appear at the end of
  10259. routines where there is nothing that can be stripped. [Kit] }
  10260. if not ThisLabel.is_used then
  10261. RemoveDeadCodeAfterJump(p);
  10262. end;
  10263. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10264. var
  10265. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10266. Unconditional, PotentialModified: Boolean;
  10267. OperPtr: POper;
  10268. NewRef: TReference;
  10269. InstrList: array of taicpu;
  10270. InstrMax, Index: Integer;
  10271. const
  10272. {$ifdef DEBUG_AOPTCPU}
  10273. SNoFlags: shortstring = ' so the flags aren''t modified';
  10274. {$else DEBUG_AOPTCPU}
  10275. SNoFlags = '';
  10276. {$endif DEBUG_AOPTCPU}
  10277. begin
  10278. Result:=false;
  10279. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10280. begin
  10281. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10282. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10283. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10284. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10285. GetNextInstruction(hp1, hp2) and
  10286. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10287. { Change from: To:
  10288. set(C) %reg j(~C) label
  10289. test %reg,%reg/cmp $0,%reg
  10290. je label
  10291. set(C) %reg j(C) label
  10292. test %reg,%reg/cmp $0,%reg
  10293. jne label
  10294. (Also do something similar with sete/setne instead of je/jne)
  10295. }
  10296. begin
  10297. { Before we do anything else, we need to check the instructions
  10298. in between SETcc and TEST to make sure they don't modify the
  10299. FLAGS register - if -O2 or under, there won't be any
  10300. instructions between SET and TEST }
  10301. TransferUsedRegs(TmpUsedRegs);
  10302. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10303. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10304. begin
  10305. next := p;
  10306. SetLength(InstrList, 0);
  10307. InstrMax := -1;
  10308. PotentialModified := False;
  10309. { Make a note of every instruction that modifies the FLAGS
  10310. register }
  10311. while GetNextInstruction(next, next) and (next <> hp1) do
  10312. begin
  10313. if next.typ <> ait_instruction then
  10314. { GetNextInstructionUsingReg should have returned False }
  10315. InternalError(2021051701);
  10316. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10317. begin
  10318. case taicpu(next).opcode of
  10319. A_SETcc,
  10320. A_CMOVcc,
  10321. A_Jcc:
  10322. begin
  10323. if PotentialModified then
  10324. { Not safe because the flags were modified earlier }
  10325. Exit
  10326. else
  10327. { Condition is the same as the initial SETcc, so this is safe
  10328. (don't add to instruction list though) }
  10329. Continue;
  10330. end;
  10331. A_ADD:
  10332. begin
  10333. if (taicpu(next).opsize = S_B) or
  10334. { LEA doesn't support 8-bit operands }
  10335. (taicpu(next).oper[1]^.typ <> top_reg) or
  10336. { Must write to a register }
  10337. (taicpu(next).oper[0]^.typ = top_ref) then
  10338. { Require a constant or a register }
  10339. Exit;
  10340. PotentialModified := True;
  10341. end;
  10342. A_SUB:
  10343. begin
  10344. if (taicpu(next).opsize = S_B) or
  10345. { LEA doesn't support 8-bit operands }
  10346. (taicpu(next).oper[1]^.typ <> top_reg) or
  10347. { Must write to a register }
  10348. (taicpu(next).oper[0]^.typ <> top_const) or
  10349. (taicpu(next).oper[0]^.val = $80000000) then
  10350. { Can't subtract a register with LEA - also
  10351. check that the value isn't -2^31, as this
  10352. can't be negated }
  10353. Exit;
  10354. PotentialModified := True;
  10355. end;
  10356. A_SAL,
  10357. A_SHL:
  10358. begin
  10359. if (taicpu(next).opsize = S_B) or
  10360. { LEA doesn't support 8-bit operands }
  10361. (taicpu(next).oper[1]^.typ <> top_reg) or
  10362. { Must write to a register }
  10363. (taicpu(next).oper[0]^.typ <> top_const) or
  10364. (taicpu(next).oper[0]^.val < 0) or
  10365. (taicpu(next).oper[0]^.val > 3) then
  10366. Exit;
  10367. PotentialModified := True;
  10368. end;
  10369. A_IMUL:
  10370. begin
  10371. if (taicpu(next).ops <> 3) or
  10372. (taicpu(next).oper[1]^.typ <> top_reg) or
  10373. { Must write to a register }
  10374. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10375. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10376. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10377. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10378. Exit
  10379. else
  10380. PotentialModified := True;
  10381. end;
  10382. else
  10383. { Don't know how to change this, so abort }
  10384. Exit;
  10385. end;
  10386. { Contains highest index (so instruction count - 1) }
  10387. Inc(InstrMax);
  10388. if InstrMax > High(InstrList) then
  10389. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10390. InstrList[InstrMax] := taicpu(next);
  10391. end;
  10392. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10393. end;
  10394. if not Assigned(next) or (next <> hp1) then
  10395. { It should be equal to hp1 }
  10396. InternalError(2021051702);
  10397. { Cycle through each instruction and check to see if we can
  10398. change them to versions that don't modify the flags }
  10399. if (InstrMax >= 0) then
  10400. begin
  10401. for Index := 0 to InstrMax do
  10402. case InstrList[Index].opcode of
  10403. A_ADD:
  10404. begin
  10405. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10406. InstrList[Index].opcode := A_LEA;
  10407. reference_reset(NewRef, 1, []);
  10408. NewRef.base := InstrList[Index].oper[1]^.reg;
  10409. if InstrList[Index].oper[0]^.typ = top_reg then
  10410. begin
  10411. NewRef.index := InstrList[Index].oper[0]^.reg;
  10412. NewRef.scalefactor := 1;
  10413. end
  10414. else
  10415. NewRef.offset := InstrList[Index].oper[0]^.val;
  10416. InstrList[Index].loadref(0, NewRef);
  10417. end;
  10418. A_SUB:
  10419. begin
  10420. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10421. InstrList[Index].opcode := A_LEA;
  10422. reference_reset(NewRef, 1, []);
  10423. NewRef.base := InstrList[Index].oper[1]^.reg;
  10424. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10425. InstrList[Index].loadref(0, NewRef);
  10426. end;
  10427. A_SHL,
  10428. A_SAL:
  10429. begin
  10430. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10431. InstrList[Index].opcode := A_LEA;
  10432. reference_reset(NewRef, 1, []);
  10433. NewRef.index := InstrList[Index].oper[1]^.reg;
  10434. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10435. InstrList[Index].loadref(0, NewRef);
  10436. end;
  10437. A_IMUL:
  10438. begin
  10439. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10440. InstrList[Index].opcode := A_LEA;
  10441. reference_reset(NewRef, 1, []);
  10442. NewRef.index := InstrList[Index].oper[1]^.reg;
  10443. case InstrList[Index].oper[0]^.val of
  10444. 2, 4, 8:
  10445. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10446. else {3, 5 and 9}
  10447. begin
  10448. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10449. NewRef.base := InstrList[Index].oper[1]^.reg;
  10450. end;
  10451. end;
  10452. InstrList[Index].loadref(0, NewRef);
  10453. end;
  10454. else
  10455. InternalError(2021051710);
  10456. end;
  10457. end;
  10458. { Mark the FLAGS register as used across this whole block }
  10459. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10460. end;
  10461. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10462. JumpC := taicpu(hp2).condition;
  10463. Unconditional := False;
  10464. if conditions_equal(JumpC, C_E) then
  10465. SetC := inverse_cond(taicpu(p).condition)
  10466. else if conditions_equal(JumpC, C_NE) then
  10467. SetC := taicpu(p).condition
  10468. else
  10469. { We've got something weird here (and inefficent) }
  10470. begin
  10471. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10472. SetC := C_NONE;
  10473. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10474. if condition_in(C_AE, JumpC) then
  10475. Unconditional := True
  10476. else
  10477. { Not sure what to do with this jump - drop out }
  10478. Exit;
  10479. end;
  10480. RemoveInstruction(hp1);
  10481. if Unconditional then
  10482. MakeUnconditional(taicpu(hp2))
  10483. else
  10484. begin
  10485. if SetC = C_NONE then
  10486. InternalError(2018061402);
  10487. taicpu(hp2).SetCondition(SetC);
  10488. end;
  10489. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10490. TmpUsedRegs }
  10491. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10492. begin
  10493. RemoveCurrentp(p, hp2);
  10494. if taicpu(hp2).opcode = A_SETcc then
  10495. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10496. else
  10497. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10498. end
  10499. else
  10500. if taicpu(hp2).opcode = A_SETcc then
  10501. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10502. else
  10503. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10504. Result := True;
  10505. end
  10506. else if
  10507. { Make sure the instructions are adjacent }
  10508. (
  10509. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10510. GetNextInstruction(p, hp1)
  10511. ) and
  10512. MatchInstruction(hp1, A_MOV, [S_B]) and
  10513. { Writing to memory is allowed }
  10514. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10515. begin
  10516. {
  10517. Watch out for sequences such as:
  10518. set(c)b %regb
  10519. movb %regb,(ref)
  10520. movb $0,1(ref)
  10521. movb $0,2(ref)
  10522. movb $0,3(ref)
  10523. Much more efficient to turn it into:
  10524. movl $0,%regl
  10525. set(c)b %regb
  10526. movl %regl,(ref)
  10527. Or:
  10528. set(c)b %regb
  10529. movzbl %regb,%regl
  10530. movl %regl,(ref)
  10531. }
  10532. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10533. GetNextInstruction(hp1, hp2) and
  10534. MatchInstruction(hp2, A_MOV, [S_B]) and
  10535. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10536. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10537. begin
  10538. { Don't do anything else except set Result to True }
  10539. end
  10540. else
  10541. begin
  10542. if taicpu(p).oper[0]^.typ = top_reg then
  10543. begin
  10544. TransferUsedRegs(TmpUsedRegs);
  10545. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10546. end;
  10547. { If it's not a register, it's a memory address }
  10548. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10549. begin
  10550. { Even if the register is still in use, we can minimise the
  10551. pipeline stall by changing the MOV into another SETcc. }
  10552. taicpu(hp1).opcode := A_SETcc;
  10553. taicpu(hp1).condition := taicpu(p).condition;
  10554. if taicpu(hp1).oper[1]^.typ = top_ref then
  10555. begin
  10556. { Swapping the operand pointers like this is probably a
  10557. bit naughty, but it is far faster than using loadoper
  10558. to transfer the reference from oper[1] to oper[0] if
  10559. you take into account the extra procedure calls and
  10560. the memory allocation and deallocation required }
  10561. OperPtr := taicpu(hp1).oper[1];
  10562. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10563. taicpu(hp1).oper[0] := OperPtr;
  10564. end
  10565. else
  10566. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10567. taicpu(hp1).clearop(1);
  10568. taicpu(hp1).ops := 1;
  10569. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10570. end
  10571. else
  10572. begin
  10573. if taicpu(hp1).oper[1]^.typ = top_reg then
  10574. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10575. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10576. RemoveInstruction(hp1);
  10577. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10578. end
  10579. end;
  10580. Result := True;
  10581. end;
  10582. end;
  10583. end;
  10584. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10585. var
  10586. hp1: tai;
  10587. Count: Integer;
  10588. OrigLabel: TAsmLabel;
  10589. begin
  10590. result := False;
  10591. { Sometimes, the optimisations below can permit this }
  10592. RemoveDeadCodeAfterJump(p);
  10593. 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
  10594. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10595. begin
  10596. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10597. { Also a side-effect of optimisations }
  10598. if CollapseZeroDistJump(p, OrigLabel) then
  10599. begin
  10600. Result := True;
  10601. Exit;
  10602. end;
  10603. hp1 := GetLabelWithSym(OrigLabel);
  10604. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10605. begin
  10606. if taicpu(hp1).opcode = A_RET then
  10607. begin
  10608. {
  10609. change
  10610. jmp .L1
  10611. ...
  10612. .L1:
  10613. ret
  10614. into
  10615. ret
  10616. }
  10617. begin
  10618. ConvertJumpToRET(p, hp1);
  10619. result:=true;
  10620. end;
  10621. end
  10622. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10623. not (cs_opt_size in current_settings.optimizerswitches) and
  10624. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10625. begin
  10626. Result := True;
  10627. Exit;
  10628. end;
  10629. end;
  10630. end;
  10631. end;
  10632. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10633. begin
  10634. Result := assigned(p) and
  10635. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10636. (taicpu(p).oper[1]^.typ = top_reg) and
  10637. (
  10638. (taicpu(p).oper[0]^.typ = top_reg) or
  10639. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10640. it is not expected that this can cause a seg. violation }
  10641. (
  10642. (taicpu(p).oper[0]^.typ = top_ref) and
  10643. { TODO: Can we detect which references become constants at this
  10644. stage so we don't have to do a blanket ban? }
  10645. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10646. (
  10647. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10648. (
  10649. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10650. not RefModified and
  10651. { If the reference also appears in the condition, then we know it's safe, otherwise
  10652. any kind of access violation would have occurred already }
  10653. Assigned(cond_p) and
  10654. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10655. (cond_p.typ = ait_instruction) and
  10656. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10657. { Just consider 2-operand comparison instructions for now to be safe }
  10658. (taicpu(cond_p).ops = 2) and
  10659. (
  10660. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10661. (
  10662. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10663. { Don't risk identical registers but different offsets, as we may have constructs
  10664. such as buffer streams with things like length fields that indicate whether
  10665. any more data follows. And there are probably some contrived examples where
  10666. writing to offsets behind the one being read also lead to access violations }
  10667. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10668. (
  10669. { Check that we're not modifying a register that appears in the reference }
  10670. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10671. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10672. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10673. )
  10674. )
  10675. )
  10676. )
  10677. )
  10678. )
  10679. );
  10680. end;
  10681. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10682. begin
  10683. { Update integer registers, ignoring deallocations }
  10684. repeat
  10685. while assigned(p) and
  10686. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10687. (p.typ = ait_label) or
  10688. ((p.typ = ait_marker) and
  10689. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10690. p := tai(p.next);
  10691. while assigned(p) and
  10692. (p.typ=ait_RegAlloc) Do
  10693. begin
  10694. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10695. begin
  10696. case tai_regalloc(p).ratype of
  10697. ra_alloc :
  10698. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10699. else
  10700. ;
  10701. end;
  10702. end;
  10703. p := tai(p.next);
  10704. end;
  10705. until not(assigned(p)) or
  10706. (not(p.typ in SkipInstr) and
  10707. not((p.typ = ait_label) and
  10708. labelCanBeSkipped(tai_label(p))));
  10709. end;
  10710. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10711. var
  10712. hp1,hp2: tai;
  10713. carryadd_opcode : TAsmOp;
  10714. symbol: TAsmSymbol;
  10715. increg, tmpreg: TRegister;
  10716. RefModified: Boolean;
  10717. {$ifndef i8086}
  10718. { Code and variables specific to CMOV optimisations }
  10719. hp3,hp4,hp5,
  10720. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10721. l, c, w, x : Longint;
  10722. condition, second_condition : TAsmCond;
  10723. FoundMatchingJump, RegMatch: Boolean;
  10724. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10725. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10726. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10727. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10728. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10729. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10730. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10731. new register to store the constant }
  10732. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10733. var
  10734. RegSize: TSubRegister;
  10735. CurrentVal: TCGInt;
  10736. ANewReg: TRegister;
  10737. X: ShortInt;
  10738. begin
  10739. Result := False;
  10740. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10741. Exit;
  10742. if StoredCount >= MAX_CMOV_REGISTERS then
  10743. { Arrays are full }
  10744. Exit;
  10745. { Remember that CMOV can't encode 8-bit registers }
  10746. case taicpu(p).opsize of
  10747. S_W:
  10748. RegSize := R_SUBW;
  10749. S_L:
  10750. RegSize := R_SUBD;
  10751. {$ifdef x86_64}
  10752. S_Q:
  10753. RegSize := R_SUBQ;
  10754. {$endif x86_64}
  10755. else
  10756. InternalError(2021100401);
  10757. end;
  10758. { See if the value has already been reserved for another CMOV instruction }
  10759. CurrentVal := taicpu(p).oper[0]^.val;
  10760. for X := 0 to StoredCount - 1 do
  10761. if ConstVals[X] = CurrentVal then
  10762. begin
  10763. ConstRegs[StoredCount] := ConstRegs[X];
  10764. ConstSizes[StoredCount] := RegSize;
  10765. ConstVals[StoredCount] := CurrentVal;
  10766. Result := True;
  10767. Inc(StoredCount);
  10768. { Don't increase CMOVCount this time, since we're re-using a register }
  10769. Exit;
  10770. end;
  10771. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10772. if ANewReg = NR_NO then
  10773. { No free registers }
  10774. Exit;
  10775. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10776. up vying for the same register }
  10777. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10778. ConstRegs[StoredCount] := ANewReg;
  10779. ConstSizes[StoredCount] := RegSize;
  10780. ConstVals[StoredCount] := CurrentVal;
  10781. Inc(StoredCount);
  10782. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10783. MOV required adds complexity and will cause diminishing returns
  10784. sooner than normal. This is more of an approximate weighting than
  10785. anything else. }
  10786. Inc(CMOVCount);
  10787. Result := True;
  10788. end;
  10789. {$endif i8086}
  10790. begin
  10791. result:=false;
  10792. if GetNextInstruction(p,hp1) then
  10793. begin
  10794. if (hp1.typ=ait_label) then
  10795. begin
  10796. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10797. Exit;
  10798. end
  10799. else if (hp1.typ<>ait_instruction) then
  10800. Exit;
  10801. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10802. if (
  10803. (
  10804. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10805. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10806. (Taicpu(hp1).oper[0]^.val=1)
  10807. ) or
  10808. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10809. ) and
  10810. GetNextInstruction(hp1,hp2) and
  10811. SkipAligns(hp2, hp2) and
  10812. (hp2.typ = ait_label) and
  10813. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10814. { jb @@1 cmc
  10815. inc/dec operand --> adc/sbb operand,0
  10816. @@1:
  10817. ... and ...
  10818. jnb @@1
  10819. inc/dec operand --> adc/sbb operand,0
  10820. @@1: }
  10821. begin
  10822. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10823. begin
  10824. case taicpu(hp1).opcode of
  10825. A_INC,
  10826. A_ADD:
  10827. carryadd_opcode:=A_ADC;
  10828. A_DEC,
  10829. A_SUB:
  10830. carryadd_opcode:=A_SBB;
  10831. else
  10832. InternalError(2021011001);
  10833. end;
  10834. Taicpu(p).clearop(0);
  10835. Taicpu(p).ops:=0;
  10836. Taicpu(p).is_jmp:=false;
  10837. Taicpu(p).opcode:=A_CMC;
  10838. Taicpu(p).condition:=C_NONE;
  10839. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10840. Taicpu(hp1).ops:=2;
  10841. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10842. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10843. else
  10844. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10845. Taicpu(hp1).loadconst(0,0);
  10846. Taicpu(hp1).opcode:=carryadd_opcode;
  10847. result:=true;
  10848. exit;
  10849. end
  10850. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10851. begin
  10852. case taicpu(hp1).opcode of
  10853. A_INC,
  10854. A_ADD:
  10855. carryadd_opcode:=A_ADC;
  10856. A_DEC,
  10857. A_SUB:
  10858. carryadd_opcode:=A_SBB;
  10859. else
  10860. InternalError(2021011002);
  10861. end;
  10862. Taicpu(hp1).ops:=2;
  10863. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10864. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10865. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10866. else
  10867. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10868. Taicpu(hp1).loadconst(0,0);
  10869. Taicpu(hp1).opcode:=carryadd_opcode;
  10870. RemoveCurrentP(p, hp1);
  10871. result:=true;
  10872. exit;
  10873. end
  10874. {
  10875. jcc @@1 setcc tmpreg
  10876. inc/dec/add/sub operand -> (movzx tmpreg)
  10877. @@1: add/sub tmpreg,operand
  10878. While this increases code size slightly, it makes the code much faster if the
  10879. jump is unpredictable
  10880. }
  10881. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10882. begin
  10883. { search for an available register which is volatile }
  10884. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10885. if increg <> NR_NO then
  10886. begin
  10887. { We don't need to check if tmpreg is in hp1 or not, because
  10888. it will be marked as in use at p (if not, this is
  10889. indictive of a compiler bug). }
  10890. TAsmLabel(symbol).decrefs;
  10891. Taicpu(p).clearop(0);
  10892. Taicpu(p).ops:=1;
  10893. Taicpu(p).is_jmp:=false;
  10894. Taicpu(p).opcode:=A_SETcc;
  10895. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10896. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10897. Taicpu(p).loadreg(0,increg);
  10898. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10899. begin
  10900. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10901. R_SUBW:
  10902. begin
  10903. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10904. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10905. end;
  10906. R_SUBD:
  10907. begin
  10908. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10909. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10910. end;
  10911. {$ifdef x86_64}
  10912. R_SUBQ:
  10913. begin
  10914. { MOVZX doesn't have a 64-bit variant, because
  10915. the 32-bit version implicitly zeroes the
  10916. upper 32-bits of the destination register }
  10917. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10918. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10919. setsubreg(tmpreg, R_SUBQ);
  10920. end;
  10921. {$endif x86_64}
  10922. else
  10923. Internalerror(2020030601);
  10924. end;
  10925. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10926. asml.InsertAfter(hp2,p);
  10927. end
  10928. else
  10929. tmpreg := increg;
  10930. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10931. begin
  10932. Taicpu(hp1).ops:=2;
  10933. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10934. end;
  10935. Taicpu(hp1).loadreg(0,tmpreg);
  10936. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10937. Result := True;
  10938. { p is no longer a Jcc instruction, so exit }
  10939. Exit;
  10940. end;
  10941. end;
  10942. end;
  10943. { Detect the following:
  10944. jmp<cond> @Lbl1
  10945. jmp @Lbl2
  10946. ...
  10947. @Lbl1:
  10948. ret
  10949. Change to:
  10950. jmp<inv_cond> @Lbl2
  10951. ret
  10952. }
  10953. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10954. begin
  10955. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10956. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10957. MatchInstruction(hp2,A_RET,[S_NO]) then
  10958. begin
  10959. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10960. { Change label address to that of the unconditional jump }
  10961. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10962. TAsmLabel(symbol).DecRefs;
  10963. taicpu(hp1).opcode := A_RET;
  10964. taicpu(hp1).is_jmp := false;
  10965. taicpu(hp1).ops := taicpu(hp2).ops;
  10966. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10967. case taicpu(hp2).ops of
  10968. 0:
  10969. taicpu(hp1).clearop(0);
  10970. 1:
  10971. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10972. else
  10973. internalerror(2016041302);
  10974. end;
  10975. end;
  10976. {$ifndef i8086}
  10977. end
  10978. {
  10979. convert
  10980. j<c> .L1
  10981. mov 1,reg
  10982. jmp .L2
  10983. .L1
  10984. mov 0,reg
  10985. .L2
  10986. into
  10987. mov 0,reg
  10988. set<not(c)> reg
  10989. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10990. would destroy the flag contents
  10991. }
  10992. else if MatchInstruction(hp1,A_MOV,[]) and
  10993. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10994. {$ifdef i386}
  10995. (
  10996. { Under i386, ESI, EDI, EBP and ESP
  10997. don't have an 8-bit representation }
  10998. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10999. ) and
  11000. {$endif i386}
  11001. (taicpu(hp1).oper[0]^.val=1) and
  11002. GetNextInstruction(hp1,hp2) and
  11003. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  11004. GetNextInstruction(hp2,hp3) and
  11005. { skip align }
  11006. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  11007. (hp3.typ=ait_label) and
  11008. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  11009. (tai_label(hp3).labsym.getrefs=1) and
  11010. GetNextInstruction(hp3,hp4) and
  11011. MatchInstruction(hp4,A_MOV,[]) and
  11012. MatchOpType(taicpu(hp4),top_const,top_reg) and
  11013. (taicpu(hp4).oper[0]^.val=0) and
  11014. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  11015. GetNextInstruction(hp4,hp5) and
  11016. (hp5.typ=ait_label) and
  11017. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  11018. (tai_label(hp5).labsym.getrefs=1) then
  11019. begin
  11020. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  11021. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  11022. { remove last label }
  11023. RemoveInstruction(hp5);
  11024. { remove second label }
  11025. RemoveInstruction(hp3);
  11026. { if align is present remove it }
  11027. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  11028. RemoveInstruction(hp3);
  11029. { remove jmp }
  11030. RemoveInstruction(hp2);
  11031. if taicpu(hp1).opsize=S_B then
  11032. RemoveInstruction(hp1)
  11033. else
  11034. taicpu(hp1).loadconst(0,0);
  11035. taicpu(hp4).opcode:=A_SETcc;
  11036. taicpu(hp4).opsize:=S_B;
  11037. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  11038. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  11039. taicpu(hp4).opercnt:=1;
  11040. taicpu(hp4).ops:=1;
  11041. taicpu(hp4).freeop(1);
  11042. RemoveCurrentP(p);
  11043. Result:=true;
  11044. exit;
  11045. end
  11046. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  11047. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  11048. begin
  11049. { check for
  11050. jCC xxx
  11051. <several movs>
  11052. xxx:
  11053. Also spot:
  11054. Jcc xxx
  11055. <several movs>
  11056. jmp xxx
  11057. Change to:
  11058. <several cmovs with inverted condition>
  11059. jmp xxx (only for the 2nd case)
  11060. }
  11061. hp2 := p;
  11062. hp_lblxxx := hp1;
  11063. hp_flagalloc := nil;
  11064. hp_stop := nil;
  11065. FoundMatchingJump := False;
  11066. { Remember the first instruction in the first block of MOVs }
  11067. hpmov1 := hp1;
  11068. TransferUsedRegs(TmpUsedRegs);
  11069. while assigned(hp_lblxxx) and
  11070. { stop on labels }
  11071. (hp_lblxxx.typ <> ait_label) do
  11072. begin
  11073. { Keep track of all integer registers that are used }
  11074. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11075. if hp_lblxxx.typ = ait_instruction then
  11076. begin
  11077. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  11078. IsJumpToLabel(taicpu(hp_lblxxx)) then
  11079. begin
  11080. hp_stop := hp_lblxxx;
  11081. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  11082. begin
  11083. { We found Jcc xxx; <several movs>; Jmp xxx }
  11084. FoundMatchingJump := True;
  11085. Break;
  11086. end;
  11087. { If it's not the jump we're looking for, it's
  11088. possibly the "if..else" variant }
  11089. end
  11090. { Check to see if we have a valid MOV instruction instead }
  11091. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11092. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11093. Break
  11094. else
  11095. { This will be a valid MOV }
  11096. hp_stop := hp_lblxxx;
  11097. end;
  11098. hp2 := hp_lblxxx;
  11099. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11100. end;
  11101. { Just make sure the last MOV is included if there's no jump }
  11102. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11103. hp_stop := hp_lblxxx;
  11104. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11105. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11106. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11107. jmp yyy; xxx:; movs; yyy:" variation }
  11108. if assigned(hp_lblxxx) and
  11109. (
  11110. { If we found JMP xxx, we don't actually need a label
  11111. (hp_lblxxx is the JMP instruction instead) }
  11112. FoundMatchingJump or
  11113. { Make sure we actually have the right label }
  11114. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11115. ) then
  11116. begin
  11117. { Use TmpUsedRegs to track registers that we reserve }
  11118. { When allocating temporary registers, try to look one
  11119. instruction back, as defining them before a CMP or TEST
  11120. instruction will be faster, and also avoid picking a
  11121. register that was only just deallocated }
  11122. if GetLastInstruction(p, hp_prev) and
  11123. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11124. begin
  11125. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11126. for l := 0 to 1 do
  11127. with taicpu(hp_prev).oper[l]^ do
  11128. case typ of
  11129. top_reg:
  11130. if getregtype(reg) = R_INTREGISTER then
  11131. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11132. top_ref:
  11133. begin
  11134. if
  11135. {$ifdef x86_64}
  11136. (ref^.base <> NR_RIP) and
  11137. {$endif x86_64}
  11138. (ref^.base <> NR_NO) then
  11139. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11140. if (ref^.index <> NR_NO) then
  11141. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11142. end
  11143. else
  11144. ;
  11145. end;
  11146. { When inserting instructions before hp_prev, try to insert
  11147. them before the allocation of the FLAGS register }
  11148. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11149. { If not found, set it equal to hp_prev so it's something sensible }
  11150. hp_flagalloc := hp_prev;
  11151. hp_prev2 := nil;
  11152. { When dealing with a comparison against zero, take
  11153. note of the instruction before it to see if we can
  11154. move instructions further back in order to benefit
  11155. PostPeepholeOptTestOr.
  11156. }
  11157. if (
  11158. (
  11159. (taicpu(hp_prev).opcode = A_CMP) and
  11160. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11161. ) or
  11162. (
  11163. (taicpu(hp_prev).opcode = A_TEST) and
  11164. (
  11165. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11166. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11167. )
  11168. )
  11169. ) and
  11170. GetLastInstruction(hp_prev, hp_prev2) then
  11171. begin
  11172. if (hp_prev2.typ = ait_instruction) and
  11173. { These instructions set the zero flag if the result is zero }
  11174. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11175. begin
  11176. { Also mark all the registers in this previous instruction
  11177. as 'in use', even if they've just been deallocated }
  11178. for l := 0 to 1 do
  11179. with taicpu(hp_prev2).oper[l]^ do
  11180. case typ of
  11181. top_reg:
  11182. if getregtype(reg) = R_INTREGISTER then
  11183. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11184. top_ref:
  11185. begin
  11186. if
  11187. {$ifdef x86_64}
  11188. (ref^.base <> NR_RIP) and
  11189. {$endif x86_64}
  11190. (ref^.base <> NR_NO) then
  11191. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11192. if (ref^.index <> NR_NO) then
  11193. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11194. end
  11195. else
  11196. ;
  11197. end;
  11198. end
  11199. else
  11200. { Unsuitable instruction }
  11201. hp_prev2 := nil;
  11202. end;
  11203. end
  11204. else
  11205. begin
  11206. hp_prev := p;
  11207. { When inserting instructions before hp_prev, try to insert
  11208. them before the allocation of the FLAGS register }
  11209. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11210. { If not found, set it equal to p so it's something sensible }
  11211. hp_flagalloc := p;
  11212. hp_prev2 := nil;
  11213. end;
  11214. l := 0;
  11215. c := 0;
  11216. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11217. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11218. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11219. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11220. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11221. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11222. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11223. RefModified := False;
  11224. while assigned(hp1) and
  11225. { Stop on the label we found }
  11226. (hp1 <> hp_lblxxx) do
  11227. begin
  11228. case hp1.typ of
  11229. ait_instruction:
  11230. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11231. begin
  11232. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11233. begin
  11234. Inc(l);
  11235. { MOV instruction will be writing to a register }
  11236. if Assigned(hp_prev) and
  11237. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11238. (hp_prev.typ = ait_instruction) and
  11239. (taicpu(hp_prev).ops = 2) and
  11240. (
  11241. (
  11242. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11243. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11244. ) or
  11245. (
  11246. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11247. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11248. )
  11249. ) then
  11250. { It is no longer safe to use the reference in the condition.
  11251. this prevents problems such as:
  11252. mov (%reg),%reg
  11253. mov (%reg),...
  11254. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11255. (fixes #40165)
  11256. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11257. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11258. }
  11259. RefModified := True;
  11260. end
  11261. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11262. { CMOV with constants grows the code size }
  11263. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11264. begin
  11265. { Register was reserved by TryCMOVConst and
  11266. stored on ConstRegs[c] }
  11267. end
  11268. else
  11269. Break;
  11270. end
  11271. else
  11272. Break;
  11273. else
  11274. ;
  11275. end;
  11276. GetNextInstruction(hp1,hp1);
  11277. end;
  11278. if (hp1 = hp_lblxxx) then
  11279. begin
  11280. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11281. begin
  11282. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11283. TmpUsedRegs[R_INTREGISTER].Clear;
  11284. x := 0;
  11285. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11286. condition := inverse_cond(taicpu(p).condition);
  11287. UpdateUsedRegs(tai(p.next));
  11288. hp1 := hpmov1;
  11289. repeat
  11290. if not Assigned(hp1) then
  11291. InternalError(2018062900);
  11292. if (hp1.typ = ait_instruction) then
  11293. begin
  11294. { Extra safeguard }
  11295. if (taicpu(hp1).opcode <> A_MOV) then
  11296. InternalError(2018062901);
  11297. if taicpu(hp1).oper[0]^.typ = top_const then
  11298. begin
  11299. if x >= MAX_CMOV_REGISTERS then
  11300. InternalError(2021100410);
  11301. { If it's in TmpUsedRegs, then this register
  11302. is being used more than once and hence has
  11303. already had its value defined (it gets
  11304. added to UsedRegs through AllocRegBetween
  11305. below) }
  11306. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11307. begin
  11308. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11309. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11310. asml.InsertBefore(hp_new, hp_flagalloc);
  11311. if Assigned(hp_prev2) then
  11312. TrySwapMovOp(hp_prev2, hp_new);
  11313. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11314. ConstMovs[X] := hp_new;
  11315. end
  11316. else
  11317. { We just need an instruction between hp_prev and hp1
  11318. where we know the register is marked as in use }
  11319. hp_new := hpmov1;
  11320. { Keep track of largest write for this register so it can be optimised later }
  11321. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11322. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11323. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11324. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11325. Inc(x);
  11326. end;
  11327. taicpu(hp1).opcode := A_CMOVcc;
  11328. taicpu(hp1).condition := condition;
  11329. end;
  11330. UpdateUsedRegs(tai(hp1.next));
  11331. GetNextInstruction(hp1, hp1);
  11332. until (hp1 = hp_lblxxx);
  11333. { Update initialisation MOVs to the smallest possible size }
  11334. for c := 0 to x - 1 do
  11335. if Assigned(ConstMovs[c]) then
  11336. begin
  11337. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11338. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11339. end;
  11340. hp2 := hp_lblxxx;
  11341. repeat
  11342. if not Assigned(hp2) then
  11343. InternalError(2018062910);
  11344. case hp2.typ of
  11345. ait_label:
  11346. { What we expected - break out of the loop (it won't be a dead label at the top of
  11347. a cluster because that was optimised at an earlier stage) }
  11348. Break;
  11349. ait_align:
  11350. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11351. begin
  11352. hp2 := tai(hp2.Next);
  11353. Continue;
  11354. end;
  11355. ait_instruction:
  11356. begin
  11357. if taicpu(hp2).opcode<>A_JMP then
  11358. InternalError(2018062912);
  11359. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11360. Break;
  11361. end
  11362. else
  11363. begin
  11364. { Might be a comment or temporary allocation entry }
  11365. if not (hp2.typ in SkipInstr) then
  11366. InternalError(2018062911);
  11367. hp2 := tai(hp2.Next);
  11368. Continue;
  11369. end;
  11370. end;
  11371. until False;
  11372. { Now we can safely decrement the reference count }
  11373. tasmlabel(symbol).decrefs;
  11374. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11375. { Remove the original jump }
  11376. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11377. if hp2.typ=ait_instruction then
  11378. begin
  11379. p := hp2;
  11380. Result := True;
  11381. end
  11382. else
  11383. begin
  11384. UpdateUsedRegs(tai(hp2.next));
  11385. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11386. { Remove the label if this is its final reference }
  11387. if (tasmlabel(symbol).getrefs=0) then
  11388. begin
  11389. { Make sure the aligns get stripped too }
  11390. hp1 := tai(hp_lblxxx.Previous);
  11391. while Assigned(hp1) and (hp1.typ = ait_align) do
  11392. begin
  11393. hp_lblxxx := hp1;
  11394. hp1 := tai(hp_lblxxx.Previous);
  11395. end;
  11396. StripLabelFast(hp_lblxxx);
  11397. end;
  11398. end;
  11399. Exit;
  11400. end;
  11401. end
  11402. else if assigned(hp_lblxxx) and
  11403. { check further for
  11404. jCC xxx
  11405. <several movs 1>
  11406. jmp yyy
  11407. xxx:
  11408. <several movs 2>
  11409. yyy:
  11410. }
  11411. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11412. { hp1 should be pointing to jmp yyy }
  11413. MatchInstruction(hp1, A_JMP, []) and
  11414. { real label and jump, no further references to the
  11415. label are allowed }
  11416. (TAsmLabel(symbol).getrefs=1) and
  11417. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11418. begin
  11419. hp_jump := hp1;
  11420. { Don't set c to zero }
  11421. l := 0;
  11422. w := 0;
  11423. GetNextInstruction(hp_lblxxx, hpmov2);
  11424. hp2 := hp_lblxxx;
  11425. hp_lblyyy := hpmov2;
  11426. while assigned(hp_lblyyy) and
  11427. { stop on labels }
  11428. (hp_lblyyy.typ <> ait_label) do
  11429. begin
  11430. { Keep track of all integer registers that are used }
  11431. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11432. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11433. Break;
  11434. hp2 := hp_lblyyy;
  11435. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11436. end;
  11437. { Analyse the second batch of MOVs to see if the setup is valid }
  11438. RefModified := False;
  11439. hp1 := hpmov2;
  11440. while assigned(hp1) and
  11441. (hp1 <> hp_lblyyy) do
  11442. begin
  11443. case hp1.typ of
  11444. ait_instruction:
  11445. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11446. begin
  11447. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11448. begin
  11449. Inc(l);
  11450. { MOV instruction will be writing to a register }
  11451. if Assigned(hp_prev) and
  11452. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11453. (hp_prev.typ = ait_instruction) and
  11454. (taicpu(hp_prev).ops = 2) and
  11455. (
  11456. (
  11457. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11458. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11459. ) or
  11460. (
  11461. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11462. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11463. )
  11464. ) then
  11465. { It is no longer safe to use the reference in the condition.
  11466. this prevents problems such as:
  11467. mov (%reg),%reg
  11468. mov (%reg),...
  11469. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11470. (fixes #40165)
  11471. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11472. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11473. }
  11474. RefModified := True;
  11475. end
  11476. else if not (cs_opt_size in current_settings.optimizerswitches)
  11477. { CMOV with constants grows the code size }
  11478. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11479. begin
  11480. { Register was reserved by TryCMOVConst and
  11481. stored on ConstRegs[c] }
  11482. end
  11483. else
  11484. Break;
  11485. end
  11486. else
  11487. Break;
  11488. else
  11489. ;
  11490. end;
  11491. GetNextInstruction(hp1,hp1);
  11492. end;
  11493. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11494. TmpUsedRegs[R_INTREGISTER].Clear;
  11495. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11496. (hp1 = hp_lblyyy) and
  11497. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11498. begin
  11499. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11500. second_condition := taicpu(p).condition;
  11501. condition := inverse_cond(taicpu(p).condition);
  11502. UpdateUsedRegs(tai(p.next));
  11503. { Scan through the first set of MOVs to update UsedRegs,
  11504. but don't process them yet }
  11505. hp1 := hpmov1;
  11506. repeat
  11507. if not Assigned(hp1) then
  11508. InternalError(2018062901);
  11509. UpdateUsedRegs(tai(hp1.next));
  11510. GetNextInstruction(hp1, hp1);
  11511. until (hp1 = hp_lblxxx);
  11512. UpdateUsedRegs(tai(hp_lblxxx.next));
  11513. { Process the second set of MOVs first,
  11514. because if a destination register is
  11515. shared between the first and second MOV
  11516. sets, it is more efficient to turn the
  11517. first one into a MOV instruction and place
  11518. it before the CMP if possible, but we
  11519. won't know which registers are shared
  11520. until we've processed at least one list,
  11521. so we might as well make it the second
  11522. one since that won't be modified again. }
  11523. hp1 := hpmov2;
  11524. repeat
  11525. if not Assigned(hp1) then
  11526. InternalError(2018062902);
  11527. if (hp1.typ = ait_instruction) then
  11528. begin
  11529. { Extra safeguard }
  11530. if (taicpu(hp1).opcode <> A_MOV) then
  11531. InternalError(2018062903);
  11532. if taicpu(hp1).oper[0]^.typ = top_const then
  11533. begin
  11534. RegMatch := False;
  11535. for x := 0 to c - 1 do
  11536. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11537. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11538. begin
  11539. RegMatch := True;
  11540. { If it's in TmpUsedRegs, then this register
  11541. is being used more than once and hence has
  11542. already had its value defined (it gets
  11543. added to UsedRegs through AllocRegBetween
  11544. below) }
  11545. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11546. begin
  11547. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11548. asml.InsertBefore(hp_new, hp_flagalloc);
  11549. if Assigned(hp_prev2) then
  11550. TrySwapMovOp(hp_prev2, hp_new);
  11551. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11552. ConstMovs[X] := hp_new;
  11553. end
  11554. else
  11555. { We just need an instruction between hp_prev and hp1
  11556. where we know the register is marked as in use }
  11557. hp_new := hpmov2;
  11558. { Keep track of largest write for this register so it can be optimised later }
  11559. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11560. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11561. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11562. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11563. Break;
  11564. end;
  11565. if not RegMatch then
  11566. InternalError(2021100411);
  11567. end;
  11568. taicpu(hp1).opcode := A_CMOVcc;
  11569. taicpu(hp1).condition := second_condition;
  11570. { Store these writes to search for
  11571. duplicates later on }
  11572. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11573. Inc(w);
  11574. end;
  11575. UpdateUsedRegs(tai(hp1.next));
  11576. GetNextInstruction(hp1, hp1);
  11577. until (hp1 = hp_lblyyy);
  11578. { Now do the first set of MOVs }
  11579. hp1 := hpmov1;
  11580. repeat
  11581. if not Assigned(hp1) then
  11582. InternalError(2018062904);
  11583. if (hp1.typ = ait_instruction) then
  11584. begin
  11585. RegMatch := False;
  11586. { Extra safeguard }
  11587. if (taicpu(hp1).opcode <> A_MOV) then
  11588. InternalError(2018062905);
  11589. { Search through the RegWrites list to see
  11590. if there are any opposing CMOV pairs that
  11591. write to the same register }
  11592. for x := 0 to w - 1 do
  11593. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11594. begin
  11595. { We have a match. Keep this as a MOV }
  11596. { Move ahead in preparation }
  11597. GetNextInstruction(hp1, hp1);
  11598. RegMatch := True;
  11599. Break;
  11600. end;
  11601. if RegMatch then
  11602. Continue;
  11603. if taicpu(hp1).oper[0]^.typ = top_const then
  11604. begin
  11605. RegMatch := False;
  11606. for x := 0 to c - 1 do
  11607. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11608. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11609. begin
  11610. RegMatch := True;
  11611. { If it's in TmpUsedRegs, then this register
  11612. is being used more than once and hence has
  11613. already had its value defined (it gets
  11614. added to UsedRegs through AllocRegBetween
  11615. below) }
  11616. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11617. begin
  11618. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11619. asml.InsertBefore(hp_new, hp_flagalloc);
  11620. if Assigned(hp_prev2) then
  11621. TrySwapMovOp(hp_prev2, hp_new);
  11622. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11623. ConstMovs[X] := hp_new;
  11624. end
  11625. else
  11626. { We just need an instruction between hp_prev and hp1
  11627. where we know the register is marked as in use }
  11628. hp_new := hpmov1;
  11629. { Keep track of largest write for this register so it can be optimised later }
  11630. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11631. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11632. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11633. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11634. Break;
  11635. end;
  11636. if not RegMatch then
  11637. InternalError(2021100412);
  11638. end;
  11639. taicpu(hp1).opcode := A_CMOVcc;
  11640. taicpu(hp1).condition := condition;
  11641. end;
  11642. GetNextInstruction(hp1, hp1);
  11643. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11644. { Update initialisation MOVs to the smallest possible size }
  11645. for x := 0 to c - 1 do
  11646. if Assigned(ConstMovs[x]) then
  11647. begin
  11648. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11649. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11650. end;
  11651. UpdateUsedRegs(tai(hp_jump.next));
  11652. UpdateUsedRegs(tai(hp_lblyyy.next));
  11653. { Get first instruction after label }
  11654. hp1 := p;
  11655. GetNextInstruction(hp_lblyyy, p);
  11656. { Don't dereference yet, as doing so will cause
  11657. GetNextInstruction to skip the label and
  11658. optional align marker. [Kit] }
  11659. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11660. { remove Jcc }
  11661. RemoveInstruction(hp1);
  11662. { Now we can safely decrement it }
  11663. tasmlabel(symbol).decrefs;
  11664. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11665. { Make sure the aligns get stripped too }
  11666. hp1 := tai(hp_lblxxx.Previous);
  11667. while Assigned(hp1) and (hp1.typ = ait_align) do
  11668. begin
  11669. hp_lblxxx := hp1;
  11670. hp1 := tai(hp_lblxxx.Previous);
  11671. end;
  11672. StripLabelFast(hp_lblxxx);
  11673. { remove jmp }
  11674. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11675. RemoveInstruction(hp_jump);
  11676. { As before, now we can safely decrement it }
  11677. TAsmLabel(symbol).decrefs;
  11678. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11679. if TAsmLabel(symbol).getrefs = 0 then
  11680. begin
  11681. { Make sure the aligns get stripped too }
  11682. hp1 := tai(hp_lblyyy.Previous);
  11683. while Assigned(hp1) and (hp1.typ = ait_align) do
  11684. begin
  11685. hp_lblyyy := hp1;
  11686. hp1 := tai(hp_lblyyy.Previous);
  11687. end;
  11688. StripLabelFast(hp_lblyyy);
  11689. end;
  11690. if Assigned(p) then
  11691. result := True;
  11692. exit;
  11693. end;
  11694. end;
  11695. end;
  11696. {$endif i8086}
  11697. end;
  11698. end;
  11699. end;
  11700. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11701. var
  11702. hp1,hp2,hp3: tai;
  11703. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11704. NewSize: TOpSize;
  11705. NewRegSize: TSubRegister;
  11706. Limit: TCgInt;
  11707. SwapOper: POper;
  11708. begin
  11709. result:=false;
  11710. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11711. GetNextInstruction(p,hp1) and
  11712. (hp1.typ = ait_instruction);
  11713. if reg_and_hp1_is_instr and
  11714. (
  11715. (taicpu(hp1).opcode <> A_LEA) or
  11716. { If the LEA instruction can be converted into an arithmetic instruction,
  11717. it may be possible to then fold it. }
  11718. (
  11719. { If the flags register is in use, don't change the instruction
  11720. to an ADD otherwise this will scramble the flags. [Kit] }
  11721. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11722. ConvertLEA(taicpu(hp1))
  11723. )
  11724. ) and
  11725. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11726. GetNextInstruction(hp1,hp2) and
  11727. MatchInstruction(hp2,A_MOV,[]) and
  11728. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11729. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11730. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11731. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11732. {$ifdef i386}
  11733. { not all registers have byte size sub registers on i386 }
  11734. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11735. {$endif i386}
  11736. (((taicpu(hp1).ops=2) and
  11737. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11738. ((taicpu(hp1).ops=1) and
  11739. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11740. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11741. begin
  11742. { change movsX/movzX reg/ref, reg2
  11743. add/sub/or/... reg3/$const, reg2
  11744. mov reg2 reg/ref
  11745. to add/sub/or/... reg3/$const, reg/ref }
  11746. { by example:
  11747. movswl %si,%eax movswl %si,%eax p
  11748. decl %eax addl %edx,%eax hp1
  11749. movw %ax,%si movw %ax,%si hp2
  11750. ->
  11751. movswl %si,%eax movswl %si,%eax p
  11752. decw %eax addw %edx,%eax hp1
  11753. movw %ax,%si movw %ax,%si hp2
  11754. }
  11755. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11756. {
  11757. ->
  11758. movswl %si,%eax movswl %si,%eax p
  11759. decw %si addw %dx,%si hp1
  11760. movw %ax,%si movw %ax,%si hp2
  11761. }
  11762. case taicpu(hp1).ops of
  11763. 1:
  11764. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11765. 2:
  11766. begin
  11767. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11768. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11769. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11770. end;
  11771. else
  11772. internalerror(2008042702);
  11773. end;
  11774. {
  11775. ->
  11776. decw %si addw %dx,%si p
  11777. }
  11778. DebugMsg(SPeepholeOptimization + 'var3',p);
  11779. RemoveCurrentP(p, hp1);
  11780. RemoveInstruction(hp2);
  11781. Result := True;
  11782. Exit;
  11783. end;
  11784. if reg_and_hp1_is_instr and
  11785. (taicpu(hp1).opcode = A_MOV) and
  11786. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11787. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11788. {$ifdef x86_64}
  11789. { check for implicit extension to 64 bit }
  11790. or
  11791. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11792. (taicpu(hp1).opsize=S_Q) and
  11793. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11794. )
  11795. {$endif x86_64}
  11796. )
  11797. then
  11798. begin
  11799. { change
  11800. movx %reg1,%reg2
  11801. mov %reg2,%reg3
  11802. dealloc %reg2
  11803. into
  11804. movx %reg,%reg3
  11805. }
  11806. TransferUsedRegs(TmpUsedRegs);
  11807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11808. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11809. begin
  11810. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11811. {$ifdef x86_64}
  11812. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11813. (taicpu(hp1).opsize=S_Q) then
  11814. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11815. else
  11816. {$endif x86_64}
  11817. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11818. RemoveInstruction(hp1);
  11819. Result := True;
  11820. Exit;
  11821. end;
  11822. end;
  11823. if reg_and_hp1_is_instr and
  11824. ((taicpu(hp1).opcode=A_MOV) or
  11825. (taicpu(hp1).opcode=A_ADD) or
  11826. (taicpu(hp1).opcode=A_SUB) or
  11827. (taicpu(hp1).opcode=A_CMP) or
  11828. (taicpu(hp1).opcode=A_OR) or
  11829. (taicpu(hp1).opcode=A_XOR) or
  11830. (taicpu(hp1).opcode=A_AND)
  11831. ) and
  11832. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11833. begin
  11834. AndTest := (taicpu(hp1).opcode=A_AND) and
  11835. GetNextInstruction(hp1, hp2) and
  11836. (hp2.typ = ait_instruction) and
  11837. (
  11838. (
  11839. (taicpu(hp2).opcode=A_TEST) and
  11840. (
  11841. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11842. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11843. (
  11844. { If the AND and TEST instructions share a constant, this is also valid }
  11845. (taicpu(hp1).oper[0]^.typ = top_const) and
  11846. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11847. )
  11848. ) and
  11849. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11850. ) or
  11851. (
  11852. (taicpu(hp2).opcode=A_CMP) and
  11853. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11854. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11855. )
  11856. );
  11857. { change
  11858. movx (oper),%reg2
  11859. and $x,%reg2
  11860. test %reg2,%reg2
  11861. dealloc %reg2
  11862. into
  11863. op %reg1,%reg3
  11864. if the second op accesses only the bits stored in reg1
  11865. }
  11866. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11867. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11868. (taicpu(hp1).oper[0]^.typ = top_const) and
  11869. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11870. AndTest then
  11871. begin
  11872. { Check if the AND constant is in range }
  11873. case taicpu(p).opsize of
  11874. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11875. begin
  11876. NewSize := S_B;
  11877. Limit := $FF;
  11878. end;
  11879. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11880. begin
  11881. NewSize := S_W;
  11882. Limit := $FFFF;
  11883. end;
  11884. {$ifdef x86_64}
  11885. S_LQ:
  11886. begin
  11887. NewSize := S_L;
  11888. Limit := $FFFFFFFF;
  11889. end;
  11890. {$endif x86_64}
  11891. else
  11892. InternalError(2021120303);
  11893. end;
  11894. if (
  11895. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11896. { Check for negative operands }
  11897. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11898. ) and
  11899. GetNextInstruction(hp2,hp3) and
  11900. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11901. (taicpu(hp3).condition in [C_E,C_NE]) then
  11902. begin
  11903. TransferUsedRegs(TmpUsedRegs);
  11904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11905. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11906. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11907. begin
  11908. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11909. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11910. taicpu(hp1).opcode := A_TEST;
  11911. taicpu(hp1).opsize := NewSize;
  11912. RemoveInstruction(hp2);
  11913. RemoveCurrentP(p, hp1);
  11914. Result:=true;
  11915. exit;
  11916. end;
  11917. end;
  11918. end;
  11919. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11920. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11921. (taicpu(hp1).opsize=S_B)) or
  11922. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11923. (taicpu(hp1).opsize=S_W))
  11924. {$ifdef x86_64}
  11925. or ((taicpu(p).opsize=S_LQ) and
  11926. (taicpu(hp1).opsize=S_L))
  11927. {$endif x86_64}
  11928. ) and
  11929. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11930. begin
  11931. { change
  11932. movx %reg1,%reg2
  11933. op %reg2,%reg3
  11934. dealloc %reg2
  11935. into
  11936. op %reg1,%reg3
  11937. if the second op accesses only the bits stored in reg1
  11938. }
  11939. TransferUsedRegs(TmpUsedRegs);
  11940. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11941. if AndTest then
  11942. begin
  11943. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11944. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11945. end
  11946. else
  11947. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11948. if not RegUsed then
  11949. begin
  11950. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11951. if taicpu(p).oper[0]^.typ=top_reg then
  11952. begin
  11953. case taicpu(hp1).opsize of
  11954. S_B:
  11955. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11956. S_W:
  11957. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11958. S_L:
  11959. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11960. else
  11961. Internalerror(2020102301);
  11962. end;
  11963. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11964. end
  11965. else
  11966. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11967. RemoveCurrentP(p);
  11968. if AndTest then
  11969. RemoveInstruction(hp2);
  11970. result:=true;
  11971. exit;
  11972. end;
  11973. end
  11974. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11975. (
  11976. { Bitwise operations only }
  11977. (taicpu(hp1).opcode=A_AND) or
  11978. (taicpu(hp1).opcode=A_TEST) or
  11979. (
  11980. (taicpu(hp1).oper[0]^.typ = top_const) and
  11981. (
  11982. (taicpu(hp1).opcode=A_OR) or
  11983. (taicpu(hp1).opcode=A_XOR)
  11984. )
  11985. )
  11986. ) and
  11987. (
  11988. (taicpu(hp1).oper[0]^.typ = top_const) or
  11989. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11990. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11991. ) then
  11992. begin
  11993. { change
  11994. movx %reg2,%reg2
  11995. op const,%reg2
  11996. into
  11997. op const,%reg2 (smaller version)
  11998. movx %reg2,%reg2
  11999. also change
  12000. movx %reg1,%reg2
  12001. and/test (oper),%reg2
  12002. dealloc %reg2
  12003. into
  12004. and/test (oper),%reg1
  12005. }
  12006. case taicpu(p).opsize of
  12007. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12008. begin
  12009. NewSize := S_B;
  12010. NewRegSize := R_SUBL;
  12011. Limit := $FF;
  12012. end;
  12013. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12014. begin
  12015. NewSize := S_W;
  12016. NewRegSize := R_SUBW;
  12017. Limit := $FFFF;
  12018. end;
  12019. {$ifdef x86_64}
  12020. S_LQ:
  12021. begin
  12022. NewSize := S_L;
  12023. NewRegSize := R_SUBD;
  12024. Limit := $FFFFFFFF;
  12025. end;
  12026. {$endif x86_64}
  12027. else
  12028. Internalerror(2021120302);
  12029. end;
  12030. TransferUsedRegs(TmpUsedRegs);
  12031. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12032. if AndTest then
  12033. begin
  12034. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12035. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12036. end
  12037. else
  12038. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12039. if
  12040. (
  12041. (taicpu(p).opcode = A_MOVZX) and
  12042. (
  12043. (taicpu(hp1).opcode=A_AND) or
  12044. (taicpu(hp1).opcode=A_TEST)
  12045. ) and
  12046. not (
  12047. { If both are references, then the final instruction will have
  12048. both operands as references, which is not allowed }
  12049. (taicpu(p).oper[0]^.typ = top_ref) and
  12050. (taicpu(hp1).oper[0]^.typ = top_ref)
  12051. ) and
  12052. not RegUsed
  12053. ) or
  12054. (
  12055. (
  12056. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12057. not RegUsed
  12058. ) and
  12059. (taicpu(p).oper[0]^.typ = top_reg) and
  12060. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12061. (taicpu(hp1).oper[0]^.typ = top_const) and
  12062. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12063. ) then
  12064. begin
  12065. {$if defined(i386) or defined(i8086)}
  12066. { If the target size is 8-bit, make sure we can actually encode it }
  12067. 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
  12068. Exit;
  12069. {$endif i386 or i8086}
  12070. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12071. taicpu(hp1).opsize := NewSize;
  12072. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12073. if AndTest then
  12074. begin
  12075. RemoveInstruction(hp2);
  12076. if not RegUsed then
  12077. begin
  12078. taicpu(hp1).opcode := A_TEST;
  12079. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12080. begin
  12081. { Make sure the reference is the second operand }
  12082. SwapOper := taicpu(hp1).oper[0];
  12083. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12084. taicpu(hp1).oper[1] := SwapOper;
  12085. end;
  12086. end;
  12087. end;
  12088. case taicpu(hp1).oper[0]^.typ of
  12089. top_reg:
  12090. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12091. top_const:
  12092. { For the AND/TEST case }
  12093. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12094. else
  12095. ;
  12096. end;
  12097. if RegUsed then
  12098. begin
  12099. AsmL.Remove(p);
  12100. AsmL.InsertAfter(p, hp1);
  12101. p := hp1;
  12102. end
  12103. else
  12104. RemoveCurrentP(p, hp1);
  12105. result:=true;
  12106. exit;
  12107. end;
  12108. end;
  12109. end;
  12110. if reg_and_hp1_is_instr and
  12111. (taicpu(p).oper[0]^.typ = top_reg) and
  12112. (
  12113. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12114. ) and
  12115. (taicpu(hp1).oper[0]^.typ = top_const) and
  12116. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12117. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12118. { Minimum shift value allowed is the bit difference between the sizes }
  12119. (taicpu(hp1).oper[0]^.val >=
  12120. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12121. 8 * (
  12122. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12123. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12124. )
  12125. ) then
  12126. begin
  12127. { For:
  12128. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12129. shl/sal ##, %reg1
  12130. Remove the movsx/movzx instruction if the shift overwrites the
  12131. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12132. }
  12133. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12134. RemoveCurrentP(p, hp1);
  12135. Result := True;
  12136. Exit;
  12137. end
  12138. else if reg_and_hp1_is_instr and
  12139. (taicpu(p).oper[0]^.typ = top_reg) and
  12140. (
  12141. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12142. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12143. ) and
  12144. (taicpu(hp1).oper[0]^.typ = top_const) and
  12145. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12146. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12147. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12148. (taicpu(hp1).oper[0]^.val <
  12149. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12150. 8 * (
  12151. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12152. )
  12153. ) then
  12154. begin
  12155. { For:
  12156. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12157. sar ##, %reg1 shr ##, %reg1
  12158. Move the shift to before the movx instruction if the shift value
  12159. is not too large.
  12160. }
  12161. asml.Remove(hp1);
  12162. asml.InsertBefore(hp1, p);
  12163. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12164. case taicpu(p).opsize of
  12165. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12166. taicpu(hp1).opsize := S_B;
  12167. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12168. taicpu(hp1).opsize := S_W;
  12169. {$ifdef x86_64}
  12170. S_LQ:
  12171. taicpu(hp1).opsize := S_L;
  12172. {$endif}
  12173. else
  12174. InternalError(2020112401);
  12175. end;
  12176. if (taicpu(hp1).opcode = A_SHR) then
  12177. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12178. else
  12179. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12180. Result := True;
  12181. end;
  12182. if reg_and_hp1_is_instr and
  12183. (taicpu(p).oper[0]^.typ = top_reg) and
  12184. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12185. (
  12186. (taicpu(hp1).opcode = taicpu(p).opcode)
  12187. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12188. {$ifdef x86_64}
  12189. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12190. {$endif x86_64}
  12191. ) then
  12192. begin
  12193. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12194. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12195. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12196. begin
  12197. {
  12198. For example:
  12199. movzbw %al,%ax
  12200. movzwl %ax,%eax
  12201. Compress into:
  12202. movzbl %al,%eax
  12203. }
  12204. RegUsed := False;
  12205. case taicpu(p).opsize of
  12206. S_BW:
  12207. case taicpu(hp1).opsize of
  12208. S_WL:
  12209. begin
  12210. taicpu(p).opsize := S_BL;
  12211. RegUsed := True;
  12212. end;
  12213. {$ifdef x86_64}
  12214. S_WQ:
  12215. begin
  12216. if taicpu(p).opcode = A_MOVZX then
  12217. begin
  12218. taicpu(p).opsize := S_BL;
  12219. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12220. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12221. end
  12222. else
  12223. taicpu(p).opsize := S_BQ;
  12224. RegUsed := True;
  12225. end;
  12226. {$endif x86_64}
  12227. else
  12228. ;
  12229. end;
  12230. {$ifdef x86_64}
  12231. S_BL:
  12232. case taicpu(hp1).opsize of
  12233. S_LQ:
  12234. begin
  12235. if taicpu(p).opcode = A_MOVZX then
  12236. begin
  12237. taicpu(p).opsize := S_BL;
  12238. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12239. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12240. end
  12241. else
  12242. taicpu(p).opsize := S_BQ;
  12243. RegUsed := True;
  12244. end;
  12245. else
  12246. ;
  12247. end;
  12248. S_WL:
  12249. case taicpu(hp1).opsize of
  12250. S_LQ:
  12251. begin
  12252. if taicpu(p).opcode = A_MOVZX then
  12253. begin
  12254. taicpu(p).opsize := S_WL;
  12255. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12256. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12257. end
  12258. else
  12259. taicpu(p).opsize := S_WQ;
  12260. RegUsed := True;
  12261. end;
  12262. else
  12263. ;
  12264. end;
  12265. {$endif x86_64}
  12266. else
  12267. ;
  12268. end;
  12269. if RegUsed then
  12270. begin
  12271. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12272. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12273. RemoveInstruction(hp1);
  12274. Result := True;
  12275. Exit;
  12276. end;
  12277. end;
  12278. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12279. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12280. GetNextInstruction(hp1, hp2) and
  12281. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12282. (
  12283. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12284. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12285. {$ifdef x86_64}
  12286. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12287. {$endif x86_64}
  12288. ) and
  12289. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12290. (
  12291. (
  12292. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12293. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12294. ) or
  12295. (
  12296. { Only allow the operands in reverse order for TEST instructions }
  12297. (taicpu(hp2).opcode = A_TEST) and
  12298. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12299. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12300. )
  12301. ) then
  12302. begin
  12303. {
  12304. For example:
  12305. movzbl %al,%eax
  12306. movzbl (ref),%edx
  12307. andl %edx,%eax
  12308. (%edx deallocated)
  12309. Change to:
  12310. andb (ref),%al
  12311. movzbl %al,%eax
  12312. Rules are:
  12313. - First two instructions have the same opcode and opsize
  12314. - First instruction's operands are the same super-register
  12315. - Second instruction operates on a different register
  12316. - Third instruction is AND, OR, XOR or TEST
  12317. - Third instruction's operands are the destination registers of the first two instructions
  12318. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12319. - Second instruction's destination register is deallocated afterwards
  12320. }
  12321. TransferUsedRegs(TmpUsedRegs);
  12322. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12323. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12324. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12325. begin
  12326. case taicpu(p).opsize of
  12327. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12328. NewSize := S_B;
  12329. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12330. NewSize := S_W;
  12331. {$ifdef x86_64}
  12332. S_LQ:
  12333. NewSize := S_L;
  12334. {$endif x86_64}
  12335. else
  12336. InternalError(2021120301);
  12337. end;
  12338. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12339. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12340. taicpu(hp2).opsize := NewSize;
  12341. RemoveInstruction(hp1);
  12342. { With TEST, it's best to keep the MOVX instruction at the top }
  12343. if (taicpu(hp2).opcode <> A_TEST) then
  12344. begin
  12345. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12346. asml.Remove(p);
  12347. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12348. asml.InsertAfter(p, hp2);
  12349. p := hp2;
  12350. end
  12351. else
  12352. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12353. Result := True;
  12354. Exit;
  12355. end;
  12356. end;
  12357. end;
  12358. if taicpu(p).opcode=A_MOVZX then
  12359. begin
  12360. { removes superfluous And's after movzx's }
  12361. if reg_and_hp1_is_instr and
  12362. (taicpu(hp1).opcode = A_AND) and
  12363. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12364. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12365. {$ifdef x86_64}
  12366. { check for implicit extension to 64 bit }
  12367. or
  12368. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12369. (taicpu(hp1).opsize=S_Q) and
  12370. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12371. )
  12372. {$endif x86_64}
  12373. )
  12374. then
  12375. begin
  12376. case taicpu(p).opsize Of
  12377. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12378. if (taicpu(hp1).oper[0]^.val = $ff) then
  12379. begin
  12380. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12381. RemoveInstruction(hp1);
  12382. Result:=true;
  12383. exit;
  12384. end;
  12385. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12386. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12387. begin
  12388. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12389. RemoveInstruction(hp1);
  12390. Result:=true;
  12391. exit;
  12392. end;
  12393. {$ifdef x86_64}
  12394. S_LQ:
  12395. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12396. begin
  12397. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12398. RemoveInstruction(hp1);
  12399. Result:=true;
  12400. exit;
  12401. end;
  12402. {$endif x86_64}
  12403. else
  12404. ;
  12405. end;
  12406. { we cannot get rid of the and, but can we get rid of the movz ?}
  12407. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12408. begin
  12409. case taicpu(p).opsize Of
  12410. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12411. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12412. begin
  12413. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12414. RemoveCurrentP(p,hp1);
  12415. Result:=true;
  12416. exit;
  12417. end;
  12418. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12419. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12420. begin
  12421. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12422. RemoveCurrentP(p,hp1);
  12423. Result:=true;
  12424. exit;
  12425. end;
  12426. {$ifdef x86_64}
  12427. S_LQ:
  12428. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12429. begin
  12430. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12431. RemoveCurrentP(p,hp1);
  12432. Result:=true;
  12433. exit;
  12434. end;
  12435. {$endif x86_64}
  12436. else
  12437. ;
  12438. end;
  12439. end;
  12440. end;
  12441. { changes some movzx constructs to faster synonyms (all examples
  12442. are given with eax/ax, but are also valid for other registers)}
  12443. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12444. begin
  12445. case taicpu(p).opsize of
  12446. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12447. (the machine code is equivalent to movzbl %al,%eax), but the
  12448. code generator still generates that assembler instruction and
  12449. it is silently converted. This should probably be checked.
  12450. [Kit] }
  12451. S_BW:
  12452. begin
  12453. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12454. (
  12455. not IsMOVZXAcceptable
  12456. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12457. or (
  12458. (cs_opt_size in current_settings.optimizerswitches) and
  12459. (taicpu(p).oper[1]^.reg = NR_AX)
  12460. )
  12461. ) then
  12462. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12463. begin
  12464. DebugMsg(SPeepholeOptimization + 'var7',p);
  12465. taicpu(p).opcode := A_AND;
  12466. taicpu(p).changeopsize(S_W);
  12467. taicpu(p).loadConst(0,$ff);
  12468. Result := True;
  12469. end
  12470. else if not IsMOVZXAcceptable and
  12471. GetNextInstruction(p, hp1) and
  12472. (tai(hp1).typ = ait_instruction) and
  12473. (taicpu(hp1).opcode = A_AND) and
  12474. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12475. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12476. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12477. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12478. begin
  12479. DebugMsg(SPeepholeOptimization + 'var8',p);
  12480. taicpu(p).opcode := A_MOV;
  12481. taicpu(p).changeopsize(S_W);
  12482. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12483. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12484. Result := True;
  12485. end;
  12486. end;
  12487. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12488. S_BL:
  12489. if not IsMOVZXAcceptable then
  12490. begin
  12491. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12492. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12493. begin
  12494. DebugMsg(SPeepholeOptimization + 'var9',p);
  12495. taicpu(p).opcode := A_AND;
  12496. taicpu(p).changeopsize(S_L);
  12497. taicpu(p).loadConst(0,$ff);
  12498. Result := True;
  12499. end
  12500. else if GetNextInstruction(p, hp1) and
  12501. (tai(hp1).typ = ait_instruction) and
  12502. (taicpu(hp1).opcode = A_AND) and
  12503. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12504. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12505. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12506. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12507. begin
  12508. DebugMsg(SPeepholeOptimization + 'var10',p);
  12509. taicpu(p).opcode := A_MOV;
  12510. taicpu(p).changeopsize(S_L);
  12511. { do not use R_SUBWHOLE
  12512. as movl %rdx,%eax
  12513. is invalid in assembler PM }
  12514. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12515. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12516. Result := True;
  12517. end;
  12518. end;
  12519. {$endif i8086}
  12520. S_WL:
  12521. if not IsMOVZXAcceptable then
  12522. begin
  12523. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12524. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12525. begin
  12526. DebugMsg(SPeepholeOptimization + 'var11',p);
  12527. taicpu(p).opcode := A_AND;
  12528. taicpu(p).changeopsize(S_L);
  12529. taicpu(p).loadConst(0,$ffff);
  12530. Result := True;
  12531. end
  12532. else if GetNextInstruction(p, hp1) and
  12533. (tai(hp1).typ = ait_instruction) and
  12534. (taicpu(hp1).opcode = A_AND) and
  12535. (taicpu(hp1).oper[0]^.typ = top_const) and
  12536. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12537. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12538. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12539. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12540. begin
  12541. DebugMsg(SPeepholeOptimization + 'var12',p);
  12542. taicpu(p).opcode := A_MOV;
  12543. taicpu(p).changeopsize(S_L);
  12544. { do not use R_SUBWHOLE
  12545. as movl %rdx,%eax
  12546. is invalid in assembler PM }
  12547. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12548. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12549. Result := True;
  12550. end;
  12551. end;
  12552. else
  12553. InternalError(2017050705);
  12554. end;
  12555. end
  12556. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12557. begin
  12558. if GetNextInstruction(p, hp1) and
  12559. (tai(hp1).typ = ait_instruction) and
  12560. (taicpu(hp1).opcode = A_AND) and
  12561. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12562. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12563. begin
  12564. //taicpu(p).opcode := A_MOV;
  12565. case taicpu(p).opsize Of
  12566. S_BL:
  12567. begin
  12568. DebugMsg(SPeepholeOptimization + 'var13',p);
  12569. taicpu(hp1).changeopsize(S_L);
  12570. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12571. end;
  12572. S_WL:
  12573. begin
  12574. DebugMsg(SPeepholeOptimization + 'var14',p);
  12575. taicpu(hp1).changeopsize(S_L);
  12576. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12577. end;
  12578. S_BW:
  12579. begin
  12580. DebugMsg(SPeepholeOptimization + 'var15',p);
  12581. taicpu(hp1).changeopsize(S_W);
  12582. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12583. end;
  12584. else
  12585. Internalerror(2017050704)
  12586. end;
  12587. Result := True;
  12588. end;
  12589. end;
  12590. end;
  12591. end;
  12592. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12593. var
  12594. hp1, hp2 : tai;
  12595. MaskLength : Cardinal;
  12596. MaskedBits : TCgInt;
  12597. ActiveReg : TRegister;
  12598. begin
  12599. Result:=false;
  12600. { There are no optimisations for reference targets }
  12601. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12602. Exit;
  12603. while GetNextInstruction(p, hp1) and
  12604. (hp1.typ = ait_instruction) do
  12605. begin
  12606. if (taicpu(p).oper[0]^.typ = top_const) then
  12607. begin
  12608. case taicpu(hp1).opcode of
  12609. A_AND:
  12610. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12611. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12612. { the second register must contain the first one, so compare their subreg types }
  12613. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12614. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12615. { change
  12616. and const1, reg
  12617. and const2, reg
  12618. to
  12619. and (const1 and const2), reg
  12620. }
  12621. begin
  12622. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12623. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12624. RemoveCurrentP(p, hp1);
  12625. Result:=true;
  12626. exit;
  12627. end;
  12628. A_CMP:
  12629. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12630. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12631. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12632. { Just check that the condition on the next instruction is compatible }
  12633. GetNextInstruction(hp1, hp2) and
  12634. (hp2.typ = ait_instruction) and
  12635. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12636. then
  12637. { change
  12638. and 2^n, reg
  12639. cmp 2^n, reg
  12640. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12641. to
  12642. and 2^n, reg
  12643. test reg, reg
  12644. j(~c) / set(~c) / cmov(~c)
  12645. }
  12646. begin
  12647. { Keep TEST instruction in, rather than remove it, because
  12648. it may trigger other optimisations such as MovAndTest2Test }
  12649. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12650. taicpu(hp1).opcode := A_TEST;
  12651. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12652. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12653. Result := True;
  12654. Exit;
  12655. end
  12656. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12657. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12658. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12659. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12660. { change
  12661. and $ff/$ff/$ffff, reg
  12662. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12663. dealloc reg
  12664. to
  12665. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12666. }
  12667. begin
  12668. TransferUsedRegs(TmpUsedRegs);
  12669. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12670. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12671. begin
  12672. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12673. case taicpu(p).oper[0]^.val of
  12674. $ff:
  12675. begin
  12676. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12677. taicpu(hp1).opsize:=S_B;
  12678. end;
  12679. $ffff:
  12680. begin
  12681. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12682. taicpu(hp1).opsize:=S_W;
  12683. end;
  12684. $ffffffff:
  12685. begin
  12686. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12687. taicpu(hp1).opsize:=S_L;
  12688. end;
  12689. else
  12690. Internalerror(2023030401);
  12691. end;
  12692. RemoveCurrentP(p);
  12693. Result := True;
  12694. Exit;
  12695. end;
  12696. end;
  12697. A_MOVZX:
  12698. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12699. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12700. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12701. (
  12702. (
  12703. (taicpu(p).opsize=S_W) and
  12704. (taicpu(hp1).opsize=S_BW)
  12705. ) or
  12706. (
  12707. (taicpu(p).opsize=S_L) and
  12708. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12709. )
  12710. {$ifdef x86_64}
  12711. or
  12712. (
  12713. (taicpu(p).opsize=S_Q) and
  12714. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12715. )
  12716. {$endif x86_64}
  12717. ) then
  12718. begin
  12719. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12720. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12721. ) or
  12722. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12723. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12724. then
  12725. begin
  12726. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12727. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12728. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12729. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12730. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12731. }
  12732. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12733. RemoveInstruction(hp1);
  12734. { See if there are other optimisations possible }
  12735. Continue;
  12736. end;
  12737. end;
  12738. A_SHL:
  12739. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12740. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12741. begin
  12742. {$ifopt R+}
  12743. {$define RANGE_WAS_ON}
  12744. {$R-}
  12745. {$endif}
  12746. { get length of potential and mask }
  12747. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12748. { really a mask? }
  12749. {$ifdef RANGE_WAS_ON}
  12750. {$R+}
  12751. {$endif}
  12752. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12753. { unmasked part shifted out? }
  12754. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12755. begin
  12756. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12757. RemoveCurrentP(p, hp1);
  12758. Result:=true;
  12759. exit;
  12760. end;
  12761. end;
  12762. A_SHR:
  12763. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12764. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12765. (taicpu(hp1).oper[0]^.val <= 63) then
  12766. begin
  12767. { Does SHR combined with the AND cover all the bits?
  12768. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12769. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12770. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12771. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12772. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12773. begin
  12774. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12775. RemoveCurrentP(p, hp1);
  12776. Result := True;
  12777. Exit;
  12778. end;
  12779. end;
  12780. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12781. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12782. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12783. begin
  12784. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12785. (
  12786. (
  12787. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12788. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12789. ) or (
  12790. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12791. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12792. {$ifdef x86_64}
  12793. ) or (
  12794. (taicpu(hp1).opsize = S_LQ) and
  12795. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12796. {$endif x86_64}
  12797. )
  12798. ) then
  12799. begin
  12800. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12801. begin
  12802. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12803. RemoveInstruction(hp1);
  12804. { See if there are other optimisations possible }
  12805. Continue;
  12806. end;
  12807. { The super-registers are the same though.
  12808. Note that this change by itself doesn't improve
  12809. code speed, but it opens up other optimisations. }
  12810. {$ifdef x86_64}
  12811. { Convert 64-bit register to 32-bit }
  12812. case taicpu(hp1).opsize of
  12813. S_BQ:
  12814. begin
  12815. taicpu(hp1).opsize := S_BL;
  12816. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12817. end;
  12818. S_WQ:
  12819. begin
  12820. taicpu(hp1).opsize := S_WL;
  12821. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12822. end
  12823. else
  12824. ;
  12825. end;
  12826. {$endif x86_64}
  12827. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12828. taicpu(hp1).opcode := A_MOVZX;
  12829. { See if there are other optimisations possible }
  12830. Continue;
  12831. end;
  12832. end;
  12833. else
  12834. ;
  12835. end;
  12836. end
  12837. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12838. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12839. begin
  12840. {$ifdef x86_64}
  12841. if (taicpu(p).opsize = S_Q) then
  12842. begin
  12843. { Never necessary }
  12844. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12845. RemoveCurrentP(p, hp1);
  12846. Result := True;
  12847. Exit;
  12848. end;
  12849. {$endif x86_64}
  12850. { Forward check to determine necessity of and %reg,%reg }
  12851. TransferUsedRegs(TmpUsedRegs);
  12852. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12853. { Saves on a bunch of dereferences }
  12854. ActiveReg := taicpu(p).oper[1]^.reg;
  12855. case taicpu(hp1).opcode of
  12856. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12857. if (
  12858. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12859. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12860. ) and
  12861. (
  12862. (taicpu(hp1).opcode <> A_MOV) or
  12863. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12864. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12865. ) and
  12866. not (
  12867. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12868. (taicpu(hp1).opcode = A_MOV) and
  12869. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12870. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12871. ) and
  12872. (
  12873. (
  12874. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12875. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12876. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12877. ) or
  12878. (
  12879. {$ifdef x86_64}
  12880. (
  12881. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12882. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12883. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12884. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12885. ) and
  12886. {$endif x86_64}
  12887. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12888. )
  12889. ) then
  12890. begin
  12891. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12892. RemoveCurrentP(p, hp1);
  12893. Result := True;
  12894. Exit;
  12895. end;
  12896. A_ADD,
  12897. A_AND,
  12898. A_BSF,
  12899. A_BSR,
  12900. A_BTC,
  12901. A_BTR,
  12902. A_BTS,
  12903. A_OR,
  12904. A_SUB,
  12905. A_XOR:
  12906. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12907. if (
  12908. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12909. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12910. ) and
  12911. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12912. begin
  12913. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12914. RemoveCurrentP(p, hp1);
  12915. Result := True;
  12916. Exit;
  12917. end;
  12918. A_CMP,
  12919. A_TEST:
  12920. if (
  12921. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12922. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12923. ) and
  12924. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12925. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12926. begin
  12927. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12928. RemoveCurrentP(p, hp1);
  12929. Result := True;
  12930. Exit;
  12931. end;
  12932. A_BSWAP,
  12933. A_NEG,
  12934. A_NOT:
  12935. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12936. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12937. begin
  12938. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12939. RemoveCurrentP(p, hp1);
  12940. Result := True;
  12941. Exit;
  12942. end;
  12943. else
  12944. ;
  12945. end;
  12946. end;
  12947. if (taicpu(hp1).is_jmp) and
  12948. (taicpu(hp1).opcode<>A_JMP) and
  12949. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12950. begin
  12951. { change
  12952. and x, reg
  12953. jxx
  12954. to
  12955. test x, reg
  12956. jxx
  12957. if reg is deallocated before the
  12958. jump, but only if it's a conditional jump (PFV)
  12959. }
  12960. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12961. taicpu(p).opcode := A_TEST;
  12962. Exit;
  12963. end;
  12964. Break;
  12965. end;
  12966. { Lone AND tests }
  12967. if (taicpu(p).oper[0]^.typ = top_const) then
  12968. begin
  12969. {
  12970. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12971. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12972. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12973. }
  12974. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12975. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12976. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12977. begin
  12978. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12979. if taicpu(p).opsize = S_L then
  12980. begin
  12981. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12982. Result := True;
  12983. end;
  12984. end;
  12985. end;
  12986. { Backward check to determine necessity of and %reg,%reg }
  12987. if (taicpu(p).oper[0]^.typ = top_reg) and
  12988. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12989. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12990. GetLastInstruction(p, hp2) and
  12991. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12992. { Check size of adjacent instruction to determine if the AND is
  12993. effectively a null operation }
  12994. (
  12995. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12996. { Note: Don't include S_Q }
  12997. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12998. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12999. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13000. ) then
  13001. begin
  13002. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13003. { If GetNextInstruction returned False, hp1 will be nil }
  13004. RemoveCurrentP(p, hp1);
  13005. Result := True;
  13006. Exit;
  13007. end;
  13008. end;
  13009. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13010. var
  13011. hp1, hp2: tai;
  13012. NewRef: TReference;
  13013. Distance: Cardinal;
  13014. TempTracking: TAllUsedRegs;
  13015. { This entire nested function is used in an if-statement below, but we
  13016. want to avoid all the used reg transfers and GetNextInstruction calls
  13017. until we really have to check }
  13018. function MemRegisterNotUsedLater: Boolean; inline;
  13019. var
  13020. hp2: tai;
  13021. begin
  13022. TransferUsedRegs(TmpUsedRegs);
  13023. hp2 := p;
  13024. repeat
  13025. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13026. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13027. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13028. end;
  13029. begin
  13030. Result := False;
  13031. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13032. (taicpu(p).oper[1]^.typ = top_reg) then
  13033. begin
  13034. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13035. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13036. (hp1.typ <> ait_instruction) or
  13037. not
  13038. (
  13039. (cs_opt_level3 in current_settings.optimizerswitches) or
  13040. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13041. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13042. ) then
  13043. Exit;
  13044. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13045. addq $x, %rax
  13046. movq %rax, %rdx
  13047. sarq $63, %rdx
  13048. (%rax still in use)
  13049. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13050. leaq $x(%rax),%rdx
  13051. addq $x, %rax
  13052. sarq $63, %rdx
  13053. ...which is okay since it breaks the dependency chain between
  13054. addq and movq, but if OptPass2MOV is called first:
  13055. addq $x, %rax
  13056. cqto
  13057. ...which is better in all ways, taking only 2 cycles to execute
  13058. and much smaller in code size.
  13059. }
  13060. { The extra register tracking is quite strenuous }
  13061. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13062. MatchInstruction(hp1, A_MOV, []) then
  13063. begin
  13064. { Update the register tracking to the MOV instruction }
  13065. CopyUsedRegs(TempTracking);
  13066. hp2 := p;
  13067. repeat
  13068. UpdateUsedRegs(tai(hp2.Next));
  13069. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13070. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13071. OptPass2ADD get called again }
  13072. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13073. begin
  13074. { Reset the tracking to the current instruction }
  13075. RestoreUsedRegs(TempTracking);
  13076. ReleaseUsedRegs(TempTracking);
  13077. Result := True;
  13078. Exit;
  13079. end;
  13080. { Reset the tracking to the current instruction }
  13081. RestoreUsedRegs(TempTracking);
  13082. ReleaseUsedRegs(TempTracking);
  13083. { If OptPass2MOV returned True, we don't need to set Result to
  13084. True if hp1 didn't change because the ADD instruction didn't
  13085. get modified and we'll be evaluating hp1 again when the
  13086. peephole optimizer reaches it }
  13087. end;
  13088. { Change:
  13089. add %reg2,%reg1
  13090. (%reg2 not modified in between)
  13091. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13092. To:
  13093. mov/s/z #(%reg1,%reg2),%reg1
  13094. }
  13095. if (taicpu(p).oper[0]^.typ = top_reg) and
  13096. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13097. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13098. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13099. (
  13100. (
  13101. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13102. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13103. { r/esp cannot be an index }
  13104. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13105. ) or (
  13106. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13107. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13108. )
  13109. ) and (
  13110. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13111. (
  13112. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13113. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13114. MemRegisterNotUsedLater
  13115. )
  13116. ) then
  13117. begin
  13118. if (
  13119. { Instructions are guaranteed to be adjacent on -O2 and under }
  13120. (cs_opt_level3 in current_settings.optimizerswitches) and
  13121. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13122. ) then
  13123. begin
  13124. { If the other register is used in between, move the MOV
  13125. instruction to right after the ADD instruction so a
  13126. saving can still be made }
  13127. Asml.Remove(hp1);
  13128. Asml.InsertAfter(hp1, p);
  13129. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13130. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13131. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13132. RemoveCurrentp(p, hp1);
  13133. end
  13134. else
  13135. begin
  13136. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13137. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13138. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13139. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13140. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13141. { hp1 may not be the immediate next instruction under -O3 }
  13142. RemoveCurrentp(p)
  13143. else
  13144. RemoveCurrentp(p, hp1);
  13145. end;
  13146. Result := True;
  13147. Exit;
  13148. end;
  13149. { Change:
  13150. addl/q $x,%reg1
  13151. movl/q %reg1,%reg2
  13152. To:
  13153. leal/q $x(%reg1),%reg2
  13154. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13155. Breaks the dependency chain.
  13156. }
  13157. if (taicpu(p).oper[0]^.typ = top_const) and
  13158. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13159. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13160. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13161. (
  13162. { Instructions are guaranteed to be adjacent on -O2 and under }
  13163. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13164. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13165. ) then
  13166. begin
  13167. TransferUsedRegs(TmpUsedRegs);
  13168. hp2 := p;
  13169. repeat
  13170. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13171. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13172. if (
  13173. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13174. not (cs_opt_size in current_settings.optimizerswitches) or
  13175. (
  13176. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13177. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13178. )
  13179. ) then
  13180. begin
  13181. { Change the MOV instruction to a LEA instruction, and update the
  13182. first operand }
  13183. reference_reset(NewRef, 1, []);
  13184. NewRef.base := taicpu(p).oper[1]^.reg;
  13185. NewRef.scalefactor := 1;
  13186. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13187. taicpu(hp1).opcode := A_LEA;
  13188. taicpu(hp1).loadref(0, NewRef);
  13189. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13190. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13191. begin
  13192. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13193. { Move what is now the LEA instruction to before the ADD instruction }
  13194. Asml.Remove(hp1);
  13195. Asml.InsertBefore(hp1, p);
  13196. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13197. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13198. p := hp1;
  13199. end
  13200. else
  13201. begin
  13202. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13203. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13204. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13205. { hp1 may not be the immediate next instruction under -O3 }
  13206. RemoveCurrentp(p)
  13207. else
  13208. RemoveCurrentp(p, hp1);
  13209. end;
  13210. Result := True;
  13211. end;
  13212. end;
  13213. end;
  13214. end;
  13215. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13216. var
  13217. SubReg: TSubRegister;
  13218. begin
  13219. Result:=false;
  13220. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13221. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13222. with taicpu(p).oper[0]^.ref^ do
  13223. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13224. begin
  13225. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13226. begin
  13227. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13228. taicpu(p).opcode := A_ADD;
  13229. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13230. Result := True;
  13231. end
  13232. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13233. begin
  13234. if (base <> NR_NO) then
  13235. begin
  13236. if (scalefactor <= 1) then
  13237. begin
  13238. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13239. taicpu(p).opcode := A_ADD;
  13240. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13241. Result := True;
  13242. end;
  13243. end
  13244. else
  13245. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13246. if (scalefactor in [2, 4, 8]) then
  13247. begin
  13248. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13249. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13250. taicpu(p).opcode := A_SHL;
  13251. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13252. Result := True;
  13253. end;
  13254. end;
  13255. end;
  13256. end;
  13257. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13258. var
  13259. hp1, hp2: tai;
  13260. NewRef: TReference;
  13261. Distance: Cardinal;
  13262. TempTracking: TAllUsedRegs;
  13263. begin
  13264. Result := False;
  13265. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13266. MatchOpType(taicpu(p),top_const,top_reg) then
  13267. begin
  13268. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13269. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13270. (hp1.typ <> ait_instruction) or
  13271. not
  13272. (
  13273. (cs_opt_level3 in current_settings.optimizerswitches) or
  13274. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13275. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13276. ) then
  13277. Exit;
  13278. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13279. subq $x, %rax
  13280. movq %rax, %rdx
  13281. sarq $63, %rdx
  13282. (%rax still in use)
  13283. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13284. leaq $-x(%rax),%rdx
  13285. movq $x, %rax
  13286. sarq $63, %rdx
  13287. ...which is okay since it breaks the dependency chain between
  13288. subq and movq, but if OptPass2MOV is called first:
  13289. subq $x, %rax
  13290. cqto
  13291. ...which is better in all ways, taking only 2 cycles to execute
  13292. and much smaller in code size.
  13293. }
  13294. { The extra register tracking is quite strenuous }
  13295. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13296. MatchInstruction(hp1, A_MOV, []) then
  13297. begin
  13298. { Update the register tracking to the MOV instruction }
  13299. CopyUsedRegs(TempTracking);
  13300. hp2 := p;
  13301. repeat
  13302. UpdateUsedRegs(tai(hp2.Next));
  13303. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13304. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13305. OptPass2SUB get called again }
  13306. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13307. begin
  13308. { Reset the tracking to the current instruction }
  13309. RestoreUsedRegs(TempTracking);
  13310. ReleaseUsedRegs(TempTracking);
  13311. Result := True;
  13312. Exit;
  13313. end;
  13314. { Reset the tracking to the current instruction }
  13315. RestoreUsedRegs(TempTracking);
  13316. ReleaseUsedRegs(TempTracking);
  13317. { If OptPass2MOV returned True, we don't need to set Result to
  13318. True if hp1 didn't change because the SUB instruction didn't
  13319. get modified and we'll be evaluating hp1 again when the
  13320. peephole optimizer reaches it }
  13321. end;
  13322. { Change:
  13323. subl/q $x,%reg1
  13324. movl/q %reg1,%reg2
  13325. To:
  13326. leal/q $-x(%reg1),%reg2
  13327. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13328. Breaks the dependency chain and potentially permits the removal of
  13329. a CMP instruction if one follows.
  13330. }
  13331. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13332. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13333. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13334. (
  13335. { Instructions are guaranteed to be adjacent on -O2 and under }
  13336. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13337. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13338. ) then
  13339. begin
  13340. TransferUsedRegs(TmpUsedRegs);
  13341. hp2 := p;
  13342. repeat
  13343. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13344. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13345. if (
  13346. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13347. not (cs_opt_size in current_settings.optimizerswitches) or
  13348. (
  13349. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13350. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13351. )
  13352. ) then
  13353. begin
  13354. { Change the MOV instruction to a LEA instruction, and update the
  13355. first operand }
  13356. reference_reset(NewRef, 1, []);
  13357. NewRef.base := taicpu(p).oper[1]^.reg;
  13358. NewRef.scalefactor := 1;
  13359. NewRef.offset := -taicpu(p).oper[0]^.val;
  13360. taicpu(hp1).opcode := A_LEA;
  13361. taicpu(hp1).loadref(0, NewRef);
  13362. TransferUsedRegs(TmpUsedRegs);
  13363. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13364. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13365. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13366. begin
  13367. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13368. { Move what is now the LEA instruction to before the SUB instruction }
  13369. Asml.Remove(hp1);
  13370. Asml.InsertBefore(hp1, p);
  13371. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13372. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13373. p := hp1;
  13374. end
  13375. else
  13376. begin
  13377. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13378. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13379. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13380. { hp1 may not be the immediate next instruction under -O3 }
  13381. RemoveCurrentp(p)
  13382. else
  13383. RemoveCurrentp(p, hp1);
  13384. end;
  13385. Result := True;
  13386. end;
  13387. end;
  13388. end;
  13389. end;
  13390. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13391. begin
  13392. { we can skip all instructions not messing with the stack pointer }
  13393. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13394. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13395. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13396. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13397. ({(taicpu(hp1).ops=0) or }
  13398. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13399. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13400. ) and }
  13401. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13402. )
  13403. ) do
  13404. GetNextInstruction(hp1,hp1);
  13405. Result:=assigned(hp1);
  13406. end;
  13407. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13408. var
  13409. hp1, hp2, hp3, hp4, hp5: tai;
  13410. begin
  13411. Result:=false;
  13412. hp5:=nil;
  13413. { replace
  13414. leal(q) x(<stackpointer>),<stackpointer>
  13415. call procname
  13416. leal(q) -x(<stackpointer>),<stackpointer>
  13417. ret
  13418. by
  13419. jmp procname
  13420. but do it only on level 4 because it destroys stack back traces
  13421. }
  13422. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13423. MatchOpType(taicpu(p),top_ref,top_reg) and
  13424. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13425. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13426. { the -8 or -24 are not required, but bail out early if possible,
  13427. higher values are unlikely }
  13428. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13429. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13430. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13431. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13432. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13433. GetNextInstruction(p, hp1) and
  13434. { Take a copy of hp1 }
  13435. SetAndTest(hp1, hp4) and
  13436. { trick to skip label }
  13437. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13438. SkipSimpleInstructions(hp1) and
  13439. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13440. GetNextInstruction(hp1, hp2) and
  13441. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13442. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13443. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13444. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13445. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13446. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13447. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13448. { Segment register will be NR_NO }
  13449. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13450. GetNextInstruction(hp2, hp3) and
  13451. { trick to skip label }
  13452. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13453. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13454. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13455. SetAndTest(hp3,hp5) and
  13456. GetNextInstruction(hp3,hp3) and
  13457. MatchInstruction(hp3,A_RET,[S_NO])
  13458. )
  13459. ) and
  13460. (taicpu(hp3).ops=0) then
  13461. begin
  13462. taicpu(hp1).opcode := A_JMP;
  13463. taicpu(hp1).is_jmp := true;
  13464. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13465. RemoveCurrentP(p, hp4);
  13466. RemoveInstruction(hp2);
  13467. RemoveInstruction(hp3);
  13468. if Assigned(hp5) then
  13469. begin
  13470. AsmL.Remove(hp5);
  13471. ASmL.InsertBefore(hp5,hp1)
  13472. end;
  13473. Result:=true;
  13474. end;
  13475. end;
  13476. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13477. {$ifdef x86_64}
  13478. var
  13479. hp1, hp2, hp3, hp4, hp5: tai;
  13480. {$endif x86_64}
  13481. begin
  13482. Result:=false;
  13483. {$ifdef x86_64}
  13484. hp5:=nil;
  13485. { replace
  13486. push %rax
  13487. call procname
  13488. pop %rcx
  13489. ret
  13490. by
  13491. jmp procname
  13492. but do it only on level 4 because it destroys stack back traces
  13493. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13494. for all supported calling conventions
  13495. }
  13496. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13497. MatchOpType(taicpu(p),top_reg) and
  13498. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13499. GetNextInstruction(p, hp1) and
  13500. { Take a copy of hp1 }
  13501. SetAndTest(hp1, hp4) and
  13502. { trick to skip label }
  13503. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13504. SkipSimpleInstructions(hp1) and
  13505. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13506. GetNextInstruction(hp1, hp2) and
  13507. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13508. MatchOpType(taicpu(hp2),top_reg) and
  13509. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13510. GetNextInstruction(hp2, hp3) and
  13511. { trick to skip label }
  13512. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13513. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13514. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13515. SetAndTest(hp3,hp5) and
  13516. GetNextInstruction(hp3,hp3) and
  13517. MatchInstruction(hp3,A_RET,[S_NO])
  13518. )
  13519. ) and
  13520. (taicpu(hp3).ops=0) then
  13521. begin
  13522. taicpu(hp1).opcode := A_JMP;
  13523. taicpu(hp1).is_jmp := true;
  13524. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13525. RemoveCurrentP(p, hp4);
  13526. RemoveInstruction(hp2);
  13527. RemoveInstruction(hp3);
  13528. if Assigned(hp5) then
  13529. begin
  13530. AsmL.Remove(hp5);
  13531. ASmL.InsertBefore(hp5,hp1)
  13532. end;
  13533. Result:=true;
  13534. end;
  13535. {$endif x86_64}
  13536. end;
  13537. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13538. var
  13539. Value, RegName: string;
  13540. begin
  13541. Result:=false;
  13542. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13543. begin
  13544. case taicpu(p).oper[0]^.val of
  13545. 0:
  13546. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13547. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13548. begin
  13549. { change "mov $0,%reg" into "xor %reg,%reg" }
  13550. taicpu(p).opcode := A_XOR;
  13551. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13552. Result := True;
  13553. {$ifdef x86_64}
  13554. end
  13555. else if (taicpu(p).opsize = S_Q) then
  13556. begin
  13557. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13558. { The actual optimization }
  13559. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13560. taicpu(p).changeopsize(S_L);
  13561. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13562. Result := True;
  13563. end;
  13564. $1..$FFFFFFFF:
  13565. begin
  13566. { Code size reduction by J. Gareth "Kit" Moreton }
  13567. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13568. case taicpu(p).opsize of
  13569. S_Q:
  13570. begin
  13571. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13572. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13573. { The actual optimization }
  13574. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13575. taicpu(p).changeopsize(S_L);
  13576. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13577. Result := True;
  13578. end;
  13579. else
  13580. { Do nothing };
  13581. end;
  13582. {$endif x86_64}
  13583. end;
  13584. -1:
  13585. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13586. if (cs_opt_size in current_settings.optimizerswitches) and
  13587. (taicpu(p).opsize <> S_B) and
  13588. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13589. begin
  13590. { change "mov $-1,%reg" into "or $-1,%reg" }
  13591. { NOTES:
  13592. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13593. - This operation creates a false dependency on the register, so only do it when optimising for size
  13594. - 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
  13595. }
  13596. taicpu(p).opcode := A_OR;
  13597. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13598. Result := True;
  13599. end;
  13600. else
  13601. { Do nothing };
  13602. end;
  13603. end;
  13604. end;
  13605. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13606. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13607. begin
  13608. Result := False;
  13609. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13610. Exit;
  13611. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13612. so don't bother optimising }
  13613. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13614. Exit;
  13615. if (taicpu(p).oper[0]^.typ <> top_const) or
  13616. { If the value can fit into an 8-bit signed integer, a smaller
  13617. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13618. falls within this range }
  13619. (
  13620. (taicpu(p).oper[0]^.val > -128) and
  13621. (taicpu(p).oper[0]^.val <= 127)
  13622. ) then
  13623. Exit;
  13624. { If we're optimising for size, this is acceptable }
  13625. if (cs_opt_size in current_settings.optimizerswitches) then
  13626. Exit(True);
  13627. if (taicpu(p).oper[1]^.typ = top_reg) and
  13628. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13629. Exit(True);
  13630. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13631. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13632. Exit(True);
  13633. end;
  13634. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13635. var
  13636. hp1: tai;
  13637. Value: TCGInt;
  13638. begin
  13639. Result := False;
  13640. if MatchOpType(taicpu(p), top_const, top_reg) then
  13641. begin
  13642. { Detect:
  13643. andw x, %ax (0 <= x < $8000)
  13644. ...
  13645. movzwl %ax,%eax
  13646. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13647. }
  13648. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13649. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13650. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13651. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13652. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13653. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13654. begin
  13655. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13656. taicpu(hp1).opcode := A_CWDE;
  13657. taicpu(hp1).clearop(0);
  13658. taicpu(hp1).clearop(1);
  13659. taicpu(hp1).ops := 0;
  13660. { A change was made, but not with p, so don't set Result, but
  13661. notify the compiler that a change was made }
  13662. Include(OptsToCheck, aoc_ForceNewIteration);
  13663. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13664. end;
  13665. end;
  13666. { If "not x" is a power of 2 (popcnt = 1), change:
  13667. and $x, %reg/ref
  13668. To:
  13669. btr lb(x), %reg/ref
  13670. }
  13671. if IsBTXAcceptable(p) and
  13672. (
  13673. { Make sure a TEST doesn't follow that plays with the register }
  13674. not GetNextInstruction(p, hp1) or
  13675. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13676. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13677. ) then
  13678. begin
  13679. {$push}{$R-}{$Q-}
  13680. { Value is a sign-extended 32-bit integer - just correct it
  13681. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13682. checks to see if this operand is an immediate. }
  13683. Value := not taicpu(p).oper[0]^.val;
  13684. {$pop}
  13685. {$ifdef x86_64}
  13686. if taicpu(p).opsize = S_L then
  13687. {$endif x86_64}
  13688. Value := Value and $FFFFFFFF;
  13689. if (PopCnt(QWord(Value)) = 1) then
  13690. begin
  13691. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13692. taicpu(p).opcode := A_BTR;
  13693. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13694. Result := True;
  13695. Exit;
  13696. end;
  13697. end;
  13698. end;
  13699. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13700. begin
  13701. Result := False;
  13702. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13703. Exit;
  13704. { Convert:
  13705. movswl %ax,%eax -> cwtl
  13706. movslq %eax,%rax -> cdqe
  13707. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13708. refer to the same opcode and depends only on the assembler's
  13709. current operand-size attribute. [Kit]
  13710. }
  13711. with taicpu(p) do
  13712. case opsize of
  13713. S_WL:
  13714. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13715. begin
  13716. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13717. opcode := A_CWDE;
  13718. clearop(0);
  13719. clearop(1);
  13720. ops := 0;
  13721. Result := True;
  13722. end;
  13723. {$ifdef x86_64}
  13724. S_LQ:
  13725. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13726. begin
  13727. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13728. opcode := A_CDQE;
  13729. clearop(0);
  13730. clearop(1);
  13731. ops := 0;
  13732. Result := True;
  13733. end;
  13734. {$endif x86_64}
  13735. else
  13736. ;
  13737. end;
  13738. end;
  13739. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13740. var
  13741. hp1, hp2: tai;
  13742. IdentityMask, Shift: TCGInt;
  13743. LimitSize: Topsize;
  13744. DoNotMerge: Boolean;
  13745. begin
  13746. Result := False;
  13747. { All these optimisations work on "shr const,%reg" }
  13748. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13749. Exit;
  13750. DoNotMerge := False;
  13751. Shift := taicpu(p).oper[0]^.val;
  13752. LimitSize := taicpu(p).opsize;
  13753. hp1 := p;
  13754. repeat
  13755. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13756. Break;
  13757. { Detect:
  13758. shr x, %reg
  13759. and y, %reg
  13760. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13761. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13762. }
  13763. case taicpu(hp1).opcode of
  13764. A_AND:
  13765. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13766. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13767. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13768. begin
  13769. { Make sure the FLAGS register isn't in use }
  13770. TransferUsedRegs(TmpUsedRegs);
  13771. hp2 := p;
  13772. repeat
  13773. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13774. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13775. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13776. begin
  13777. { Generate the identity mask }
  13778. case taicpu(p).opsize of
  13779. S_B:
  13780. IdentityMask := $FF shr Shift;
  13781. S_W:
  13782. IdentityMask := $FFFF shr Shift;
  13783. S_L:
  13784. IdentityMask := $FFFFFFFF shr Shift;
  13785. {$ifdef x86_64}
  13786. S_Q:
  13787. { We need to force the operands to be unsigned 64-bit
  13788. integers otherwise the wrong value is generated }
  13789. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13790. {$endif x86_64}
  13791. else
  13792. InternalError(2022081501);
  13793. end;
  13794. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13795. begin
  13796. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13797. { All the possible 1 bits are covered, so we can remove the AND }
  13798. hp2 := tai(hp1.Previous);
  13799. RemoveInstruction(hp1);
  13800. { p wasn't actually changed, so don't set Result to True,
  13801. but a change was nonetheless made elsewhere }
  13802. Include(OptsToCheck, aoc_ForceNewIteration);
  13803. { Do another pass in case other AND or MOVZX instructions
  13804. follow }
  13805. hp1 := hp2;
  13806. Continue;
  13807. end;
  13808. end;
  13809. end;
  13810. A_TEST, A_CMP, A_Jcc:
  13811. { Skip over conditional jumps and relevant comparisons }
  13812. Continue;
  13813. A_MOVZX:
  13814. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13815. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13816. begin
  13817. { Since the original register is being read as is, subsequent
  13818. SHRs must not be merged at this point }
  13819. DoNotMerge := True;
  13820. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13821. begin
  13822. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13823. begin
  13824. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13825. { All the possible 1 bits are covered, so we can remove the AND }
  13826. hp2 := tai(hp1.Previous);
  13827. RemoveInstruction(hp1);
  13828. hp1 := hp2;
  13829. end
  13830. else { Different register target }
  13831. begin
  13832. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13833. taicpu(hp1).opcode := A_MOV;
  13834. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13835. case taicpu(hp1).opsize of
  13836. S_BW:
  13837. taicpu(hp1).opsize := S_W;
  13838. S_BL, S_WL:
  13839. taicpu(hp1).opsize := S_L;
  13840. else
  13841. InternalError(2022081503);
  13842. end;
  13843. end;
  13844. end
  13845. else if (Shift > 0) and
  13846. (taicpu(p).opsize = S_W) and
  13847. (taicpu(hp1).opsize = S_WL) and
  13848. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13849. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13850. begin
  13851. { Detect:
  13852. shr x, %ax (x > 0)
  13853. ...
  13854. movzwl %ax,%eax
  13855. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13856. }
  13857. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13858. taicpu(hp1).opcode := A_CWDE;
  13859. taicpu(hp1).clearop(0);
  13860. taicpu(hp1).clearop(1);
  13861. taicpu(hp1).ops := 0;
  13862. end;
  13863. { Move onto the next instruction }
  13864. Continue;
  13865. end;
  13866. A_SHL, A_SAL, A_SHR:
  13867. if (taicpu(hp1).opsize <= LimitSize) and
  13868. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13869. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13870. begin
  13871. { Make sure the sizes don't exceed the register size limit
  13872. (measured by the shift value falling below the limit) }
  13873. if taicpu(hp1).opsize < LimitSize then
  13874. LimitSize := taicpu(hp1).opsize;
  13875. if taicpu(hp1).opcode = A_SHR then
  13876. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13877. else
  13878. begin
  13879. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13880. DoNotMerge := True;
  13881. end;
  13882. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13883. Break;
  13884. { Since we've established that the combined shift is within
  13885. limits, we can actually combine the adjacent SHR
  13886. instructions even if they're different sizes }
  13887. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13888. begin
  13889. hp2 := tai(hp1.Previous);
  13890. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13891. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13892. RemoveInstruction(hp1);
  13893. hp1 := hp2;
  13894. end;
  13895. { Move onto the next instruction }
  13896. Continue;
  13897. end;
  13898. else
  13899. ;
  13900. end;
  13901. Break;
  13902. until False;
  13903. { Detect the following (looking backwards):
  13904. shr %cl,%reg
  13905. shr x, %reg
  13906. Swap the two SHR instructions to minimise a pipeline stall.
  13907. }
  13908. if GetLastInstruction(p, hp1) and
  13909. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13910. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13911. { First operand will be %cl }
  13912. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13913. { Just to be sure }
  13914. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13915. begin
  13916. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13917. { Moving the entries this way ensures the register tracking remains correct }
  13918. Asml.Remove(p);
  13919. Asml.InsertBefore(p, hp1);
  13920. p := hp1;
  13921. { Don't set Result to True because the current instruction is now
  13922. "shr %cl,%reg" and there's nothing more we can do with it }
  13923. end;
  13924. end;
  13925. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13926. var
  13927. hp1, hp2: tai;
  13928. Opposite, SecondOpposite: TAsmOp;
  13929. NewCond: TAsmCond;
  13930. begin
  13931. Result := False;
  13932. { Change:
  13933. add/sub 128,(dest)
  13934. To:
  13935. sub/add -128,(dest)
  13936. This generaally takes fewer bytes to encode because -128 can be stored
  13937. in a signed byte, whereas +128 cannot.
  13938. }
  13939. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13940. begin
  13941. if taicpu(p).opcode = A_ADD then
  13942. Opposite := A_SUB
  13943. else
  13944. Opposite := A_ADD;
  13945. { Be careful if the flags are in use, because the CF flag inverts
  13946. when changing from ADD to SUB and vice versa }
  13947. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13948. GetNextInstruction(p, hp1) then
  13949. begin
  13950. TransferUsedRegs(TmpUsedRegs);
  13951. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13952. hp2 := hp1;
  13953. { Scan ahead to check if everything's safe }
  13954. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13955. begin
  13956. if (hp1.typ <> ait_instruction) then
  13957. { Probably unsafe since the flags are still in use }
  13958. Exit;
  13959. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13960. { Stop searching at an unconditional jump }
  13961. Break;
  13962. if not
  13963. (
  13964. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13965. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13966. ) and
  13967. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13968. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13969. Exit;
  13970. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13971. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13972. { Move to the next instruction }
  13973. GetNextInstruction(hp1, hp1);
  13974. end;
  13975. while Assigned(hp2) and (hp2 <> hp1) do
  13976. begin
  13977. NewCond := C_None;
  13978. case taicpu(hp2).condition of
  13979. C_A, C_NBE:
  13980. NewCond := C_BE;
  13981. C_B, C_C, C_NAE:
  13982. NewCond := C_AE;
  13983. C_AE, C_NB, C_NC:
  13984. NewCond := C_B;
  13985. C_BE, C_NA:
  13986. NewCond := C_A;
  13987. else
  13988. { No change needed };
  13989. end;
  13990. if NewCond <> C_None then
  13991. begin
  13992. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13993. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13994. taicpu(hp2).condition := NewCond;
  13995. end
  13996. else
  13997. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13998. begin
  13999. { Because of the flipping of the carry bit, to ensure
  14000. the operation remains equivalent, ADC becomes SBB
  14001. and vice versa, and the constant is not-inverted.
  14002. If multiple ADCs or SBBs appear in a row, each one
  14003. changed causes the carry bit to invert, so they all
  14004. need to be flipped }
  14005. if taicpu(hp2).opcode = A_ADC then
  14006. SecondOpposite := A_SBB
  14007. else
  14008. SecondOpposite := A_ADC;
  14009. if taicpu(hp2).oper[0]^.typ <> top_const then
  14010. { Should have broken out of this optimisation already }
  14011. InternalError(2021112901);
  14012. 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]^) + ' -> ' +
  14013. 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);
  14014. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14015. taicpu(hp2).opcode := SecondOpposite;
  14016. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14017. end;
  14018. { Move to the next instruction }
  14019. GetNextInstruction(hp2, hp2);
  14020. end;
  14021. if (hp2 <> hp1) then
  14022. InternalError(2021111501);
  14023. end;
  14024. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14025. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14026. taicpu(p).opcode := Opposite;
  14027. taicpu(p).oper[0]^.val := -128;
  14028. { No further optimisations can be made on this instruction, so move
  14029. onto the next one to save time }
  14030. p := tai(p.Next);
  14031. UpdateUsedRegs(p);
  14032. Result := True;
  14033. Exit;
  14034. end;
  14035. { Detect:
  14036. add/sub %reg2,(dest)
  14037. add/sub x, (dest)
  14038. (dest can be a register or a reference)
  14039. Swap the instructions to minimise a pipeline stall. This reverses the
  14040. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14041. optimisations could be made.
  14042. }
  14043. if (taicpu(p).oper[0]^.typ = top_reg) and
  14044. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14045. (
  14046. (
  14047. (taicpu(p).oper[1]^.typ = top_reg) and
  14048. { We can try searching further ahead if we're writing to a register }
  14049. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14050. ) or
  14051. (
  14052. (taicpu(p).oper[1]^.typ = top_ref) and
  14053. GetNextInstruction(p, hp1)
  14054. )
  14055. ) and
  14056. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14057. (taicpu(hp1).oper[0]^.typ = top_const) and
  14058. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14059. begin
  14060. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14061. TransferUsedRegs(TmpUsedRegs);
  14062. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14063. hp2 := p;
  14064. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14065. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14066. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14067. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14068. begin
  14069. asml.remove(hp1);
  14070. asml.InsertBefore(hp1, p);
  14071. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14072. Result := True;
  14073. end;
  14074. end;
  14075. end;
  14076. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14077. var
  14078. hp1: tai;
  14079. begin
  14080. Result:=false;
  14081. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14082. while GetNextInstruction(p, hp1) and
  14083. TrySwapMovCmp(p, hp1) do
  14084. begin
  14085. if MatchInstruction(hp1, A_MOV, []) then
  14086. begin
  14087. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14088. begin
  14089. { A little hacky, but since CMP doesn't read the flags, only
  14090. modify them, it's safe if they get scrambled by MOV -> XOR }
  14091. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14092. Result := PostPeepholeOptMov(hp1);
  14093. {$ifdef x86_64}
  14094. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14095. { Used to shrink instruction size }
  14096. PostPeepholeOptXor(hp1);
  14097. {$endif x86_64}
  14098. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14099. end
  14100. else
  14101. begin
  14102. Result := PostPeepholeOptMov(hp1);
  14103. {$ifdef x86_64}
  14104. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14105. { Used to shrink instruction size }
  14106. PostPeepholeOptXor(hp1);
  14107. {$endif x86_64}
  14108. end;
  14109. end;
  14110. { Enabling this flag is actually a null operation, but it marks
  14111. the code as 'modified' during this pass }
  14112. Include(OptsToCheck, aoc_ForceNewIteration);
  14113. end;
  14114. { change "cmp $0, %reg" to "test %reg, %reg" }
  14115. if MatchOpType(taicpu(p),top_const,top_reg) and
  14116. (taicpu(p).oper[0]^.val = 0) then
  14117. begin
  14118. taicpu(p).opcode := A_TEST;
  14119. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14120. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14121. Result:=true;
  14122. end;
  14123. end;
  14124. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14125. var
  14126. IsTestConstX, IsValid : Boolean;
  14127. hp1,hp2 : tai;
  14128. begin
  14129. Result:=false;
  14130. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14131. if (taicpu(p).opcode = A_TEST) then
  14132. while GetNextInstruction(p, hp1) and
  14133. TrySwapMovCmp(p, hp1) do
  14134. begin
  14135. if MatchInstruction(hp1, A_MOV, []) then
  14136. begin
  14137. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14138. begin
  14139. { A little hacky, but since TEST doesn't read the flags, only
  14140. modify them, it's safe if they get scrambled by MOV -> XOR }
  14141. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14142. Result := PostPeepholeOptMov(hp1);
  14143. {$ifdef x86_64}
  14144. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14145. { Used to shrink instruction size }
  14146. PostPeepholeOptXor(hp1);
  14147. {$endif x86_64}
  14148. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14149. end
  14150. else
  14151. begin
  14152. Result := PostPeepholeOptMov(hp1);
  14153. {$ifdef x86_64}
  14154. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14155. { Used to shrink instruction size }
  14156. PostPeepholeOptXor(hp1);
  14157. {$endif x86_64}
  14158. end;
  14159. end;
  14160. { Enabling this flag is actually a null operation, but it marks
  14161. the code as 'modified' during this pass }
  14162. Include(OptsToCheck, aoc_ForceNewIteration);
  14163. end;
  14164. { If x is a power of 2 (popcnt = 1), change:
  14165. or $x, %reg/ref
  14166. To:
  14167. bts lb(x), %reg/ref
  14168. }
  14169. if (taicpu(p).opcode = A_OR) and
  14170. IsBTXAcceptable(p) and
  14171. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14172. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14173. (
  14174. { Don't optimise if a test instruction follows }
  14175. not GetNextInstruction(p, hp1) or
  14176. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14177. ) then
  14178. begin
  14179. 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);
  14180. taicpu(p).opcode := A_BTS;
  14181. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14182. Result := True;
  14183. Exit;
  14184. end;
  14185. { If x is a power of 2 (popcnt = 1), change:
  14186. test $x, %reg/ref
  14187. je / sete / cmove (or jne / setne)
  14188. To:
  14189. bt lb(x), %reg/ref
  14190. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14191. }
  14192. if (taicpu(p).opcode = A_TEST) and
  14193. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14194. (taicpu(p).oper[0]^.typ = top_const) and
  14195. (
  14196. (cs_opt_size in current_settings.optimizerswitches) or
  14197. (
  14198. (taicpu(p).oper[1]^.typ = top_reg) and
  14199. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14200. ) or
  14201. (
  14202. (taicpu(p).oper[1]^.typ <> top_reg) and
  14203. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14204. )
  14205. ) and
  14206. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14207. { For sizes less than S_L, the byte size is equal or larger with BT,
  14208. so don't bother optimising }
  14209. (taicpu(p).opsize >= S_L) then
  14210. begin
  14211. IsValid := True;
  14212. { Check the next set of instructions, watching the FLAGS register
  14213. and the conditions used }
  14214. TransferUsedRegs(TmpUsedRegs);
  14215. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14216. hp1 := p;
  14217. hp2 := nil;
  14218. while GetNextInstruction(hp1, hp1) do
  14219. begin
  14220. if not Assigned(hp2) then
  14221. { The first instruction after TEST }
  14222. hp2 := hp1;
  14223. if (hp1.typ <> ait_instruction) then
  14224. begin
  14225. { If the flags are no longer in use, everything is fine }
  14226. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14227. IsValid := False;
  14228. Break;
  14229. end;
  14230. case taicpu(hp1).condition of
  14231. C_None:
  14232. begin
  14233. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14234. { Something is not quite normal, so play safe and don't change }
  14235. IsValid := False;
  14236. Break;
  14237. end;
  14238. C_E, C_Z, C_NE, C_NZ:
  14239. { This is fine };
  14240. else
  14241. begin
  14242. { Unsupported condition }
  14243. IsValid := False;
  14244. Break;
  14245. end;
  14246. end;
  14247. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14248. end;
  14249. if IsValid then
  14250. begin
  14251. while hp2 <> hp1 do
  14252. begin
  14253. case taicpu(hp2).condition of
  14254. C_Z, C_E:
  14255. taicpu(hp2).condition := C_NC;
  14256. C_NZ, C_NE:
  14257. taicpu(hp2).condition := C_C;
  14258. else
  14259. { Should not get this by this point }
  14260. InternalError(2022110701);
  14261. end;
  14262. GetNextInstruction(hp2, hp2);
  14263. end;
  14264. 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);
  14265. taicpu(p).opcode := A_BT;
  14266. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14267. Result := True;
  14268. Exit;
  14269. end;
  14270. end;
  14271. { removes the line marked with (x) from the sequence
  14272. and/or/xor/add/sub/... $x, %y
  14273. test/or %y, %y | test $-1, %y (x)
  14274. j(n)z _Label
  14275. as the first instruction already adjusts the ZF
  14276. %y operand may also be a reference }
  14277. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14278. MatchOperand(taicpu(p).oper[0]^,-1);
  14279. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14280. GetLastInstruction(p, hp1) and
  14281. (tai(hp1).typ = ait_instruction) and
  14282. GetNextInstruction(p,hp2) and
  14283. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14284. case taicpu(hp1).opcode Of
  14285. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14286. { These two instructions set the zero flag if the result is zero }
  14287. A_POPCNT, A_LZCNT:
  14288. begin
  14289. if (
  14290. { With POPCNT, an input of zero will set the zero flag
  14291. because the population count of zero is zero }
  14292. (taicpu(hp1).opcode = A_POPCNT) and
  14293. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14294. (
  14295. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14296. { Faster than going through the second half of the 'or'
  14297. condition below }
  14298. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14299. )
  14300. ) or (
  14301. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14302. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14303. { and in case of carry for A(E)/B(E)/C/NC }
  14304. (
  14305. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14306. (
  14307. (taicpu(hp1).opcode <> A_ADD) and
  14308. (taicpu(hp1).opcode <> A_SUB) and
  14309. (taicpu(hp1).opcode <> A_LZCNT)
  14310. )
  14311. )
  14312. ) then
  14313. begin
  14314. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14315. RemoveCurrentP(p, hp2);
  14316. Result:=true;
  14317. Exit;
  14318. end;
  14319. end;
  14320. A_SHL, A_SAL, A_SHR, A_SAR:
  14321. begin
  14322. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14323. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14324. { therefore, it's only safe to do this optimization for }
  14325. { shifts by a (nonzero) constant }
  14326. (taicpu(hp1).oper[0]^.typ = top_const) and
  14327. (taicpu(hp1).oper[0]^.val <> 0) and
  14328. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14329. { and in case of carry for A(E)/B(E)/C/NC }
  14330. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14331. begin
  14332. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14333. RemoveCurrentP(p, hp2);
  14334. Result:=true;
  14335. Exit;
  14336. end;
  14337. end;
  14338. A_DEC, A_INC, A_NEG:
  14339. begin
  14340. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14341. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14342. { and in case of carry for A(E)/B(E)/C/NC }
  14343. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14344. begin
  14345. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14346. RemoveCurrentP(p, hp2);
  14347. Result:=true;
  14348. Exit;
  14349. end;
  14350. end;
  14351. A_ANDN, A_BZHI:
  14352. begin
  14353. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14354. { Only the zero and sign flags are consistent with what the result is }
  14355. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14356. begin
  14357. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14358. RemoveCurrentP(p, hp2);
  14359. Result:=true;
  14360. Exit;
  14361. end;
  14362. end;
  14363. A_BEXTR:
  14364. begin
  14365. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14366. { Only the zero flag is set }
  14367. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14368. begin
  14369. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14370. RemoveCurrentP(p, hp2);
  14371. Result:=true;
  14372. Exit;
  14373. end;
  14374. end;
  14375. else
  14376. ;
  14377. end; { case }
  14378. { change "test $-1,%reg" into "test %reg,%reg" }
  14379. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14380. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14381. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14382. if MatchInstruction(p, A_OR, []) and
  14383. { Can only match if they're both registers }
  14384. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14385. begin
  14386. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14387. taicpu(p).opcode := A_TEST;
  14388. { No need to set Result to True, as we've done all the optimisations we can }
  14389. end;
  14390. end;
  14391. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14392. var
  14393. hp1,hp3 : tai;
  14394. {$ifndef x86_64}
  14395. hp2 : taicpu;
  14396. {$endif x86_64}
  14397. begin
  14398. Result:=false;
  14399. hp3:=nil;
  14400. {$ifndef x86_64}
  14401. { don't do this on modern CPUs, this really hurts them due to
  14402. broken call/ret pairing }
  14403. if (current_settings.optimizecputype < cpu_Pentium2) and
  14404. not(cs_create_pic in current_settings.moduleswitches) and
  14405. GetNextInstruction(p, hp1) and
  14406. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14407. MatchOpType(taicpu(hp1),top_ref) and
  14408. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14409. begin
  14410. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14411. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14412. InsertLLItem(p.previous, p, hp2);
  14413. taicpu(p).opcode := A_JMP;
  14414. taicpu(p).is_jmp := true;
  14415. RemoveInstruction(hp1);
  14416. Result:=true;
  14417. end
  14418. else
  14419. {$endif x86_64}
  14420. { replace
  14421. call procname
  14422. ret
  14423. by
  14424. jmp procname
  14425. but do it only on level 4 because it destroys stack back traces
  14426. else if the subroutine is marked as no return, remove the ret
  14427. }
  14428. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14429. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14430. GetNextInstruction(p, hp1) and
  14431. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14432. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14433. SetAndTest(hp1,hp3) and
  14434. GetNextInstruction(hp1,hp1) and
  14435. MatchInstruction(hp1,A_RET,[S_NO])
  14436. )
  14437. ) and
  14438. (taicpu(hp1).ops=0) then
  14439. begin
  14440. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14441. { we might destroy stack alignment here if we do not do a call }
  14442. (target_info.stackalign<=sizeof(SizeUInt)) then
  14443. begin
  14444. taicpu(p).opcode := A_JMP;
  14445. taicpu(p).is_jmp := true;
  14446. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14447. end
  14448. else
  14449. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14450. RemoveInstruction(hp1);
  14451. if Assigned(hp3) then
  14452. begin
  14453. AsmL.Remove(hp3);
  14454. AsmL.InsertBefore(hp3,p)
  14455. end;
  14456. Result:=true;
  14457. end;
  14458. end;
  14459. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14460. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14461. begin
  14462. case OpSize of
  14463. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14464. Result := (Val <= $FF) and (Val >= -128);
  14465. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14466. Result := (Val <= $FFFF) and (Val >= -32768);
  14467. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14468. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14469. else
  14470. Result := True;
  14471. end;
  14472. end;
  14473. var
  14474. hp1, hp2 : tai;
  14475. SizeChange: Boolean;
  14476. PreMessage: string;
  14477. begin
  14478. Result := False;
  14479. if (taicpu(p).oper[0]^.typ = top_reg) and
  14480. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14481. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14482. begin
  14483. { Change (using movzbl %al,%eax as an example):
  14484. movzbl %al, %eax movzbl %al, %eax
  14485. cmpl x, %eax testl %eax,%eax
  14486. To:
  14487. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14488. movzbl %al, %eax movzbl %al, %eax
  14489. Smaller instruction and minimises pipeline stall as the CPU
  14490. doesn't have to wait for the register to get zero-extended. [Kit]
  14491. Also allow if the smaller of the two registers is being checked,
  14492. as this still removes the false dependency.
  14493. }
  14494. if
  14495. (
  14496. (
  14497. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14498. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14499. ) or (
  14500. { If MatchOperand returns True, they must both be registers }
  14501. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14502. )
  14503. ) and
  14504. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14505. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14506. begin
  14507. 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);
  14508. asml.Remove(hp1);
  14509. asml.InsertBefore(hp1, p);
  14510. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14511. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14512. begin
  14513. taicpu(hp1).opcode := A_TEST;
  14514. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14515. end;
  14516. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14517. case taicpu(p).opsize of
  14518. S_BW, S_BL:
  14519. begin
  14520. SizeChange := taicpu(hp1).opsize <> S_B;
  14521. taicpu(hp1).changeopsize(S_B);
  14522. end;
  14523. S_WL:
  14524. begin
  14525. SizeChange := taicpu(hp1).opsize <> S_W;
  14526. taicpu(hp1).changeopsize(S_W);
  14527. end
  14528. else
  14529. InternalError(2020112701);
  14530. end;
  14531. UpdateUsedRegs(tai(p.Next));
  14532. { Check if the register is used aferwards - if not, we can
  14533. remove the movzx instruction completely }
  14534. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14535. begin
  14536. { Hp1 is a better position than p for debugging purposes }
  14537. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14538. RemoveCurrentp(p, hp1);
  14539. Result := True;
  14540. end;
  14541. if SizeChange then
  14542. DebugMsg(SPeepholeOptimization + PreMessage +
  14543. 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)
  14544. else
  14545. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14546. Exit;
  14547. end;
  14548. { Change (using movzwl %ax,%eax as an example):
  14549. movzwl %ax, %eax
  14550. movb %al, (dest) (Register is smaller than read register in movz)
  14551. To:
  14552. movb %al, (dest) (Move one back to avoid a false dependency)
  14553. movzwl %ax, %eax
  14554. }
  14555. if (taicpu(hp1).opcode = A_MOV) and
  14556. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14557. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14558. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14559. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14560. begin
  14561. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14562. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14563. asml.Remove(hp1);
  14564. asml.InsertBefore(hp1, p);
  14565. if taicpu(hp1).oper[1]^.typ = top_reg then
  14566. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14567. { Check if the register is used aferwards - if not, we can
  14568. remove the movzx instruction completely }
  14569. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14570. begin
  14571. { Hp1 is a better position than p for debugging purposes }
  14572. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14573. RemoveCurrentp(p, hp1);
  14574. Result := True;
  14575. end;
  14576. Exit;
  14577. end;
  14578. end;
  14579. end;
  14580. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14581. var
  14582. hp1: tai;
  14583. {$ifdef x86_64}
  14584. PreMessage, RegName: string;
  14585. {$endif x86_64}
  14586. begin
  14587. Result := False;
  14588. { If x is a power of 2 (popcnt = 1), change:
  14589. xor $x, %reg/ref
  14590. To:
  14591. btc lb(x), %reg/ref
  14592. }
  14593. if IsBTXAcceptable(p) and
  14594. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14595. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14596. (
  14597. { Don't optimise if a test instruction follows }
  14598. not GetNextInstruction(p, hp1) or
  14599. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14600. ) then
  14601. begin
  14602. 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);
  14603. taicpu(p).opcode := A_BTC;
  14604. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14605. Result := True;
  14606. Exit;
  14607. end;
  14608. {$ifdef x86_64}
  14609. { Code size reduction by J. Gareth "Kit" Moreton }
  14610. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14611. as this removes the REX prefix }
  14612. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14613. Exit;
  14614. if taicpu(p).oper[0]^.typ <> top_reg then
  14615. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14616. InternalError(2018011500);
  14617. case taicpu(p).opsize of
  14618. S_Q:
  14619. begin
  14620. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14621. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14622. { The actual optimization }
  14623. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14624. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14625. taicpu(p).changeopsize(S_L);
  14626. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14627. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14628. end;
  14629. else
  14630. ;
  14631. end;
  14632. {$endif x86_64}
  14633. end;
  14634. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14635. var
  14636. XReg: TRegister;
  14637. begin
  14638. Result := False;
  14639. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14640. Smaller encoding and slightly faster on some platforms (also works for
  14641. ZMM-sized registers) }
  14642. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14643. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14644. begin
  14645. XReg := taicpu(p).oper[0]^.reg;
  14646. if (taicpu(p).oper[1]^.reg = XReg) then
  14647. begin
  14648. taicpu(p).changeopsize(S_XMM);
  14649. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14650. if (cs_opt_size in current_settings.optimizerswitches) then
  14651. begin
  14652. { Change input registers to %xmm0 to reduce size. Note that
  14653. there's a risk of a false dependency doing this, so only
  14654. optimise for size here }
  14655. XReg := NR_XMM0;
  14656. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14657. end
  14658. else
  14659. begin
  14660. setsubreg(XReg, R_SUBMMX);
  14661. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14662. end;
  14663. taicpu(p).oper[0]^.reg := XReg;
  14664. taicpu(p).oper[1]^.reg := XReg;
  14665. Result := True;
  14666. end;
  14667. end;
  14668. end;
  14669. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14670. var
  14671. OperIdx: Integer;
  14672. begin
  14673. for OperIdx := 0 to p.ops - 1 do
  14674. if p.oper[OperIdx]^.typ = top_ref then
  14675. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14676. end;
  14677. end.