aoptx86.pas 747 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. { remove mov reg1,reg1? }
  2916. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2917. then
  2918. begin
  2919. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2920. { take care of the register (de)allocs following p }
  2921. RemoveCurrentP(p);
  2922. Result := True;
  2923. exit;
  2924. end;
  2925. { Prevent compiler warnings }
  2926. p_SourceReg := NR_NO;
  2927. p_TargetReg := NR_NO;
  2928. if taicpu(p).oper[1]^.typ = top_reg then
  2929. begin
  2930. { Saves on a large number of dereferences }
  2931. p_TargetReg := taicpu(p).oper[1]^.reg;
  2932. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2933. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2934. else
  2935. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2936. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2937. begin
  2938. if (taicpu(hp1).opcode = A_AND) and
  2939. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2940. begin
  2941. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2942. begin
  2943. case taicpu(p).opsize of
  2944. S_L:
  2945. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2946. begin
  2947. { Optimize out:
  2948. mov x, %reg
  2949. and ffffffffh, %reg
  2950. }
  2951. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2952. RemoveInstruction(hp1);
  2953. Result:=true;
  2954. exit;
  2955. end;
  2956. S_Q: { TODO: Confirm if this is even possible }
  2957. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2958. begin
  2959. { Optimize out:
  2960. mov x, %reg
  2961. and ffffffffffffffffh, %reg
  2962. }
  2963. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result:=true;
  2966. exit;
  2967. end;
  2968. else
  2969. ;
  2970. end;
  2971. if (
  2972. { Make sure that if a reference is used, its registers
  2973. are not modified in between }
  2974. (
  2975. (taicpu(p).oper[0]^.typ = top_reg) and
  2976. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2977. ) or
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_ref) and
  2980. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2981. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end;
  3085. if IsMOVZXAcceptable and
  3086. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3151. { Make sure we deal with any reference counts that were increased }
  3152. if taicpu(hp1).oper[1]^.typ = top_ref then
  3153. begin
  3154. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3155. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3156. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3157. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3158. end;
  3159. { Safeguard if "and" is followed by a conditional command }
  3160. TransferUsedRegs(TmpUsedRegs);
  3161. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3162. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3163. begin
  3164. { At this point, the "and" command is effectively equivalent to
  3165. "test %reg,%reg". This will be handled separately by the
  3166. Peephole Optimizer. [Kit] }
  3167. DebugMsg(SPeepholeOptimization + PreMessage +
  3168. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3169. end
  3170. else
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. RemoveInstruction(hp1);
  3175. end;
  3176. Result := True;
  3177. Exit;
  3178. end;
  3179. end;
  3180. end;
  3181. { Ensure nothing in between p and hp1 would make optimisations
  3182. invalid, such as the source register being modified }
  3183. if (
  3184. (taicpu(p).oper[0]^.typ = top_reg) and
  3185. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3186. ) or
  3187. (
  3188. (taicpu(p).oper[0]^.typ = top_ref) and
  3189. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3190. { Make sure we check separately whether p_TargetReg is used as part of the reference when required }
  3191. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3192. ) or
  3193. (taicpu(p).oper[0]^.typ = top_const) then
  3194. begin
  3195. if taicpu(p).oper[0]^.typ = top_reg then
  3196. begin
  3197. p_SourceReg := taicpu(p).oper[0]^.reg;
  3198. { Look for:
  3199. mov %reg1,%reg2
  3200. ??? %reg2,r/m
  3201. Change to:
  3202. mov %reg1,%reg2
  3203. ??? %reg1,r/m
  3204. }
  3205. if RegReadByInstruction(p_TargetReg, hp1) and
  3206. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3207. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3208. begin
  3209. { A change has occurred, just not in p }
  3210. Include(OptsToCheck, aoc_ForceNewIteration);
  3211. TransferUsedRegs(TmpUsedRegs);
  3212. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3213. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3214. { Just in case something didn't get modified (e.g. an
  3215. implicit register) }
  3216. not RegReadByInstruction(p_TargetReg, hp1) then
  3217. begin
  3218. { We can remove the original MOV }
  3219. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3220. RemoveCurrentP(p);
  3221. { UsedRegs got updated by RemoveCurrentp }
  3222. Result := True;
  3223. Exit;
  3224. end;
  3225. { If we know a MOV instruction has become a null operation, we might as well
  3226. get rid of it now to save time. }
  3227. if (taicpu(hp1).opcode = A_MOV) and
  3228. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3229. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3230. { Just being a register is enough to confirm it's a null operation }
  3231. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3232. begin
  3233. Result := True;
  3234. { Speed-up to reduce a pipeline stall... if we had something like...
  3235. movl %eax,%edx
  3236. movw %dx,%ax
  3237. ... the second instruction would change to movw %ax,%ax, but
  3238. given that it is now %ax that's active rather than %eax,
  3239. penalties might occur due to a partial register write, so instead,
  3240. change it to a MOVZX instruction when optimising for speed.
  3241. }
  3242. if not (cs_opt_size in current_settings.optimizerswitches) and
  3243. IsMOVZXAcceptable and
  3244. (taicpu(hp1).opsize < taicpu(p).opsize)
  3245. {$ifdef x86_64}
  3246. { operations already implicitly set the upper 64 bits to zero }
  3247. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3248. {$endif x86_64}
  3249. then
  3250. begin
  3251. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3252. case taicpu(p).opsize of
  3253. S_W:
  3254. if taicpu(hp1).opsize = S_B then
  3255. taicpu(hp1).opsize := S_BL
  3256. else
  3257. InternalError(2020012911);
  3258. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3259. case taicpu(hp1).opsize of
  3260. S_B:
  3261. taicpu(hp1).opsize := S_BL;
  3262. S_W:
  3263. taicpu(hp1).opsize := S_WL;
  3264. else
  3265. InternalError(2020012912);
  3266. end;
  3267. else
  3268. InternalError(2020012910);
  3269. end;
  3270. taicpu(hp1).opcode := A_MOVZX;
  3271. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3272. end
  3273. else
  3274. begin
  3275. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3276. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3277. RemoveInstruction(hp1);
  3278. { The instruction after what was hp1 is now the immediate next instruction,
  3279. so we can continue to make optimisations if it's present }
  3280. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3281. Exit;
  3282. hp1 := hp2;
  3283. end;
  3284. end;
  3285. end;
  3286. end
  3287. else if taicpu(p).oper[0]^.typ = top_const then
  3288. begin
  3289. if (taicpu(hp1).opcode = A_OR) and
  3290. (taicpu(p).oper[1]^.typ = top_reg) and
  3291. MatchOperand(taicpu(p).oper[0]^, 0) and
  3292. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3293. begin
  3294. { mov 0, %reg
  3295. or ###,%reg
  3296. Change to (only if the flags are not used):
  3297. mov ###,%reg
  3298. }
  3299. TransferUsedRegs(TmpUsedRegs);
  3300. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3301. DoOptimisation := True;
  3302. { Even if the flags are used, we might be able to do the optimisation
  3303. if the conditions are predictable }
  3304. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3305. begin
  3306. { Only perform if ### = %reg (the same register) or equal to 0,
  3307. so %reg is guaranteed to still have a value of zero }
  3308. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3309. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3310. begin
  3311. hp2 := hp1;
  3312. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3313. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3314. GetNextInstruction(hp2, hp3) do
  3315. begin
  3316. { Don't continue modifying if the flags state is getting changed }
  3317. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3318. Break;
  3319. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3320. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3321. begin
  3322. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3323. begin
  3324. { Condition is always true }
  3325. case taicpu(hp3).opcode of
  3326. A_Jcc:
  3327. begin
  3328. { Check for jump shortcuts before we destroy the condition }
  3329. hp4 := hp3;
  3330. DoJumpOptimizations(hp3, TempBool);
  3331. { Make sure hp3 hasn't changed }
  3332. if (hp4 = hp3) then
  3333. begin
  3334. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3335. MakeUnconditional(taicpu(hp3));
  3336. end;
  3337. Result := True;
  3338. end;
  3339. A_CMOVcc:
  3340. begin
  3341. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3342. taicpu(hp3).opcode := A_MOV;
  3343. taicpu(hp3).condition := C_None;
  3344. Result := True;
  3345. end;
  3346. A_SETcc:
  3347. begin
  3348. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3349. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3350. taicpu(hp3).opcode := A_MOV;
  3351. taicpu(hp3).ops := 2;
  3352. taicpu(hp3).condition := C_None;
  3353. taicpu(hp3).opsize := S_B;
  3354. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3355. taicpu(hp3).loadconst(0, 1);
  3356. Result := True;
  3357. end;
  3358. else
  3359. InternalError(2021090701);
  3360. end;
  3361. end
  3362. 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
  3363. begin
  3364. { Condition is always false }
  3365. case taicpu(hp3).opcode of
  3366. A_Jcc:
  3367. begin
  3368. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3369. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3370. RemoveInstruction(hp3);
  3371. Result := True;
  3372. { Since hp3 was deleted, hp2 must not be updated }
  3373. Continue;
  3374. end;
  3375. A_CMOVcc:
  3376. begin
  3377. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3378. RemoveInstruction(hp3);
  3379. Result := True;
  3380. { Since hp3 was deleted, hp2 must not be updated }
  3381. Continue;
  3382. end;
  3383. A_SETcc:
  3384. begin
  3385. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3386. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3387. taicpu(hp3).opcode := A_MOV;
  3388. taicpu(hp3).ops := 2;
  3389. taicpu(hp3).condition := C_None;
  3390. taicpu(hp3).opsize := S_B;
  3391. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3392. taicpu(hp3).loadconst(0, 0);
  3393. Result := True;
  3394. end;
  3395. else
  3396. InternalError(2021090702);
  3397. end;
  3398. end
  3399. else
  3400. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3401. DoOptimisation := False;
  3402. end;
  3403. hp2 := hp3;
  3404. end;
  3405. if DoOptimisation then
  3406. begin
  3407. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3408. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3409. { Flags are still in use - don't optimise }
  3410. DoOptimisation := False;
  3411. end;
  3412. end
  3413. else
  3414. DoOptimisation := False;
  3415. end;
  3416. if DoOptimisation then
  3417. begin
  3418. {$ifdef x86_64}
  3419. { OR only supports 32-bit sign-extended constants for 64-bit
  3420. instructions, so compensate for this if the constant is
  3421. encoded as a value greater than or equal to 2^31 }
  3422. if (taicpu(hp1).opsize = S_Q) and
  3423. (taicpu(hp1).oper[0]^.typ = top_const) and
  3424. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3425. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3426. {$endif x86_64}
  3427. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3428. taicpu(hp1).opcode := A_MOV;
  3429. RemoveCurrentP(p);
  3430. Result := True;
  3431. Exit;
  3432. end;
  3433. end;
  3434. end;
  3435. end;
  3436. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3437. overwrites the original destination register. e.g.
  3438. movl ###,%reg2d
  3439. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3440. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3441. }
  3442. if (taicpu(p).oper[1]^.typ = top_reg) and
  3443. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3444. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3445. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3446. begin
  3447. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3448. begin
  3449. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3450. case taicpu(p).oper[0]^.typ of
  3451. top_const:
  3452. { We have something like:
  3453. movb $x, %regb
  3454. movzbl %regb,%regd
  3455. Change to:
  3456. movl $x, %regd
  3457. }
  3458. begin
  3459. case taicpu(hp1).opsize of
  3460. S_BW:
  3461. begin
  3462. convert_mov_value(A_MOVSX, $FF);
  3463. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3464. taicpu(p).opsize := S_W;
  3465. end;
  3466. S_BL:
  3467. begin
  3468. convert_mov_value(A_MOVSX, $FF);
  3469. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3470. taicpu(p).opsize := S_L;
  3471. end;
  3472. S_WL:
  3473. begin
  3474. convert_mov_value(A_MOVSX, $FFFF);
  3475. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3476. taicpu(p).opsize := S_L;
  3477. end;
  3478. {$ifdef x86_64}
  3479. S_BQ:
  3480. begin
  3481. convert_mov_value(A_MOVSX, $FF);
  3482. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3483. taicpu(p).opsize := S_Q;
  3484. end;
  3485. S_WQ:
  3486. begin
  3487. convert_mov_value(A_MOVSX, $FFFF);
  3488. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3489. taicpu(p).opsize := S_Q;
  3490. end;
  3491. S_LQ:
  3492. begin
  3493. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3494. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3495. taicpu(p).opsize := S_Q;
  3496. end;
  3497. {$endif x86_64}
  3498. else
  3499. { If hp1 was a MOV instruction, it should have been
  3500. optimised already }
  3501. InternalError(2020021001);
  3502. end;
  3503. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3504. RemoveInstruction(hp1);
  3505. Result := True;
  3506. Exit;
  3507. end;
  3508. top_ref:
  3509. begin
  3510. { We have something like:
  3511. movb mem, %regb
  3512. movzbl %regb,%regd
  3513. Change to:
  3514. movzbl mem, %regd
  3515. }
  3516. if (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3517. begin
  3518. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3519. taicpu(p).opcode := taicpu(hp1).opcode;
  3520. taicpu(p).opsize := taicpu(hp1).opsize;
  3521. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3522. RemoveInstruction(hp1);
  3523. Result := True;
  3524. Exit;
  3525. end;
  3526. end;
  3527. else
  3528. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3529. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3530. Exit;
  3531. end;
  3532. end
  3533. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3534. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3535. optimised }
  3536. else
  3537. begin
  3538. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3539. RemoveCurrentP(p);
  3540. Result := True;
  3541. Exit;
  3542. end;
  3543. end;
  3544. end;
  3545. end;
  3546. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3547. { All the next optimisations require a next instruction }
  3548. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3549. Exit;
  3550. { Next instruction is also a MOV ? }
  3551. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3552. begin
  3553. if MatchOpType(taicpu(p), top_const, top_ref) and
  3554. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3555. TryConstMerge(p, hp1) then
  3556. begin
  3557. Result := True;
  3558. { In case we have four byte writes in a row, check for 2 more
  3559. right now so we don't have to wait for another iteration of
  3560. pass 1
  3561. }
  3562. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3563. case taicpu(p).opsize of
  3564. S_W:
  3565. begin
  3566. if GetNextInstruction(p, hp1) and
  3567. MatchInstruction(hp1, A_MOV, [S_B]) and
  3568. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3569. GetNextInstruction(hp1, hp2) and
  3570. MatchInstruction(hp2, A_MOV, [S_B]) and
  3571. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3572. { Try to merge the two bytes }
  3573. TryConstMerge(hp1, hp2) then
  3574. { Now try to merge the two words (hp2 will get deleted) }
  3575. TryConstMerge(p, hp1);
  3576. end;
  3577. S_L:
  3578. begin
  3579. { Though this only really benefits x86_64 and not i386, it
  3580. gets a potential optimisation done faster and hence
  3581. reduces the number of times OptPass1MOV is entered }
  3582. if GetNextInstruction(p, hp1) and
  3583. MatchInstruction(hp1, A_MOV, [S_W]) and
  3584. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3585. GetNextInstruction(hp1, hp2) and
  3586. MatchInstruction(hp2, A_MOV, [S_W]) and
  3587. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3588. { Try to merge the two words }
  3589. TryConstMerge(hp1, hp2) then
  3590. { This will always fail on i386, so don't bother
  3591. calling it unless we're doing x86_64 }
  3592. {$ifdef x86_64}
  3593. { Now try to merge the two longwords (hp2 will get deleted) }
  3594. TryConstMerge(p, hp1)
  3595. {$endif x86_64}
  3596. ;
  3597. end;
  3598. else
  3599. ;
  3600. end;
  3601. Exit;
  3602. end;
  3603. if (taicpu(p).oper[1]^.typ = top_reg) and
  3604. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3605. begin
  3606. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3607. TransferUsedRegs(TmpUsedRegs);
  3608. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3609. { we have
  3610. mov x, %treg
  3611. mov %treg, y
  3612. }
  3613. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3614. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3615. { we've got
  3616. mov x, %treg
  3617. mov %treg, y
  3618. with %treg is not used after }
  3619. case taicpu(p).oper[0]^.typ Of
  3620. { top_reg is covered by DeepMOVOpt }
  3621. top_const:
  3622. begin
  3623. { change
  3624. mov const, %treg
  3625. mov %treg, y
  3626. to
  3627. mov const, y
  3628. }
  3629. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3630. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3631. begin
  3632. if taicpu(hp1).oper[1]^.typ=top_reg then
  3633. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3634. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3635. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3636. RemoveInstruction(hp1);
  3637. Result:=true;
  3638. Exit;
  3639. end;
  3640. end;
  3641. top_ref:
  3642. case taicpu(hp1).oper[1]^.typ of
  3643. top_reg:
  3644. begin
  3645. { change
  3646. mov mem, %treg
  3647. mov %treg, %reg
  3648. to
  3649. mov mem, %reg"
  3650. }
  3651. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3652. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3653. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3654. RemoveInstruction(hp1);
  3655. Result:=true;
  3656. Exit;
  3657. end;
  3658. top_ref:
  3659. begin
  3660. {$ifdef x86_64}
  3661. { Look for the following to simplify:
  3662. mov x(mem1), %reg
  3663. mov %reg, y(mem2)
  3664. mov x+8(mem1), %reg
  3665. mov %reg, y+8(mem2)
  3666. Change to:
  3667. movdqu x(mem1), %xmmreg
  3668. movdqu %xmmreg, y(mem2)
  3669. ...but only as long as the memory blocks don't overlap
  3670. }
  3671. SourceRef := taicpu(p).oper[0]^.ref^;
  3672. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3673. if (taicpu(p).opsize = S_Q) and
  3674. GetNextInstruction(hp1, hp2) and
  3675. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3676. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3677. begin
  3678. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3679. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3680. Inc(SourceRef.offset, 8);
  3681. if UseAVX then
  3682. begin
  3683. MovAligned := A_VMOVDQA;
  3684. MovUnaligned := A_VMOVDQU;
  3685. end
  3686. else
  3687. begin
  3688. MovAligned := A_MOVDQA;
  3689. MovUnaligned := A_MOVDQU;
  3690. end;
  3691. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3692. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3693. begin
  3694. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3695. Inc(TargetRef.offset, 8);
  3696. if GetNextInstruction(hp2, hp3) and
  3697. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3698. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3699. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3700. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3701. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3702. begin
  3703. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3704. if NewMMReg <> NR_NO then
  3705. begin
  3706. { Remember that the offsets are 8 ahead }
  3707. if ((SourceRef.offset mod 16) = 8) and
  3708. (
  3709. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3710. (SourceRef.base = current_procinfo.framepointer) or
  3711. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3712. ) then
  3713. taicpu(p).opcode := MovAligned
  3714. else
  3715. taicpu(p).opcode := MovUnaligned;
  3716. taicpu(p).opsize := S_XMM;
  3717. taicpu(p).oper[1]^.reg := NewMMReg;
  3718. if ((TargetRef.offset mod 16) = 8) and
  3719. (
  3720. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3721. (TargetRef.base = current_procinfo.framepointer) or
  3722. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3723. ) then
  3724. taicpu(hp1).opcode := MovAligned
  3725. else
  3726. taicpu(hp1).opcode := MovUnaligned;
  3727. taicpu(hp1).opsize := S_XMM;
  3728. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3729. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3730. RemoveInstruction(hp2);
  3731. RemoveInstruction(hp3);
  3732. Result := True;
  3733. Exit;
  3734. end;
  3735. end;
  3736. end
  3737. else
  3738. begin
  3739. { See if the next references are 8 less rather than 8 greater }
  3740. Dec(SourceRef.offset, 16); { -8 the other way }
  3741. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3742. begin
  3743. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3744. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3745. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3746. GetNextInstruction(hp2, hp3) and
  3747. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3748. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3749. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3750. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3751. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3752. begin
  3753. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3754. if NewMMReg <> NR_NO then
  3755. begin
  3756. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3757. if ((SourceRef.offset mod 16) = 0) and
  3758. (
  3759. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3760. (SourceRef.base = current_procinfo.framepointer) or
  3761. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3762. ) then
  3763. taicpu(hp2).opcode := MovAligned
  3764. else
  3765. taicpu(hp2).opcode := MovUnaligned;
  3766. taicpu(hp2).opsize := S_XMM;
  3767. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3768. if ((TargetRef.offset mod 16) = 0) and
  3769. (
  3770. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3771. (TargetRef.base = current_procinfo.framepointer) or
  3772. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3773. ) then
  3774. taicpu(hp3).opcode := MovAligned
  3775. else
  3776. taicpu(hp3).opcode := MovUnaligned;
  3777. taicpu(hp3).opsize := S_XMM;
  3778. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3779. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3780. RemoveInstruction(hp1);
  3781. RemoveCurrentP(p, hp2);
  3782. Result := True;
  3783. Exit;
  3784. end;
  3785. end;
  3786. end;
  3787. end;
  3788. end;
  3789. {$endif x86_64}
  3790. end;
  3791. else
  3792. { The write target should be a reg or a ref }
  3793. InternalError(2021091601);
  3794. end;
  3795. else
  3796. ;
  3797. end
  3798. else
  3799. { %treg is used afterwards, but all eventualities
  3800. other than the first MOV instruction being a constant
  3801. are covered by DeepMOVOpt, so only check for that }
  3802. if (taicpu(p).oper[0]^.typ = top_const) and
  3803. (
  3804. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3805. not (cs_opt_size in current_settings.optimizerswitches) or
  3806. (taicpu(hp1).opsize = S_B)
  3807. ) and
  3808. (
  3809. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3810. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3811. ) then
  3812. begin
  3813. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3814. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3815. end;
  3816. end;
  3817. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3818. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3819. { mov reg1, mem1 or mov mem1, reg1
  3820. mov mem2, reg2 mov reg2, mem2}
  3821. begin
  3822. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3823. { mov reg1, mem1 or mov mem1, reg1
  3824. mov mem2, reg1 mov reg2, mem1}
  3825. begin
  3826. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3827. { Removes the second statement from
  3828. mov reg1, mem1/reg2
  3829. mov mem1/reg2, reg1 }
  3830. begin
  3831. if taicpu(p).oper[0]^.typ=top_reg then
  3832. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3833. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3834. RemoveInstruction(hp1);
  3835. Result:=true;
  3836. exit;
  3837. end
  3838. else
  3839. begin
  3840. TransferUsedRegs(TmpUsedRegs);
  3841. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3842. if (taicpu(p).oper[1]^.typ = top_ref) and
  3843. { mov reg1, mem1
  3844. mov mem2, reg1 }
  3845. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3846. GetNextInstruction(hp1, hp2) and
  3847. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3848. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3849. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3850. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3851. { change to
  3852. mov reg1, mem1 mov reg1, mem1
  3853. mov mem2, reg1 cmp reg1, mem2
  3854. cmp mem1, reg1
  3855. }
  3856. begin
  3857. RemoveInstruction(hp2);
  3858. taicpu(hp1).opcode := A_CMP;
  3859. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3860. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3861. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3862. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3863. end;
  3864. end;
  3865. end
  3866. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3867. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3868. begin
  3869. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3870. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3871. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3872. end
  3873. else
  3874. begin
  3875. TransferUsedRegs(TmpUsedRegs);
  3876. if GetNextInstruction(hp1, hp2) and
  3877. MatchOpType(taicpu(p),top_ref,top_reg) and
  3878. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3879. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3880. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3881. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3882. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3883. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3884. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3885. { mov mem1, %reg1
  3886. mov %reg1, mem2
  3887. mov mem2, reg2
  3888. to:
  3889. mov mem1, reg2
  3890. mov reg2, mem2}
  3891. begin
  3892. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3893. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3894. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3895. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3896. RemoveInstruction(hp2);
  3897. Result := True;
  3898. end
  3899. {$ifdef i386}
  3900. { this is enabled for i386 only, as the rules to create the reg sets below
  3901. are too complicated for x86-64, so this makes this code too error prone
  3902. on x86-64
  3903. }
  3904. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3905. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3906. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3907. { mov mem1, reg1 mov mem1, reg1
  3908. mov reg1, mem2 mov reg1, mem2
  3909. mov mem2, reg2 mov mem2, reg1
  3910. to: to:
  3911. mov mem1, reg1 mov mem1, reg1
  3912. mov mem1, reg2 mov reg1, mem2
  3913. mov reg1, mem2
  3914. or (if mem1 depends on reg1
  3915. and/or if mem2 depends on reg2)
  3916. to:
  3917. mov mem1, reg1
  3918. mov reg1, mem2
  3919. mov reg1, reg2
  3920. }
  3921. begin
  3922. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3923. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3924. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3925. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3926. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3927. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3928. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3929. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3930. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3931. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3932. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3933. end
  3934. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3935. begin
  3936. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3937. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3938. end
  3939. else
  3940. begin
  3941. RemoveInstruction(hp2);
  3942. end
  3943. {$endif i386}
  3944. ;
  3945. end;
  3946. end
  3947. { movl [mem1],reg1
  3948. movl [mem1],reg2
  3949. to
  3950. movl [mem1],reg1
  3951. movl reg1,reg2
  3952. }
  3953. else if not CheckMovMov2MovMov2(p, hp1) and
  3954. { movl const1,[mem1]
  3955. movl [mem1],reg1
  3956. to
  3957. movl const1,reg1
  3958. movl reg1,[mem1]
  3959. }
  3960. MatchOpType(Taicpu(p),top_const,top_ref) and
  3961. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3962. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3963. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3964. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3965. begin
  3966. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3967. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3968. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3969. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3970. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3971. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3972. Result:=true;
  3973. exit;
  3974. end;
  3975. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3976. { Change:
  3977. movl %reg1,%reg2
  3978. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3979. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3980. To:
  3981. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3982. movl x(%reg1),%reg1
  3983. movl %reg1,%regX
  3984. }
  3985. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3986. begin
  3987. p_SourceReg := taicpu(p).oper[0]^.reg;
  3988. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3989. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3990. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3991. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3992. GetNextInstruction(hp1, hp2) and
  3993. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3994. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3995. begin
  3996. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3997. if RegInRef(p_TargetReg, SourceRef) and
  3998. { If %reg1 also appears in the second reference, then it will
  3999. not refer to the same memory block as the first reference }
  4000. not RegInRef(p_SourceReg, SourceRef) then
  4001. begin
  4002. { Check to see if the references match if %reg2 is changed to %reg1 }
  4003. if SourceRef.base = p_TargetReg then
  4004. SourceRef.base := p_SourceReg;
  4005. if SourceRef.index = p_TargetReg then
  4006. SourceRef.index := p_SourceReg;
  4007. { RefsEqual also checks to ensure both references are non-volatile }
  4008. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4009. begin
  4010. taicpu(hp2).loadreg(0, p_SourceReg);
  4011. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4012. Result := True;
  4013. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4014. begin
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4016. RemoveCurrentP(p, hp1);
  4017. Exit;
  4018. end
  4019. else
  4020. begin
  4021. { Check to see if %reg2 is no longer in use }
  4022. TransferUsedRegs(TmpUsedRegs);
  4023. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4025. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4026. begin
  4027. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4028. RemoveCurrentP(p, hp1);
  4029. Exit;
  4030. end;
  4031. end;
  4032. { If we reach this point, p and hp1 weren't actually modified,
  4033. so we can do a bit more work on this pass }
  4034. end;
  4035. end;
  4036. end;
  4037. end;
  4038. end;
  4039. {$ifdef x86_64}
  4040. { Change:
  4041. movl %reg1l,%reg2l
  4042. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4043. To:
  4044. movl %reg1l,%reg2l
  4045. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4046. If %reg1 = %reg3, convert to:
  4047. movl %reg1l,%reg2l
  4048. andl %reg1l,%reg1l
  4049. }
  4050. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  4051. MatchOpType(taicpu(p), top_reg, top_reg) and
  4052. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  4053. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  4054. begin
  4055. TransferUsedRegs(TmpUsedRegs);
  4056. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4057. taicpu(hp1).opsize := S_L;
  4058. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  4059. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4060. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  4061. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  4062. begin
  4063. { %reg1 = %reg3 }
  4064. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  4065. taicpu(hp1).opcode := A_AND;
  4066. end
  4067. else
  4068. begin
  4069. { %reg1 <> %reg3 }
  4070. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  4071. end;
  4072. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4073. begin
  4074. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  4075. RemoveCurrentP(p, hp1);
  4076. Result := True;
  4077. Exit;
  4078. end
  4079. else
  4080. begin
  4081. { Initial instruction wasn't actually changed }
  4082. Include(OptsToCheck, aoc_ForceNewIteration);
  4083. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4084. appears below since %reg1 has technically changed }
  4085. if taicpu(hp1).opcode = A_AND then
  4086. Exit;
  4087. end;
  4088. end;
  4089. {$endif x86_64}
  4090. { search further than the next instruction for a mov (as long as it's not a jump) }
  4091. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4092. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4093. (taicpu(p).oper[1]^.typ = top_reg) and
  4094. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4095. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4096. begin
  4097. { we work with hp2 here, so hp1 can be still used later on when
  4098. checking for GetNextInstruction_p }
  4099. hp3 := hp1;
  4100. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4101. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4102. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4103. TransferUsedRegs(TmpUsedRegs);
  4104. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4105. if NotFirstIteration then
  4106. JumpTracking := TLinkedList.Create
  4107. else
  4108. JumpTracking := nil;
  4109. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4110. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4111. (hp2.typ=ait_instruction) do
  4112. begin
  4113. case taicpu(hp2).opcode of
  4114. A_POP:
  4115. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4116. begin
  4117. if not CrossJump and
  4118. not RegUsedBetween(p_TargetReg, p, hp2) then
  4119. begin
  4120. { We can remove the original MOV since the register
  4121. wasn't used between it and its popping from the stack }
  4122. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4123. RemoveCurrentp(p, hp1);
  4124. Result := True;
  4125. JumpTracking.Free;
  4126. Exit;
  4127. end;
  4128. { Can't go any further }
  4129. Break;
  4130. end;
  4131. A_MOV:
  4132. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4133. ((taicpu(p).oper[0]^.typ=top_const) or
  4134. ((taicpu(p).oper[0]^.typ=top_reg) and
  4135. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4136. )
  4137. ) then
  4138. begin
  4139. { we have
  4140. mov x, %treg
  4141. mov %treg, y
  4142. }
  4143. { We don't need to call UpdateUsedRegs for every instruction between
  4144. p and hp2 because the register we're concerned about will not
  4145. become deallocated (otherwise GetNextInstructionUsingReg would
  4146. have stopped at an earlier instruction). [Kit] }
  4147. TempRegUsed :=
  4148. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4149. RegReadByInstruction(p_TargetReg, hp3) or
  4150. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4151. case taicpu(p).oper[0]^.typ Of
  4152. top_reg:
  4153. begin
  4154. { change
  4155. mov %reg, %treg
  4156. mov %treg, y
  4157. to
  4158. mov %reg, y
  4159. }
  4160. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4161. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4162. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4163. begin
  4164. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4165. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4166. if TempRegUsed then
  4167. begin
  4168. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4169. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4170. { Set the start of the next GetNextInstructionUsingRegCond search
  4171. to start at the entry right before hp2 (which is about to be removed) }
  4172. hp3 := tai(hp2.Previous);
  4173. RemoveInstruction(hp2);
  4174. Include(OptsToCheck, aoc_ForceNewIteration);
  4175. { See if there's more we can optimise }
  4176. Continue;
  4177. end
  4178. else
  4179. begin
  4180. RemoveInstruction(hp2);
  4181. { We can remove the original MOV too }
  4182. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4183. RemoveCurrentP(p, hp1);
  4184. Result:=true;
  4185. JumpTracking.Free;
  4186. Exit;
  4187. end;
  4188. end
  4189. else
  4190. begin
  4191. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4192. taicpu(hp2).loadReg(0, p_SourceReg);
  4193. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4194. { Check to see if the register also appears in the reference }
  4195. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4196. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4197. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4198. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4199. begin
  4200. { Don't remove the first instruction if the temporary register is in use }
  4201. if not TempRegUsed then
  4202. begin
  4203. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4204. RemoveCurrentP(p, hp1);
  4205. Result:=true;
  4206. JumpTracking.Free;
  4207. Exit;
  4208. end;
  4209. { No need to set Result to True here. If there's another instruction later
  4210. on that can be optimised, it will be detected when the main Pass 1 loop
  4211. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4212. hp3 := hp2;
  4213. Continue;
  4214. end;
  4215. end;
  4216. end;
  4217. top_const:
  4218. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4219. begin
  4220. { change
  4221. mov const, %treg
  4222. mov %treg, y
  4223. to
  4224. mov const, y
  4225. }
  4226. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4227. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4228. begin
  4229. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4230. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4231. if TempRegUsed then
  4232. begin
  4233. { Don't remove the first instruction if the temporary register is in use }
  4234. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4235. { No need to set Result to True. If there's another instruction later on
  4236. that can be optimised, it will be detected when the main Pass 1 loop
  4237. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4238. end
  4239. else
  4240. begin
  4241. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4242. RemoveCurrentP(p, hp1);
  4243. Result:=true;
  4244. Exit;
  4245. end;
  4246. end;
  4247. end;
  4248. else
  4249. Internalerror(2019103001);
  4250. end;
  4251. end
  4252. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4253. begin
  4254. if not CrossJump and
  4255. not RegUsedBetween(p_TargetReg, p, hp2) and
  4256. not RegReadByInstruction(p_TargetReg, hp2) then
  4257. begin
  4258. { Register is not used before it is overwritten }
  4259. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4260. RemoveCurrentp(p, hp1);
  4261. Result := True;
  4262. Exit;
  4263. end;
  4264. if (taicpu(p).oper[0]^.typ = top_const) and
  4265. (taicpu(hp2).oper[0]^.typ = top_const) then
  4266. begin
  4267. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4268. begin
  4269. { Same value - register hasn't changed }
  4270. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4271. RemoveInstruction(hp2);
  4272. Include(OptsToCheck, aoc_ForceNewIteration);
  4273. { See if there's more we can optimise }
  4274. Continue;
  4275. end;
  4276. end;
  4277. {$ifdef x86_64}
  4278. end
  4279. { Change:
  4280. movl %reg1l,%reg2l
  4281. ...
  4282. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4283. To:
  4284. movl %reg1l,%reg2l
  4285. ...
  4286. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4287. If %reg1 = %reg3, convert to:
  4288. movl %reg1l,%reg2l
  4289. ...
  4290. andl %reg1l,%reg1l
  4291. }
  4292. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4293. (taicpu(p).oper[0]^.typ = top_reg) and
  4294. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4295. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4296. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4297. begin
  4298. TempRegUsed :=
  4299. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4300. RegReadByInstruction(p_TargetReg, hp3) or
  4301. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4302. taicpu(hp2).opsize := S_L;
  4303. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4304. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4305. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4306. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4307. begin
  4308. { %reg1 = %reg3 }
  4309. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4310. taicpu(hp2).opcode := A_AND;
  4311. end
  4312. else
  4313. begin
  4314. { %reg1 <> %reg3 }
  4315. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4316. end;
  4317. if not TempRegUsed then
  4318. begin
  4319. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4320. RemoveCurrentP(p, hp1);
  4321. Result := True;
  4322. Exit;
  4323. end
  4324. else
  4325. begin
  4326. { Initial instruction wasn't actually changed }
  4327. Include(OptsToCheck, aoc_ForceNewIteration);
  4328. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4329. appears below since %reg1 has technically changed }
  4330. if taicpu(hp2).opcode = A_AND then
  4331. Break;
  4332. end;
  4333. {$endif x86_64}
  4334. end
  4335. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4336. GetNextInstruction(hp2, hp4) and
  4337. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4338. { Optimise the following first:
  4339. movl [mem1],reg1
  4340. movl [mem1],reg2
  4341. to
  4342. movl [mem1],reg1
  4343. movl reg1,reg2
  4344. If [mem1] contains the target register and reg1 is the
  4345. the source register, this optimisation will get missed
  4346. and produce less efficient code later on.
  4347. }
  4348. if CheckMovMov2MovMov2(hp2, hp4) then
  4349. { Initial instruction wasn't actually changed }
  4350. Include(OptsToCheck, aoc_ForceNewIteration);
  4351. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4352. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4353. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4354. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4355. begin
  4356. {
  4357. Change from:
  4358. mov ###, %reg
  4359. ...
  4360. movs/z %reg,%reg (Same register, just different sizes)
  4361. To:
  4362. movs/z ###, %reg (Longer version)
  4363. ...
  4364. (remove)
  4365. }
  4366. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4367. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4368. { Keep the first instruction as mov if ### is a constant }
  4369. if taicpu(p).oper[0]^.typ = top_const then
  4370. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4371. else
  4372. begin
  4373. taicpu(p).opcode := taicpu(hp2).opcode;
  4374. taicpu(p).opsize := taicpu(hp2).opsize;
  4375. end;
  4376. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4377. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4378. RemoveInstruction(hp2);
  4379. Result := True;
  4380. JumpTracking.Free;
  4381. Exit;
  4382. end;
  4383. else
  4384. { Move down to the if-block below };
  4385. end;
  4386. { Also catches MOV/S/Z instructions that aren't modified }
  4387. if taicpu(p).oper[0]^.typ = top_reg then
  4388. begin
  4389. p_SourceReg := taicpu(p).oper[0]^.reg;
  4390. if
  4391. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4392. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4393. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4394. begin
  4395. Result := True;
  4396. { Just in case something didn't get modified (e.g. an
  4397. implicit register). Also, if it does read from this
  4398. register, then there's no longer an advantage to
  4399. changing the register on subsequent instructions.}
  4400. if not RegReadByInstruction(p_TargetReg, hp2) then
  4401. begin
  4402. { If a conditional jump was crossed, do not delete
  4403. the original MOV no matter what }
  4404. if not CrossJump and
  4405. { RegEndOfLife returns True if the register is
  4406. deallocated before the next instruction or has
  4407. been loaded with a new value }
  4408. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4409. begin
  4410. { We can remove the original MOV }
  4411. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4412. RemoveCurrentp(p, hp1);
  4413. JumpTracking.Free;
  4414. Result := True;
  4415. Exit;
  4416. end;
  4417. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4418. begin
  4419. { See if there's more we can optimise }
  4420. hp3 := hp2;
  4421. Continue;
  4422. end;
  4423. end;
  4424. end;
  4425. end;
  4426. { Break out of the while loop under normal circumstances }
  4427. Break;
  4428. end;
  4429. JumpTracking.Free;
  4430. end;
  4431. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4432. (taicpu(p).oper[1]^.typ = top_reg) and
  4433. (taicpu(p).opsize = S_L) and
  4434. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4435. (hp2.typ = ait_instruction) and
  4436. (taicpu(hp2).opcode = A_AND) and
  4437. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4438. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4439. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4440. ) then
  4441. begin
  4442. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4443. begin
  4444. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4445. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4446. begin
  4447. { Optimize out:
  4448. mov x, %reg
  4449. and ffffffffh, %reg
  4450. }
  4451. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4452. RemoveInstruction(hp2);
  4453. Result:=true;
  4454. exit;
  4455. end;
  4456. end;
  4457. end;
  4458. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4459. x >= RetOffset) as it doesn't do anything (it writes either to a
  4460. parameter or to the temporary storage room for the function
  4461. result)
  4462. }
  4463. if IsExitCode(hp1) and
  4464. (taicpu(p).oper[1]^.typ = top_ref) and
  4465. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4466. (
  4467. (
  4468. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4469. not (
  4470. assigned(current_procinfo.procdef.funcretsym) and
  4471. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4472. )
  4473. ) or
  4474. { Also discard writes to the stack that are below the base pointer,
  4475. as this is temporary storage rather than a function result on the
  4476. stack, say. }
  4477. (
  4478. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4479. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4480. )
  4481. ) then
  4482. begin
  4483. RemoveCurrentp(p, hp1);
  4484. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4485. RemoveLastDeallocForFuncRes(p);
  4486. Result:=true;
  4487. exit;
  4488. end;
  4489. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4490. begin
  4491. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4492. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4493. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4494. begin
  4495. { change
  4496. mov reg1, mem1
  4497. test/cmp x, mem1
  4498. to
  4499. mov reg1, mem1
  4500. test/cmp x, reg1
  4501. }
  4502. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4503. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4504. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4505. Result := True;
  4506. Exit;
  4507. end;
  4508. if DoMovCmpMemOpt(p, hp1) then
  4509. begin
  4510. Result := True;
  4511. Exit;
  4512. end;
  4513. end;
  4514. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4515. { If the flags register is in use, don't change the instruction to an
  4516. ADD otherwise this will scramble the flags. [Kit] }
  4517. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4518. begin
  4519. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4520. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4521. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4522. ) or
  4523. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4524. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4525. )
  4526. ) then
  4527. { mov reg1,ref
  4528. lea reg2,[reg1,reg2]
  4529. to
  4530. add reg2,ref}
  4531. begin
  4532. TransferUsedRegs(TmpUsedRegs);
  4533. { reg1 may not be used afterwards }
  4534. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4535. begin
  4536. Taicpu(hp1).opcode:=A_ADD;
  4537. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4538. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4539. RemoveCurrentp(p, hp1);
  4540. result:=true;
  4541. exit;
  4542. end;
  4543. end;
  4544. { If the LEA instruction can be converted into an arithmetic instruction,
  4545. it may be possible to then fold it in the next optimisation, otherwise
  4546. there's nothing more that can be optimised here. }
  4547. if not ConvertLEA(taicpu(hp1)) then
  4548. Exit;
  4549. end;
  4550. if (taicpu(p).oper[1]^.typ = top_reg) and
  4551. (hp1.typ = ait_instruction) and
  4552. GetNextInstruction(hp1, hp2) and
  4553. MatchInstruction(hp2,A_MOV,[]) and
  4554. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4555. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4556. (
  4557. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4558. {$ifdef x86_64}
  4559. or
  4560. (
  4561. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4562. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4563. )
  4564. {$endif x86_64}
  4565. ) then
  4566. begin
  4567. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4568. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4569. { change movsX/movzX reg/ref, reg2
  4570. add/sub/or/... reg3/$const, reg2
  4571. mov reg2 reg/ref
  4572. dealloc reg2
  4573. to
  4574. add/sub/or/... reg3/$const, reg/ref }
  4575. begin
  4576. TransferUsedRegs(TmpUsedRegs);
  4577. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4578. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4579. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4580. begin
  4581. { by example:
  4582. movswl %si,%eax movswl %si,%eax p
  4583. decl %eax addl %edx,%eax hp1
  4584. movw %ax,%si movw %ax,%si hp2
  4585. ->
  4586. movswl %si,%eax movswl %si,%eax p
  4587. decw %eax addw %edx,%eax hp1
  4588. movw %ax,%si movw %ax,%si hp2
  4589. }
  4590. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4591. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4592. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4593. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4594. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4595. {
  4596. ->
  4597. movswl %si,%eax movswl %si,%eax p
  4598. decw %si addw %dx,%si hp1
  4599. movw %ax,%si movw %ax,%si hp2
  4600. }
  4601. case taicpu(hp1).ops of
  4602. 1:
  4603. begin
  4604. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4605. if taicpu(hp1).oper[0]^.typ=top_reg then
  4606. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4607. end;
  4608. 2:
  4609. begin
  4610. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4611. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4612. (taicpu(hp1).opcode<>A_SHL) and
  4613. (taicpu(hp1).opcode<>A_SHR) and
  4614. (taicpu(hp1).opcode<>A_SAR) then
  4615. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4616. end;
  4617. else
  4618. internalerror(2008042701);
  4619. end;
  4620. {
  4621. ->
  4622. decw %si addw %dx,%si p
  4623. }
  4624. RemoveInstruction(hp2);
  4625. RemoveCurrentP(p, hp1);
  4626. Result:=True;
  4627. Exit;
  4628. end;
  4629. end;
  4630. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4631. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4632. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4633. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4634. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4635. )
  4636. {$ifdef i386}
  4637. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4638. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4639. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4640. {$endif i386}
  4641. then
  4642. { change movsX/movzX reg/ref, reg2
  4643. add/sub/or/... regX/$const, reg2
  4644. mov reg2, reg3
  4645. dealloc reg2
  4646. to
  4647. movsX/movzX reg/ref, reg3
  4648. add/sub/or/... reg3/$const, reg3
  4649. }
  4650. begin
  4651. TransferUsedRegs(TmpUsedRegs);
  4652. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4653. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4654. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4655. begin
  4656. { by example:
  4657. movswl %si,%eax movswl %si,%eax p
  4658. decl %eax addl %edx,%eax hp1
  4659. movw %ax,%si movw %ax,%si hp2
  4660. ->
  4661. movswl %si,%eax movswl %si,%eax p
  4662. decw %eax addw %edx,%eax hp1
  4663. movw %ax,%si movw %ax,%si hp2
  4664. }
  4665. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4666. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4667. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4668. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4669. { limit size of constants as well to avoid assembler errors, but
  4670. check opsize to avoid overflow when left shifting the 1 }
  4671. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4672. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4673. {$ifdef x86_64}
  4674. { Be careful of, for example:
  4675. movl %reg1,%reg2
  4676. addl %reg3,%reg2
  4677. movq %reg2,%reg4
  4678. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4679. }
  4680. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4681. begin
  4682. taicpu(hp2).changeopsize(S_L);
  4683. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4684. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4685. end;
  4686. {$endif x86_64}
  4687. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4688. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4689. if taicpu(p).oper[0]^.typ=top_reg then
  4690. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4691. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4692. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4693. {
  4694. ->
  4695. movswl %si,%eax movswl %si,%eax p
  4696. decw %si addw %dx,%si hp1
  4697. movw %ax,%si movw %ax,%si hp2
  4698. }
  4699. case taicpu(hp1).ops of
  4700. 1:
  4701. begin
  4702. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4703. if taicpu(hp1).oper[0]^.typ=top_reg then
  4704. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4705. end;
  4706. 2:
  4707. begin
  4708. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4709. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4710. (taicpu(hp1).opcode<>A_SHL) and
  4711. (taicpu(hp1).opcode<>A_SHR) and
  4712. (taicpu(hp1).opcode<>A_SAR) then
  4713. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4714. end;
  4715. else
  4716. internalerror(2018111801);
  4717. end;
  4718. {
  4719. ->
  4720. decw %si addw %dx,%si p
  4721. }
  4722. RemoveInstruction(hp2);
  4723. end;
  4724. end;
  4725. end;
  4726. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4727. GetNextInstruction(hp1, hp2) and
  4728. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4729. MatchOperand(Taicpu(p).oper[0]^,0) and
  4730. (Taicpu(p).oper[1]^.typ = top_reg) and
  4731. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4732. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4733. { mov reg1,0
  4734. bts reg1,operand1 --> mov reg1,operand2
  4735. or reg1,operand2 bts reg1,operand1}
  4736. begin
  4737. Taicpu(hp2).opcode:=A_MOV;
  4738. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4739. asml.remove(hp1);
  4740. insertllitem(hp2,hp2.next,hp1);
  4741. RemoveCurrentp(p, hp1);
  4742. Result:=true;
  4743. exit;
  4744. end;
  4745. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4746. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4747. GetNextInstruction(hp1, hp2) and
  4748. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4749. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4750. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4751. { change
  4752. mov reg1,reg2
  4753. sub reg3,reg2
  4754. cmp reg3,reg1
  4755. into
  4756. mov reg1,reg2
  4757. sub reg3,reg2
  4758. }
  4759. begin
  4760. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4761. RemoveInstruction(hp2);
  4762. Result:=true;
  4763. exit;
  4764. end;
  4765. {
  4766. mov ref,reg0
  4767. <op> reg0,reg1
  4768. dealloc reg0
  4769. to
  4770. <op> ref,reg1
  4771. }
  4772. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4773. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4774. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4775. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4776. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4777. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4778. begin
  4779. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4780. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4781. RemoveCurrentp(p, hp1);
  4782. Result:=true;
  4783. exit;
  4784. end;
  4785. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4786. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4787. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4788. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4789. begin
  4790. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4791. {$ifdef x86_64}
  4792. { Convert:
  4793. movq x(ref),%reg64
  4794. shrq y,%reg64
  4795. To:
  4796. movl x+4(ref),%reg32
  4797. shrl y-32,%reg32 (Remove if y = 32)
  4798. }
  4799. if (taicpu(p).opsize = S_Q) and
  4800. (taicpu(hp1).opcode = A_SHR) and
  4801. (taicpu(hp1).oper[0]^.val >= 32) then
  4802. begin
  4803. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4804. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4805. { Convert to 32-bit }
  4806. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4807. taicpu(p).opsize := S_L;
  4808. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4809. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4810. if (taicpu(hp1).oper[0]^.val = 32) then
  4811. begin
  4812. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4813. RemoveInstruction(hp1);
  4814. end
  4815. else
  4816. begin
  4817. { This will potentially open up more arithmetic operations since
  4818. the peephole optimizer now has a big hint that only the lower
  4819. 32 bits are currently in use (and opcodes are smaller in size) }
  4820. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4821. taicpu(hp1).opsize := S_L;
  4822. Dec(taicpu(hp1).oper[0]^.val, 32);
  4823. DebugMsg(SPeepholeOptimization + PreMessage +
  4824. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4825. end;
  4826. Result := True;
  4827. Exit;
  4828. end;
  4829. {$endif x86_64}
  4830. { Convert:
  4831. movl x(ref),%reg
  4832. shrl $24,%reg
  4833. To:
  4834. movzbl x+3(ref),%reg
  4835. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4836. Also accept sar instead of shr, but convert to movsx instead of movzx
  4837. }
  4838. if taicpu(hp1).opcode = A_SHR then
  4839. MovUnaligned := A_MOVZX
  4840. else
  4841. MovUnaligned := A_MOVSX;
  4842. NewSize := S_NO;
  4843. NewOffset := 0;
  4844. case taicpu(p).opsize of
  4845. S_B:
  4846. { No valid combinations };
  4847. S_W:
  4848. if (taicpu(hp1).oper[0]^.val = 8) then
  4849. begin
  4850. NewSize := S_BW;
  4851. NewOffset := 1;
  4852. end;
  4853. S_L:
  4854. case taicpu(hp1).oper[0]^.val of
  4855. 16:
  4856. begin
  4857. NewSize := S_WL;
  4858. NewOffset := 2;
  4859. end;
  4860. 24:
  4861. begin
  4862. NewSize := S_BL;
  4863. NewOffset := 3;
  4864. end;
  4865. else
  4866. ;
  4867. end;
  4868. {$ifdef x86_64}
  4869. S_Q:
  4870. case taicpu(hp1).oper[0]^.val of
  4871. 32:
  4872. begin
  4873. if taicpu(hp1).opcode = A_SAR then
  4874. begin
  4875. { 32-bit to 64-bit is a distinct instruction }
  4876. MovUnaligned := A_MOVSXD;
  4877. NewSize := S_LQ;
  4878. NewOffset := 4;
  4879. end
  4880. else
  4881. { Should have been handled by MovShr2Mov above }
  4882. InternalError(2022081811);
  4883. end;
  4884. 48:
  4885. begin
  4886. NewSize := S_WQ;
  4887. NewOffset := 6;
  4888. end;
  4889. 56:
  4890. begin
  4891. NewSize := S_BQ;
  4892. NewOffset := 7;
  4893. end;
  4894. else
  4895. ;
  4896. end;
  4897. {$endif x86_64}
  4898. else
  4899. InternalError(2022081810);
  4900. end;
  4901. if (NewSize <> S_NO) and
  4902. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4903. begin
  4904. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4905. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4906. debug_op2str(MovUnaligned);
  4907. {$ifdef x86_64}
  4908. if MovUnaligned <> A_MOVSXD then
  4909. { Don't add size suffix for MOVSXD }
  4910. {$endif x86_64}
  4911. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4912. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4913. taicpu(p).opcode := MovUnaligned;
  4914. taicpu(p).opsize := NewSize;
  4915. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4916. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4917. RemoveInstruction(hp1);
  4918. Result := True;
  4919. Exit;
  4920. end;
  4921. end;
  4922. { Backward optimisation shared with OptPass2MOV }
  4923. if FuncMov2Func(p, hp1) then
  4924. begin
  4925. Result := True;
  4926. Exit;
  4927. end;
  4928. end;
  4929. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4930. var
  4931. hp1 : tai;
  4932. begin
  4933. Result:=false;
  4934. if taicpu(p).ops <> 2 then
  4935. exit;
  4936. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4937. GetNextInstruction(p,hp1) then
  4938. begin
  4939. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4940. (taicpu(hp1).ops = 2) then
  4941. begin
  4942. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4943. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4944. { movXX reg1, mem1 or movXX mem1, reg1
  4945. movXX mem2, reg2 movXX reg2, mem2}
  4946. begin
  4947. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4948. { movXX reg1, mem1 or movXX mem1, reg1
  4949. movXX mem2, reg1 movXX reg2, mem1}
  4950. begin
  4951. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4952. begin
  4953. { Removes the second statement from
  4954. movXX reg1, mem1/reg2
  4955. movXX mem1/reg2, reg1
  4956. }
  4957. if taicpu(p).oper[0]^.typ=top_reg then
  4958. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4959. { Removes the second statement from
  4960. movXX mem1/reg1, reg2
  4961. movXX reg2, mem1/reg1
  4962. }
  4963. if (taicpu(p).oper[1]^.typ=top_reg) and
  4964. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4965. begin
  4966. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4967. RemoveInstruction(hp1);
  4968. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4969. Result:=true;
  4970. exit;
  4971. end
  4972. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4973. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4974. begin
  4975. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4976. RemoveInstruction(hp1);
  4977. Result:=true;
  4978. exit;
  4979. end;
  4980. end
  4981. end;
  4982. end;
  4983. end;
  4984. end;
  4985. end;
  4986. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4987. var
  4988. hp1 : tai;
  4989. begin
  4990. result:=false;
  4991. { replace
  4992. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4993. MovX %mreg2,%mreg1
  4994. dealloc %mreg2
  4995. by
  4996. <Op>X %mreg2,%mreg1
  4997. ?
  4998. }
  4999. if GetNextInstruction(p,hp1) and
  5000. { we mix single and double opperations here because we assume that the compiler
  5001. generates vmovapd only after double operations and vmovaps only after single operations }
  5002. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5003. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5004. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5005. (taicpu(p).oper[0]^.typ=top_reg) then
  5006. begin
  5007. TransferUsedRegs(TmpUsedRegs);
  5008. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5009. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5010. begin
  5011. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5012. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5013. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5014. RemoveInstruction(hp1);
  5015. result:=true;
  5016. end;
  5017. end;
  5018. end;
  5019. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5020. var
  5021. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5022. JumpLabel, JumpLabel_dist: TAsmLabel;
  5023. FirstValue, SecondValue: TCGInt;
  5024. function OptimizeJump(var InputP: tai): Boolean;
  5025. var
  5026. TempBool: Boolean;
  5027. begin
  5028. Result := False;
  5029. TempBool := True;
  5030. if DoJumpOptimizations(InputP, TempBool) or
  5031. not TempBool then
  5032. begin
  5033. Result := True;
  5034. if Assigned(InputP) then
  5035. begin
  5036. { CollapseZeroDistJump will be set to the label or an align
  5037. before it after the jump if it optimises, whether or not
  5038. the label is live or dead }
  5039. if (InputP.typ = ait_align) or
  5040. (
  5041. (InputP.typ = ait_label) and
  5042. not (tai_label(InputP).labsym.is_used)
  5043. ) then
  5044. GetNextInstruction(InputP, InputP);
  5045. end;
  5046. Exit;
  5047. end;
  5048. end;
  5049. begin
  5050. Result := False;
  5051. if (taicpu(p).oper[0]^.typ = top_const) and
  5052. (taicpu(p).oper[0]^.val <> -1) then
  5053. begin
  5054. { Convert unsigned maximum constants to -1 to aid optimisation }
  5055. case taicpu(p).opsize of
  5056. S_B:
  5057. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5058. begin
  5059. taicpu(p).oper[0]^.val := -1;
  5060. Result := True;
  5061. Exit;
  5062. end;
  5063. S_W:
  5064. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5065. begin
  5066. taicpu(p).oper[0]^.val := -1;
  5067. Result := True;
  5068. Exit;
  5069. end;
  5070. S_L:
  5071. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5072. begin
  5073. taicpu(p).oper[0]^.val := -1;
  5074. Result := True;
  5075. Exit;
  5076. end;
  5077. {$ifdef x86_64}
  5078. S_Q:
  5079. { Storing anything greater than $7FFFFFFF is not possible so do
  5080. nothing };
  5081. {$endif x86_64}
  5082. else
  5083. InternalError(2021121001);
  5084. end;
  5085. end;
  5086. if GetNextInstruction(p, hp1) and
  5087. TrySwapMovCmp(p, hp1) then
  5088. begin
  5089. Result := True;
  5090. Exit;
  5091. end;
  5092. p_label := nil;
  5093. JumpLabel := nil;
  5094. if MatchInstruction(hp1, A_Jcc, []) then
  5095. begin
  5096. if OptimizeJump(hp1) then
  5097. begin
  5098. Result := True;
  5099. if Assigned(hp1) then
  5100. begin
  5101. { CollapseZeroDistJump will be set to the label or an align
  5102. before it after the jump if it optimises, whether or not
  5103. the label is live or dead }
  5104. if (hp1.typ = ait_align) or
  5105. (
  5106. (hp1.typ = ait_label) and
  5107. not (tai_label(hp1).labsym.is_used)
  5108. ) then
  5109. GetNextInstruction(hp1, hp1);
  5110. end;
  5111. TransferUsedRegs(TmpUsedRegs);
  5112. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5113. if not Assigned(hp1) or
  5114. (
  5115. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5116. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5117. ) then
  5118. begin
  5119. { No more conditional jumps; conditional statement is no longer required }
  5120. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5121. RemoveCurrentP(p);
  5122. end;
  5123. Exit;
  5124. end;
  5125. if IsJumpToLabel(taicpu(hp1)) then
  5126. begin
  5127. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5128. if Assigned(JumpLabel) then
  5129. p_label := getlabelwithsym(JumpLabel);
  5130. end;
  5131. end;
  5132. { Search for:
  5133. test $x,(reg/ref)
  5134. jne @lbl1
  5135. test $y,(reg/ref) (same register or reference)
  5136. jne @lbl1
  5137. Change to:
  5138. test $(x or y),(reg/ref)
  5139. jne @lbl1
  5140. (Note, this doesn't work with je instead of jne)
  5141. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5142. Also search for:
  5143. test $x,(reg/ref)
  5144. je @lbl1
  5145. ...
  5146. test $y,(reg/ref)
  5147. je/jne @lbl2
  5148. If (x or y) = x, then the second jump is deterministic
  5149. }
  5150. if (
  5151. (
  5152. (taicpu(p).oper[0]^.typ = top_const) or
  5153. (
  5154. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5155. (taicpu(p).oper[0]^.typ = top_reg) and
  5156. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5157. )
  5158. ) and
  5159. MatchInstruction(hp1, A_JCC, [])
  5160. ) then
  5161. begin
  5162. if (taicpu(p).oper[0]^.typ = top_reg) and
  5163. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5164. FirstValue := -1
  5165. else
  5166. FirstValue := taicpu(p).oper[0]^.val;
  5167. { If we have several test/jne's in a row, it might be the case that
  5168. the second label doesn't go to the same location, but the one
  5169. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5170. so accommodate for this with a while loop.
  5171. }
  5172. hp1_last := hp1;
  5173. while (
  5174. (
  5175. (taicpu(p).oper[1]^.typ = top_reg) and
  5176. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5177. ) or GetNextInstruction(hp1_last, p_dist)
  5178. ) and (p_dist.typ = ait_instruction) do
  5179. begin
  5180. if (
  5181. (
  5182. (taicpu(p_dist).opcode = A_TEST) and
  5183. (
  5184. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5185. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5186. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5187. )
  5188. ) or
  5189. (
  5190. { cmp 0,%reg = test %reg,%reg }
  5191. (taicpu(p_dist).opcode = A_CMP) and
  5192. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5193. )
  5194. ) and
  5195. { Make sure the destination operands are actually the same }
  5196. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5197. GetNextInstruction(p_dist, hp1_dist) and
  5198. MatchInstruction(hp1_dist, A_JCC, []) then
  5199. begin
  5200. if OptimizeJump(hp1_dist) then
  5201. begin
  5202. Result := True;
  5203. Exit;
  5204. end;
  5205. if
  5206. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5207. (
  5208. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5209. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5210. ) then
  5211. SecondValue := -1
  5212. else
  5213. SecondValue := taicpu(p_dist).oper[0]^.val;
  5214. { If both of the TEST constants are identical, delete the
  5215. second TEST that is unnecessary (be careful though, just
  5216. in case the flags are modified in between) }
  5217. if (FirstValue = SecondValue) then
  5218. begin
  5219. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5220. begin
  5221. { Since the second jump's condition is a subset of the first, we
  5222. know it will never branch because the first jump dominates it.
  5223. Get it out of the way now rather than wait for the jump
  5224. optimisations for a speed boost. }
  5225. if IsJumpToLabel(taicpu(hp1_dist)) then
  5226. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5227. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5228. RemoveInstruction(hp1_dist);
  5229. Result := True;
  5230. end
  5231. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5232. begin
  5233. { If the inverse of the first condition is a subset of the second,
  5234. the second one will definitely branch if the first one doesn't }
  5235. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5236. { We can remove the TEST instruction too }
  5237. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5238. RemoveInstruction(p_dist);
  5239. MakeUnconditional(taicpu(hp1_dist));
  5240. RemoveDeadCodeAfterJump(hp1_dist);
  5241. { Since the jump is now unconditional, we can't
  5242. continue any further with this particular
  5243. optimisation. The original TEST is still intact
  5244. though, so there might be something else we can
  5245. do }
  5246. Include(OptsToCheck, aoc_ForceNewIteration);
  5247. Break;
  5248. end;
  5249. if Result or
  5250. { If a jump wasn't removed or made unconditional, only
  5251. remove the identical TEST instruction if the flags
  5252. weren't modified }
  5253. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5254. begin
  5255. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5256. RemoveInstruction(p_dist);
  5257. { If the jump was removed or made unconditional, we
  5258. don't need to allocate NR_DEFAULTFLAGS over the
  5259. entire range }
  5260. if not Result then
  5261. begin
  5262. { Mark the flags as 'in use' over the entire range }
  5263. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5264. { Speed gain - continue search from the Jcc instruction }
  5265. hp1_last := hp1_dist;
  5266. { Only the TEST instruction was removed, and the
  5267. original was unchanged, so we can safely do
  5268. another iteration of the while loop }
  5269. Include(OptsToCheck, aoc_ForceNewIteration);
  5270. Continue;
  5271. end;
  5272. Exit;
  5273. end;
  5274. end;
  5275. hp1_last := nil;
  5276. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5277. (
  5278. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5279. { Always adjacent under -O2 and under }
  5280. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5281. (
  5282. GetNextInstruction(hp1, hp1_last) and
  5283. (hp1_last = p_dist)
  5284. )
  5285. ) and
  5286. (
  5287. (
  5288. { Test the following variant:
  5289. test $x,(reg/ref)
  5290. jne @lbl1
  5291. test $y,(reg/ref)
  5292. je @lbl2
  5293. @lbl1:
  5294. Becomes:
  5295. test $(x or y),(reg/ref)
  5296. je @lbl2
  5297. @lbl1: (may become a dead label)
  5298. }
  5299. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5300. GetNextInstruction(hp1_dist, hp1_last) and
  5301. (hp1_last = p_label)
  5302. ) or
  5303. (
  5304. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5305. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5306. then the second jump will never branch, so it can also be
  5307. removed regardless of where it goes }
  5308. (
  5309. (FirstValue = -1) or
  5310. (SecondValue = -1) or
  5311. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5312. )
  5313. )
  5314. ) then
  5315. begin
  5316. { Same jump location... can be a register since nothing's changed }
  5317. { If any of the entries are equivalent to test %reg,%reg, then the
  5318. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5319. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5320. if (hp1_last = p_label) then
  5321. begin
  5322. { Variant }
  5323. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5324. RemoveInstruction(p_dist);
  5325. if Assigned(JumpLabel) then
  5326. JumpLabel.decrefs;
  5327. RemoveInstruction(hp1);
  5328. end
  5329. else
  5330. begin
  5331. { Only remove the second test if no jumps or other conditional instructions follow }
  5332. TransferUsedRegs(TmpUsedRegs);
  5333. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5334. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5335. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5336. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5337. begin
  5338. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5339. RemoveInstruction(p_dist);
  5340. { Remove the first jump, not the second, to keep
  5341. any register deallocations between the second
  5342. TEST/JNE pair in the same place. Aids future
  5343. optimisation. }
  5344. if Assigned(JumpLabel) then
  5345. JumpLabel.decrefs;
  5346. RemoveInstruction(hp1);
  5347. end
  5348. else
  5349. begin
  5350. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5351. if IsJumpToLabel(taicpu(hp1_dist)) then
  5352. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5353. { Remove second jump in this instance }
  5354. RemoveInstruction(hp1_dist);
  5355. end;
  5356. end;
  5357. Result := True;
  5358. Exit;
  5359. end;
  5360. end;
  5361. if { If -O2 and under, it may stop on any old instruction }
  5362. (cs_opt_level3 in current_settings.optimizerswitches) and
  5363. (taicpu(p).oper[1]^.typ = top_reg) and
  5364. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5365. begin
  5366. hp1_last := p_dist;
  5367. Continue;
  5368. end;
  5369. Break;
  5370. end;
  5371. end;
  5372. { Search for:
  5373. test %reg,%reg
  5374. j(c1) @lbl1
  5375. ...
  5376. @lbl:
  5377. test %reg,%reg (same register)
  5378. j(c2) @lbl2
  5379. If c2 is a subset of c1, change to:
  5380. test %reg,%reg
  5381. j(c1) @lbl2
  5382. (@lbl1 may become a dead label as a result)
  5383. }
  5384. if (taicpu(p).oper[1]^.typ = top_reg) and
  5385. (taicpu(p).oper[0]^.typ = top_reg) and
  5386. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5387. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5388. Assigned(p_label) and
  5389. GetNextInstruction(p_label, p_dist) and
  5390. MatchInstruction(p_dist, A_TEST, []) and
  5391. { It's fine if the second test uses smaller sub-registers }
  5392. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5393. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5394. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5395. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5396. GetNextInstruction(p_dist, hp1_dist) and
  5397. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5398. begin
  5399. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5400. if JumpLabel = JumpLabel_dist then
  5401. { This is an infinite loop }
  5402. Exit;
  5403. { Best optimisation when the first condition is a subset (or equal) of the second }
  5404. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5405. begin
  5406. { Any registers used here will already be allocated }
  5407. if Assigned(JumpLabel) then
  5408. JumpLabel.DecRefs;
  5409. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5410. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5411. Result := True;
  5412. Exit;
  5413. end;
  5414. end;
  5415. end;
  5416. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5417. var
  5418. hp1, hp2: tai;
  5419. ActiveReg: TRegister;
  5420. OldOffset: asizeint;
  5421. ThisConst: TCGInt;
  5422. function RegDeallocated: Boolean;
  5423. begin
  5424. TransferUsedRegs(TmpUsedRegs);
  5425. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5426. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5427. end;
  5428. begin
  5429. result:=false;
  5430. hp1 := nil;
  5431. { replace
  5432. addX const,%reg1
  5433. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5434. dealloc %reg1
  5435. by
  5436. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5437. }
  5438. if MatchOpType(taicpu(p),top_const,top_reg) then
  5439. begin
  5440. ActiveReg := taicpu(p).oper[1]^.reg;
  5441. { Ensures the entire register was updated }
  5442. if (taicpu(p).opsize >= S_L) and
  5443. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5444. MatchInstruction(hp1,A_LEA,[]) and
  5445. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5446. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5447. (
  5448. { Cover the case where the register in the reference is also the destination register }
  5449. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5450. (
  5451. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5452. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5453. RegDeallocated
  5454. )
  5455. ) then
  5456. begin
  5457. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5458. {$push}
  5459. {$R-}{$Q-}
  5460. { Explicitly disable overflow checking for these offset calculation
  5461. as those do not matter for the final result }
  5462. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5463. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5464. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5465. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5466. {$pop}
  5467. {$ifdef x86_64}
  5468. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5469. begin
  5470. { Overflow; abort }
  5471. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5472. end
  5473. else
  5474. {$endif x86_64}
  5475. begin
  5476. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5477. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5478. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5479. RemoveCurrentP(p, hp1)
  5480. else
  5481. RemoveCurrentP(p);
  5482. result:=true;
  5483. Exit;
  5484. end;
  5485. end;
  5486. if (
  5487. { Save calling GetNextInstructionUsingReg again }
  5488. Assigned(hp1) or
  5489. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5490. ) and
  5491. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5492. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5493. begin
  5494. if taicpu(hp1).oper[0]^.typ = top_const then
  5495. begin
  5496. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5497. if taicpu(hp1).opcode = A_ADD then
  5498. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5499. else
  5500. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5501. Result := True;
  5502. { Handle any overflows }
  5503. case taicpu(p).opsize of
  5504. S_B:
  5505. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5506. S_W:
  5507. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5508. S_L:
  5509. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5510. {$ifdef x86_64}
  5511. S_Q:
  5512. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5513. { Overflow; abort }
  5514. Result := False
  5515. else
  5516. taicpu(p).oper[0]^.val := ThisConst;
  5517. {$endif x86_64}
  5518. else
  5519. InternalError(2021102610);
  5520. end;
  5521. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5522. if Result then
  5523. begin
  5524. if (taicpu(p).oper[0]^.val < 0) and
  5525. (
  5526. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5527. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5528. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5529. ) then
  5530. begin
  5531. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5532. taicpu(p).opcode := A_SUB;
  5533. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5534. end
  5535. else
  5536. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5537. RemoveInstruction(hp1);
  5538. end;
  5539. end
  5540. else
  5541. begin
  5542. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5543. TransferUsedRegs(TmpUsedRegs);
  5544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5545. hp2 := p;
  5546. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5547. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5548. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5549. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5550. begin
  5551. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5552. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5553. Asml.Remove(p);
  5554. Asml.InsertAfter(p, hp1);
  5555. p := hp1;
  5556. Result := True;
  5557. Exit;
  5558. end;
  5559. end;
  5560. end;
  5561. if DoArithCombineOpt(p) then
  5562. Result:=true;
  5563. end;
  5564. end;
  5565. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5566. var
  5567. hp1, hp2: tai;
  5568. ref: Integer;
  5569. saveref: treference;
  5570. offsetcalc: Int64;
  5571. TempReg: TRegister;
  5572. Multiple: TCGInt;
  5573. Adjacent, IntermediateRegDiscarded: Boolean;
  5574. begin
  5575. Result:=false;
  5576. { play save and throw an error if LEA uses a seg register prefix,
  5577. this is most likely an error somewhere else }
  5578. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5579. internalerror(2022022001);
  5580. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5581. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5582. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5583. (
  5584. { do not mess with leas accessing the stack pointer
  5585. unless it's a null operation }
  5586. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5587. (
  5588. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5589. (taicpu(p).oper[0]^.ref^.offset = 0)
  5590. )
  5591. ) and
  5592. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5593. begin
  5594. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5595. begin
  5596. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5597. begin
  5598. taicpu(p).opcode := A_MOV;
  5599. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5600. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5601. end
  5602. else
  5603. begin
  5604. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5605. RemoveCurrentP(p);
  5606. end;
  5607. Result:=true;
  5608. exit;
  5609. end
  5610. else if (
  5611. { continue to use lea to adjust the stack pointer,
  5612. it is the recommended way, but only if not optimizing for size }
  5613. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5614. (cs_opt_size in current_settings.optimizerswitches)
  5615. ) and
  5616. { If the flags register is in use, don't change the instruction
  5617. to an ADD otherwise this will scramble the flags. [Kit] }
  5618. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5619. ConvertLEA(taicpu(p)) then
  5620. begin
  5621. Result:=true;
  5622. exit;
  5623. end;
  5624. end;
  5625. { Don't optimise if the stack or frame pointer is the destination register }
  5626. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5627. Exit;
  5628. if GetNextInstruction(p,hp1) and
  5629. (hp1.typ=ait_instruction) then
  5630. begin
  5631. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5632. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5633. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5634. begin
  5635. TransferUsedRegs(TmpUsedRegs);
  5636. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5637. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5638. begin
  5639. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5640. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5641. RemoveInstruction(hp1);
  5642. result:=true;
  5643. exit;
  5644. end;
  5645. end;
  5646. { changes
  5647. lea <ref1>, reg1
  5648. <op> ...,<ref. with reg1>,...
  5649. to
  5650. <op> ...,<ref1>,... }
  5651. { find a reference which uses reg1 }
  5652. 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
  5653. ref:=0
  5654. 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
  5655. ref:=1
  5656. else
  5657. ref:=-1;
  5658. if (ref<>-1) and
  5659. { reg1 must be either the base or the index }
  5660. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5661. begin
  5662. { reg1 can be removed from the reference }
  5663. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5664. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5665. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5666. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5667. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5668. else
  5669. Internalerror(2019111201);
  5670. { check if the can insert all data of the lea into the second instruction }
  5671. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5672. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5673. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5674. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5675. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5676. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5677. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5678. {$ifdef x86_64}
  5679. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5680. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5681. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5682. )
  5683. {$endif x86_64}
  5684. then
  5685. begin
  5686. { reg1 might not used by the second instruction after it is remove from the reference }
  5687. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5688. begin
  5689. TransferUsedRegs(TmpUsedRegs);
  5690. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5691. { reg1 is not updated so it might not be used afterwards }
  5692. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5693. begin
  5694. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5695. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5696. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5697. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5698. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5699. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5700. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5701. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5702. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5703. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5704. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5705. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5706. RemoveCurrentP(p, hp1);
  5707. result:=true;
  5708. exit;
  5709. end
  5710. end;
  5711. end;
  5712. { recover }
  5713. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5714. end;
  5715. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5716. if Adjacent or
  5717. { Check further ahead (up to 2 instructions ahead for -O2) }
  5718. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5719. begin
  5720. { Check common LEA/LEA conditions }
  5721. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5722. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5723. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5724. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5725. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5726. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5727. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5728. (
  5729. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5730. calling it (since it calls GetNextInstruction) }
  5731. Adjacent or
  5732. (
  5733. (
  5734. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5735. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5736. ) and (
  5737. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5738. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5739. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5740. )
  5741. )
  5742. ) then
  5743. begin
  5744. TransferUsedRegs(TmpUsedRegs);
  5745. hp2 := p;
  5746. repeat
  5747. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5748. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5749. IntermediateRegDiscarded :=
  5750. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5751. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5752. { changes
  5753. lea offset1(regX,scale), reg1
  5754. lea offset2(reg1,reg1), reg2
  5755. to
  5756. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5757. and
  5758. lea offset1(regX,scale1), reg1
  5759. lea offset2(reg1,scale2), reg2
  5760. to
  5761. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5762. and
  5763. lea offset1(regX,scale1), reg1
  5764. lea offset2(reg3,reg1,scale2), reg2
  5765. to
  5766. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5767. ... so long as the final scale does not exceed 8
  5768. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5769. }
  5770. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5771. (
  5772. { Don't optimise if size is a concern and the intermediate register remains in use }
  5773. IntermediateRegDiscarded or
  5774. not (cs_opt_size in current_settings.optimizerswitches)
  5775. ) and
  5776. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5777. (
  5778. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5779. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5780. ) and (
  5781. (
  5782. { lea (reg1,scale2), reg2 variant }
  5783. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5784. (
  5785. Adjacent or
  5786. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5787. ) and
  5788. (
  5789. (
  5790. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5791. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5792. ) or (
  5793. { lea (regX,regX), reg1 variant }
  5794. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5795. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5796. )
  5797. )
  5798. ) or (
  5799. { lea (reg1,reg1), reg1 variant }
  5800. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5801. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5802. )
  5803. ) then
  5804. begin
  5805. { Make everything homogeneous to make calculations easier }
  5806. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5807. begin
  5808. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5809. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5810. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5811. else
  5812. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5813. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5814. end;
  5815. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5816. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5817. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5818. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5819. begin
  5820. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5821. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5822. begin
  5823. { Put the register to change in the index register }
  5824. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5825. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5826. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5827. end;
  5828. { Change lea (reg,reg) to lea(,reg,2) }
  5829. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5830. begin
  5831. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5832. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5833. end;
  5834. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5835. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5836. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5837. { Just to prevent miscalculations }
  5838. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5839. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5840. else
  5841. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5842. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5843. if IntermediateRegDiscarded then
  5844. begin
  5845. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5846. RemoveCurrentP(p);
  5847. end
  5848. else
  5849. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5850. result:=true;
  5851. exit;
  5852. end;
  5853. end;
  5854. { changes
  5855. lea offset1(regX), reg1
  5856. lea offset2(reg1), reg2
  5857. to
  5858. lea offset1+offset2(regX), reg2 }
  5859. if (
  5860. { Don't optimise if size is a concern and the intermediate register remains in use }
  5861. IntermediateRegDiscarded or
  5862. not (cs_opt_size in current_settings.optimizerswitches)
  5863. ) and
  5864. (
  5865. (
  5866. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5867. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5868. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5869. ) or (
  5870. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5871. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5872. (
  5873. (
  5874. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5875. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5876. ) or (
  5877. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5878. (
  5879. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5880. (
  5881. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5882. (
  5883. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5884. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5885. )
  5886. )
  5887. )
  5888. )
  5889. )
  5890. )
  5891. ) then
  5892. begin
  5893. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5894. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5895. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5896. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5897. begin
  5898. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5899. begin
  5900. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5901. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5902. { if the register is used as index and base, we have to increase for base as well
  5903. and adapt base }
  5904. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5905. begin
  5906. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5907. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5908. end;
  5909. end
  5910. else
  5911. begin
  5912. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5913. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5914. end;
  5915. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5916. begin
  5917. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5918. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5919. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5920. { Catch the situation where the base = index
  5921. and treat this as *2. The scalefactor of
  5922. p will be 0 or 1 due to the conditional
  5923. checks above. Fixes i40647 }
  5924. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5925. else
  5926. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5927. end;
  5928. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5929. if IntermediateRegDiscarded then
  5930. begin
  5931. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5932. RemoveCurrentP(p);
  5933. end
  5934. else
  5935. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5936. result:=true;
  5937. exit;
  5938. end;
  5939. end;
  5940. end;
  5941. { Change:
  5942. leal/q $x(%reg1),%reg2
  5943. ...
  5944. shll/q $y,%reg2
  5945. To:
  5946. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5947. }
  5948. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5949. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5950. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5951. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5952. (taicpu(hp1).oper[0]^.val <= 3) then
  5953. begin
  5954. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5955. TransferUsedRegs(TmpUsedRegs);
  5956. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5957. if
  5958. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5959. (this works even if scalefactor is zero) }
  5960. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5961. { Ensure offset doesn't go out of bounds }
  5962. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5963. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5964. (
  5965. (
  5966. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5967. (
  5968. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5969. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5970. (
  5971. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5972. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5973. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5974. )
  5975. )
  5976. ) or (
  5977. (
  5978. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5979. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5980. ) and
  5981. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5982. )
  5983. ) then
  5984. begin
  5985. repeat
  5986. with taicpu(p).oper[0]^.ref^ do
  5987. begin
  5988. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5989. if index = base then
  5990. begin
  5991. if Multiple > 4 then
  5992. { Optimisation will no longer work because resultant
  5993. scale factor will exceed 8 }
  5994. Break;
  5995. base := NR_NO;
  5996. scalefactor := 2;
  5997. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5998. end
  5999. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6000. begin
  6001. { Scale factor only works on the index register }
  6002. index := base;
  6003. base := NR_NO;
  6004. end;
  6005. { For safety }
  6006. if scalefactor <= 1 then
  6007. begin
  6008. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6009. scalefactor := Multiple;
  6010. end
  6011. else
  6012. begin
  6013. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6014. scalefactor := scalefactor * Multiple;
  6015. end;
  6016. offset := offset * Multiple;
  6017. end;
  6018. RemoveInstruction(hp1);
  6019. Result := True;
  6020. Exit;
  6021. { This repeat..until loop exists for the benefit of Break }
  6022. until True;
  6023. end;
  6024. end;
  6025. end;
  6026. end;
  6027. end;
  6028. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6029. var
  6030. hp1 : tai;
  6031. SubInstr: Boolean;
  6032. ThisConst: TCGInt;
  6033. const
  6034. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6035. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6036. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6037. begin
  6038. Result := False;
  6039. if taicpu(p).oper[0]^.typ <> top_const then
  6040. { Should have been confirmed before calling }
  6041. InternalError(2021102601);
  6042. SubInstr := (taicpu(p).opcode = A_SUB);
  6043. if GetLastInstruction(p, hp1) and
  6044. (hp1.typ = ait_instruction) and
  6045. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6046. begin
  6047. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6048. { Bad size }
  6049. InternalError(2022042001);
  6050. case taicpu(hp1).opcode Of
  6051. A_INC:
  6052. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6053. begin
  6054. if SubInstr then
  6055. ThisConst := taicpu(p).oper[0]^.val - 1
  6056. else
  6057. ThisConst := taicpu(p).oper[0]^.val + 1;
  6058. end
  6059. else
  6060. Exit;
  6061. A_DEC:
  6062. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6063. begin
  6064. if SubInstr then
  6065. ThisConst := taicpu(p).oper[0]^.val + 1
  6066. else
  6067. ThisConst := taicpu(p).oper[0]^.val - 1;
  6068. end
  6069. else
  6070. Exit;
  6071. A_SUB:
  6072. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6073. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6074. begin
  6075. if SubInstr then
  6076. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6077. else
  6078. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6079. end
  6080. else
  6081. Exit;
  6082. A_ADD:
  6083. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6084. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6085. begin
  6086. if SubInstr then
  6087. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6088. else
  6089. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6090. end
  6091. else
  6092. Exit;
  6093. else
  6094. Exit;
  6095. end;
  6096. { Check that the values are in range }
  6097. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6098. { Overflow; abort }
  6099. Exit;
  6100. if (ThisConst = 0) then
  6101. begin
  6102. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6103. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6104. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6105. RemoveInstruction(hp1);
  6106. hp1 := tai(p.next);
  6107. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6108. if not GetLastInstruction(hp1, p) then
  6109. p := hp1;
  6110. end
  6111. else
  6112. begin
  6113. if taicpu(hp1).opercnt=1 then
  6114. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6115. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6116. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6117. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6118. else
  6119. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6120. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6121. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6122. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6123. RemoveInstruction(hp1);
  6124. taicpu(p).loadconst(0, ThisConst);
  6125. end;
  6126. Result := True;
  6127. end;
  6128. end;
  6129. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6130. begin
  6131. Result := False;
  6132. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6133. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6134. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6135. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6136. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6137. (
  6138. (
  6139. (taicpu(hp1).opcode = A_TEST)
  6140. ) or (
  6141. (taicpu(hp1).opcode = A_CMP) and
  6142. { A sanity check more than anything }
  6143. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6144. )
  6145. ) then
  6146. begin
  6147. { change
  6148. mov mem, %reg
  6149. ...
  6150. cmp/test x, %reg / test %reg,%reg
  6151. (reg deallocated)
  6152. to
  6153. cmp/test x, mem / cmp 0, mem
  6154. }
  6155. TransferUsedRegs(TmpUsedRegs);
  6156. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6157. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6158. begin
  6159. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6160. if (taicpu(hp1).opcode = A_TEST) and
  6161. (
  6162. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6163. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6164. ) then
  6165. begin
  6166. taicpu(hp1).opcode := A_CMP;
  6167. taicpu(hp1).loadconst(0, 0);
  6168. end;
  6169. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6170. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6171. RemoveCurrentP(p);
  6172. if (p <> hp1) then
  6173. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6174. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6175. { Make sure the flags are allocated across the CMP instruction }
  6176. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6177. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6178. Result := True;
  6179. Exit;
  6180. end;
  6181. end;
  6182. end;
  6183. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6184. var
  6185. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6186. ThisReg, SecondReg: TRegister;
  6187. JumpLoc: TAsmLabel;
  6188. NewSize: TOpSize;
  6189. begin
  6190. Result := False;
  6191. {
  6192. Convert:
  6193. j<c> .L1
  6194. .L2:
  6195. mov 1,reg
  6196. jmp .L3 (or ret, although it might not be a RET yet)
  6197. .L1:
  6198. mov 0,reg
  6199. jmp .L3 (or ret)
  6200. ( As long as .L3 <> .L1 or .L2)
  6201. To:
  6202. mov 0,reg
  6203. set<not(c)> reg
  6204. jmp .L3 (or ret)
  6205. .L2:
  6206. mov 1,reg
  6207. jmp .L3 (or ret)
  6208. .L1:
  6209. mov 0,reg
  6210. jmp .L3 (or ret)
  6211. }
  6212. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6213. Exit;
  6214. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6215. if GetNextInstruction(hp_label, hp2) and
  6216. MatchInstruction(hp2,A_MOV,[]) and
  6217. (taicpu(hp2).oper[0]^.typ = top_const) and
  6218. (
  6219. (
  6220. (taicpu(hp2).oper[1]^.typ = top_reg)
  6221. {$ifdef i386}
  6222. { Under i386, ESI, EDI, EBP and ESP
  6223. don't have an 8-bit representation }
  6224. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6225. {$endif i386}
  6226. ) or (
  6227. {$ifdef i386}
  6228. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6229. {$endif i386}
  6230. (taicpu(hp2).opsize = S_B)
  6231. )
  6232. ) and
  6233. GetNextInstruction(hp2, hp3) and
  6234. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6235. (
  6236. (taicpu(hp3).opcode=A_RET) or
  6237. (
  6238. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6239. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6240. )
  6241. ) and
  6242. GetNextInstruction(hp3, hp4) and
  6243. (hp4.typ=ait_label) and
  6244. (tai_label(hp4).labsym=JumpLoc) and
  6245. (
  6246. not (cs_opt_size in current_settings.optimizerswitches) or
  6247. { If the initial jump is the label's only reference, then it will
  6248. become a dead label if the other conditions are met and hence
  6249. remove at least 2 instructions, including a jump }
  6250. (JumpLoc.getrefs = 1)
  6251. ) and
  6252. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6253. that will be optimised out }
  6254. GetNextInstruction(hp4, hp5) and
  6255. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6256. (taicpu(hp5).oper[0]^.typ = top_const) and
  6257. (
  6258. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6259. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6260. ) and
  6261. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6262. GetNextInstruction(hp5,hp6) and
  6263. (
  6264. (hp6.typ<>ait_label) or
  6265. SkipLabels(hp6, hp6)
  6266. ) and
  6267. (hp6.typ=ait_instruction) then
  6268. begin
  6269. { First, let's look at the two jumps that are hp3 and hp6 }
  6270. if not
  6271. (
  6272. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6273. (
  6274. (taicpu(hp6).opcode=A_RET) or
  6275. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6276. )
  6277. ) then
  6278. { If condition is False, then the JMP/RET instructions matched conventionally }
  6279. begin
  6280. { See if one of the jumps can be instantly converted into a RET }
  6281. if (taicpu(hp3).opcode=A_JMP) then
  6282. begin
  6283. { Reuse hp5 }
  6284. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6285. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6286. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6287. Exit;
  6288. if MatchInstruction(hp5, A_RET, []) then
  6289. begin
  6290. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6291. ConvertJumpToRET(hp3, hp5);
  6292. Result := True;
  6293. end
  6294. else
  6295. Exit;
  6296. end;
  6297. if (taicpu(hp6).opcode=A_JMP) then
  6298. begin
  6299. { Reuse hp5 }
  6300. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6301. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6302. Exit;
  6303. if MatchInstruction(hp5, A_RET, []) then
  6304. begin
  6305. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6306. ConvertJumpToRET(hp6, hp5);
  6307. Result := True;
  6308. end
  6309. else
  6310. Exit;
  6311. end;
  6312. if not
  6313. (
  6314. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6315. (
  6316. (taicpu(hp6).opcode=A_RET) or
  6317. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6318. )
  6319. ) then
  6320. { Still doesn't match }
  6321. Exit;
  6322. end;
  6323. if (taicpu(hp2).oper[0]^.val = 1) then
  6324. begin
  6325. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6326. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6327. end
  6328. else
  6329. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6330. if taicpu(hp2).opsize=S_B then
  6331. begin
  6332. if taicpu(hp2).oper[1]^.typ = top_reg then
  6333. begin
  6334. SecondReg := taicpu(hp2).oper[1]^.reg;
  6335. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6336. end
  6337. else
  6338. begin
  6339. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6340. SecondReg := NR_NO;
  6341. end;
  6342. hp_pos := p;
  6343. hp_allocstart := hp4;
  6344. end
  6345. else
  6346. begin
  6347. { Will be a register because the size can't be S_B otherwise }
  6348. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6349. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6350. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6351. if (cs_opt_size in current_settings.optimizerswitches) then
  6352. begin
  6353. { Favour using MOVZX when optimising for size }
  6354. case taicpu(hp2).opsize of
  6355. S_W:
  6356. NewSize := S_BW;
  6357. S_L:
  6358. NewSize := S_BL;
  6359. {$ifdef x86_64}
  6360. S_Q:
  6361. begin
  6362. NewSize := S_BL;
  6363. { Will implicitly zero-extend to 64-bit }
  6364. setsubreg(SecondReg, R_SUBD);
  6365. end;
  6366. {$endif x86_64}
  6367. else
  6368. InternalError(2022101301);
  6369. end;
  6370. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6371. { Inserting it right before p will guarantee that the flags are also tracked }
  6372. Asml.InsertBefore(hp5, p);
  6373. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6374. hp_pos := hp5;
  6375. hp_allocstart := hp4;
  6376. end
  6377. else
  6378. begin
  6379. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6380. { Inserting it right before p will guarantee that the flags are also tracked }
  6381. Asml.InsertBefore(hp5, p);
  6382. hp_pos := p;
  6383. hp_allocstart := hp5;
  6384. end;
  6385. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6386. end;
  6387. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6388. taicpu(hp4).condition := taicpu(p).condition;
  6389. asml.InsertBefore(hp4, hp_pos);
  6390. if taicpu(hp3).is_jmp then
  6391. begin
  6392. JumpLoc.decrefs;
  6393. MakeUnconditional(taicpu(p));
  6394. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6395. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6396. end
  6397. else
  6398. ConvertJumpToRET(p, hp3);
  6399. if SecondReg <> NR_NO then
  6400. { Ensure the destination register is allocated over this region }
  6401. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6402. if (JumpLoc.getrefs = 0) then
  6403. RemoveDeadCodeAfterJump(hp3);
  6404. Result:=true;
  6405. exit;
  6406. end;
  6407. end;
  6408. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6409. var
  6410. hp1, hp2: tai;
  6411. ActiveReg: TRegister;
  6412. OldOffset: asizeint;
  6413. ThisConst: TCGInt;
  6414. function RegDeallocated: Boolean;
  6415. begin
  6416. TransferUsedRegs(TmpUsedRegs);
  6417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6418. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6419. end;
  6420. begin
  6421. Result:=false;
  6422. hp1 := nil;
  6423. { replace
  6424. subX const,%reg1
  6425. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6426. dealloc %reg1
  6427. by
  6428. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6429. }
  6430. if MatchOpType(taicpu(p),top_const,top_reg) then
  6431. begin
  6432. ActiveReg := taicpu(p).oper[1]^.reg;
  6433. { Ensures the entire register was updated }
  6434. if (taicpu(p).opsize >= S_L) and
  6435. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6436. MatchInstruction(hp1,A_LEA,[]) and
  6437. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6438. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6439. (
  6440. { Cover the case where the register in the reference is also the destination register }
  6441. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6442. (
  6443. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6444. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6445. RegDeallocated
  6446. )
  6447. ) then
  6448. begin
  6449. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6450. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6451. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6452. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6453. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6454. {$ifdef x86_64}
  6455. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6456. begin
  6457. { Overflow; abort }
  6458. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6459. end
  6460. else
  6461. {$endif x86_64}
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6464. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6465. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6466. RemoveCurrentP(p, hp1)
  6467. else
  6468. RemoveCurrentP(p);
  6469. result:=true;
  6470. Exit;
  6471. end;
  6472. end;
  6473. if (
  6474. { Save calling GetNextInstructionUsingReg again }
  6475. Assigned(hp1) or
  6476. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6477. ) and
  6478. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6479. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6480. begin
  6481. if taicpu(hp1).oper[0]^.typ = top_const then
  6482. begin
  6483. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6484. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6485. Result := True;
  6486. { Handle any overflows }
  6487. case taicpu(p).opsize of
  6488. S_B:
  6489. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6490. S_W:
  6491. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6492. S_L:
  6493. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6494. {$ifdef x86_64}
  6495. S_Q:
  6496. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6497. { Overflow; abort }
  6498. Result := False
  6499. else
  6500. taicpu(p).oper[0]^.val := ThisConst;
  6501. {$endif x86_64}
  6502. else
  6503. InternalError(2021102611);
  6504. end;
  6505. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6506. if Result then
  6507. begin
  6508. if (taicpu(p).oper[0]^.val < 0) and
  6509. (
  6510. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6511. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6512. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6513. ) then
  6514. begin
  6515. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6516. taicpu(p).opcode := A_SUB;
  6517. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6518. end
  6519. else
  6520. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6521. RemoveInstruction(hp1);
  6522. end;
  6523. end
  6524. else
  6525. begin
  6526. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6527. TransferUsedRegs(TmpUsedRegs);
  6528. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6529. hp2 := p;
  6530. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6531. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6532. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6533. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6534. begin
  6535. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6536. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6537. Asml.Remove(p);
  6538. Asml.InsertAfter(p, hp1);
  6539. p := hp1;
  6540. Result := True;
  6541. Exit;
  6542. end;
  6543. end;
  6544. end;
  6545. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6546. { * change "sub/add const1, reg" or "dec reg" followed by
  6547. "sub const2, reg" to one "sub ..., reg" }
  6548. {$ifdef i386}
  6549. if (taicpu(p).oper[0]^.val = 2) and
  6550. (ActiveReg = NR_ESP) and
  6551. { Don't do the sub/push optimization if the sub }
  6552. { comes from setting up the stack frame (JM) }
  6553. (not(GetLastInstruction(p,hp1)) or
  6554. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6555. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6556. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6557. begin
  6558. hp1 := tai(p.next);
  6559. while Assigned(hp1) and
  6560. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6561. not RegReadByInstruction(NR_ESP,hp1) and
  6562. not RegModifiedByInstruction(NR_ESP,hp1) do
  6563. hp1 := tai(hp1.next);
  6564. if Assigned(hp1) and
  6565. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6566. begin
  6567. taicpu(hp1).changeopsize(S_L);
  6568. if taicpu(hp1).oper[0]^.typ=top_reg then
  6569. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6570. hp1 := tai(p.next);
  6571. RemoveCurrentp(p, hp1);
  6572. Result:=true;
  6573. exit;
  6574. end;
  6575. end;
  6576. {$endif i386}
  6577. if DoArithCombineOpt(p) then
  6578. Result:=true;
  6579. end;
  6580. end;
  6581. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6582. var
  6583. TmpBool1,TmpBool2 : Boolean;
  6584. tmpref : treference;
  6585. hp1,hp2: tai;
  6586. mask, shiftval: tcgint;
  6587. begin
  6588. Result:=false;
  6589. { All these optimisations work on "shl/sal const,%reg" }
  6590. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6591. Exit;
  6592. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6593. (taicpu(p).oper[0]^.val <= 3) then
  6594. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6595. begin
  6596. { should we check the next instruction? }
  6597. TmpBool1 := True;
  6598. { have we found an add/sub which could be
  6599. integrated in the lea? }
  6600. TmpBool2 := False;
  6601. reference_reset(tmpref,2,[]);
  6602. TmpRef.index := taicpu(p).oper[1]^.reg;
  6603. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6604. while TmpBool1 and
  6605. GetNextInstruction(p, hp1) and
  6606. (tai(hp1).typ = ait_instruction) and
  6607. ((((taicpu(hp1).opcode = A_ADD) or
  6608. (taicpu(hp1).opcode = A_SUB)) and
  6609. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6610. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6611. (((taicpu(hp1).opcode = A_INC) or
  6612. (taicpu(hp1).opcode = A_DEC)) and
  6613. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6614. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6615. ((taicpu(hp1).opcode = A_LEA) and
  6616. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6617. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6618. (not GetNextInstruction(hp1,hp2) or
  6619. not instrReadsFlags(hp2)) Do
  6620. begin
  6621. TmpBool1 := False;
  6622. if taicpu(hp1).opcode=A_LEA then
  6623. begin
  6624. if (TmpRef.base = NR_NO) and
  6625. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6626. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6627. { Segment register isn't a concern here }
  6628. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6629. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6630. begin
  6631. TmpBool1 := True;
  6632. TmpBool2 := True;
  6633. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6634. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6635. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6636. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6637. RemoveInstruction(hp1);
  6638. end
  6639. end
  6640. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6641. begin
  6642. TmpBool1 := True;
  6643. TmpBool2 := True;
  6644. case taicpu(hp1).opcode of
  6645. A_ADD:
  6646. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6647. A_SUB:
  6648. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6649. else
  6650. internalerror(2019050536);
  6651. end;
  6652. RemoveInstruction(hp1);
  6653. end
  6654. else
  6655. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6656. (((taicpu(hp1).opcode = A_ADD) and
  6657. (TmpRef.base = NR_NO)) or
  6658. (taicpu(hp1).opcode = A_INC) or
  6659. (taicpu(hp1).opcode = A_DEC)) then
  6660. begin
  6661. TmpBool1 := True;
  6662. TmpBool2 := True;
  6663. case taicpu(hp1).opcode of
  6664. A_ADD:
  6665. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6666. A_INC:
  6667. inc(TmpRef.offset);
  6668. A_DEC:
  6669. dec(TmpRef.offset);
  6670. else
  6671. internalerror(2019050535);
  6672. end;
  6673. RemoveInstruction(hp1);
  6674. end;
  6675. end;
  6676. if TmpBool2
  6677. {$ifndef x86_64}
  6678. or
  6679. ((current_settings.optimizecputype < cpu_Pentium2) and
  6680. (taicpu(p).oper[0]^.val <= 3) and
  6681. not(cs_opt_size in current_settings.optimizerswitches))
  6682. {$endif x86_64}
  6683. then
  6684. begin
  6685. if not(TmpBool2) and
  6686. (taicpu(p).oper[0]^.val=1) then
  6687. begin
  6688. taicpu(p).opcode := A_ADD;
  6689. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6690. end
  6691. else
  6692. begin
  6693. taicpu(p).opcode := A_LEA;
  6694. taicpu(p).loadref(0, TmpRef);
  6695. end;
  6696. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6697. Result := True;
  6698. end;
  6699. end
  6700. {$ifndef x86_64}
  6701. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6702. begin
  6703. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6704. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6705. (unlike shl, which is only Tairable in the U pipe) }
  6706. if taicpu(p).oper[0]^.val=1 then
  6707. begin
  6708. taicpu(p).opcode := A_ADD;
  6709. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6710. Result := True;
  6711. end
  6712. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6713. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6714. else if (taicpu(p).opsize = S_L) and
  6715. (taicpu(p).oper[0]^.val<= 3) then
  6716. begin
  6717. reference_reset(tmpref,2,[]);
  6718. TmpRef.index := taicpu(p).oper[1]^.reg;
  6719. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6720. taicpu(p).opcode := A_LEA;
  6721. taicpu(p).loadref(0, TmpRef);
  6722. Result := True;
  6723. end;
  6724. end
  6725. {$endif x86_64}
  6726. else if
  6727. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6728. (
  6729. (
  6730. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6731. SetAndTest(hp1, hp2)
  6732. {$ifdef x86_64}
  6733. ) or
  6734. (
  6735. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6736. GetNextInstruction(hp1, hp2) and
  6737. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6738. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6739. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6740. {$endif x86_64}
  6741. )
  6742. ) and
  6743. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6744. begin
  6745. { Change:
  6746. shl x, %reg1
  6747. mov -(1<<x), %reg2
  6748. and %reg2, %reg1
  6749. Or:
  6750. shl x, %reg1
  6751. and -(1<<x), %reg1
  6752. To just:
  6753. shl x, %reg1
  6754. Since the and operation only zeroes bits that are already zero from the shl operation
  6755. }
  6756. case taicpu(p).oper[0]^.val of
  6757. 8:
  6758. mask:=$FFFFFFFFFFFFFF00;
  6759. 16:
  6760. mask:=$FFFFFFFFFFFF0000;
  6761. 32:
  6762. mask:=$FFFFFFFF00000000;
  6763. 63:
  6764. { Constant pre-calculated to prevent overflow errors with Int64 }
  6765. mask:=$8000000000000000;
  6766. else
  6767. begin
  6768. if taicpu(p).oper[0]^.val >= 64 then
  6769. { Shouldn't happen realistically, since the register
  6770. is guaranteed to be set to zero at this point }
  6771. mask := 0
  6772. else
  6773. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6774. end;
  6775. end;
  6776. if taicpu(hp1).oper[0]^.val = mask then
  6777. begin
  6778. { Everything checks out, perform the optimisation, as long as
  6779. the FLAGS register isn't being used}
  6780. TransferUsedRegs(TmpUsedRegs);
  6781. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6782. {$ifdef x86_64}
  6783. if (hp1 <> hp2) then
  6784. begin
  6785. { "shl/mov/and" version }
  6786. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6787. { Don't do the optimisation if the FLAGS register is in use }
  6788. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6789. begin
  6790. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6791. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6792. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6793. begin
  6794. RemoveInstruction(hp1);
  6795. Result := True;
  6796. end;
  6797. { Only set Result to True if the 'mov' instruction was removed }
  6798. RemoveInstruction(hp2);
  6799. end;
  6800. end
  6801. else
  6802. {$endif x86_64}
  6803. begin
  6804. { "shl/and" version }
  6805. { Don't do the optimisation if the FLAGS register is in use }
  6806. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6807. begin
  6808. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6809. RemoveInstruction(hp1);
  6810. Result := True;
  6811. end;
  6812. end;
  6813. Exit;
  6814. end
  6815. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6816. begin
  6817. { Even if the mask doesn't allow for its removal, we might be
  6818. able to optimise the mask for the "shl/and" version, which
  6819. may permit other peephole optimisations }
  6820. {$ifdef DEBUG_AOPTCPU}
  6821. mask := taicpu(hp1).oper[0]^.val and mask;
  6822. if taicpu(hp1).oper[0]^.val <> mask then
  6823. begin
  6824. DebugMsg(
  6825. SPeepholeOptimization +
  6826. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6827. ' to $' + debug_tostr(mask) +
  6828. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6829. taicpu(hp1).oper[0]^.val := mask;
  6830. end;
  6831. {$else DEBUG_AOPTCPU}
  6832. { If debugging is off, just set the operand even if it's the same }
  6833. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6834. {$endif DEBUG_AOPTCPU}
  6835. end;
  6836. end;
  6837. {
  6838. change
  6839. shl/sal const,reg
  6840. <op> ...(...,reg,1),...
  6841. into
  6842. <op> ...(...,reg,1 shl const),...
  6843. if const in 1..3
  6844. }
  6845. if MatchOpType(taicpu(p), top_const, top_reg) and
  6846. (taicpu(p).oper[0]^.val in [1..3]) and
  6847. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6848. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6849. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6850. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6851. MatchOpType(taicpu(hp1),top_ref))
  6852. ) and
  6853. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6854. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6855. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6856. begin
  6857. TransferUsedRegs(TmpUsedRegs);
  6858. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6859. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6860. begin
  6861. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6862. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6863. RemoveCurrentP(p);
  6864. Result:=true;
  6865. exit;
  6866. end;
  6867. end;
  6868. if MatchOpType(taicpu(p), top_const, top_reg) and
  6869. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6870. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6871. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6872. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6873. begin
  6874. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6875. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6876. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6877. {$ifdef x86_64}
  6878. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6879. {$endif x86_64}
  6880. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6881. begin
  6882. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6883. taicpu(hp1).opcode:=A_MOV;
  6884. taicpu(hp1).oper[0]^.val:=0;
  6885. end
  6886. else
  6887. begin
  6888. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6889. taicpu(hp1).oper[0]^.val:=shiftval;
  6890. end;
  6891. RemoveCurrentP(p);
  6892. Result:=true;
  6893. exit;
  6894. end;
  6895. end;
  6896. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6897. begin
  6898. case shr_size of
  6899. S_B:
  6900. { No valid combinations }
  6901. Result := False;
  6902. S_W:
  6903. Result := (Shift >= 8) and (movz_size = S_BW);
  6904. S_L:
  6905. Result :=
  6906. (Shift >= 24) { Any opsize is valid for this shift } or
  6907. ((Shift >= 16) and (movz_size = S_WL));
  6908. {$ifdef x86_64}
  6909. S_Q:
  6910. Result :=
  6911. (Shift >= 56) { Any opsize is valid for this shift } or
  6912. ((Shift >= 48) and (movz_size = S_WL));
  6913. {$endif x86_64}
  6914. else
  6915. InternalError(2022081510);
  6916. end;
  6917. end;
  6918. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6919. var
  6920. hp1, hp2: tai;
  6921. Shift: TCGInt;
  6922. LimitSize: Topsize;
  6923. DoNotMerge: Boolean;
  6924. begin
  6925. Result := False;
  6926. { All these optimisations work on "shr const,%reg" }
  6927. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6928. Exit;
  6929. DoNotMerge := False;
  6930. Shift := taicpu(p).oper[0]^.val;
  6931. LimitSize := taicpu(p).opsize;
  6932. hp1 := p;
  6933. repeat
  6934. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6935. Exit;
  6936. case taicpu(hp1).opcode of
  6937. A_TEST, A_CMP, A_Jcc:
  6938. { Skip over conditional jumps and relevant comparisons }
  6939. Continue;
  6940. A_MOVZX:
  6941. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6942. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6943. begin
  6944. { Since the original register is being read as is, subsequent
  6945. SHRs must not be merged at this point }
  6946. DoNotMerge := True;
  6947. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6948. begin
  6949. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6950. begin
  6951. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6952. taicpu(hp1).opcode := A_MOV;
  6953. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6954. case taicpu(hp1).opsize of
  6955. S_BW:
  6956. taicpu(hp1).opsize := S_W;
  6957. S_BL, S_WL:
  6958. taicpu(hp1).opsize := S_L;
  6959. else
  6960. InternalError(2022081503);
  6961. end;
  6962. { p itself hasn't changed, so no need to set Result to True }
  6963. Include(OptsToCheck, aoc_ForceNewIteration);
  6964. { See if there's anything afterwards that can be
  6965. optimised, since the input register hasn't changed }
  6966. Continue;
  6967. end;
  6968. { NOTE: If the MOVZX instruction reads and writes the same
  6969. register, defer this to the post-peephole optimisation stage }
  6970. Exit;
  6971. end;
  6972. end;
  6973. A_SHL, A_SAL, A_SHR:
  6974. if (taicpu(hp1).opsize <= LimitSize) and
  6975. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6976. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6977. begin
  6978. { Make sure the sizes don't exceed the register size limit
  6979. (measured by the shift value falling below the limit) }
  6980. if taicpu(hp1).opsize < LimitSize then
  6981. LimitSize := taicpu(hp1).opsize;
  6982. if taicpu(hp1).opcode = A_SHR then
  6983. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6984. else
  6985. begin
  6986. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6987. DoNotMerge := True;
  6988. end;
  6989. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6990. Exit;
  6991. { Since we've established that the combined shift is within
  6992. limits, we can actually combine the adjacent SHR
  6993. instructions even if they're different sizes }
  6994. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6995. begin
  6996. hp2 := tai(hp1.Previous);
  6997. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6998. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6999. RemoveInstruction(hp1);
  7000. hp1 := hp2;
  7001. { Though p has changed, only the constant has, and its
  7002. effects can still be detected on the next iteration of
  7003. the repeat..until loop }
  7004. Include(OptsToCheck, aoc_ForceNewIteration);
  7005. end;
  7006. { Move onto the next instruction }
  7007. Continue;
  7008. end;
  7009. else
  7010. ;
  7011. end;
  7012. Break;
  7013. until False;
  7014. end;
  7015. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7016. var
  7017. CurrentRef: TReference;
  7018. FullReg: TRegister;
  7019. hp1, hp2: tai;
  7020. begin
  7021. Result := False;
  7022. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7023. Exit;
  7024. { We assume you've checked if the operand is actually a reference by
  7025. this point. If it isn't, you'll most likely get an access violation }
  7026. CurrentRef := first_mov.oper[1]^.ref^;
  7027. { Memory must be aligned }
  7028. if (CurrentRef.offset mod 4) <> 0 then
  7029. Exit;
  7030. Inc(CurrentRef.offset);
  7031. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7032. if MatchOperand(second_mov.oper[0]^, 0) and
  7033. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7034. GetNextInstruction(second_mov, hp1) and
  7035. (hp1.typ = ait_instruction) and
  7036. (taicpu(hp1).opcode = A_MOV) and
  7037. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7038. (taicpu(hp1).oper[0]^.val = 0) then
  7039. begin
  7040. Inc(CurrentRef.offset);
  7041. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7042. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7043. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7044. begin
  7045. case taicpu(hp1).opsize of
  7046. S_B:
  7047. if GetNextInstruction(hp1, hp2) and
  7048. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7049. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7050. (taicpu(hp2).oper[0]^.val = 0) then
  7051. begin
  7052. Inc(CurrentRef.offset);
  7053. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7054. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7055. (taicpu(hp2).opsize = S_B) then
  7056. begin
  7057. RemoveInstruction(hp1);
  7058. RemoveInstruction(hp2);
  7059. first_mov.opsize := S_L;
  7060. if first_mov.oper[0]^.typ = top_reg then
  7061. begin
  7062. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7063. { Reuse second_mov as a MOVZX instruction }
  7064. second_mov.opcode := A_MOVZX;
  7065. second_mov.opsize := S_BL;
  7066. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7067. second_mov.loadreg(1, FullReg);
  7068. first_mov.oper[0]^.reg := FullReg;
  7069. asml.Remove(second_mov);
  7070. asml.InsertBefore(second_mov, first_mov);
  7071. end
  7072. else
  7073. { It's a value }
  7074. begin
  7075. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7076. RemoveInstruction(second_mov);
  7077. end;
  7078. Result := True;
  7079. Exit;
  7080. end;
  7081. end;
  7082. S_W:
  7083. begin
  7084. RemoveInstruction(hp1);
  7085. first_mov.opsize := S_L;
  7086. if first_mov.oper[0]^.typ = top_reg then
  7087. begin
  7088. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7089. { Reuse second_mov as a MOVZX instruction }
  7090. second_mov.opcode := A_MOVZX;
  7091. second_mov.opsize := S_BL;
  7092. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7093. second_mov.loadreg(1, FullReg);
  7094. first_mov.oper[0]^.reg := FullReg;
  7095. asml.Remove(second_mov);
  7096. asml.InsertBefore(second_mov, first_mov);
  7097. end
  7098. else
  7099. { It's a value }
  7100. begin
  7101. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7102. RemoveInstruction(second_mov);
  7103. end;
  7104. Result := True;
  7105. Exit;
  7106. end;
  7107. else
  7108. ;
  7109. end;
  7110. end;
  7111. end;
  7112. end;
  7113. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7114. { returns true if a "continue" should be done after this optimization }
  7115. var
  7116. hp1, hp2, hp3: tai;
  7117. begin
  7118. Result := false;
  7119. hp3 := nil;
  7120. if MatchOpType(taicpu(p),top_ref) and
  7121. GetNextInstruction(p, hp1) and
  7122. (hp1.typ = ait_instruction) and
  7123. (((taicpu(hp1).opcode = A_FLD) and
  7124. (taicpu(p).opcode = A_FSTP)) or
  7125. ((taicpu(p).opcode = A_FISTP) and
  7126. (taicpu(hp1).opcode = A_FILD))) and
  7127. MatchOpType(taicpu(hp1),top_ref) and
  7128. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7129. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7130. begin
  7131. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7132. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7133. GetNextInstruction(hp1, hp2) and
  7134. (((hp2.typ = ait_instruction) and
  7135. IsExitCode(hp2) and
  7136. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7137. not(assigned(current_procinfo.procdef.funcretsym) and
  7138. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7139. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7140. { fstp <temp>
  7141. fld <temp>
  7142. <dealloc> <temp>
  7143. }
  7144. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7145. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7146. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7147. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7148. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7149. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7150. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7151. )
  7152. )
  7153. ) then
  7154. begin
  7155. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7156. RemoveInstruction(hp1);
  7157. RemoveCurrentP(p, hp2);
  7158. { first case: exit code }
  7159. if hp2.typ = ait_instruction then
  7160. RemoveLastDeallocForFuncRes(p);
  7161. Result := true;
  7162. end
  7163. else
  7164. { we can do this only in fast math mode as fstp is rounding ...
  7165. ... still disabled as it breaks the compiler and/or rtl }
  7166. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7167. { ... or if another fstp equal to the first one follows }
  7168. GetNextInstruction(hp1,hp2) and
  7169. (hp2.typ = ait_instruction) and
  7170. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7171. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7172. begin
  7173. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7174. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7175. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7176. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7177. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7178. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7179. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7180. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7181. ) then
  7182. begin
  7183. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7184. RemoveCurrentP(p,hp2);
  7185. RemoveInstruction(hp1);
  7186. Result := true;
  7187. end
  7188. else if { fst can't store an extended/comp value }
  7189. (taicpu(p).opsize <> S_FX) and
  7190. (taicpu(p).opsize <> S_IQ) then
  7191. begin
  7192. if (taicpu(p).opcode = A_FSTP) then
  7193. taicpu(p).opcode := A_FST
  7194. else
  7195. taicpu(p).opcode := A_FIST;
  7196. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7197. RemoveInstruction(hp1);
  7198. Result := true;
  7199. end;
  7200. end;
  7201. end;
  7202. end;
  7203. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7204. var
  7205. hp1, hp2, hp3: tai;
  7206. begin
  7207. result:=false;
  7208. if MatchOpType(taicpu(p),top_reg) and
  7209. GetNextInstruction(p, hp1) and
  7210. (hp1.typ = Ait_Instruction) and
  7211. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7212. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7213. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7214. { change to
  7215. fld reg fxxx reg,st
  7216. fxxxp st, st1 (hp1)
  7217. Remark: non commutative operations must be reversed!
  7218. }
  7219. begin
  7220. case taicpu(hp1).opcode Of
  7221. A_FMULP,A_FADDP,
  7222. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7223. begin
  7224. case taicpu(hp1).opcode Of
  7225. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7226. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7227. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7228. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7229. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7230. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7231. else
  7232. internalerror(2019050534);
  7233. end;
  7234. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7235. taicpu(hp1).oper[1]^.reg := NR_ST;
  7236. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7237. RemoveCurrentP(p, hp1);
  7238. Result:=true;
  7239. exit;
  7240. end;
  7241. else
  7242. ;
  7243. end;
  7244. end
  7245. else
  7246. if MatchOpType(taicpu(p),top_ref) and
  7247. GetNextInstruction(p, hp2) and
  7248. (hp2.typ = Ait_Instruction) and
  7249. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7250. (taicpu(p).opsize in [S_FS, S_FL]) and
  7251. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7252. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7253. if GetLastInstruction(p, hp1) and
  7254. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7255. MatchOpType(taicpu(hp1),top_ref) and
  7256. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7257. if ((taicpu(hp2).opcode = A_FMULP) or
  7258. (taicpu(hp2).opcode = A_FADDP)) then
  7259. { change to
  7260. fld/fst mem1 (hp1) fld/fst mem1
  7261. fld mem1 (p) fadd/
  7262. faddp/ fmul st, st
  7263. fmulp st, st1 (hp2) }
  7264. begin
  7265. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7266. RemoveCurrentP(p, hp1);
  7267. if (taicpu(hp2).opcode = A_FADDP) then
  7268. taicpu(hp2).opcode := A_FADD
  7269. else
  7270. taicpu(hp2).opcode := A_FMUL;
  7271. taicpu(hp2).oper[1]^.reg := NR_ST;
  7272. end
  7273. else
  7274. { change to
  7275. fld/fst mem1 (hp1) fld/fst mem1
  7276. fld mem1 (p) fld st
  7277. }
  7278. begin
  7279. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7280. taicpu(p).changeopsize(S_FL);
  7281. taicpu(p).loadreg(0,NR_ST);
  7282. end
  7283. else
  7284. begin
  7285. case taicpu(hp2).opcode Of
  7286. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7287. { change to
  7288. fld/fst mem1 (hp1) fld/fst mem1
  7289. fld mem2 (p) fxxx mem2
  7290. fxxxp st, st1 (hp2) }
  7291. begin
  7292. case taicpu(hp2).opcode Of
  7293. A_FADDP: taicpu(p).opcode := A_FADD;
  7294. A_FMULP: taicpu(p).opcode := A_FMUL;
  7295. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7296. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7297. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7298. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7299. else
  7300. internalerror(2019050533);
  7301. end;
  7302. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7303. RemoveInstruction(hp2);
  7304. end
  7305. else
  7306. ;
  7307. end
  7308. end
  7309. end;
  7310. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7311. begin
  7312. Result := condition_in(cond1, cond2) or
  7313. { Not strictly subsets due to the actual flags checked, but because we're
  7314. comparing integers, E is a subset of AE and GE and their aliases }
  7315. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7316. end;
  7317. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7318. var
  7319. v: TCGInt;
  7320. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7321. FirstMatch, TempBool: Boolean;
  7322. NewReg: TRegister;
  7323. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7324. begin
  7325. Result:=false;
  7326. { All these optimisations need a next instruction }
  7327. if not GetNextInstruction(p, hp1) then
  7328. Exit;
  7329. true_hp1 := hp1;
  7330. { Search for:
  7331. cmp ###,###
  7332. j(c1) @lbl1
  7333. ...
  7334. @lbl:
  7335. cmp ###,### (same comparison as above)
  7336. j(c2) @lbl2
  7337. If c1 is a subset of c2, change to:
  7338. cmp ###,###
  7339. j(c1) @lbl2
  7340. (@lbl1 may become a dead label as a result)
  7341. }
  7342. { Also handle cases where there are multiple jumps in a row }
  7343. p_jump := hp1;
  7344. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7345. begin
  7346. Prefetch(p_jump.Next);
  7347. if IsJumpToLabel(taicpu(p_jump)) then
  7348. begin
  7349. { Do jump optimisations first in case the condition becomes
  7350. unnecessary }
  7351. TempBool := True;
  7352. if DoJumpOptimizations(p_jump, TempBool) or
  7353. not TempBool then
  7354. begin
  7355. if Assigned(p_jump) then
  7356. begin
  7357. { CollapseZeroDistJump will be set to the label or an align
  7358. before it after the jump if it optimises, whether or not
  7359. the label is live or dead }
  7360. if (p_jump.typ = ait_align) or
  7361. (
  7362. (p_jump.typ = ait_label) and
  7363. not (tai_label(p_jump).labsym.is_used)
  7364. ) then
  7365. GetNextInstruction(p_jump, p_jump);
  7366. end;
  7367. TransferUsedRegs(TmpUsedRegs);
  7368. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7369. if not Assigned(p_jump) or
  7370. (
  7371. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7372. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7373. ) then
  7374. begin
  7375. { No more conditional jumps; conditional statement is no longer required }
  7376. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7377. RemoveCurrentP(p);
  7378. Result := True;
  7379. Exit;
  7380. end;
  7381. hp1 := p_jump;
  7382. Include(OptsToCheck, aoc_ForceNewIteration);
  7383. Continue;
  7384. end;
  7385. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7386. if GetNextInstruction(p_jump, hp2) and
  7387. (
  7388. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7389. not TempBool
  7390. ) then
  7391. begin
  7392. hp1 := p_jump;
  7393. Include(OptsToCheck, aoc_ForceNewIteration);
  7394. Continue;
  7395. end;
  7396. p_label := nil;
  7397. if Assigned(JumpLabel) then
  7398. p_label := getlabelwithsym(JumpLabel);
  7399. if Assigned(p_label) and
  7400. GetNextInstruction(p_label, p_dist) and
  7401. MatchInstruction(p_dist, A_CMP, []) and
  7402. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7403. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7404. GetNextInstruction(p_dist, hp1_dist) and
  7405. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7406. begin
  7407. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7408. if JumpLabel = JumpLabel_dist then
  7409. { This is an infinite loop }
  7410. Exit;
  7411. { Best optimisation when the first condition is a subset (or equal) of the second }
  7412. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7413. begin
  7414. { Any registers used here will already be allocated }
  7415. if Assigned(JumpLabel) then
  7416. JumpLabel.DecRefs;
  7417. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7418. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7419. Include(OptsToCheck, aoc_ForceNewIteration);
  7420. { Don't exit yet. Since p and p_jump haven't actually been
  7421. removed, we can check for more on this iteration }
  7422. end
  7423. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7424. GetNextInstruction(hp1_dist, hp1_label) and
  7425. (hp1_label.typ = ait_label) then
  7426. begin
  7427. JumpLabel_far := tai_label(hp1_label).labsym;
  7428. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7429. { This is an infinite loop }
  7430. Exit;
  7431. if Assigned(JumpLabel_far) then
  7432. begin
  7433. { In this situation, if the first jump branches, the second one will never,
  7434. branch so change the destination label to after the second jump }
  7435. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7436. if Assigned(JumpLabel) then
  7437. JumpLabel.DecRefs;
  7438. JumpLabel_far.IncRefs;
  7439. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7440. Result := True;
  7441. { Don't exit yet. Since p and p_jump haven't actually been
  7442. removed, we can check for more on this iteration }
  7443. Continue;
  7444. end;
  7445. end;
  7446. end;
  7447. end;
  7448. { Search for:
  7449. cmp ###,###
  7450. j(c1) @lbl1
  7451. cmp ###,### (same as first)
  7452. Remove second cmp
  7453. }
  7454. if GetNextInstruction(p_jump, hp2) and
  7455. (
  7456. (
  7457. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7458. (
  7459. (
  7460. MatchOpType(taicpu(p), top_const, top_reg) and
  7461. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7462. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7463. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7464. ) or (
  7465. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7466. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7467. )
  7468. )
  7469. ) or (
  7470. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7471. MatchOperand(taicpu(p).oper[0]^, 0) and
  7472. (taicpu(p).oper[1]^.typ = top_reg) and
  7473. MatchInstruction(hp2, A_TEST, []) and
  7474. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7475. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7476. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7477. )
  7478. ) then
  7479. begin
  7480. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7481. TransferUsedRegs(TmpUsedRegs);
  7482. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7483. RemoveInstruction(hp2);
  7484. Result := True;
  7485. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7486. end
  7487. else
  7488. begin
  7489. { hp2 is the next instruction, so save time and just set p_jump
  7490. to it instead of calling GetNextInstruction below }
  7491. p_jump := hp2;
  7492. Continue;
  7493. end;
  7494. GetNextInstruction(p_jump, p_jump);
  7495. end;
  7496. if (
  7497. { Don't call GetNextInstruction again if we already have it }
  7498. (true_hp1 = p_jump) or
  7499. GetNextInstruction(p, hp1)
  7500. ) and
  7501. MatchInstruction(hp1, A_Jcc, []) and
  7502. IsJumpToLabel(taicpu(hp1)) and
  7503. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7504. GetNextInstruction(hp1, hp2) then
  7505. begin
  7506. {
  7507. cmp x, y (or "cmp y, x")
  7508. je @lbl
  7509. mov x, y
  7510. @lbl:
  7511. (x and y can be constants, registers or references)
  7512. Change to:
  7513. mov x, y (x and y will always be equal in the end)
  7514. @lbl: (may beceome a dead label)
  7515. Also:
  7516. cmp x, y (or "cmp y, x")
  7517. jne @lbl
  7518. mov x, y
  7519. @lbl:
  7520. (x and y can be constants, registers or references)
  7521. Change to:
  7522. Absolutely nothing! (Except @lbl if it's still live)
  7523. }
  7524. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7525. (
  7526. (
  7527. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7528. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7529. ) or (
  7530. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7531. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7532. )
  7533. ) and
  7534. GetNextInstruction(hp2, hp1_label) and
  7535. (hp1_label.typ = ait_label) and
  7536. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7537. begin
  7538. tai_label(hp1_label).labsym.DecRefs;
  7539. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7540. begin
  7541. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7542. RemoveInstruction(hp2);
  7543. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7544. end
  7545. else
  7546. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7547. RemoveInstruction(hp1);
  7548. RemoveCurrentp(p, hp2);
  7549. Result := True;
  7550. Exit;
  7551. end;
  7552. {
  7553. Try to optimise the following:
  7554. cmp $x,### ($x and $y can be registers or constants)
  7555. je @lbl1 (only reference)
  7556. cmp $y,### (### are identical)
  7557. @Lbl:
  7558. sete %reg1
  7559. Change to:
  7560. cmp $x,###
  7561. sete %reg2 (allocate new %reg2)
  7562. cmp $y,###
  7563. sete %reg1
  7564. orb %reg2,%reg1
  7565. (dealloc %reg2)
  7566. This adds an instruction (so don't perform under -Os), but it removes
  7567. a conditional branch.
  7568. }
  7569. if not (cs_opt_size in current_settings.optimizerswitches) and
  7570. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7571. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7572. { The first operand of CMP instructions can only be a register or
  7573. immediate anyway, so no need to check }
  7574. GetNextInstruction(hp2, p_label) and
  7575. (p_label.typ = ait_label) and
  7576. (tai_label(p_label).labsym.getrefs = 1) and
  7577. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7578. GetNextInstruction(p_label, p_dist) and
  7579. MatchInstruction(p_dist, A_SETcc, []) and
  7580. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7581. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7582. begin
  7583. TransferUsedRegs(TmpUsedRegs);
  7584. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7585. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7586. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7587. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7588. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7589. { Get the instruction after the SETcc instruction so we can
  7590. allocate a new register over the entire range }
  7591. GetNextInstruction(p_dist, hp1_dist) then
  7592. begin
  7593. { Register can appear in p if it's not used afterwards, so only
  7594. allocate between hp1 and hp1_dist }
  7595. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7596. if NewReg <> NR_NO then
  7597. begin
  7598. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7599. { Change the jump instruction into a SETcc instruction }
  7600. taicpu(hp1).opcode := A_SETcc;
  7601. taicpu(hp1).opsize := S_B;
  7602. taicpu(hp1).loadreg(0, NewReg);
  7603. { This is now a dead label }
  7604. tai_label(p_label).labsym.decrefs;
  7605. { Prefer adding before the next instruction so the FLAGS
  7606. register is deallicated first }
  7607. AsmL.InsertBefore(
  7608. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7609. hp1_dist
  7610. );
  7611. Result := True;
  7612. { Don't exit yet, as p wasn't changed and hp1, while
  7613. modified, is still intact and might be optimised by the
  7614. SETcc optimisation below }
  7615. end;
  7616. end;
  7617. end;
  7618. end;
  7619. if (taicpu(p).oper[0]^.typ = top_const) and
  7620. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7621. begin
  7622. if (taicpu(p).oper[0]^.val = 0) and
  7623. (taicpu(p).oper[1]^.typ = top_reg) then
  7624. begin
  7625. hp2 := p;
  7626. FirstMatch := True;
  7627. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7628. anything meaningful once it's converted to "test %reg,%reg";
  7629. additionally, some jumps will always (or never) branch, so
  7630. evaluate every jump immediately following the
  7631. comparison, optimising the conditions if possible.
  7632. Similarly with SETcc... those that are always set to 0 or 1
  7633. are changed to MOV instructions }
  7634. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7635. (
  7636. GetNextInstruction(hp2, hp1) and
  7637. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7638. ) do
  7639. begin
  7640. Prefetch(hp1.Next);
  7641. FirstMatch := False;
  7642. case taicpu(hp1).condition of
  7643. C_B, C_C, C_NAE, C_O:
  7644. { For B/NAE:
  7645. Will never branch since an unsigned integer can never be below zero
  7646. For C/O:
  7647. Result cannot overflow because 0 is being subtracted
  7648. }
  7649. begin
  7650. if taicpu(hp1).opcode = A_Jcc then
  7651. begin
  7652. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7653. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7654. RemoveInstruction(hp1);
  7655. { Since hp1 was deleted, hp2 must not be updated }
  7656. Continue;
  7657. end
  7658. else
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7661. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7662. taicpu(hp1).opcode := A_MOV;
  7663. taicpu(hp1).ops := 2;
  7664. taicpu(hp1).condition := C_None;
  7665. taicpu(hp1).opsize := S_B;
  7666. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7667. taicpu(hp1).loadconst(0, 0);
  7668. end;
  7669. end;
  7670. C_BE, C_NA:
  7671. begin
  7672. { Will only branch if equal to zero }
  7673. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7674. taicpu(hp1).condition := C_E;
  7675. end;
  7676. C_A, C_NBE:
  7677. begin
  7678. { Will only branch if not equal to zero }
  7679. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7680. taicpu(hp1).condition := C_NE;
  7681. end;
  7682. C_AE, C_NB, C_NC, C_NO:
  7683. begin
  7684. { Will always branch }
  7685. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7686. if taicpu(hp1).opcode = A_Jcc then
  7687. begin
  7688. MakeUnconditional(taicpu(hp1));
  7689. { Any jumps/set that follow will now be dead code }
  7690. RemoveDeadCodeAfterJump(taicpu(hp1));
  7691. Break;
  7692. end
  7693. else
  7694. begin
  7695. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7696. taicpu(hp1).opcode := A_MOV;
  7697. taicpu(hp1).ops := 2;
  7698. taicpu(hp1).condition := C_None;
  7699. taicpu(hp1).opsize := S_B;
  7700. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7701. taicpu(hp1).loadconst(0, 1);
  7702. end;
  7703. end;
  7704. C_None:
  7705. InternalError(2020012201);
  7706. C_P, C_PE, C_NP, C_PO:
  7707. { We can't handle parity checks and they should never be generated
  7708. after a general-purpose CMP (it's used in some floating-point
  7709. comparisons that don't use CMP) }
  7710. InternalError(2020012202);
  7711. else
  7712. { Zero/Equality, Sign, their complements and all of the
  7713. signed comparisons do not need to be converted };
  7714. end;
  7715. hp2 := hp1;
  7716. end;
  7717. { Convert the instruction to a TEST }
  7718. taicpu(p).opcode := A_TEST;
  7719. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7720. Result := True;
  7721. Exit;
  7722. end
  7723. else
  7724. begin
  7725. TransferUsedRegs(TmpUsedRegs);
  7726. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7727. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7728. begin
  7729. if (taicpu(p).oper[0]^.val = 1) and
  7730. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7731. begin
  7732. { Convert; To:
  7733. cmp $1,r/m cmp $0,r/m
  7734. jl @lbl jle @lbl
  7735. (Also do inverted conditions)
  7736. }
  7737. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7738. taicpu(p).oper[0]^.val := 0;
  7739. if taicpu(hp1).condition in [C_L, C_NGE] then
  7740. taicpu(hp1).condition := C_LE
  7741. else
  7742. taicpu(hp1).condition := C_NLE;
  7743. { If the instruction is now "cmp $0,%reg", convert it to a
  7744. TEST (and effectively do the work of the "cmp $0,%reg" in
  7745. the block above)
  7746. }
  7747. if (taicpu(p).oper[1]^.typ = top_reg) then
  7748. begin
  7749. taicpu(p).opcode := A_TEST;
  7750. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7751. end;
  7752. Result := True;
  7753. Exit;
  7754. end
  7755. else if (taicpu(p).oper[1]^.typ = top_reg)
  7756. {$ifdef x86_64}
  7757. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7758. {$endif x86_64}
  7759. then
  7760. begin
  7761. { cmp register,$8000 neg register
  7762. je target --> jo target
  7763. .... only if register is deallocated before jump.}
  7764. case Taicpu(p).opsize of
  7765. S_B: v:=$80;
  7766. S_W: v:=$8000;
  7767. S_L: v:=qword($80000000);
  7768. else
  7769. internalerror(2013112905);
  7770. end;
  7771. if (taicpu(p).oper[0]^.val=v) and
  7772. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7773. begin
  7774. TransferUsedRegs(TmpUsedRegs);
  7775. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7776. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7777. begin
  7778. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7779. Taicpu(p).opcode:=A_NEG;
  7780. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7781. Taicpu(p).clearop(1);
  7782. Taicpu(p).ops:=1;
  7783. if Taicpu(hp1).condition=C_E then
  7784. Taicpu(hp1).condition:=C_O
  7785. else
  7786. Taicpu(hp1).condition:=C_NO;
  7787. Result:=true;
  7788. exit;
  7789. end;
  7790. end;
  7791. end;
  7792. end;
  7793. end;
  7794. end;
  7795. if TrySwapMovCmp(p, hp1) then
  7796. begin
  7797. Result := True;
  7798. Exit;
  7799. end;
  7800. end;
  7801. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7802. var
  7803. hp1: tai;
  7804. begin
  7805. {
  7806. remove the second (v)pxor from
  7807. pxor reg,reg
  7808. ...
  7809. pxor reg,reg
  7810. }
  7811. Result:=false;
  7812. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7813. MatchOpType(taicpu(p),top_reg,top_reg) and
  7814. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7815. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7816. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7817. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7818. begin
  7819. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7820. RemoveInstruction(hp1);
  7821. Result:=true;
  7822. Exit;
  7823. end
  7824. {
  7825. replace
  7826. pxor reg1,reg1
  7827. movapd/s reg1,reg2
  7828. dealloc reg1
  7829. by
  7830. pxor reg2,reg2
  7831. }
  7832. else if GetNextInstruction(p,hp1) and
  7833. { we mix single and double opperations here because we assume that the compiler
  7834. generates vmovapd only after double operations and vmovaps only after single operations }
  7835. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7836. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7837. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7838. (taicpu(p).oper[0]^.typ=top_reg) then
  7839. begin
  7840. TransferUsedRegs(TmpUsedRegs);
  7841. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7842. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7843. begin
  7844. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7845. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7846. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7847. RemoveInstruction(hp1);
  7848. result:=true;
  7849. end;
  7850. end;
  7851. end;
  7852. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7853. var
  7854. hp1: tai;
  7855. begin
  7856. {
  7857. remove the second (v)pxor from
  7858. (v)pxor reg,reg
  7859. ...
  7860. (v)pxor reg,reg
  7861. }
  7862. Result:=false;
  7863. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7864. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7865. begin
  7866. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7867. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7868. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7869. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7870. begin
  7871. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7872. RemoveInstruction(hp1);
  7873. Result:=true;
  7874. Exit;
  7875. end;
  7876. {$ifdef x86_64}
  7877. {
  7878. replace
  7879. vpxor reg1,reg1,reg1
  7880. vmov reg,mem
  7881. by
  7882. movq $0,mem
  7883. }
  7884. if GetNextInstruction(p,hp1) and
  7885. MatchInstruction(hp1,A_VMOVSD,[]) and
  7886. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7887. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7888. begin
  7889. TransferUsedRegs(TmpUsedRegs);
  7890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7891. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7892. begin
  7893. taicpu(hp1).loadconst(0,0);
  7894. taicpu(hp1).opcode:=A_MOV;
  7895. taicpu(hp1).opsize:=S_Q;
  7896. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7897. RemoveCurrentP(p);
  7898. result:=true;
  7899. Exit;
  7900. end;
  7901. end;
  7902. {$endif x86_64}
  7903. end
  7904. {
  7905. replace
  7906. vpxor reg1,reg1,reg2
  7907. by
  7908. vpxor reg2,reg2,reg2
  7909. to avoid unncessary data dependencies
  7910. }
  7911. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7912. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7913. begin
  7914. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7915. { avoid unncessary data dependency }
  7916. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7917. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7918. result:=true;
  7919. exit;
  7920. end;
  7921. Result:=OptPass1VOP(p);
  7922. end;
  7923. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7924. var
  7925. hp1 : tai;
  7926. begin
  7927. result:=false;
  7928. { replace
  7929. IMul const,%mreg1,%mreg2
  7930. Mov %reg2,%mreg3
  7931. dealloc %mreg3
  7932. by
  7933. Imul const,%mreg1,%mreg23
  7934. }
  7935. if (taicpu(p).ops=3) and
  7936. GetNextInstruction(p,hp1) and
  7937. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7938. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7939. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7940. begin
  7941. TransferUsedRegs(TmpUsedRegs);
  7942. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7943. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7944. begin
  7945. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7946. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7947. RemoveInstruction(hp1);
  7948. result:=true;
  7949. end;
  7950. end;
  7951. end;
  7952. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7953. var
  7954. hp1 : tai;
  7955. begin
  7956. result:=false;
  7957. { replace
  7958. IMul %reg0,%reg1,%reg2
  7959. Mov %reg2,%reg3
  7960. dealloc %reg2
  7961. by
  7962. Imul %reg0,%reg1,%reg3
  7963. }
  7964. if GetNextInstruction(p,hp1) and
  7965. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7966. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7967. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7968. begin
  7969. TransferUsedRegs(TmpUsedRegs);
  7970. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7971. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7972. begin
  7973. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7974. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7975. RemoveInstruction(hp1);
  7976. result:=true;
  7977. end;
  7978. end;
  7979. end;
  7980. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7981. var
  7982. hp1: tai;
  7983. begin
  7984. Result:=false;
  7985. { get rid of
  7986. (v)cvtss2sd reg0,<reg1,>reg2
  7987. (v)cvtss2sd reg2,<reg2,>reg0
  7988. }
  7989. if GetNextInstruction(p,hp1) and
  7990. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7991. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7992. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7993. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7994. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7995. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7996. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7997. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7998. )
  7999. ) then
  8000. begin
  8001. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8002. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8003. begin
  8004. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8005. RemoveCurrentP(p);
  8006. RemoveInstruction(hp1);
  8007. end
  8008. else
  8009. begin
  8010. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8011. if taicpu(hp1).opcode=A_CVTSD2SS then
  8012. begin
  8013. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8014. taicpu(p).opcode:=A_MOVAPS;
  8015. end
  8016. else
  8017. begin
  8018. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8019. taicpu(p).opcode:=A_VMOVAPS;
  8020. end;
  8021. taicpu(p).ops:=2;
  8022. RemoveInstruction(hp1);
  8023. end;
  8024. Result:=true;
  8025. Exit;
  8026. end;
  8027. end;
  8028. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8029. var
  8030. hp1, hp2, hp3, hp4, hp5: tai;
  8031. ThisReg: TRegister;
  8032. begin
  8033. Result := False;
  8034. if not GetNextInstruction(p,hp1) then
  8035. Exit;
  8036. {
  8037. convert
  8038. j<c> .L1
  8039. mov 1,reg
  8040. jmp .L2
  8041. .L1
  8042. mov 0,reg
  8043. .L2
  8044. into
  8045. mov 0,reg
  8046. set<not(c)> reg
  8047. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8048. would destroy the flag contents
  8049. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8050. executed at the same time as a previous comparison.
  8051. set<not(c)> reg
  8052. movzx reg, reg
  8053. }
  8054. if MatchInstruction(hp1,A_MOV,[]) and
  8055. (taicpu(hp1).oper[0]^.typ = top_const) and
  8056. (
  8057. (
  8058. (taicpu(hp1).oper[1]^.typ = top_reg)
  8059. {$ifdef i386}
  8060. { Under i386, ESI, EDI, EBP and ESP
  8061. don't have an 8-bit representation }
  8062. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8063. {$endif i386}
  8064. ) or (
  8065. {$ifdef i386}
  8066. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8067. {$endif i386}
  8068. (taicpu(hp1).opsize = S_B)
  8069. )
  8070. ) and
  8071. GetNextInstruction(hp1,hp2) and
  8072. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8073. GetNextInstruction(hp2,hp3) and
  8074. (hp3.typ=ait_label) and
  8075. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8076. GetNextInstruction(hp3,hp4) and
  8077. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8078. (taicpu(hp4).oper[0]^.typ = top_const) and
  8079. (
  8080. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8081. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8082. ) and
  8083. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8084. GetNextInstruction(hp4,hp5) and
  8085. (hp5.typ=ait_label) and
  8086. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  8087. begin
  8088. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8089. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8090. tai_label(hp3).labsym.DecRefs;
  8091. { If this isn't the only reference to the middle label, we can
  8092. still make a saving - only that the first jump and everything
  8093. that follows will remain. }
  8094. if (tai_label(hp3).labsym.getrefs = 0) then
  8095. begin
  8096. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8097. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8098. else
  8099. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8100. { remove jump, first label and second MOV (also catching any aligns) }
  8101. repeat
  8102. if not GetNextInstruction(hp2, hp3) then
  8103. InternalError(2021040810);
  8104. RemoveInstruction(hp2);
  8105. hp2 := hp3;
  8106. until hp2 = hp5;
  8107. { Don't decrement reference count before the removal loop
  8108. above, otherwise GetNextInstruction won't stop on the
  8109. the label }
  8110. tai_label(hp5).labsym.DecRefs;
  8111. end
  8112. else
  8113. begin
  8114. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8115. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8116. else
  8117. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8118. end;
  8119. taicpu(p).opcode:=A_SETcc;
  8120. taicpu(p).opsize:=S_B;
  8121. taicpu(p).is_jmp:=False;
  8122. if taicpu(hp1).opsize=S_B then
  8123. begin
  8124. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8125. if taicpu(hp1).oper[1]^.typ = top_reg then
  8126. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8127. RemoveInstruction(hp1);
  8128. end
  8129. else
  8130. begin
  8131. { Will be a register because the size can't be S_B otherwise }
  8132. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8133. taicpu(p).loadreg(0, ThisReg);
  8134. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8135. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8136. begin
  8137. case taicpu(hp1).opsize of
  8138. S_W:
  8139. taicpu(hp1).opsize := S_BW;
  8140. S_L:
  8141. taicpu(hp1).opsize := S_BL;
  8142. {$ifdef x86_64}
  8143. S_Q:
  8144. begin
  8145. taicpu(hp1).opsize := S_BL;
  8146. { Change the destination register to 32-bit }
  8147. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8148. end;
  8149. {$endif x86_64}
  8150. else
  8151. InternalError(2021040820);
  8152. end;
  8153. taicpu(hp1).opcode := A_MOVZX;
  8154. taicpu(hp1).loadreg(0, ThisReg);
  8155. end
  8156. else
  8157. begin
  8158. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8159. { hp1 is already a MOV instruction with the correct register }
  8160. taicpu(hp1).loadconst(0, 0);
  8161. { Inserting it right before p will guarantee that the flags are also tracked }
  8162. asml.Remove(hp1);
  8163. asml.InsertBefore(hp1, p);
  8164. end;
  8165. end;
  8166. Result:=true;
  8167. exit;
  8168. end
  8169. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8170. Result := TryJccStcClcOpt(p, hp1)
  8171. else if (hp1.typ = ait_label) then
  8172. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8173. end;
  8174. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8175. var
  8176. hp1, hp2, hp3: tai;
  8177. SourceRef, TargetRef: TReference;
  8178. CurrentReg: TRegister;
  8179. begin
  8180. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8181. if not UseAVX then
  8182. InternalError(2021100501);
  8183. Result := False;
  8184. { Look for the following to simplify:
  8185. vmovdqa/u x(mem1), %xmmreg
  8186. vmovdqa/u %xmmreg, y(mem2)
  8187. vmovdqa/u x+16(mem1), %xmmreg
  8188. vmovdqa/u %xmmreg, y+16(mem2)
  8189. Change to:
  8190. vmovdqa/u x(mem1), %ymmreg
  8191. vmovdqa/u %ymmreg, y(mem2)
  8192. vpxor %ymmreg, %ymmreg, %ymmreg
  8193. ( The VPXOR instruction is to zero the upper half, thus removing the
  8194. need to call the potentially expensive VZEROUPPER instruction. Other
  8195. peephole optimisations can remove VPXOR if it's unnecessary )
  8196. }
  8197. TransferUsedRegs(TmpUsedRegs);
  8198. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8199. { NOTE: In the optimisations below, if the references dictate that an
  8200. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8201. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8202. if (taicpu(p).opsize = S_XMM) and
  8203. MatchOpType(taicpu(p), top_ref, top_reg) and
  8204. GetNextInstruction(p, hp1) and
  8205. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8206. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8207. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8208. begin
  8209. SourceRef := taicpu(p).oper[0]^.ref^;
  8210. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8211. if GetNextInstruction(hp1, hp2) and
  8212. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8213. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8214. begin
  8215. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8216. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8217. Inc(SourceRef.offset, 16);
  8218. { Reuse the register in the first block move }
  8219. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8220. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8221. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8222. begin
  8223. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8224. Inc(TargetRef.offset, 16);
  8225. if GetNextInstruction(hp2, hp3) and
  8226. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8227. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8228. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8229. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8230. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8231. begin
  8232. { Update the register tracking to the new size }
  8233. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8234. { Remember that the offsets are 16 ahead }
  8235. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8236. if not (
  8237. ((SourceRef.offset mod 32) = 16) and
  8238. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8239. ) then
  8240. taicpu(p).opcode := A_VMOVDQU;
  8241. taicpu(p).opsize := S_YMM;
  8242. taicpu(p).oper[1]^.reg := CurrentReg;
  8243. if not (
  8244. ((TargetRef.offset mod 32) = 16) and
  8245. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8246. ) then
  8247. taicpu(hp1).opcode := A_VMOVDQU;
  8248. taicpu(hp1).opsize := S_YMM;
  8249. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8250. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8251. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8252. if (pi_uses_ymm in current_procinfo.flags) then
  8253. RemoveInstruction(hp2)
  8254. else
  8255. begin
  8256. taicpu(hp2).opcode := A_VPXOR;
  8257. taicpu(hp2).opsize := S_YMM;
  8258. taicpu(hp2).loadreg(0, CurrentReg);
  8259. taicpu(hp2).loadreg(1, CurrentReg);
  8260. taicpu(hp2).loadreg(2, CurrentReg);
  8261. taicpu(hp2).ops := 3;
  8262. end;
  8263. RemoveInstruction(hp3);
  8264. Result := True;
  8265. Exit;
  8266. end;
  8267. end
  8268. else
  8269. begin
  8270. { See if the next references are 16 less rather than 16 greater }
  8271. Dec(SourceRef.offset, 32); { -16 the other way }
  8272. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8273. begin
  8274. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8275. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8276. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8277. GetNextInstruction(hp2, hp3) and
  8278. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8279. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8280. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8281. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8282. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8283. begin
  8284. { Update the register tracking to the new size }
  8285. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8286. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8287. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8288. if not(
  8289. ((SourceRef.offset mod 32) = 0) and
  8290. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8291. ) then
  8292. taicpu(hp2).opcode := A_VMOVDQU;
  8293. taicpu(hp2).opsize := S_YMM;
  8294. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8295. if not (
  8296. ((TargetRef.offset mod 32) = 0) and
  8297. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8298. ) then
  8299. taicpu(hp3).opcode := A_VMOVDQU;
  8300. taicpu(hp3).opsize := S_YMM;
  8301. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8302. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8303. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8304. if (pi_uses_ymm in current_procinfo.flags) then
  8305. RemoveInstruction(hp1)
  8306. else
  8307. begin
  8308. taicpu(hp1).opcode := A_VPXOR;
  8309. taicpu(hp1).opsize := S_YMM;
  8310. taicpu(hp1).loadreg(0, CurrentReg);
  8311. taicpu(hp1).loadreg(1, CurrentReg);
  8312. taicpu(hp1).loadreg(2, CurrentReg);
  8313. taicpu(hp1).ops := 3;
  8314. Asml.Remove(hp1);
  8315. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8316. end;
  8317. RemoveCurrentP(p, hp2);
  8318. Result := True;
  8319. Exit;
  8320. end;
  8321. end;
  8322. end;
  8323. end;
  8324. end;
  8325. end;
  8326. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8327. var
  8328. hp2, hp3, first_assignment: tai;
  8329. IncCount, OperIdx: Integer;
  8330. OrigLabel: TAsmLabel;
  8331. begin
  8332. Count := 0;
  8333. Result := False;
  8334. first_assignment := nil;
  8335. if (LoopCount >= 20) then
  8336. begin
  8337. { Guard against infinite loops }
  8338. Exit;
  8339. end;
  8340. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8341. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8342. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8343. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8344. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8345. Exit;
  8346. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8347. {
  8348. change
  8349. jmp .L1
  8350. ...
  8351. .L1:
  8352. mov ##, ## ( multiple movs possible )
  8353. jmp/ret
  8354. into
  8355. mov ##, ##
  8356. jmp/ret
  8357. }
  8358. if not Assigned(hp1) then
  8359. begin
  8360. hp1 := GetLabelWithSym(OrigLabel);
  8361. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8362. Exit;
  8363. end;
  8364. hp2 := hp1;
  8365. while Assigned(hp2) do
  8366. begin
  8367. if Assigned(hp2) and (hp2.typ = ait_label) then
  8368. SkipLabels(hp2,hp2);
  8369. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8370. Break;
  8371. case taicpu(hp2).opcode of
  8372. A_MOVSD:
  8373. begin
  8374. if taicpu(hp2).ops = 0 then
  8375. { Wrong MOVSD }
  8376. Break;
  8377. Inc(Count);
  8378. if Count >= 5 then
  8379. { Too many to be worthwhile }
  8380. Break;
  8381. GetNextInstruction(hp2, hp2);
  8382. Continue;
  8383. end;
  8384. A_MOV,
  8385. A_MOVD,
  8386. A_MOVQ,
  8387. A_MOVSX,
  8388. {$ifdef x86_64}
  8389. A_MOVSXD,
  8390. {$endif x86_64}
  8391. A_MOVZX,
  8392. A_MOVAPS,
  8393. A_MOVUPS,
  8394. A_MOVSS,
  8395. A_MOVAPD,
  8396. A_MOVUPD,
  8397. A_MOVDQA,
  8398. A_MOVDQU,
  8399. A_VMOVSS,
  8400. A_VMOVAPS,
  8401. A_VMOVUPS,
  8402. A_VMOVSD,
  8403. A_VMOVAPD,
  8404. A_VMOVUPD,
  8405. A_VMOVDQA,
  8406. A_VMOVDQU:
  8407. begin
  8408. Inc(Count);
  8409. if Count >= 5 then
  8410. { Too many to be worthwhile }
  8411. Break;
  8412. GetNextInstruction(hp2, hp2);
  8413. Continue;
  8414. end;
  8415. A_JMP:
  8416. begin
  8417. { Guard against infinite loops }
  8418. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8419. Exit;
  8420. { Analyse this jump first in case it also duplicates assignments }
  8421. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8422. begin
  8423. { Something did change! }
  8424. Result := True;
  8425. Inc(Count, IncCount);
  8426. if Count >= 5 then
  8427. begin
  8428. { Too many to be worthwhile }
  8429. Exit;
  8430. end;
  8431. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8432. Break;
  8433. end;
  8434. Result := True;
  8435. Break;
  8436. end;
  8437. A_RET:
  8438. begin
  8439. Result := True;
  8440. Break;
  8441. end;
  8442. else
  8443. Break;
  8444. end;
  8445. end;
  8446. if Result then
  8447. begin
  8448. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8449. if Count = 0 then
  8450. begin
  8451. Result := False;
  8452. Exit;
  8453. end;
  8454. TransferUsedRegs(TmpUsedRegs);
  8455. hp3 := p;
  8456. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8457. while True do
  8458. begin
  8459. if Assigned(hp1) and (hp1.typ = ait_label) then
  8460. SkipLabels(hp1,hp1);
  8461. case hp1.typ of
  8462. ait_regalloc:
  8463. if tai_regalloc(hp1).ratype = ra_dealloc then
  8464. begin
  8465. { Duplicate the register deallocation... }
  8466. hp3:=tai(hp1.getcopy);
  8467. if first_assignment = nil then
  8468. first_assignment := hp3;
  8469. asml.InsertBefore(hp3, p);
  8470. { ... but also reallocate it after the jump }
  8471. hp3:=tai(hp1.getcopy);
  8472. tai_regalloc(hp3).ratype := ra_alloc;
  8473. asml.InsertAfter(hp3, p);
  8474. end;
  8475. ait_instruction:
  8476. case taicpu(hp1).opcode of
  8477. A_JMP:
  8478. begin
  8479. { Change the original jump to the new destination }
  8480. OrigLabel.decrefs;
  8481. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8482. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8483. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8484. if not Assigned(first_assignment) then
  8485. InternalError(2021040810)
  8486. else
  8487. p := first_assignment;
  8488. Exit;
  8489. end;
  8490. A_RET:
  8491. begin
  8492. { Now change the jump into a RET instruction }
  8493. ConvertJumpToRET(p, hp1);
  8494. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8495. if not Assigned(first_assignment) then
  8496. InternalError(2021040811)
  8497. else
  8498. p := first_assignment;
  8499. Exit;
  8500. end;
  8501. else
  8502. begin
  8503. { Duplicate the MOV instruction }
  8504. hp3:=tai(hp1.getcopy);
  8505. if first_assignment = nil then
  8506. first_assignment := hp3;
  8507. asml.InsertBefore(hp3, p);
  8508. { Make sure the compiler knows about any final registers written here }
  8509. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8510. with taicpu(hp3).oper[OperIdx]^ do
  8511. begin
  8512. case typ of
  8513. top_ref:
  8514. begin
  8515. if (ref^.base <> NR_NO) and
  8516. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8517. (
  8518. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8519. (
  8520. { Allow the frame pointer if it's not being used by the procedure as such }
  8521. Assigned(current_procinfo) and
  8522. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8523. )
  8524. )
  8525. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8526. then
  8527. begin
  8528. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8529. if not Assigned(first_assignment) then
  8530. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8531. end;
  8532. if (ref^.index <> NR_NO) and
  8533. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8534. (
  8535. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8536. (
  8537. { Allow the frame pointer if it's not being used by the procedure as such }
  8538. Assigned(current_procinfo) and
  8539. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8540. )
  8541. )
  8542. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8543. (ref^.index <> ref^.base) then
  8544. begin
  8545. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8546. if not Assigned(first_assignment) then
  8547. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8548. end;
  8549. end;
  8550. top_reg:
  8551. begin
  8552. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8553. if not Assigned(first_assignment) then
  8554. IncludeRegInUsedRegs(reg, UsedRegs);
  8555. end;
  8556. else
  8557. ;
  8558. end;
  8559. end;
  8560. end;
  8561. end;
  8562. else
  8563. InternalError(2021040720);
  8564. end;
  8565. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8566. { Should have dropped out earlier }
  8567. InternalError(2021040710);
  8568. end;
  8569. end;
  8570. end;
  8571. const
  8572. WriteOp: array[0..3] of set of TInsChange = (
  8573. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8574. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8575. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8576. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8577. RegWriteFlags: array[0..7] of set of TInsChange = (
  8578. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8579. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8580. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8581. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8582. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8583. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8584. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8585. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8586. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8587. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8588. var
  8589. hp2: tai;
  8590. X: Integer;
  8591. begin
  8592. { If we have something like:
  8593. op ###,###
  8594. mov ###,###
  8595. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8596. interfere in regards to what they write to.
  8597. NOTE: p must be a 2-operand instruction
  8598. }
  8599. Result := False;
  8600. if (hp1.typ <> ait_instruction) or
  8601. taicpu(hp1).is_jmp or
  8602. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8603. Exit;
  8604. { NOP is a pipeline fence, likely marking the beginning of the function
  8605. epilogue, so drop out. Similarly, drop out if POP or RET are
  8606. encountered }
  8607. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8608. Exit;
  8609. if (taicpu(hp1).opcode = A_MOVSD) and
  8610. (taicpu(hp1).ops = 0) then
  8611. { Wrong MOVSD }
  8612. Exit;
  8613. { Check for writes to specific registers first }
  8614. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8615. for X := 0 to 7 do
  8616. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8617. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8618. Exit;
  8619. for X := 0 to taicpu(hp1).ops - 1 do
  8620. begin
  8621. { Check to see if this operand writes to something }
  8622. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8623. { And matches something in the CMP/TEST instruction }
  8624. (
  8625. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8626. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8627. (
  8628. { If it's a register, make sure the register written to doesn't
  8629. appear in the cmp instruction as part of a reference }
  8630. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8631. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8632. )
  8633. ) then
  8634. Exit;
  8635. end;
  8636. { Check p to make sure it doesn't write to something that affects hp1 }
  8637. { Check for writes to specific registers first }
  8638. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8639. for X := 0 to 7 do
  8640. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8641. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8642. Exit;
  8643. for X := 0 to taicpu(p).ops - 1 do
  8644. begin
  8645. { Check to see if this operand writes to something }
  8646. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8647. { And matches something in hp1 }
  8648. (taicpu(p).oper[X]^.typ = top_reg) and
  8649. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8650. Exit;
  8651. end;
  8652. { The instruction can be safely moved }
  8653. asml.Remove(hp1);
  8654. { Try to insert after the last instructions where the FLAGS register is not
  8655. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8656. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8657. asml.InsertBefore(hp1, hp2)
  8658. { Failing that, try to insert after the last instructions where the
  8659. FLAGS register is not yet in use }
  8660. else if GetLastInstruction(p, hp2) and
  8661. (
  8662. (hp2.typ <> ait_instruction) or
  8663. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8664. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8665. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8666. ) then
  8667. asml.InsertAfter(hp1, hp2)
  8668. else
  8669. { Note, if p.Previous is nil (even if it should logically never be the
  8670. case), FindRegAllocBackward immediately exits with False and so we
  8671. safely land here (we can't just pass p because FindRegAllocBackward
  8672. immediately exits on an instruction). [Kit] }
  8673. asml.InsertBefore(hp1, p);
  8674. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8675. { We can't trust UsedRegs because we're looking backwards, although we
  8676. know the registers are allocated after p at the very least, so manually
  8677. create tai_regalloc objects if needed }
  8678. for X := 0 to taicpu(hp1).ops - 1 do
  8679. case taicpu(hp1).oper[X]^.typ of
  8680. top_reg:
  8681. begin
  8682. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8683. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8684. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8685. end;
  8686. top_ref:
  8687. begin
  8688. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8689. begin
  8690. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8691. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8692. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8693. end;
  8694. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8695. begin
  8696. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8697. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8698. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8699. end;
  8700. end;
  8701. else
  8702. ;
  8703. end;
  8704. Result := True;
  8705. end;
  8706. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8707. var
  8708. hp2: tai;
  8709. X: Integer;
  8710. begin
  8711. { If we have something like:
  8712. cmp ###,%reg1
  8713. mov 0,%reg2
  8714. And no modified registers are shared, move the instruction to before
  8715. the comparison as this means it can be optimised without worrying
  8716. about the FLAGS register. (CMP/MOV is generated by
  8717. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8718. As long as the second instruction doesn't use the flags or one of the
  8719. registers used by CMP or TEST (also check any references that use the
  8720. registers), then it can be moved prior to the comparison.
  8721. }
  8722. Result := False;
  8723. if not TrySwapMovOp(p, hp1) then
  8724. Exit;
  8725. if taicpu(hp1).opcode = A_LEA then
  8726. { The flags will be overwritten by the CMP/TEST instruction }
  8727. ConvertLEA(taicpu(hp1));
  8728. Result := True;
  8729. { Can we move it one further back? }
  8730. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8731. { Check to see if CMP/TEST is a comparison against zero }
  8732. (
  8733. (
  8734. (taicpu(p).opcode = A_CMP) and
  8735. MatchOperand(taicpu(p).oper[0]^, 0)
  8736. ) or
  8737. (
  8738. (taicpu(p).opcode = A_TEST) and
  8739. (
  8740. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8741. MatchOperand(taicpu(p).oper[0]^, -1)
  8742. )
  8743. )
  8744. ) and
  8745. { These instructions set the zero flag if the result is zero }
  8746. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8747. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8748. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8749. TrySwapMovOp(hp2, hp1);
  8750. end;
  8751. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8752. var
  8753. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8754. JumpLabel: TAsmLabel;
  8755. TmpBool: Boolean;
  8756. begin
  8757. Result := False;
  8758. { Look for:
  8759. stc/clc
  8760. j(c) .L1
  8761. ...
  8762. .L1:
  8763. set(n)cb %reg
  8764. (flags deallocated)
  8765. j(c) .L2
  8766. Change to:
  8767. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8768. j(c) .L2
  8769. }
  8770. p_last := p;
  8771. while GetNextInstruction(p_last, hp1) and
  8772. (hp1.typ = ait_instruction) and
  8773. IsJumpToLabel(taicpu(hp1)) do
  8774. begin
  8775. if DoJumpOptimizations(hp1, TmpBool) then
  8776. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8777. Continue;
  8778. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8779. if not Assigned(JumpLabel) then
  8780. InternalError(2024012801);
  8781. { Optimise the J(c); stc/clc optimisation first since this will
  8782. get missed if the main optimisation takes place }
  8783. if (taicpu(hp1).opcode = A_JCC) then
  8784. begin
  8785. if GetNextInstruction(hp1, hp2) and
  8786. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8787. TryJccStcClcOpt(hp1, hp2) then
  8788. begin
  8789. Result := True;
  8790. Exit;
  8791. end;
  8792. hp2 := nil; { Suppress compiler warning }
  8793. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8794. { Make sure the flags aren't used again }
  8795. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8796. begin
  8797. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8798. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8799. begin
  8800. if (taicpu(p).opcode = A_STC) then
  8801. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8802. else
  8803. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8804. MakeUnconditional(taicpu(hp1));
  8805. { Move the jump to after the flag deallocations }
  8806. Asml.Remove(hp1);
  8807. Asml.InsertAfter(hp1, hp2);
  8808. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8809. Result := True;
  8810. Exit;
  8811. end
  8812. else
  8813. begin
  8814. if (taicpu(p).opcode = A_STC) then
  8815. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8816. else
  8817. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8818. { In this case, the jump is deterministic in that it will never be taken }
  8819. JumpLabel.DecRefs;
  8820. RemoveInstruction(hp1);
  8821. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8822. Result := True;
  8823. Exit;
  8824. end;
  8825. end;
  8826. end;
  8827. hp2 := nil; { Suppress compiler warning }
  8828. if
  8829. { Make sure the carry flag doesn't appear in the jump conditions }
  8830. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8831. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8832. GetNextInstruction(hp2, p_dist) and
  8833. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8834. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8835. begin
  8836. case taicpu(p_dist).opcode of
  8837. A_Jcc:
  8838. begin
  8839. if DoJumpOptimizations(p_dist, TmpBool) then
  8840. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8841. Continue;
  8842. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8843. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8844. begin
  8845. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8846. JumpLabel.decrefs;
  8847. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8848. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8849. Result := True;
  8850. Exit;
  8851. end
  8852. else if GetNextInstruction(p_dist, hp1_dist) and
  8853. (hp1_dist.typ = ait_label) then
  8854. begin
  8855. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8856. JumpLabel.decrefs;
  8857. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8858. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8859. Result := True;
  8860. Exit;
  8861. end;
  8862. end;
  8863. A_SETcc:
  8864. if { Make sure the flags aren't used again }
  8865. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8866. GetNextInstruction(hp2, hp1_dist) and
  8867. (hp1_dist.typ = ait_instruction) and
  8868. IsJumpToLabel(taicpu(hp1_dist)) and
  8869. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8870. { This works if hp1_dist or both are regular JMP instructions }
  8871. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8872. (
  8873. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8874. { Make sure the register isn't still in use, otherwise it
  8875. may get corrupted (fixes #40659) }
  8876. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8877. ) then
  8878. begin
  8879. taicpu(p).allocate_oper(2);
  8880. taicpu(p).ops := 2;
  8881. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8882. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8883. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8884. taicpu(p).opcode := A_MOV;
  8885. taicpu(p).opsize := S_B;
  8886. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8887. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8888. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8889. JumpLabel.decrefs;
  8890. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8891. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8892. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8893. (tai_regalloc(hp2).ratype = ra_alloc) then
  8894. begin
  8895. Asml.Remove(hp2);
  8896. Asml.InsertAfter(hp2, p);
  8897. end;
  8898. Result := True;
  8899. Exit;
  8900. end;
  8901. else
  8902. ;
  8903. end;
  8904. end;
  8905. p_last := hp1;
  8906. end;
  8907. end;
  8908. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8909. var
  8910. hp2, hp3: tai;
  8911. TempBool: Boolean;
  8912. begin
  8913. Result := False;
  8914. {
  8915. j(c) .L1
  8916. stc/clc
  8917. .L1:
  8918. jc/jnc .L2
  8919. (Flags deallocated)
  8920. Change to:
  8921. j)c) .L1
  8922. jmp .L2
  8923. .L1:
  8924. jc/jnc .L2
  8925. Then call DoJumpOptimizations to convert to:
  8926. j(nc) .L2
  8927. .L1: (may become a dead label)
  8928. jc/jnc .L2
  8929. }
  8930. if GetNextInstruction(hp1, hp2) and
  8931. (hp2.typ = ait_label) and
  8932. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8933. GetNextInstruction(hp2, hp3) and
  8934. MatchInstruction(hp3, A_Jcc, []) and
  8935. (
  8936. (
  8937. (taicpu(hp3).condition = C_C) and
  8938. (taicpu(hp1).opcode = A_STC)
  8939. ) or (
  8940. (taicpu(hp3).condition = C_NC) and
  8941. (taicpu(hp1).opcode = A_CLC)
  8942. )
  8943. ) and
  8944. { Make sure the flags aren't used again }
  8945. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8946. begin
  8947. taicpu(hp1).allocate_oper(1);
  8948. taicpu(hp1).ops := 1;
  8949. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8950. taicpu(hp1).opcode := A_JMP;
  8951. taicpu(hp1).is_jmp := True;
  8952. TempBool := True; { Prevent compiler warnings }
  8953. if DoJumpOptimizations(p, TempBool) then
  8954. Result := True
  8955. else
  8956. Include(OptsToCheck, aoc_ForceNewIteration);
  8957. end;
  8958. end;
  8959. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8960. begin
  8961. { This generally only executes under -O3 and above }
  8962. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8963. end;
  8964. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8965. var
  8966. hp1, hp2: tai;
  8967. FoundComparison: Boolean;
  8968. begin
  8969. { Run the pass 1 optimisations as well, since they may have some effect
  8970. after the CMOV blocks are created in OptPass2Jcc }
  8971. Result := False;
  8972. { Result := OptPass1CMOVcc(p);
  8973. if Result then
  8974. Exit;}
  8975. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8976. and make a slightly inefficent result on branching-type blocks, notably
  8977. when setting a function result then jumping to the function epilogue.
  8978. In this case, change:
  8979. cmov(c) %reg1,%reg2
  8980. j(c) @lbl
  8981. (%reg2 deallocated)
  8982. To:
  8983. mov %reg11,%reg2
  8984. j(c) @lbl
  8985. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8986. jump because if it's not present, we may end up with a jump that's
  8987. completely unrelated.
  8988. }
  8989. hp1 := p;
  8990. while GetNextInstruction(hp1, hp1) and
  8991. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8992. if (hp1.typ = ait_instruction) and
  8993. (taicpu(hp1).opcode = A_Jcc) and
  8994. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8995. begin
  8996. TransferUsedRegs(TmpUsedRegs);
  8997. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8998. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8999. (
  9000. { See if we can find a more distant instruction that overwrites
  9001. the destination register }
  9002. (cs_opt_level3 in current_settings.optimizerswitches) and
  9003. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9004. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9005. ) then
  9006. begin
  9007. if (taicpu(p).oper[0]^.typ = top_reg) then
  9008. begin
  9009. { Search backwards to see if the source register is set to a
  9010. constant }
  9011. FoundComparison := False;
  9012. hp1 := p;
  9013. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9014. begin
  9015. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9016. begin
  9017. FoundComparison := True;
  9018. Continue;
  9019. end;
  9020. { Once we find the CMP, TEST or similar instruction, we
  9021. have to stop if we find anything other than a MOV }
  9022. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9023. Break;
  9024. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9025. { Destination register was modified }
  9026. Break;
  9027. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9028. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9029. begin
  9030. { Found a constant! }
  9031. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9032. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9033. { The source register is no longer in use }
  9034. RemoveInstruction(hp1);
  9035. Break;
  9036. end;
  9037. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9038. { Some other instruction has modified the source register }
  9039. Break;
  9040. end;
  9041. end;
  9042. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9043. taicpu(p).opcode := A_MOV;
  9044. taicpu(p).condition := C_None;
  9045. { Rely on the post peephole stage to put the MOV before the
  9046. CMP/TEST instruction that appears prior }
  9047. Result := True;
  9048. Exit;
  9049. end;
  9050. end;
  9051. end;
  9052. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9053. function IsXCHGAcceptable: Boolean; inline;
  9054. begin
  9055. { Always accept if optimising for size }
  9056. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9057. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9058. than 3, so it becomes a saving compared to three MOVs with two of
  9059. them able to execute simultaneously. [Kit] }
  9060. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9061. end;
  9062. var
  9063. NewRef: TReference;
  9064. hp1, hp2, hp3, hp4: Tai;
  9065. {$ifndef x86_64}
  9066. OperIdx: Integer;
  9067. {$endif x86_64}
  9068. NewInstr : Taicpu;
  9069. NewAligh : Tai_align;
  9070. DestLabel: TAsmLabel;
  9071. TempTracking: TAllUsedRegs;
  9072. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9073. var
  9074. NextInstr: tai;
  9075. begin
  9076. Result := False;
  9077. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9078. if not GetNextInstruction(InputInstr, NextInstr) or
  9079. (
  9080. { The FLAGS register isn't always tracked properly, so do not
  9081. perform this optimisation if a conditional statement follows }
  9082. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9083. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9084. ) then
  9085. begin
  9086. reference_reset(NewRef, 1, []);
  9087. NewRef.base := taicpu(p).oper[0]^.reg;
  9088. NewRef.scalefactor := 1;
  9089. if taicpu(InputInstr).opcode = A_ADD then
  9090. begin
  9091. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9092. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9093. end
  9094. else
  9095. begin
  9096. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9097. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9098. end;
  9099. taicpu(p).opcode := A_LEA;
  9100. taicpu(p).loadref(0, NewRef);
  9101. { For the sake of debugging, have the line info match the
  9102. arithmetic instruction rather than the MOV instruction }
  9103. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9104. RemoveInstruction(InputInstr);
  9105. Result := True;
  9106. end;
  9107. end;
  9108. begin
  9109. Result:=false;
  9110. { This optimisation adds an instruction, so only do it for speed }
  9111. if not (cs_opt_size in current_settings.optimizerswitches) and
  9112. MatchOpType(taicpu(p), top_const, top_reg) and
  9113. (taicpu(p).oper[0]^.val = 0) then
  9114. begin
  9115. { To avoid compiler warning }
  9116. DestLabel := nil;
  9117. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9118. InternalError(2021040750);
  9119. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9120. Exit;
  9121. case hp1.typ of
  9122. ait_label:
  9123. begin
  9124. { Change:
  9125. mov $0,%reg mov $0,%reg
  9126. @Lbl1: @Lbl1:
  9127. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9128. je @Lbl2 jne @Lbl2
  9129. To: To:
  9130. mov $0,%reg mov $0,%reg
  9131. jmp @Lbl2 jmp @Lbl3
  9132. (align) (align)
  9133. @Lbl1: @Lbl1:
  9134. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9135. je @Lbl2 je @Lbl2
  9136. @Lbl3: <-- Only if label exists
  9137. (Not if it's optimised for size)
  9138. }
  9139. if not GetNextInstruction(hp1, hp2) then
  9140. Exit;
  9141. if (hp2.typ = ait_instruction) and
  9142. (
  9143. { Register sizes must exactly match }
  9144. (
  9145. (taicpu(hp2).opcode = A_CMP) and
  9146. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9147. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9148. ) or (
  9149. (taicpu(hp2).opcode = A_TEST) and
  9150. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9151. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9152. )
  9153. ) and GetNextInstruction(hp2, hp3) and
  9154. (hp3.typ = ait_instruction) and
  9155. (taicpu(hp3).opcode = A_JCC) and
  9156. (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
  9157. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9158. begin
  9159. { Check condition of jump }
  9160. { Always true? }
  9161. if condition_in(C_E, taicpu(hp3).condition) then
  9162. begin
  9163. { Copy label symbol and obtain matching label entry for the
  9164. conditional jump, as this will be our destination}
  9165. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9166. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9167. Result := True;
  9168. end
  9169. { Always false? }
  9170. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9171. begin
  9172. { This is only worth it if there's a jump to take }
  9173. case hp2.typ of
  9174. ait_instruction:
  9175. begin
  9176. if taicpu(hp2).opcode = A_JMP then
  9177. begin
  9178. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9179. { An unconditional jump follows the conditional jump which will always be false,
  9180. so use this jump's destination for the new jump }
  9181. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9182. Result := True;
  9183. end
  9184. else if taicpu(hp2).opcode = A_JCC then
  9185. begin
  9186. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9187. if condition_in(C_E, taicpu(hp2).condition) then
  9188. begin
  9189. { A second conditional jump follows the conditional jump which will always be false,
  9190. while the second jump is always True, so use this jump's destination for the new jump }
  9191. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9192. Result := True;
  9193. end;
  9194. { Don't risk it if the jump isn't always true (Result remains False) }
  9195. end;
  9196. end;
  9197. else
  9198. { If anything else don't optimise };
  9199. end;
  9200. end;
  9201. if Result then
  9202. begin
  9203. { Just so we have something to insert as a paremeter}
  9204. reference_reset(NewRef, 1, []);
  9205. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9206. { Now actually load the correct parameter (this also
  9207. increases the reference count) }
  9208. NewInstr.loadsymbol(0, DestLabel, 0);
  9209. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9210. begin
  9211. { Get instruction before original label (may not be p under -O3) }
  9212. if not GetLastInstruction(hp1, hp2) then
  9213. { Shouldn't fail here }
  9214. InternalError(2021040701);
  9215. end
  9216. else
  9217. hp2 := p;
  9218. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9219. AsmL.InsertAfter(NewInstr, hp2);
  9220. { Add new alignment field }
  9221. (* AsmL.InsertAfter(
  9222. cai_align.create_max(
  9223. current_settings.alignment.jumpalign,
  9224. current_settings.alignment.jumpalignskipmax
  9225. ),
  9226. NewInstr
  9227. ); *)
  9228. end;
  9229. Exit;
  9230. end;
  9231. end;
  9232. else
  9233. ;
  9234. end;
  9235. end;
  9236. if not GetNextInstruction(p, hp1) then
  9237. Exit;
  9238. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9239. begin
  9240. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9241. begin
  9242. Result := True;
  9243. Exit;
  9244. end;
  9245. { This optimisation is only effective on a second run of Pass 2,
  9246. hence -O3 or above.
  9247. Change:
  9248. mov %reg1,%reg2
  9249. cmp/test (contains %reg1)
  9250. mov x, %reg1
  9251. (another mov or a j(c))
  9252. To:
  9253. mov %reg1,%reg2
  9254. mov x, %reg1
  9255. cmp (%reg1 replaced with %reg2)
  9256. (another mov or a j(c))
  9257. The requirement of an additional MOV or a jump ensures there
  9258. isn't performance loss, since a j(c) will permit macro-fusion
  9259. with the cmp instruction, while another MOV likely means it's
  9260. not all being executed in a single cycle due to parallelisation.
  9261. }
  9262. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9263. MatchOpType(taicpu(p), top_reg, top_reg) and
  9264. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9265. GetNextInstruction(hp1, hp2) and
  9266. MatchInstruction(hp2, A_MOV, []) and
  9267. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9268. { Registers don't have to be the same size in this case }
  9269. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9270. GetNextInstruction(hp2, hp3) and
  9271. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9272. { Make sure the operands in the camparison can be safely replaced }
  9273. (
  9274. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9275. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9276. ) and
  9277. (
  9278. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9279. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9280. ) then
  9281. begin
  9282. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9283. AsmL.Remove(hp2);
  9284. AsmL.InsertAfter(hp2, p);
  9285. Result := True;
  9286. Exit;
  9287. end;
  9288. end;
  9289. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9290. begin
  9291. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9292. further, but we can't just put this jump optimisation in pass 1
  9293. because it tends to perform worse when conditional jumps are
  9294. nearby (e.g. when converting CMOV instructions). [Kit] }
  9295. CopyUsedRegs(TempTracking);
  9296. UpdateUsedRegs(tai(p.Next));
  9297. if OptPass2JMP(hp1) then
  9298. begin
  9299. { Restore register state }
  9300. RestoreUsedRegs(TempTracking);
  9301. ReleaseUsedRegs(TempTracking);
  9302. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9303. OptPass1MOV(p);
  9304. Result := True;
  9305. Exit;
  9306. end;
  9307. { If OptPass2JMP returned False, no optimisations were done to
  9308. the jump and there are no further optimisations that can be done
  9309. to the MOV instruction on this pass other than FuncMov2Func }
  9310. { Restore register state }
  9311. RestoreUsedRegs(TempTracking);
  9312. ReleaseUsedRegs(TempTracking);
  9313. Result := FuncMov2Func(p, hp1);
  9314. Exit;
  9315. end;
  9316. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9317. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9318. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9319. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9320. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9321. begin
  9322. { Change:
  9323. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9324. addl/q $x,%reg2 subl/q $x,%reg2
  9325. To:
  9326. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9327. }
  9328. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9329. { be lazy, checking separately for sub would be slightly better }
  9330. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9331. begin
  9332. TransferUsedRegs(TmpUsedRegs);
  9333. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9334. if TryMovArith2Lea(hp1) then
  9335. begin
  9336. Result := True;
  9337. Exit;
  9338. end
  9339. end
  9340. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9341. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9342. { Same as above, but also adds or subtracts to %reg2 in between.
  9343. It's still valid as long as the flags aren't in use }
  9344. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9345. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9346. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9347. { be lazy, checking separately for sub would be slightly better }
  9348. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9349. begin
  9350. TransferUsedRegs(TmpUsedRegs);
  9351. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9352. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9353. if TryMovArith2Lea(hp2) then
  9354. begin
  9355. Result := True;
  9356. Exit;
  9357. end;
  9358. end;
  9359. end;
  9360. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9361. {$ifdef x86_64}
  9362. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9363. {$else x86_64}
  9364. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9365. {$endif x86_64}
  9366. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9367. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9368. { mov reg1, reg2 mov reg1, reg2
  9369. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9370. begin
  9371. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9372. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9373. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9374. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9375. TransferUsedRegs(TmpUsedRegs);
  9376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9377. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9378. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9379. then
  9380. begin
  9381. RemoveCurrentP(p, hp1);
  9382. Result:=true;
  9383. end;
  9384. Exit;
  9385. end;
  9386. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9387. IsXCHGAcceptable and
  9388. { XCHG doesn't support 8-bit registers }
  9389. (taicpu(p).opsize <> S_B) and
  9390. MatchInstruction(hp1, A_MOV, []) and
  9391. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9392. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9393. GetNextInstruction(hp1, hp2) and
  9394. MatchInstruction(hp2, A_MOV, []) and
  9395. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9396. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9397. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9398. begin
  9399. { mov %reg1,%reg2
  9400. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9401. mov %reg2,%reg3
  9402. (%reg2 not used afterwards)
  9403. Note that xchg takes 3 cycles to execute, and generally mov's take
  9404. only one cycle apiece, but the first two mov's can be executed in
  9405. parallel, only taking 2 cycles overall. Older processors should
  9406. therefore only optimise for size. [Kit]
  9407. }
  9408. TransferUsedRegs(TmpUsedRegs);
  9409. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9410. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9411. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9412. begin
  9413. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9414. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9415. taicpu(hp1).opcode := A_XCHG;
  9416. RemoveCurrentP(p, hp1);
  9417. RemoveInstruction(hp2);
  9418. Result := True;
  9419. Exit;
  9420. end;
  9421. end;
  9422. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9423. MatchInstruction(hp1, A_SAR, []) then
  9424. begin
  9425. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9426. begin
  9427. { the use of %edx also covers the opsize being S_L }
  9428. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9429. begin
  9430. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9431. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9432. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9433. begin
  9434. { Change:
  9435. movl %eax,%edx
  9436. sarl $31,%edx
  9437. To:
  9438. cltd
  9439. }
  9440. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9441. RemoveInstruction(hp1);
  9442. taicpu(p).opcode := A_CDQ;
  9443. taicpu(p).opsize := S_NO;
  9444. taicpu(p).clearop(1);
  9445. taicpu(p).clearop(0);
  9446. taicpu(p).ops:=0;
  9447. Result := True;
  9448. Exit;
  9449. end
  9450. else if (cs_opt_size in current_settings.optimizerswitches) and
  9451. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9452. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9453. begin
  9454. { Change:
  9455. movl %edx,%eax
  9456. sarl $31,%edx
  9457. To:
  9458. movl %edx,%eax
  9459. cltd
  9460. Note that this creates a dependency between the two instructions,
  9461. so only perform if optimising for size.
  9462. }
  9463. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9464. taicpu(hp1).opcode := A_CDQ;
  9465. taicpu(hp1).opsize := S_NO;
  9466. taicpu(hp1).clearop(1);
  9467. taicpu(hp1).clearop(0);
  9468. taicpu(hp1).ops:=0;
  9469. Include(OptsToCheck, aoc_ForceNewIteration);
  9470. Exit;
  9471. end;
  9472. {$ifndef x86_64}
  9473. end
  9474. { Don't bother if CMOV is supported, because a more optimal
  9475. sequence would have been generated for the Abs() intrinsic }
  9476. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9477. { the use of %eax also covers the opsize being S_L }
  9478. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9479. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9480. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9481. GetNextInstruction(hp1, hp2) and
  9482. MatchInstruction(hp2, A_XOR, [S_L]) and
  9483. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9484. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9485. GetNextInstruction(hp2, hp3) and
  9486. MatchInstruction(hp3, A_SUB, [S_L]) and
  9487. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9488. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9489. begin
  9490. { Change:
  9491. movl %eax,%edx
  9492. sarl $31,%eax
  9493. xorl %eax,%edx
  9494. subl %eax,%edx
  9495. (Instruction that uses %edx)
  9496. (%eax deallocated)
  9497. (%edx deallocated)
  9498. To:
  9499. cltd
  9500. xorl %edx,%eax <-- Note the registers have swapped
  9501. subl %edx,%eax
  9502. (Instruction that uses %eax) <-- %eax rather than %edx
  9503. }
  9504. TransferUsedRegs(TmpUsedRegs);
  9505. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9506. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9507. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9508. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9509. begin
  9510. if GetNextInstruction(hp3, hp4) and
  9511. not RegModifiedByInstruction(NR_EDX, hp4) and
  9512. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9513. begin
  9514. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9515. taicpu(p).opcode := A_CDQ;
  9516. taicpu(p).clearop(1);
  9517. taicpu(p).clearop(0);
  9518. taicpu(p).ops:=0;
  9519. RemoveInstruction(hp1);
  9520. taicpu(hp2).loadreg(0, NR_EDX);
  9521. taicpu(hp2).loadreg(1, NR_EAX);
  9522. taicpu(hp3).loadreg(0, NR_EDX);
  9523. taicpu(hp3).loadreg(1, NR_EAX);
  9524. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9525. { Convert references in the following instruction (hp4) from %edx to %eax }
  9526. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9527. with taicpu(hp4).oper[OperIdx]^ do
  9528. case typ of
  9529. top_reg:
  9530. if getsupreg(reg) = RS_EDX then
  9531. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9532. top_ref:
  9533. begin
  9534. if getsupreg(reg) = RS_EDX then
  9535. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9536. if getsupreg(reg) = RS_EDX then
  9537. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9538. end;
  9539. else
  9540. ;
  9541. end;
  9542. Result := True;
  9543. Exit;
  9544. end;
  9545. end;
  9546. {$else x86_64}
  9547. end;
  9548. end
  9549. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9550. { the use of %rdx also covers the opsize being S_Q }
  9551. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9552. begin
  9553. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9554. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9555. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9556. begin
  9557. { Change:
  9558. movq %rax,%rdx
  9559. sarq $63,%rdx
  9560. To:
  9561. cqto
  9562. }
  9563. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9564. RemoveInstruction(hp1);
  9565. taicpu(p).opcode := A_CQO;
  9566. taicpu(p).opsize := S_NO;
  9567. taicpu(p).clearop(1);
  9568. taicpu(p).clearop(0);
  9569. taicpu(p).ops:=0;
  9570. Result := True;
  9571. Exit;
  9572. end
  9573. else if (cs_opt_size in current_settings.optimizerswitches) and
  9574. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9575. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9576. begin
  9577. { Change:
  9578. movq %rdx,%rax
  9579. sarq $63,%rdx
  9580. To:
  9581. movq %rdx,%rax
  9582. cqto
  9583. Note that this creates a dependency between the two instructions,
  9584. so only perform if optimising for size.
  9585. }
  9586. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9587. taicpu(hp1).opcode := A_CQO;
  9588. taicpu(hp1).opsize := S_NO;
  9589. taicpu(hp1).clearop(1);
  9590. taicpu(hp1).clearop(0);
  9591. taicpu(hp1).ops:=0;
  9592. Include(OptsToCheck, aoc_ForceNewIteration);
  9593. Exit;
  9594. {$endif x86_64}
  9595. end;
  9596. end;
  9597. end;
  9598. if MatchInstruction(hp1, A_MOV, []) and
  9599. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9600. { Though "GetNextInstruction" could be factored out, along with
  9601. the instructions that depend on hp2, it is an expensive call that
  9602. should be delayed for as long as possible, hence we do cheaper
  9603. checks first that are likely to be False. [Kit] }
  9604. begin
  9605. if (
  9606. (
  9607. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9608. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9609. (
  9610. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9611. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9612. )
  9613. ) or
  9614. (
  9615. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9616. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9617. (
  9618. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9619. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9620. )
  9621. )
  9622. ) and
  9623. GetNextInstruction(hp1, hp2) and
  9624. MatchInstruction(hp2, A_SAR, []) and
  9625. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9626. begin
  9627. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9628. begin
  9629. { Change:
  9630. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9631. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9632. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9633. To:
  9634. movl r/m,%eax <- Note the change in register
  9635. cltd
  9636. }
  9637. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9638. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9639. taicpu(p).loadreg(1, NR_EAX);
  9640. taicpu(hp1).opcode := A_CDQ;
  9641. taicpu(hp1).clearop(1);
  9642. taicpu(hp1).clearop(0);
  9643. taicpu(hp1).ops:=0;
  9644. RemoveInstruction(hp2);
  9645. Include(OptsToCheck, aoc_ForceNewIteration);
  9646. (*
  9647. {$ifdef x86_64}
  9648. end
  9649. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9650. { This code sequence does not get generated - however it might become useful
  9651. if and when 128-bit signed integer types make an appearance, so the code
  9652. is kept here for when it is eventually needed. [Kit] }
  9653. (
  9654. (
  9655. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9656. (
  9657. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9658. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9659. )
  9660. ) or
  9661. (
  9662. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9663. (
  9664. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9665. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9666. )
  9667. )
  9668. ) and
  9669. GetNextInstruction(hp1, hp2) and
  9670. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9671. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9672. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9673. begin
  9674. { Change:
  9675. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9676. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9677. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9678. To:
  9679. movq r/m,%rax <- Note the change in register
  9680. cqto
  9681. }
  9682. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9683. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9684. taicpu(p).loadreg(1, NR_RAX);
  9685. taicpu(hp1).opcode := A_CQO;
  9686. taicpu(hp1).clearop(1);
  9687. taicpu(hp1).clearop(0);
  9688. taicpu(hp1).ops:=0;
  9689. RemoveInstruction(hp2);
  9690. Include(OptsToCheck, aoc_ForceNewIteration);
  9691. {$endif x86_64}
  9692. *)
  9693. end;
  9694. end;
  9695. {$ifdef x86_64}
  9696. end;
  9697. if (taicpu(p).opsize = S_L) and
  9698. (taicpu(p).oper[1]^.typ = top_reg) and
  9699. (
  9700. MatchInstruction(hp1, A_MOV,[]) and
  9701. (taicpu(hp1).opsize = S_L) and
  9702. (taicpu(hp1).oper[1]^.typ = top_reg)
  9703. ) and (
  9704. GetNextInstruction(hp1, hp2) and
  9705. (tai(hp2).typ=ait_instruction) and
  9706. (taicpu(hp2).opsize = S_Q) and
  9707. (
  9708. (
  9709. MatchInstruction(hp2, A_ADD,[]) and
  9710. (taicpu(hp2).opsize = S_Q) and
  9711. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9712. (
  9713. (
  9714. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9715. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9716. ) or (
  9717. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9718. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9719. )
  9720. )
  9721. ) or (
  9722. MatchInstruction(hp2, A_LEA,[]) and
  9723. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9724. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9725. (
  9726. (
  9727. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9728. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9729. ) or (
  9730. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9731. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9732. )
  9733. ) and (
  9734. (
  9735. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9736. ) or (
  9737. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9738. )
  9739. )
  9740. )
  9741. )
  9742. ) and (
  9743. GetNextInstruction(hp2, hp3) and
  9744. MatchInstruction(hp3, A_SHR,[]) and
  9745. (taicpu(hp3).opsize = S_Q) and
  9746. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9747. (taicpu(hp3).oper[0]^.val = 1) and
  9748. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9749. ) then
  9750. begin
  9751. { Change movl x, reg1d movl x, reg1d
  9752. movl y, reg2d movl y, reg2d
  9753. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9754. shrq $1, reg1q shrq $1, reg1q
  9755. ( reg1d and reg2d can be switched around in the first two instructions )
  9756. To movl x, reg1d
  9757. addl y, reg1d
  9758. rcrl $1, reg1d
  9759. This corresponds to the common expression (x + y) shr 1, where
  9760. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9761. smaller code, but won't account for x + y causing an overflow). [Kit]
  9762. }
  9763. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9764. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9765. begin
  9766. { Change first MOV command to have the same register as the final output }
  9767. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9768. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9769. Result := True;
  9770. end
  9771. else
  9772. begin
  9773. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9774. Include(OptsToCheck, aoc_ForceNewIteration);
  9775. end;
  9776. { Change second MOV command to an ADD command. This is easier than
  9777. converting the existing command because it means we don't have to
  9778. touch 'y', which might be a complicated reference, and also the
  9779. fact that the third command might either be ADD or LEA. [Kit] }
  9780. taicpu(hp1).opcode := A_ADD;
  9781. { Delete old ADD/LEA instruction }
  9782. RemoveInstruction(hp2);
  9783. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9784. taicpu(hp3).opcode := A_RCR;
  9785. taicpu(hp3).changeopsize(S_L);
  9786. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9787. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9788. called, so FuncMov2Func below is safe to call }
  9789. {$endif x86_64}
  9790. end;
  9791. if FuncMov2Func(p, hp1) then
  9792. begin
  9793. Result := True;
  9794. Exit;
  9795. end;
  9796. end;
  9797. {$push}
  9798. {$q-}{$r-}
  9799. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9800. var
  9801. ThisReg: TRegister;
  9802. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9803. TargetSubReg: TSubRegister;
  9804. hp1, hp2: tai;
  9805. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9806. { Store list of found instructions so we don't have to call
  9807. GetNextInstructionUsingReg multiple times }
  9808. InstrList: array of taicpu;
  9809. InstrMax, Index: Integer;
  9810. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9811. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9812. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9813. WorkingValue: TCgInt;
  9814. PreMessage: string;
  9815. { Data flow analysis }
  9816. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9817. BitwiseOnly, OrXorUsed,
  9818. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9819. function CheckOverflowConditions: Boolean;
  9820. begin
  9821. Result := True;
  9822. if (TestValSignedMax > SignedUpperLimit) then
  9823. UpperSignedOverflow := True;
  9824. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9825. LowerSignedOverflow := True;
  9826. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9827. LowerUnsignedOverflow := True;
  9828. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9829. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9830. begin
  9831. { Absolute overflow }
  9832. Result := False;
  9833. Exit;
  9834. end;
  9835. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9836. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9837. ShiftDownOverflow := True;
  9838. if (TestValMin < 0) or (TestValMax < 0) then
  9839. begin
  9840. LowerUnsignedOverflow := True;
  9841. UpperUnsignedOverflow := True;
  9842. end;
  9843. end;
  9844. function AdjustInitialLoadAndSize: Boolean;
  9845. begin
  9846. Result := False;
  9847. if not p_removed then
  9848. begin
  9849. if TargetSize = MinSize then
  9850. begin
  9851. { Convert the input MOVZX to a MOV }
  9852. if (taicpu(p).oper[0]^.typ = top_reg) and
  9853. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9854. begin
  9855. { Or remove it completely! }
  9856. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9857. RemoveCurrentP(p);
  9858. p_removed := True;
  9859. end
  9860. else
  9861. begin
  9862. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9863. taicpu(p).opcode := A_MOV;
  9864. taicpu(p).oper[1]^.reg := ThisReg;
  9865. taicpu(p).opsize := TargetSize;
  9866. end;
  9867. Result := True;
  9868. end
  9869. else if TargetSize <> MaxSize then
  9870. begin
  9871. case MaxSize of
  9872. S_L:
  9873. if TargetSize = S_W then
  9874. begin
  9875. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9876. taicpu(p).opsize := S_BW;
  9877. taicpu(p).oper[1]^.reg := ThisReg;
  9878. Result := True;
  9879. end
  9880. else
  9881. InternalError(2020112341);
  9882. S_W:
  9883. if TargetSize = S_L then
  9884. begin
  9885. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9886. taicpu(p).opsize := S_BL;
  9887. taicpu(p).oper[1]^.reg := ThisReg;
  9888. Result := True;
  9889. end
  9890. else
  9891. InternalError(2020112342);
  9892. else
  9893. ;
  9894. end;
  9895. end
  9896. else if not hp1_removed and not RegInUse then
  9897. begin
  9898. { If we have something like:
  9899. movzbl (oper),%regd
  9900. add x, %regd
  9901. movzbl %regb, %regd
  9902. We can reduce the register size to the input of the final
  9903. movzbl instruction. Overflows won't have any effect.
  9904. }
  9905. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9906. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9907. begin
  9908. TargetSize := S_B;
  9909. setsubreg(ThisReg, R_SUBL);
  9910. Result := True;
  9911. end
  9912. else if (taicpu(p).opsize = S_WL) and
  9913. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9914. begin
  9915. TargetSize := S_W;
  9916. setsubreg(ThisReg, R_SUBW);
  9917. Result := True;
  9918. end;
  9919. if Result then
  9920. begin
  9921. { Convert the input MOVZX to a MOV }
  9922. if (taicpu(p).oper[0]^.typ = top_reg) and
  9923. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9924. begin
  9925. { Or remove it completely! }
  9926. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9927. RemoveCurrentP(p);
  9928. p_removed := True;
  9929. end
  9930. else
  9931. begin
  9932. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9933. taicpu(p).opcode := A_MOV;
  9934. taicpu(p).oper[1]^.reg := ThisReg;
  9935. taicpu(p).opsize := TargetSize;
  9936. end;
  9937. end;
  9938. end;
  9939. end;
  9940. end;
  9941. procedure AdjustFinalLoad;
  9942. begin
  9943. if not LowerUnsignedOverflow then
  9944. begin
  9945. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9946. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9947. begin
  9948. { Convert the output MOVZX to a MOV }
  9949. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9950. begin
  9951. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9952. if (MinSize = S_B) or
  9953. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9954. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9955. begin
  9956. { Remove it completely! }
  9957. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9958. { Be careful; if p = hp1 and p was also removed, p
  9959. will become a dangling pointer }
  9960. if p = hp1 then
  9961. begin
  9962. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9963. p_removed := True;
  9964. end
  9965. else
  9966. RemoveInstruction(hp1);
  9967. hp1_removed := True;
  9968. end;
  9969. end
  9970. else
  9971. begin
  9972. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9973. taicpu(hp1).opcode := A_MOV;
  9974. taicpu(hp1).oper[0]^.reg := ThisReg;
  9975. taicpu(hp1).opsize := TargetSize;
  9976. end;
  9977. end
  9978. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9979. begin
  9980. { Need to change the size of the output }
  9981. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9982. taicpu(hp1).oper[0]^.reg := ThisReg;
  9983. taicpu(hp1).opsize := S_BL;
  9984. end;
  9985. end;
  9986. end;
  9987. function CompressInstructions: Boolean;
  9988. var
  9989. LocalIndex: Integer;
  9990. begin
  9991. Result := False;
  9992. { The objective here is to try to find a combination that
  9993. removes one of the MOV/Z instructions. }
  9994. if (
  9995. (taicpu(p).oper[0]^.typ <> top_reg) or
  9996. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9997. ) and
  9998. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9999. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10000. begin
  10001. { Make a preference to remove the second MOVZX instruction }
  10002. case taicpu(hp1).opsize of
  10003. S_BL, S_WL:
  10004. begin
  10005. TargetSize := S_L;
  10006. TargetSubReg := R_SUBD;
  10007. end;
  10008. S_BW:
  10009. begin
  10010. TargetSize := S_W;
  10011. TargetSubReg := R_SUBW;
  10012. end;
  10013. else
  10014. InternalError(2020112302);
  10015. end;
  10016. end
  10017. else
  10018. begin
  10019. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10020. begin
  10021. { Exceeded lower bound but not upper bound }
  10022. TargetSize := MaxSize;
  10023. end
  10024. else if not LowerUnsignedOverflow then
  10025. begin
  10026. { Size didn't exceed lower bound }
  10027. TargetSize := MinSize;
  10028. end
  10029. else
  10030. Exit;
  10031. end;
  10032. case TargetSize of
  10033. S_B:
  10034. TargetSubReg := R_SUBL;
  10035. S_W:
  10036. TargetSubReg := R_SUBW;
  10037. S_L:
  10038. TargetSubReg := R_SUBD;
  10039. else
  10040. InternalError(2020112350);
  10041. end;
  10042. { Update the register to its new size }
  10043. setsubreg(ThisReg, TargetSubReg);
  10044. RegInUse := False;
  10045. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10046. begin
  10047. { Check to see if the active register is used afterwards;
  10048. if not, we can change it and make a saving. }
  10049. TransferUsedRegs(TmpUsedRegs);
  10050. { The target register may be marked as in use to cross
  10051. a jump to a distant label, so exclude it }
  10052. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10053. hp2 := p;
  10054. repeat
  10055. { Explicitly check for the excluded register (don't include the first
  10056. instruction as it may be reading from here }
  10057. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10058. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10059. begin
  10060. RegInUse := True;
  10061. Break;
  10062. end;
  10063. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10064. if not GetNextInstruction(hp2, hp2) then
  10065. InternalError(2020112340);
  10066. until (hp2 = hp1);
  10067. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10068. { We might still be able to get away with this }
  10069. RegInUse := not
  10070. (
  10071. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10072. (hp2.typ = ait_instruction) and
  10073. (
  10074. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10075. instruction that doesn't actually contain ThisReg }
  10076. (cs_opt_level3 in current_settings.optimizerswitches) or
  10077. RegInInstruction(ThisReg, hp2)
  10078. ) and
  10079. RegLoadedWithNewValue(ThisReg, hp2)
  10080. );
  10081. if not RegInUse then
  10082. begin
  10083. { Force the register size to the same as this instruction so it can be removed}
  10084. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10085. begin
  10086. TargetSize := S_L;
  10087. TargetSubReg := R_SUBD;
  10088. end
  10089. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10090. begin
  10091. TargetSize := S_W;
  10092. TargetSubReg := R_SUBW;
  10093. end;
  10094. ThisReg := taicpu(hp1).oper[1]^.reg;
  10095. setsubreg(ThisReg, TargetSubReg);
  10096. RegChanged := True;
  10097. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10098. TransferUsedRegs(TmpUsedRegs);
  10099. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10100. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10101. if p = hp1 then
  10102. begin
  10103. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10104. p_removed := True;
  10105. end
  10106. else
  10107. RemoveInstruction(hp1);
  10108. hp1_removed := True;
  10109. { Instruction will become "mov %reg,%reg" }
  10110. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10111. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10112. begin
  10113. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10114. RemoveCurrentP(p);
  10115. p_removed := True;
  10116. end
  10117. else
  10118. taicpu(p).oper[1]^.reg := ThisReg;
  10119. Result := True;
  10120. end
  10121. else
  10122. begin
  10123. if TargetSize <> MaxSize then
  10124. begin
  10125. { Since the register is in use, we have to force it to
  10126. MaxSize otherwise part of it may become undefined later on }
  10127. TargetSize := MaxSize;
  10128. case TargetSize of
  10129. S_B:
  10130. TargetSubReg := R_SUBL;
  10131. S_W:
  10132. TargetSubReg := R_SUBW;
  10133. S_L:
  10134. TargetSubReg := R_SUBD;
  10135. else
  10136. InternalError(2020112351);
  10137. end;
  10138. setsubreg(ThisReg, TargetSubReg);
  10139. end;
  10140. AdjustFinalLoad;
  10141. end;
  10142. end
  10143. else
  10144. AdjustFinalLoad;
  10145. Result := AdjustInitialLoadAndSize or Result;
  10146. { Now go through every instruction we found and change the
  10147. size. If TargetSize = MaxSize, then almost no changes are
  10148. needed and Result can remain False if it hasn't been set
  10149. yet.
  10150. If RegChanged is True, then the register requires changing
  10151. and so the point about TargetSize = MaxSize doesn't apply. }
  10152. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10153. begin
  10154. for LocalIndex := 0 to InstrMax do
  10155. begin
  10156. { If p_removed is true, then the original MOV/Z was removed
  10157. and removing the AND instruction may not be safe if it
  10158. appears first }
  10159. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10160. InternalError(2020112310);
  10161. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10162. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10163. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10164. InstrList[LocalIndex].opsize := TargetSize;
  10165. end;
  10166. Result := True;
  10167. end;
  10168. end;
  10169. begin
  10170. Result := False;
  10171. p_removed := False;
  10172. hp1_removed := False;
  10173. ThisReg := taicpu(p).oper[1]^.reg;
  10174. { Check for:
  10175. movs/z ###,%ecx (or %cx or %rcx)
  10176. ...
  10177. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10178. (dealloc %ecx)
  10179. Change to:
  10180. mov ###,%cl (if ### = %cl, then remove completely)
  10181. ...
  10182. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10183. }
  10184. if (getsupreg(ThisReg) = RS_ECX) and
  10185. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10186. (hp1.typ = ait_instruction) and
  10187. (
  10188. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10189. instruction that doesn't actually contain ECX }
  10190. (cs_opt_level3 in current_settings.optimizerswitches) or
  10191. RegInInstruction(NR_ECX, hp1) or
  10192. (
  10193. { It's common for the shift/rotate's read/write register to be
  10194. initialised in between, so under -O2 and under, search ahead
  10195. one more instruction
  10196. }
  10197. GetNextInstruction(hp1, hp1) and
  10198. (hp1.typ = ait_instruction) and
  10199. RegInInstruction(NR_ECX, hp1)
  10200. )
  10201. ) and
  10202. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10203. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10204. begin
  10205. TransferUsedRegs(TmpUsedRegs);
  10206. hp2 := p;
  10207. repeat
  10208. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10209. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10210. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10211. begin
  10212. case taicpu(p).opsize of
  10213. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10214. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10215. begin
  10216. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10217. RemoveCurrentP(p);
  10218. end
  10219. else
  10220. begin
  10221. taicpu(p).opcode := A_MOV;
  10222. taicpu(p).opsize := S_B;
  10223. taicpu(p).oper[1]^.reg := NR_CL;
  10224. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10225. end;
  10226. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10227. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10228. begin
  10229. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10230. RemoveCurrentP(p);
  10231. end
  10232. else
  10233. begin
  10234. taicpu(p).opcode := A_MOV;
  10235. taicpu(p).opsize := S_W;
  10236. taicpu(p).oper[1]^.reg := NR_CX;
  10237. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10238. end;
  10239. {$ifdef x86_64}
  10240. S_LQ:
  10241. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10242. begin
  10243. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10244. RemoveCurrentP(p);
  10245. end
  10246. else
  10247. begin
  10248. taicpu(p).opcode := A_MOV;
  10249. taicpu(p).opsize := S_L;
  10250. taicpu(p).oper[1]^.reg := NR_ECX;
  10251. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10252. end;
  10253. {$endif x86_64}
  10254. else
  10255. InternalError(2021120401);
  10256. end;
  10257. Result := True;
  10258. Exit;
  10259. end;
  10260. end;
  10261. { This is anything but quick! }
  10262. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10263. Exit;
  10264. SetLength(InstrList, 0);
  10265. InstrMax := -1;
  10266. case taicpu(p).opsize of
  10267. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10268. begin
  10269. {$if defined(i386) or defined(i8086)}
  10270. { If the target size is 8-bit, make sure we can actually encode it }
  10271. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10272. Exit;
  10273. {$endif i386 or i8086}
  10274. LowerLimit := $FF;
  10275. SignedLowerLimit := $7F;
  10276. SignedLowerLimitBottom := -128;
  10277. MinSize := S_B;
  10278. if taicpu(p).opsize = S_BW then
  10279. begin
  10280. MaxSize := S_W;
  10281. UpperLimit := $FFFF;
  10282. SignedUpperLimit := $7FFF;
  10283. SignedUpperLimitBottom := -32768;
  10284. end
  10285. else
  10286. begin
  10287. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10288. MaxSize := S_L;
  10289. UpperLimit := $FFFFFFFF;
  10290. SignedUpperLimit := $7FFFFFFF;
  10291. SignedUpperLimitBottom := -2147483648;
  10292. end;
  10293. end;
  10294. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10295. begin
  10296. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10297. LowerLimit := $FFFF;
  10298. SignedLowerLimit := $7FFF;
  10299. SignedLowerLimitBottom := -32768;
  10300. UpperLimit := $FFFFFFFF;
  10301. SignedUpperLimit := $7FFFFFFF;
  10302. SignedUpperLimitBottom := -2147483648;
  10303. MinSize := S_W;
  10304. MaxSize := S_L;
  10305. end;
  10306. {$ifdef x86_64}
  10307. S_LQ:
  10308. begin
  10309. { Both the lower and upper limits are set to 32-bit. If a limit
  10310. is breached, then optimisation is impossible }
  10311. LowerLimit := $FFFFFFFF;
  10312. SignedLowerLimit := $7FFFFFFF;
  10313. SignedLowerLimitBottom := -2147483648;
  10314. UpperLimit := $FFFFFFFF;
  10315. SignedUpperLimit := $7FFFFFFF;
  10316. SignedUpperLimitBottom := -2147483648;
  10317. MinSize := S_L;
  10318. MaxSize := S_L;
  10319. end;
  10320. {$endif x86_64}
  10321. else
  10322. InternalError(2020112301);
  10323. end;
  10324. TestValMin := 0;
  10325. TestValMax := LowerLimit;
  10326. TestValSignedMax := SignedLowerLimit;
  10327. TryShiftDownLimit := LowerLimit;
  10328. TryShiftDown := S_NO;
  10329. ShiftDownOverflow := False;
  10330. RegChanged := False;
  10331. BitwiseOnly := True;
  10332. OrXorUsed := False;
  10333. UpperSignedOverflow := False;
  10334. LowerSignedOverflow := False;
  10335. UpperUnsignedOverflow := False;
  10336. LowerUnsignedOverflow := False;
  10337. hp1 := p;
  10338. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10339. (hp1.typ = ait_instruction) and
  10340. (
  10341. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10342. instruction that doesn't actually contain ThisReg }
  10343. (cs_opt_level3 in current_settings.optimizerswitches) or
  10344. { This allows this Movx optimisation to work through the SETcc instructions
  10345. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10346. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10347. skip over these SETcc instructions). }
  10348. (taicpu(hp1).opcode = A_SETcc) or
  10349. RegInInstruction(ThisReg, hp1)
  10350. ) do
  10351. begin
  10352. case taicpu(hp1).opcode of
  10353. A_INC,A_DEC:
  10354. begin
  10355. { Has to be an exact match on the register }
  10356. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10357. Break;
  10358. if taicpu(hp1).opcode = A_INC then
  10359. begin
  10360. Inc(TestValMin);
  10361. Inc(TestValMax);
  10362. Inc(TestValSignedMax);
  10363. end
  10364. else
  10365. begin
  10366. Dec(TestValMin);
  10367. Dec(TestValMax);
  10368. Dec(TestValSignedMax);
  10369. end;
  10370. end;
  10371. A_TEST, A_CMP:
  10372. begin
  10373. if (
  10374. { Too high a risk of non-linear behaviour that breaks DFA
  10375. here, unless it's cmp $0,%reg, which is equivalent to
  10376. test %reg,%reg }
  10377. OrXorUsed and
  10378. (taicpu(hp1).opcode = A_CMP) and
  10379. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10380. ) or
  10381. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10382. { Has to be an exact match on the register }
  10383. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10384. (
  10385. { Permit "test %reg,%reg" }
  10386. (taicpu(hp1).opcode = A_TEST) and
  10387. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10388. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10389. ) or
  10390. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10391. { Make sure the comparison value is not smaller than the
  10392. smallest allowed signed value for the minimum size (e.g.
  10393. -128 for 8-bit) }
  10394. not (
  10395. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10396. { Is it in the negative range? }
  10397. (
  10398. (taicpu(hp1).oper[0]^.val < 0) and
  10399. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10400. )
  10401. ) then
  10402. Break;
  10403. { Check to see if the active register is used afterwards }
  10404. TransferUsedRegs(TmpUsedRegs);
  10405. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10406. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10407. begin
  10408. { Make sure the comparison or any previous instructions
  10409. hasn't pushed the test values outside of the range of
  10410. MinSize }
  10411. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10412. begin
  10413. { Exceeded lower bound but not upper bound }
  10414. Exit;
  10415. end
  10416. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10417. begin
  10418. { Size didn't exceed lower bound }
  10419. TargetSize := MinSize;
  10420. end
  10421. else
  10422. Break;
  10423. case TargetSize of
  10424. S_B:
  10425. TargetSubReg := R_SUBL;
  10426. S_W:
  10427. TargetSubReg := R_SUBW;
  10428. S_L:
  10429. TargetSubReg := R_SUBD;
  10430. else
  10431. InternalError(2021051002);
  10432. end;
  10433. if TargetSize <> MaxSize then
  10434. begin
  10435. { Update the register to its new size }
  10436. setsubreg(ThisReg, TargetSubReg);
  10437. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10438. taicpu(hp1).oper[1]^.reg := ThisReg;
  10439. taicpu(hp1).opsize := TargetSize;
  10440. { Convert the input MOVZX to a MOV if necessary }
  10441. AdjustInitialLoadAndSize;
  10442. if (InstrMax >= 0) then
  10443. begin
  10444. for Index := 0 to InstrMax do
  10445. begin
  10446. { If p_removed is true, then the original MOV/Z was removed
  10447. and removing the AND instruction may not be safe if it
  10448. appears first }
  10449. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10450. InternalError(2020112311);
  10451. if InstrList[Index].oper[0]^.typ = top_reg then
  10452. InstrList[Index].oper[0]^.reg := ThisReg;
  10453. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10454. InstrList[Index].opsize := MinSize;
  10455. end;
  10456. end;
  10457. Result := True;
  10458. end;
  10459. Exit;
  10460. end;
  10461. end;
  10462. A_SETcc:
  10463. begin
  10464. { This allows this Movx optimisation to work through the SETcc instructions
  10465. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10466. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10467. skip over these SETcc instructions). }
  10468. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10469. { Of course, break out if the current register is used }
  10470. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10471. Break
  10472. else
  10473. { We must use Continue so the instruction doesn't get added
  10474. to InstrList }
  10475. Continue;
  10476. end;
  10477. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10478. begin
  10479. if
  10480. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10481. { Has to be an exact match on the register }
  10482. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10483. (
  10484. (
  10485. (taicpu(hp1).oper[0]^.typ = top_const) and
  10486. (
  10487. (
  10488. (taicpu(hp1).opcode = A_SHL) and
  10489. (
  10490. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10491. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10492. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10493. )
  10494. ) or (
  10495. (taicpu(hp1).opcode <> A_SHL) and
  10496. (
  10497. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10498. { Is it in the negative range? }
  10499. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10500. )
  10501. )
  10502. )
  10503. ) or (
  10504. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10505. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10506. )
  10507. ) then
  10508. Break;
  10509. { Only process OR and XOR if there are only bitwise operations,
  10510. since otherwise they can too easily fool the data flow
  10511. analysis (they can cause non-linear behaviour) }
  10512. case taicpu(hp1).opcode of
  10513. A_ADD:
  10514. begin
  10515. if OrXorUsed then
  10516. { Too high a risk of non-linear behaviour that breaks DFA here }
  10517. Break
  10518. else
  10519. BitwiseOnly := False;
  10520. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10521. begin
  10522. TestValMin := TestValMin * 2;
  10523. TestValMax := TestValMax * 2;
  10524. TestValSignedMax := TestValSignedMax * 2;
  10525. end
  10526. else
  10527. begin
  10528. WorkingValue := taicpu(hp1).oper[0]^.val;
  10529. TestValMin := TestValMin + WorkingValue;
  10530. TestValMax := TestValMax + WorkingValue;
  10531. TestValSignedMax := TestValSignedMax + WorkingValue;
  10532. end;
  10533. end;
  10534. A_SUB:
  10535. begin
  10536. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10537. begin
  10538. TestValMin := 0;
  10539. TestValMax := 0;
  10540. TestValSignedMax := 0;
  10541. end
  10542. else
  10543. begin
  10544. if OrXorUsed then
  10545. { Too high a risk of non-linear behaviour that breaks DFA here }
  10546. Break
  10547. else
  10548. BitwiseOnly := False;
  10549. WorkingValue := taicpu(hp1).oper[0]^.val;
  10550. TestValMin := TestValMin - WorkingValue;
  10551. TestValMax := TestValMax - WorkingValue;
  10552. TestValSignedMax := TestValSignedMax - WorkingValue;
  10553. end;
  10554. end;
  10555. A_AND:
  10556. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10557. begin
  10558. { we might be able to go smaller if AND appears first }
  10559. if InstrMax = -1 then
  10560. case MinSize of
  10561. S_B:
  10562. ;
  10563. S_W:
  10564. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10565. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10566. begin
  10567. TryShiftDown := S_B;
  10568. TryShiftDownLimit := $FF;
  10569. end;
  10570. S_L:
  10571. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10572. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10573. begin
  10574. TryShiftDown := S_B;
  10575. TryShiftDownLimit := $FF;
  10576. end
  10577. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10578. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10579. begin
  10580. TryShiftDown := S_W;
  10581. TryShiftDownLimit := $FFFF;
  10582. end;
  10583. else
  10584. InternalError(2020112320);
  10585. end;
  10586. WorkingValue := taicpu(hp1).oper[0]^.val;
  10587. TestValMin := TestValMin and WorkingValue;
  10588. TestValMax := TestValMax and WorkingValue;
  10589. TestValSignedMax := TestValSignedMax and WorkingValue;
  10590. end;
  10591. A_OR:
  10592. begin
  10593. if not BitwiseOnly then
  10594. Break;
  10595. OrXorUsed := True;
  10596. WorkingValue := taicpu(hp1).oper[0]^.val;
  10597. TestValMin := TestValMin or WorkingValue;
  10598. TestValMax := TestValMax or WorkingValue;
  10599. TestValSignedMax := TestValSignedMax or WorkingValue;
  10600. end;
  10601. A_XOR:
  10602. begin
  10603. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10604. begin
  10605. TestValMin := 0;
  10606. TestValMax := 0;
  10607. TestValSignedMax := 0;
  10608. end
  10609. else
  10610. begin
  10611. if not BitwiseOnly then
  10612. Break;
  10613. OrXorUsed := True;
  10614. WorkingValue := taicpu(hp1).oper[0]^.val;
  10615. TestValMin := TestValMin xor WorkingValue;
  10616. TestValMax := TestValMax xor WorkingValue;
  10617. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10618. end;
  10619. end;
  10620. A_SHL:
  10621. begin
  10622. BitwiseOnly := False;
  10623. WorkingValue := taicpu(hp1).oper[0]^.val;
  10624. TestValMin := TestValMin shl WorkingValue;
  10625. TestValMax := TestValMax shl WorkingValue;
  10626. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10627. end;
  10628. A_SHR,
  10629. { The first instruction was MOVZX, so the value won't be negative }
  10630. A_SAR:
  10631. begin
  10632. if InstrMax <> -1 then
  10633. BitwiseOnly := False
  10634. else
  10635. { we might be able to go smaller if SHR appears first }
  10636. case MinSize of
  10637. S_B:
  10638. ;
  10639. S_W:
  10640. if (taicpu(hp1).oper[0]^.val >= 8) then
  10641. begin
  10642. TryShiftDown := S_B;
  10643. TryShiftDownLimit := $FF;
  10644. TryShiftDownSignedLimit := $7F;
  10645. TryShiftDownSignedLimitLower := -128;
  10646. end;
  10647. S_L:
  10648. if (taicpu(hp1).oper[0]^.val >= 24) then
  10649. begin
  10650. TryShiftDown := S_B;
  10651. TryShiftDownLimit := $FF;
  10652. TryShiftDownSignedLimit := $7F;
  10653. TryShiftDownSignedLimitLower := -128;
  10654. end
  10655. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10656. begin
  10657. TryShiftDown := S_W;
  10658. TryShiftDownLimit := $FFFF;
  10659. TryShiftDownSignedLimit := $7FFF;
  10660. TryShiftDownSignedLimitLower := -32768;
  10661. end;
  10662. else
  10663. InternalError(2020112321);
  10664. end;
  10665. WorkingValue := taicpu(hp1).oper[0]^.val;
  10666. if taicpu(hp1).opcode = A_SAR then
  10667. begin
  10668. TestValMin := SarInt64(TestValMin, WorkingValue);
  10669. TestValMax := SarInt64(TestValMax, WorkingValue);
  10670. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10671. end
  10672. else
  10673. begin
  10674. TestValMin := TestValMin shr WorkingValue;
  10675. TestValMax := TestValMax shr WorkingValue;
  10676. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10677. end;
  10678. end;
  10679. else
  10680. InternalError(2020112303);
  10681. end;
  10682. end;
  10683. (*
  10684. A_IMUL:
  10685. case taicpu(hp1).ops of
  10686. 2:
  10687. begin
  10688. if not MatchOpType(hp1, top_reg, top_reg) or
  10689. { Has to be an exact match on the register }
  10690. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10691. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10692. Break;
  10693. TestValMin := TestValMin * TestValMin;
  10694. TestValMax := TestValMax * TestValMax;
  10695. TestValSignedMax := TestValSignedMax * TestValMax;
  10696. end;
  10697. 3:
  10698. begin
  10699. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10700. { Has to be an exact match on the register }
  10701. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10702. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10703. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10704. { Is it in the negative range? }
  10705. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10706. Break;
  10707. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10708. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10709. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10710. end;
  10711. else
  10712. Break;
  10713. end;
  10714. A_IDIV:
  10715. case taicpu(hp1).ops of
  10716. 3:
  10717. begin
  10718. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10719. { Has to be an exact match on the register }
  10720. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10721. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10722. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10723. { Is it in the negative range? }
  10724. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10725. Break;
  10726. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10727. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10728. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10729. end;
  10730. else
  10731. Break;
  10732. end;
  10733. *)
  10734. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10735. begin
  10736. { If there are no instructions in between, then we might be able to make a saving }
  10737. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10738. Break;
  10739. { We have something like:
  10740. movzbw %dl,%dx
  10741. ...
  10742. movswl %dx,%edx
  10743. Change the latter to a zero-extension then enter the
  10744. A_MOVZX case branch.
  10745. }
  10746. {$ifdef x86_64}
  10747. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10748. begin
  10749. { this becomes a zero extension from 32-bit to 64-bit, but
  10750. the upper 32 bits are already zero, so just delete the
  10751. instruction }
  10752. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10753. RemoveInstruction(hp1);
  10754. Result := True;
  10755. Exit;
  10756. end
  10757. else
  10758. {$endif x86_64}
  10759. begin
  10760. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10761. taicpu(hp1).opcode := A_MOVZX;
  10762. {$ifdef x86_64}
  10763. case taicpu(hp1).opsize of
  10764. S_BQ:
  10765. begin
  10766. taicpu(hp1).opsize := S_BL;
  10767. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10768. end;
  10769. S_WQ:
  10770. begin
  10771. taicpu(hp1).opsize := S_WL;
  10772. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10773. end;
  10774. S_LQ:
  10775. begin
  10776. taicpu(hp1).opcode := A_MOV;
  10777. taicpu(hp1).opsize := S_L;
  10778. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10779. { In this instance, we need to break out because the
  10780. instruction is no longer MOVZX or MOVSXD }
  10781. Result := True;
  10782. Exit;
  10783. end;
  10784. else
  10785. ;
  10786. end;
  10787. {$endif x86_64}
  10788. Result := CompressInstructions;
  10789. Exit;
  10790. end;
  10791. end;
  10792. A_MOVZX:
  10793. begin
  10794. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10795. Break;
  10796. if (InstrMax = -1) then
  10797. begin
  10798. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10799. begin
  10800. { Optimise around i40003 }
  10801. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10802. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10803. {$ifndef x86_64}
  10804. and (
  10805. (taicpu(p).oper[0]^.typ <> top_reg) or
  10806. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10807. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10808. )
  10809. {$endif not x86_64}
  10810. then
  10811. begin
  10812. if (taicpu(p).oper[0]^.typ = top_reg) then
  10813. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10814. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10815. taicpu(p).opsize := S_BL;
  10816. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10817. RemoveInstruction(hp1);
  10818. Result := True;
  10819. Exit;
  10820. end;
  10821. end
  10822. else
  10823. begin
  10824. { Will return false if the second parameter isn't ThisReg
  10825. (can happen on -O2 and under) }
  10826. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10827. begin
  10828. { The two MOVZX instructions are adjacent, so remove the first one }
  10829. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10830. RemoveCurrentP(p);
  10831. Result := True;
  10832. Exit;
  10833. end;
  10834. Break;
  10835. end;
  10836. end;
  10837. Result := CompressInstructions;
  10838. Exit;
  10839. end;
  10840. else
  10841. { This includes ADC, SBB and IDIV }
  10842. Break;
  10843. end;
  10844. if not CheckOverflowConditions then
  10845. Break;
  10846. { Contains highest index (so instruction count - 1) }
  10847. Inc(InstrMax);
  10848. if InstrMax > High(InstrList) then
  10849. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10850. InstrList[InstrMax] := taicpu(hp1);
  10851. end;
  10852. end;
  10853. {$pop}
  10854. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10855. var
  10856. hp1 : tai;
  10857. begin
  10858. Result:=false;
  10859. if (taicpu(p).ops >= 2) and
  10860. ((taicpu(p).oper[0]^.typ = top_const) or
  10861. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10862. (taicpu(p).oper[1]^.typ = top_reg) and
  10863. ((taicpu(p).ops = 2) or
  10864. ((taicpu(p).oper[2]^.typ = top_reg) and
  10865. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10866. GetLastInstruction(p,hp1) and
  10867. MatchInstruction(hp1,A_MOV,[]) and
  10868. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10869. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10870. begin
  10871. TransferUsedRegs(TmpUsedRegs);
  10872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10873. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10874. { change
  10875. mov reg1,reg2
  10876. imul y,reg2 to imul y,reg1,reg2 }
  10877. begin
  10878. taicpu(p).ops := 3;
  10879. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10880. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10881. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10882. RemoveInstruction(hp1);
  10883. result:=true;
  10884. end;
  10885. end;
  10886. end;
  10887. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10888. var
  10889. ThisLabel: TAsmLabel;
  10890. begin
  10891. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10892. ThisLabel.decrefs;
  10893. taicpu(p).condition := C_None;
  10894. taicpu(p).opcode := A_RET;
  10895. taicpu(p).is_jmp := false;
  10896. taicpu(p).ops := taicpu(ret_p).ops;
  10897. case taicpu(ret_p).ops of
  10898. 0:
  10899. taicpu(p).clearop(0);
  10900. 1:
  10901. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10902. else
  10903. internalerror(2016041301);
  10904. end;
  10905. { If the original label is now dead, it might turn out that the label
  10906. immediately follows p. As a result, everything beyond it, which will
  10907. be just some final register configuration and a RET instruction, is
  10908. now dead code. [Kit] }
  10909. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10910. running RemoveDeadCodeAfterJump for each RET instruction, because
  10911. this optimisation rarely happens and most RETs appear at the end of
  10912. routines where there is nothing that can be stripped. [Kit] }
  10913. if not ThisLabel.is_used then
  10914. RemoveDeadCodeAfterJump(p);
  10915. end;
  10916. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10917. var
  10918. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10919. Unconditional, PotentialModified: Boolean;
  10920. OperPtr: POper;
  10921. NewRef: TReference;
  10922. InstrList: array of taicpu;
  10923. InstrMax, Index: Integer;
  10924. const
  10925. {$ifdef DEBUG_AOPTCPU}
  10926. SNoFlags: shortstring = ' so the flags aren''t modified';
  10927. {$else DEBUG_AOPTCPU}
  10928. SNoFlags = '';
  10929. {$endif DEBUG_AOPTCPU}
  10930. begin
  10931. Result:=false;
  10932. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10933. begin
  10934. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10935. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10936. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10937. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10938. GetNextInstruction(hp1, hp2) and
  10939. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10940. { Change from: To:
  10941. set(C) %reg j(~C) label
  10942. test %reg,%reg/cmp $0,%reg
  10943. je label
  10944. set(C) %reg j(C) label
  10945. test %reg,%reg/cmp $0,%reg
  10946. jne label
  10947. (Also do something similar with sete/setne instead of je/jne)
  10948. }
  10949. begin
  10950. { Before we do anything else, we need to check the instructions
  10951. in between SETcc and TEST to make sure they don't modify the
  10952. FLAGS register - if -O2 or under, there won't be any
  10953. instructions between SET and TEST }
  10954. TransferUsedRegs(TmpUsedRegs);
  10955. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10956. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10957. begin
  10958. next := p;
  10959. SetLength(InstrList, 0);
  10960. InstrMax := -1;
  10961. PotentialModified := False;
  10962. { Make a note of every instruction that modifies the FLAGS
  10963. register }
  10964. while GetNextInstruction(next, next) and (next <> hp1) do
  10965. begin
  10966. if next.typ <> ait_instruction then
  10967. { GetNextInstructionUsingReg should have returned False }
  10968. InternalError(2021051701);
  10969. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10970. begin
  10971. case taicpu(next).opcode of
  10972. A_SETcc,
  10973. A_CMOVcc,
  10974. A_Jcc:
  10975. begin
  10976. if PotentialModified then
  10977. { Not safe because the flags were modified earlier }
  10978. Exit
  10979. else
  10980. { Condition is the same as the initial SETcc, so this is safe
  10981. (don't add to instruction list though) }
  10982. Continue;
  10983. end;
  10984. A_ADD:
  10985. begin
  10986. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10987. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10988. (taicpu(next).oper[1]^.typ <> top_reg) or
  10989. { Must write to a register }
  10990. (taicpu(next).oper[0]^.typ = top_ref) then
  10991. { Require a constant or a register }
  10992. Exit;
  10993. PotentialModified := True;
  10994. end;
  10995. A_SUB:
  10996. begin
  10997. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10998. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10999. (taicpu(next).oper[1]^.typ <> top_reg) or
  11000. { Must write to a register }
  11001. (taicpu(next).oper[0]^.typ <> top_const) or
  11002. (taicpu(next).oper[0]^.val = $80000000) then
  11003. { Can't subtract a register with LEA - also
  11004. check that the value isn't -2^31, as this
  11005. can't be negated }
  11006. Exit;
  11007. PotentialModified := True;
  11008. end;
  11009. A_SAL,
  11010. A_SHL:
  11011. begin
  11012. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11013. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11014. (taicpu(next).oper[1]^.typ <> top_reg) or
  11015. { Must write to a register }
  11016. (taicpu(next).oper[0]^.typ <> top_const) or
  11017. (taicpu(next).oper[0]^.val < 0) or
  11018. (taicpu(next).oper[0]^.val > 3) then
  11019. Exit;
  11020. PotentialModified := True;
  11021. end;
  11022. A_IMUL:
  11023. begin
  11024. if (taicpu(next).ops <> 3) or
  11025. (taicpu(next).oper[1]^.typ <> top_reg) or
  11026. { Must write to a register }
  11027. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11028. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11029. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11030. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11031. Exit
  11032. else
  11033. PotentialModified := True;
  11034. end;
  11035. else
  11036. { Don't know how to change this, so abort }
  11037. Exit;
  11038. end;
  11039. { Contains highest index (so instruction count - 1) }
  11040. Inc(InstrMax);
  11041. if InstrMax > High(InstrList) then
  11042. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11043. InstrList[InstrMax] := taicpu(next);
  11044. end;
  11045. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11046. end;
  11047. if not Assigned(next) or (next <> hp1) then
  11048. { It should be equal to hp1 }
  11049. InternalError(2021051702);
  11050. { Cycle through each instruction and check to see if we can
  11051. change them to versions that don't modify the flags }
  11052. if (InstrMax >= 0) then
  11053. begin
  11054. for Index := 0 to InstrMax do
  11055. case InstrList[Index].opcode of
  11056. A_ADD:
  11057. begin
  11058. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11059. InstrList[Index].opcode := A_LEA;
  11060. reference_reset(NewRef, 1, []);
  11061. NewRef.base := InstrList[Index].oper[1]^.reg;
  11062. if InstrList[Index].oper[0]^.typ = top_reg then
  11063. begin
  11064. NewRef.index := InstrList[Index].oper[0]^.reg;
  11065. NewRef.scalefactor := 1;
  11066. end
  11067. else
  11068. NewRef.offset := InstrList[Index].oper[0]^.val;
  11069. InstrList[Index].loadref(0, NewRef);
  11070. end;
  11071. A_SUB:
  11072. begin
  11073. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11074. InstrList[Index].opcode := A_LEA;
  11075. reference_reset(NewRef, 1, []);
  11076. NewRef.base := InstrList[Index].oper[1]^.reg;
  11077. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11078. InstrList[Index].loadref(0, NewRef);
  11079. end;
  11080. A_SHL,
  11081. A_SAL:
  11082. begin
  11083. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11084. InstrList[Index].opcode := A_LEA;
  11085. reference_reset(NewRef, 1, []);
  11086. NewRef.index := InstrList[Index].oper[1]^.reg;
  11087. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11088. InstrList[Index].loadref(0, NewRef);
  11089. end;
  11090. A_IMUL:
  11091. begin
  11092. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11093. InstrList[Index].opcode := A_LEA;
  11094. reference_reset(NewRef, 1, []);
  11095. NewRef.index := InstrList[Index].oper[1]^.reg;
  11096. case InstrList[Index].oper[0]^.val of
  11097. 2, 4, 8:
  11098. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11099. else {3, 5 and 9}
  11100. begin
  11101. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11102. NewRef.base := InstrList[Index].oper[1]^.reg;
  11103. end;
  11104. end;
  11105. InstrList[Index].loadref(0, NewRef);
  11106. end;
  11107. else
  11108. InternalError(2021051710);
  11109. end;
  11110. end;
  11111. { Mark the FLAGS register as used across this whole block }
  11112. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11113. end;
  11114. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11115. JumpC := taicpu(hp2).condition;
  11116. Unconditional := False;
  11117. if conditions_equal(JumpC, C_E) then
  11118. SetC := inverse_cond(taicpu(p).condition)
  11119. else if conditions_equal(JumpC, C_NE) then
  11120. SetC := taicpu(p).condition
  11121. else
  11122. { We've got something weird here (and inefficent) }
  11123. begin
  11124. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11125. SetC := C_NONE;
  11126. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11127. if condition_in(C_AE, JumpC) then
  11128. Unconditional := True
  11129. else
  11130. { Not sure what to do with this jump - drop out }
  11131. Exit;
  11132. end;
  11133. RemoveInstruction(hp1);
  11134. if Unconditional then
  11135. MakeUnconditional(taicpu(hp2))
  11136. else
  11137. begin
  11138. if SetC = C_NONE then
  11139. InternalError(2018061402);
  11140. taicpu(hp2).SetCondition(SetC);
  11141. end;
  11142. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11143. TmpUsedRegs }
  11144. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11145. begin
  11146. RemoveCurrentp(p, hp2);
  11147. if taicpu(hp2).opcode = A_SETcc then
  11148. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11149. else
  11150. begin
  11151. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11152. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11153. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11154. end;
  11155. end
  11156. else
  11157. if taicpu(hp2).opcode = A_SETcc then
  11158. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11159. else
  11160. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11161. Result := True;
  11162. end
  11163. else if
  11164. { Make sure the instructions are adjacent }
  11165. (
  11166. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11167. GetNextInstruction(p, hp1)
  11168. ) and
  11169. MatchInstruction(hp1, A_MOV, [S_B]) and
  11170. { Writing to memory is allowed }
  11171. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11172. begin
  11173. {
  11174. Watch out for sequences such as:
  11175. set(c)b %regb
  11176. movb %regb,(ref)
  11177. movb $0,1(ref)
  11178. movb $0,2(ref)
  11179. movb $0,3(ref)
  11180. Much more efficient to turn it into:
  11181. movl $0,%regl
  11182. set(c)b %regb
  11183. movl %regl,(ref)
  11184. Or:
  11185. set(c)b %regb
  11186. movzbl %regb,%regl
  11187. movl %regl,(ref)
  11188. }
  11189. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11190. GetNextInstruction(hp1, hp2) and
  11191. MatchInstruction(hp2, A_MOV, [S_B]) and
  11192. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11193. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11194. begin
  11195. { Don't do anything else except set Result to True }
  11196. end
  11197. else
  11198. begin
  11199. if taicpu(p).oper[0]^.typ = top_reg then
  11200. begin
  11201. TransferUsedRegs(TmpUsedRegs);
  11202. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11203. end;
  11204. { If it's not a register, it's a memory address }
  11205. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11206. begin
  11207. { Even if the register is still in use, we can minimise the
  11208. pipeline stall by changing the MOV into another SETcc. }
  11209. taicpu(hp1).opcode := A_SETcc;
  11210. taicpu(hp1).condition := taicpu(p).condition;
  11211. if taicpu(hp1).oper[1]^.typ = top_ref then
  11212. begin
  11213. { Swapping the operand pointers like this is probably a
  11214. bit naughty, but it is far faster than using loadoper
  11215. to transfer the reference from oper[1] to oper[0] if
  11216. you take into account the extra procedure calls and
  11217. the memory allocation and deallocation required }
  11218. OperPtr := taicpu(hp1).oper[1];
  11219. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11220. taicpu(hp1).oper[0] := OperPtr;
  11221. end
  11222. else
  11223. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11224. taicpu(hp1).clearop(1);
  11225. taicpu(hp1).ops := 1;
  11226. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11227. end
  11228. else
  11229. begin
  11230. if taicpu(hp1).oper[1]^.typ = top_reg then
  11231. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11232. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11233. RemoveInstruction(hp1);
  11234. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11235. end
  11236. end;
  11237. Result := True;
  11238. end;
  11239. end;
  11240. end;
  11241. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11242. var
  11243. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11244. TargetReg: TRegister;
  11245. condition, inverted_condition: TAsmCond;
  11246. FoundMOV: Boolean;
  11247. begin
  11248. Result := False;
  11249. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11250. create the most optimial instructions possible due to limited
  11251. register availability, and there are situations where two
  11252. complementary "simple" CMOV blocks are created which, after the fact
  11253. can be merged into a "double" block. For example:
  11254. movw $257,%ax
  11255. movw $2,%r8w
  11256. xorl r9d,%r9d
  11257. testw $16,18(%rcx)
  11258. cmovew %ax,%dx
  11259. cmovew %r8w,%bx
  11260. cmovel %r9d,%r14d
  11261. movw $1283,%ax
  11262. movw $4,%r8w
  11263. movl $9,%r9d
  11264. cmovnew %ax,%dx
  11265. cmovnew %r8w,%bx
  11266. cmovnel %r9d,%r14d
  11267. The CMOVNE instructions at the end can be removed, and the
  11268. destination registers copied into the MOV instructions directly
  11269. above them, before finally being moved to before the first CMOVE
  11270. instructions, to produce:
  11271. movw $257,%ax
  11272. movw $2,%r8w
  11273. xorl r9d,%r9d
  11274. testw $16,18(%rcx)
  11275. movw $1283,%dx
  11276. movw $4,%bx
  11277. movl $9,%r14d
  11278. cmovew %ax,%dx
  11279. cmovew %r8w,%bx
  11280. cmovel %r9d,%r14d
  11281. Which can then be later optimised to:
  11282. movw $257,%ax
  11283. movw $2,%r8w
  11284. xorl r9d,%r9d
  11285. movw $1283,%dx
  11286. movw $4,%bx
  11287. movl $9,%r14d
  11288. testw $16,18(%rcx)
  11289. cmovew %ax,%dx
  11290. cmovew %r8w,%bx
  11291. cmovel %r9d,%r14d
  11292. }
  11293. TargetReg := taicpu(hp1).oper[1]^.reg;
  11294. condition := taicpu(hp1).condition;
  11295. inverted_condition := inverse_cond(condition);
  11296. pFirstMov := nil;
  11297. pLastMov := nil;
  11298. pCMOV := nil;
  11299. if (p.typ = ait_instruction) then
  11300. pCond := p
  11301. else if not GetNextInstruction(p, pCond) then
  11302. InternalError(2024012501);
  11303. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11304. { We should get the CMP or TEST instructeion }
  11305. InternalError(2024012502);
  11306. if (
  11307. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11308. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11309. ) then
  11310. begin
  11311. { We have to tread carefully here, hence why we're not using
  11312. GetNextInstructionUsingReg... we can only accept MOV and other
  11313. CMOV instructions. Anything else and we must drop out}
  11314. hp2 := hp1;
  11315. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11316. begin
  11317. if (hp2.typ <> ait_instruction) then
  11318. Exit;
  11319. case taicpu(hp2).opcode of
  11320. A_MOV:
  11321. begin
  11322. if not Assigned(pFirstMov) then
  11323. pFirstMov := hp2;
  11324. pLastMOV := hp2;
  11325. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11326. { Something different - drop out }
  11327. Exit;
  11328. { Otherwise, leave it for now }
  11329. end;
  11330. A_CMOVcc:
  11331. begin
  11332. if taicpu(hp2).condition = inverted_condition then
  11333. begin
  11334. { We found what we're looking for }
  11335. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11336. begin
  11337. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11338. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11339. begin
  11340. pCMOV := hp2;
  11341. Break;
  11342. end
  11343. else
  11344. { Unsafe reference - drop out }
  11345. Exit;
  11346. end;
  11347. end
  11348. else if taicpu(hp2).condition <> condition then
  11349. { Something weird - drop out }
  11350. Exit;
  11351. end;
  11352. else
  11353. { Invalid }
  11354. Exit;
  11355. end;
  11356. end;
  11357. if not Assigned(pCMOV) then
  11358. { No complementary CMOV found }
  11359. Exit;
  11360. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11361. begin
  11362. { Don't need to do anything special or search for a matching MOV }
  11363. Asml.Remove(pCMOV);
  11364. if RegInInstruction(TargetReg, pCond) then
  11365. { Make sure we don't overwrite the register if it's being used in the condition }
  11366. Asml.InsertAfter(pCMOV, pCond)
  11367. else
  11368. Asml.InsertBefore(pCMOV, pCond);
  11369. taicpu(pCMOV).opcode := A_MOV;
  11370. taicpu(pCMOV).condition := C_None;
  11371. { Don't need to worry about allocating new registers in these cases }
  11372. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11373. Result := True;
  11374. Exit;
  11375. end
  11376. else
  11377. begin
  11378. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11379. FoundMOV := False;
  11380. { Search for the MOV that sets the target register }
  11381. hp2 := pFirstMov;
  11382. repeat
  11383. if (taicpu(hp2).opcode = A_MOV) and
  11384. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11385. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11386. begin
  11387. { Change the destination }
  11388. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11389. if not FoundMOV then
  11390. begin
  11391. FoundMOV := True;
  11392. { Make sure the register is allocated }
  11393. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11394. end;
  11395. hp1 := tai(hp2.Previous);
  11396. Asml.Remove(hp2);
  11397. if RegInInstruction(TargetReg, pCond) then
  11398. { Make sure we don't overwrite the register if it's being used in the condition }
  11399. Asml.InsertAfter(hp2, pCond)
  11400. else
  11401. Asml.InsertBefore(hp2, pCond);
  11402. if (hp2 = pLastMov) then
  11403. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11404. Break;
  11405. hp2 := hp1;
  11406. end;
  11407. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11408. if FoundMOV then
  11409. { Delete the CMOV }
  11410. RemoveInstruction(pCMOV)
  11411. else
  11412. begin
  11413. { If no MOV was found, we have to actually move and transmute the CMOV }
  11414. Asml.Remove(pCMOV);
  11415. if RegInInstruction(TargetReg, pCond) then
  11416. { Make sure we don't overwrite the register if it's being used in the condition }
  11417. Asml.InsertAfter(pCMOV, pCond)
  11418. else
  11419. Asml.InsertBefore(pCMOV, pCond);
  11420. taicpu(pCMOV).opcode := A_MOV;
  11421. taicpu(pCMOV).condition := C_None;
  11422. end;
  11423. Result := True;
  11424. Exit;
  11425. end;
  11426. end;
  11427. end;
  11428. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11429. var
  11430. hp1, hp2, pCond: tai;
  11431. begin
  11432. Result := False;
  11433. { Search ahead for CMOV instructions }
  11434. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11435. begin
  11436. hp1 := p;
  11437. hp2 := p;
  11438. pCond := nil; { To prevent compiler warnings }
  11439. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11440. DEFAULTFLAGS }
  11441. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11442. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11443. pCond := p;
  11444. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11445. begin
  11446. if (hp1.typ <> ait_instruction) then
  11447. { Break out on markers and labels etc. }
  11448. Break;
  11449. case taicpu(hp1).opcode of
  11450. A_MOV:
  11451. { Ignore regular MOVs unless they are obviously not related
  11452. to a CMOV block }
  11453. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11454. Break;
  11455. A_CMOVcc:
  11456. if TryCmpCMovOpts(pCond, hp1) then
  11457. begin
  11458. hp1 := hp2;
  11459. { p itself isn't changed, and we're still inside a
  11460. while loop to catch subsequent CMOVs, so just flag
  11461. a new iteration }
  11462. Include(OptsToCheck, aoc_ForceNewIteration);
  11463. Continue;
  11464. end;
  11465. else
  11466. { Drop out if we find anything else }
  11467. Break;
  11468. end;
  11469. hp2 := hp1;
  11470. end;
  11471. end;
  11472. end;
  11473. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11474. var
  11475. hp1, hp2, pCond: tai;
  11476. SourceReg, TargetReg: TRegister;
  11477. begin
  11478. Result := False;
  11479. { In some situations, we end up with an inefficient arrangement of
  11480. instructions in the form of:
  11481. or %reg1,%reg2
  11482. (%reg1 deallocated)
  11483. test %reg2,%reg2
  11484. mov x,%reg2
  11485. we may be able to swap and rearrange the registers to produce:
  11486. or %reg2,%reg1
  11487. mov x,%reg2
  11488. test %reg1,%reg1
  11489. (%reg1 deallocated)
  11490. }
  11491. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11492. (taicpu(p).oper[1]^.typ = top_reg) and
  11493. (
  11494. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11495. MatchOperand(taicpu(p).oper[0]^, -1)
  11496. ) and
  11497. GetNextInstruction(p, hp1) and
  11498. MatchInstruction(hp1, A_MOV, []) and
  11499. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11500. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11501. begin
  11502. TargetReg := taicpu(p).oper[1]^.reg;
  11503. { Now look backwards to find a simple commutative operation: ADD,
  11504. IMUL (2-register version), OR, AND or XOR - whose destination
  11505. register is the same as TEST }
  11506. hp2 := p;
  11507. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11508. if RegInInstruction(TargetReg, hp2) then
  11509. begin
  11510. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11511. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11512. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11513. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11514. begin
  11515. SourceReg := taicpu(hp2).oper[0]^.reg;
  11516. if
  11517. { Make sure the MOV doesn't use the other register }
  11518. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11519. { And make sure the source register is not used afterwards }
  11520. not RegInUsedRegs(SourceReg, UsedRegs) then
  11521. begin
  11522. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11523. taicpu(hp2).oper[0]^.reg := TargetReg;
  11524. taicpu(hp2).oper[1]^.reg := SourceReg;
  11525. if taicpu(p).oper[0]^.typ = top_reg then
  11526. taicpu(p).oper[0]^.reg := SourceReg;
  11527. taicpu(p).oper[1]^.reg := SourceReg;
  11528. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11529. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11530. Include(OptsToCheck, aoc_ForceNewIteration);
  11531. { We can still check the following optimisations since
  11532. the instruction is still a TEST }
  11533. end;
  11534. end;
  11535. Break;
  11536. end;
  11537. end;
  11538. { Search ahead3 for CMOV instructions }
  11539. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11540. begin
  11541. hp1 := p;
  11542. hp2 := p;
  11543. pCond := nil; { To prevent compiler warnings }
  11544. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11545. DEFAULTFLAGS }
  11546. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11547. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11548. pCond := p;
  11549. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11550. begin
  11551. if (hp1.typ <> ait_instruction) then
  11552. { Break out on markers and labels etc. }
  11553. Break;
  11554. case taicpu(hp1).opcode of
  11555. A_MOV:
  11556. { Ignore regular MOVs unless they are obviously not related
  11557. to a CMOV block }
  11558. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11559. Break;
  11560. A_CMOVcc:
  11561. if TryCmpCMovOpts(pCond, hp1) then
  11562. begin
  11563. hp1 := hp2;
  11564. { p itself isn't changed, and we're still inside a
  11565. while loop to catch subsequent CMOVs, so just flag
  11566. a new iteration }
  11567. Include(OptsToCheck, aoc_ForceNewIteration);
  11568. Continue;
  11569. end;
  11570. else
  11571. { Drop out if we find anything else }
  11572. Break;
  11573. end;
  11574. hp2 := hp1;
  11575. end;
  11576. end;
  11577. end;
  11578. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11579. var
  11580. hp1: tai;
  11581. Count: Integer;
  11582. OrigLabel: TAsmLabel;
  11583. begin
  11584. result := False;
  11585. { Sometimes, the optimisations below can permit this }
  11586. RemoveDeadCodeAfterJump(p);
  11587. 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
  11588. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11589. begin
  11590. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11591. { Also a side-effect of optimisations }
  11592. if CollapseZeroDistJump(p, OrigLabel) then
  11593. begin
  11594. Result := True;
  11595. Exit;
  11596. end;
  11597. hp1 := GetLabelWithSym(OrigLabel);
  11598. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11599. begin
  11600. if taicpu(hp1).opcode = A_RET then
  11601. begin
  11602. {
  11603. change
  11604. jmp .L1
  11605. ...
  11606. .L1:
  11607. ret
  11608. into
  11609. ret
  11610. }
  11611. begin
  11612. ConvertJumpToRET(p, hp1);
  11613. result:=true;
  11614. end;
  11615. end
  11616. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11617. not (cs_opt_size in current_settings.optimizerswitches) and
  11618. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11619. begin
  11620. Result := True;
  11621. Exit;
  11622. end;
  11623. end;
  11624. end;
  11625. end;
  11626. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11627. begin
  11628. Result := assigned(p) and
  11629. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11630. (taicpu(p).oper[1]^.typ = top_reg) and
  11631. (
  11632. (taicpu(p).oper[0]^.typ = top_reg) or
  11633. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11634. it is not expected that this can cause a seg. violation }
  11635. (
  11636. (taicpu(p).oper[0]^.typ = top_ref) and
  11637. { TODO: Can we detect which references become constants at this
  11638. stage so we don't have to do a blanket ban? }
  11639. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11640. (
  11641. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11642. (
  11643. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11644. not RefModified and
  11645. { If the reference also appears in the condition, then we know it's safe, otherwise
  11646. any kind of access violation would have occurred already }
  11647. Assigned(cond_p) and
  11648. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11649. (cond_p.typ = ait_instruction) and
  11650. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11651. { Just consider 2-operand comparison instructions for now to be safe }
  11652. (taicpu(cond_p).ops = 2) and
  11653. (
  11654. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11655. (
  11656. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11657. { Don't risk identical registers but different offsets, as we may have constructs
  11658. such as buffer streams with things like length fields that indicate whether
  11659. any more data follows. And there are probably some contrived examples where
  11660. writing to offsets behind the one being read also lead to access violations }
  11661. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11662. (
  11663. { Check that we're not modifying a register that appears in the reference }
  11664. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11665. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11666. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11667. )
  11668. )
  11669. )
  11670. )
  11671. )
  11672. )
  11673. );
  11674. end;
  11675. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11676. begin
  11677. { Update integer registers, ignoring deallocations }
  11678. repeat
  11679. while assigned(p) and
  11680. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11681. (p.typ = ait_label) or
  11682. ((p.typ = ait_marker) and
  11683. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11684. p := tai(p.next);
  11685. while assigned(p) and
  11686. (p.typ=ait_RegAlloc) Do
  11687. begin
  11688. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11689. begin
  11690. case tai_regalloc(p).ratype of
  11691. ra_alloc :
  11692. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11693. else
  11694. ;
  11695. end;
  11696. end;
  11697. p := tai(p.next);
  11698. end;
  11699. until not(assigned(p)) or
  11700. (not(p.typ in SkipInstr) and
  11701. not((p.typ = ait_label) and
  11702. labelCanBeSkipped(tai_label(p))));
  11703. end;
  11704. {$ifndef 8086}
  11705. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11706. begin
  11707. Result := False;
  11708. EndJump := nil;
  11709. BlockStop := nil;
  11710. while (BlockStart <> fOptimizer.BlockEnd) and
  11711. { stop on labels }
  11712. (BlockStart.typ <> ait_label) do
  11713. begin
  11714. { Keep track of all integer registers that are used }
  11715. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11716. if BlockStart.typ = ait_instruction then
  11717. begin
  11718. if (taicpu(BlockStart).opcode = A_JMP) then
  11719. begin
  11720. if not IsJumpToLabel(taicpu(BlockStart)) or
  11721. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11722. Exit;
  11723. EndJump := BlockStart;
  11724. Break;
  11725. end
  11726. { Check to see if we have a valid MOV instruction instead }
  11727. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11728. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11729. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11730. begin
  11731. Exit;
  11732. end
  11733. else
  11734. { This will be a valid MOV }
  11735. fAllocationRange := BlockStart;
  11736. end;
  11737. OneBeforeBlock := BlockStart;
  11738. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11739. end;
  11740. if (BlockStart = fOptimizer.BlockEnd) then
  11741. Exit;
  11742. BlockStop := BlockStart;
  11743. Result := True;
  11744. end;
  11745. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11746. var
  11747. hp1: tai;
  11748. RefModified: Boolean;
  11749. begin
  11750. Result := 0;
  11751. hp1 := BlockStart;
  11752. RefModified := False; { As long as the condition is inverted, this can be reset }
  11753. while assigned(hp1) and
  11754. (hp1 <> BlockStop) do
  11755. begin
  11756. case hp1.typ of
  11757. ait_instruction:
  11758. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11759. begin
  11760. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11761. begin
  11762. Inc(Result);
  11763. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11764. Assigned(fCondition) and
  11765. { Will have 2 operands }
  11766. (
  11767. (
  11768. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11769. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11770. ) or
  11771. (
  11772. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11773. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11774. )
  11775. ) then
  11776. { It is no longer safe to use the reference in the condition.
  11777. this prevents problems such as:
  11778. mov (%reg),%reg
  11779. mov (%reg),...
  11780. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11781. (fixes #40165)
  11782. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11783. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11784. }
  11785. RefModified := True;
  11786. end
  11787. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11788. { CMOV with constants grows the code size }
  11789. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11790. begin
  11791. { Register was reserved by TryCMOVConst and
  11792. stored on ConstRegs }
  11793. end
  11794. else
  11795. begin
  11796. Result := -1;
  11797. Exit;
  11798. end;
  11799. end
  11800. else
  11801. begin
  11802. Result := -1;
  11803. Exit;
  11804. end;
  11805. else
  11806. { Most likely an align };
  11807. end;
  11808. fOptimizer.GetNextInstruction(hp1, hp1);
  11809. end;
  11810. end;
  11811. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11812. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11813. (this is done as a separate stage because the double types are extensions of the branching type,
  11814. but we can't discount the conditional jump until the last step) }
  11815. procedure EvaluateBranchingType;
  11816. begin
  11817. Inc(CMOVScore);
  11818. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11819. { Too many instructions to be worthwhile }
  11820. fState := tsInvalid;
  11821. end;
  11822. var
  11823. hp1: tai;
  11824. Count: Integer;
  11825. begin
  11826. { Table of valid CMOV block types
  11827. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11828. ---------- --------- --------- --------- --------- ---------
  11829. tsSimple X Yes X X X
  11830. tsDetour = 1st X X X X
  11831. tsBranching <> Mid Yes X X X
  11832. tsDouble End-label Yes * Yes X Yes
  11833. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11834. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11835. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11836. * Only one reference allowed
  11837. }
  11838. hp1 := nil; { To prevent compiler warnings }
  11839. Optimizer.CopyUsedRegs(RegisterTracking);
  11840. fOptimizer := Optimizer;
  11841. fLabel := AFirstLabel;
  11842. CMOVScore := 0;
  11843. ConstCount := 0;
  11844. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11845. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11846. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11847. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11848. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11849. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11850. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11851. fInsertionPoint := p_initialjump;
  11852. fCondition := nil;
  11853. fInitialJump := p_initialjump;
  11854. fFirstMovBlock := p_initialmov;
  11855. fFirstMovBlockStop := nil;
  11856. fSecondJump := nil;
  11857. fSecondMovBlock := nil;
  11858. fSecondMovBlockStop := nil;
  11859. fMidLabel := nil;
  11860. fSecondJump := nil;
  11861. fSecondMovBlock := nil;
  11862. fEndLabel := nil;
  11863. fAllocationRange := nil;
  11864. { Assume it all goes horribly wrong! }
  11865. fState := tsInvalid;
  11866. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11867. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11868. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11869. begin
  11870. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11871. for Count := 0 to 1 do
  11872. with taicpu(fCondition).oper[Count]^ do
  11873. case typ of
  11874. top_reg:
  11875. if getregtype(reg) = R_INTREGISTER then
  11876. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11877. top_ref:
  11878. begin
  11879. if
  11880. {$ifdef x86_64}
  11881. (ref^.base <> NR_RIP) and
  11882. {$endif x86_64}
  11883. (ref^.base <> NR_NO) then
  11884. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11885. if (ref^.index <> NR_NO) then
  11886. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11887. end
  11888. else
  11889. ;
  11890. end;
  11891. { When inserting instructions before hp_prev, try to insert them
  11892. before the allocation of the FLAGS register }
  11893. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11894. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11895. { If not found, set it equal to the condition so it's something sensible }
  11896. fInsertionPoint := fCondition;
  11897. { When dealing with a comparison against zero, take note of the
  11898. instruction before it to see if we can move instructions further
  11899. back in order to benefit PostPeepholeOptTestOr.
  11900. }
  11901. if (
  11902. (
  11903. (taicpu(fCondition).opcode = A_CMP) and
  11904. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11905. ) or
  11906. (
  11907. (taicpu(fCondition).opcode = A_TEST) and
  11908. (
  11909. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11910. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11911. )
  11912. )
  11913. ) and
  11914. Optimizer.GetLastInstruction(fCondition, hp1) then
  11915. begin
  11916. { These instructions set the zero flag if the result is zero }
  11917. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11918. begin
  11919. fInsertionPoint := hp1;
  11920. { Also mark all the registers in this previous instruction
  11921. as 'in use', even if they've just been deallocated }
  11922. for Count := 0 to 1 do
  11923. with taicpu(hp1).oper[Count]^ do
  11924. case typ of
  11925. top_reg:
  11926. if getregtype(reg) = R_INTREGISTER then
  11927. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11928. top_ref:
  11929. begin
  11930. if
  11931. {$ifdef x86_64}
  11932. (ref^.base <> NR_RIP) and
  11933. {$endif x86_64}
  11934. (ref^.base <> NR_NO) then
  11935. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11936. if (ref^.index <> NR_NO) then
  11937. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11938. end
  11939. else
  11940. ;
  11941. end;
  11942. end;
  11943. end;
  11944. end
  11945. else
  11946. fCondition := nil;
  11947. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11948. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11949. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11950. { If not found, set it equal to p so it's something sensible }
  11951. fInsertionPoint := hp1;
  11952. hp1 := p_initialmov;
  11953. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11954. Exit;
  11955. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11956. if (hp1.typ <> ait_label) then { should be on a jump }
  11957. begin
  11958. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11959. { Need a label afterwards }
  11960. Exit;
  11961. end
  11962. else
  11963. fMidLabel := hp1;
  11964. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11965. { Not the correct label }
  11966. fMidLabel := nil;
  11967. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11968. { If there's neither a 2nd jump nor correct label, then it's invalid
  11969. (see above table) }
  11970. Exit;
  11971. { Analyse the first block of MOVs more closely }
  11972. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11973. if Assigned(fSecondJump) then
  11974. begin
  11975. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11976. begin
  11977. fState := tsDetour
  11978. end
  11979. else
  11980. begin
  11981. { Need the correct mid-label for this one }
  11982. if not Assigned(fMidLabel) then
  11983. Exit;
  11984. fState := tsBranching;
  11985. end;
  11986. end
  11987. else
  11988. { No jump. but mid-label is present }
  11989. fState := tsSimple;
  11990. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11991. begin
  11992. { Invalid or too many instructions to be worthwhile }
  11993. fState := tsInvalid;
  11994. Exit;
  11995. end;
  11996. { check further for
  11997. jCC xxx
  11998. <several movs 1>
  11999. jmp yyy
  12000. xxx:
  12001. <several movs 2>
  12002. yyy:
  12003. etc.
  12004. }
  12005. if (fState = tsBranching) and
  12006. { Estimate for required savings for extra jump }
  12007. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12008. { Only one reference is allowed for double blocks }
  12009. (AFirstLabel.getrefs = 1) then
  12010. begin
  12011. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12012. fSecondMovBlock := hp1;
  12013. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12014. begin
  12015. EvaluateBranchingType;
  12016. Exit;
  12017. end;
  12018. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12019. if (hp1.typ <> ait_label) then { should be on a jump }
  12020. begin
  12021. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12022. begin
  12023. { Need a label afterwards }
  12024. EvaluateBranchingType;
  12025. Exit;
  12026. end;
  12027. end
  12028. else
  12029. fEndLabel := hp1;
  12030. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12031. { Second jump doesn't go to the end }
  12032. fEndLabel := nil;
  12033. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12034. begin
  12035. { If there's neither a 3rd jump nor correct end label, then it's
  12036. not a invalid double block, but is a valid single branching
  12037. block (see above table) }
  12038. EvaluateBranchingType;
  12039. Exit;
  12040. end;
  12041. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12042. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12043. { Invalid or too many instructions to be worthwhile }
  12044. Exit;
  12045. Inc(CMOVScore, Count);
  12046. if Assigned(fThirdJump) then
  12047. begin
  12048. if not Assigned(fSecondJump) then
  12049. fState := tsDoubleSecondBranching
  12050. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12051. fState := tsDoubleBranchSame
  12052. else
  12053. fState := tsDoubleBranchDifferent;
  12054. end
  12055. else
  12056. fState := tsDouble;
  12057. end;
  12058. if fState = tsBranching then
  12059. EvaluateBranchingType;
  12060. end;
  12061. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12062. new register to store the constant }
  12063. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12064. var
  12065. RegSize: TSubRegister;
  12066. CurrentVal: TCGInt;
  12067. ANewReg: TRegister;
  12068. X: ShortInt;
  12069. begin
  12070. Result := False;
  12071. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12072. Exit;
  12073. if ConstCount >= MAX_CMOV_REGISTERS then
  12074. { Arrays are full }
  12075. Exit;
  12076. { Remember that CMOV can't encode 8-bit registers }
  12077. case taicpu(p).opsize of
  12078. S_W:
  12079. RegSize := R_SUBW;
  12080. S_L:
  12081. RegSize := R_SUBD;
  12082. {$ifdef x86_64}
  12083. S_Q:
  12084. RegSize := R_SUBQ;
  12085. {$endif x86_64}
  12086. else
  12087. InternalError(2021100401);
  12088. end;
  12089. { See if the value has already been reserved for another CMOV instruction }
  12090. CurrentVal := taicpu(p).oper[0]^.val;
  12091. for X := 0 to ConstCount - 1 do
  12092. if ConstVals[X] = CurrentVal then
  12093. begin
  12094. ConstRegs[ConstCount] := ConstRegs[X];
  12095. ConstSizes[ConstCount] := RegSize;
  12096. ConstVals[ConstCount] := CurrentVal;
  12097. Inc(ConstCount);
  12098. Inc(Count);
  12099. Result := True;
  12100. Exit;
  12101. end;
  12102. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12103. if ANewReg = NR_NO then
  12104. { No free registers }
  12105. Exit;
  12106. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12107. up vying for the same register }
  12108. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12109. ConstRegs[ConstCount] := ANewReg;
  12110. ConstSizes[ConstCount] := RegSize;
  12111. ConstVals[ConstCount] := CurrentVal;
  12112. Inc(ConstCount);
  12113. Inc(Count);
  12114. Result := True;
  12115. end;
  12116. destructor TCMOVTracking.Done;
  12117. begin
  12118. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12119. end;
  12120. procedure TCMOVTracking.Process(out new_p: tai);
  12121. var
  12122. Count, Writes: LongInt;
  12123. RegMatch: Boolean;
  12124. hp1, hp_new: tai;
  12125. inverted_condition, condition: TAsmCond;
  12126. begin
  12127. if (fState in [tsInvalid, tsProcessed]) then
  12128. InternalError(2023110701);
  12129. { Repurpose RegisterTracking to mark registers that we've defined }
  12130. RegisterTracking[R_INTREGISTER].Clear;
  12131. Count := 0;
  12132. Writes := 0;
  12133. condition := taicpu(fInitialJump).condition;
  12134. inverted_condition := inverse_cond(condition);
  12135. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12136. doesn't get CMOVs in this case }
  12137. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12138. begin
  12139. { Include the jump in the flag tracking }
  12140. if Assigned(fThirdJump) then
  12141. begin
  12142. if (fState = tsDoubleBranchSame) then
  12143. begin
  12144. { Will be an unconditional jump, so track to the instruction before it }
  12145. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12146. InternalError(2023110710);
  12147. end
  12148. else
  12149. hp1 := fThirdJump;
  12150. end
  12151. else
  12152. hp1 := fSecondMovBlockStop;
  12153. end
  12154. else
  12155. begin
  12156. { Include a conditional jump in the flag tracking }
  12157. if Assigned(fSecondJump) then
  12158. begin
  12159. if (fState = tsDetour) then
  12160. begin
  12161. { Will be an unconditional jump, so track to the instruction before it }
  12162. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12163. InternalError(2023110711);
  12164. end
  12165. else
  12166. hp1 := fSecondJump;
  12167. end
  12168. else
  12169. hp1 := fFirstMovBlockStop;
  12170. end;
  12171. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12172. { Process the second set of MOVs first, because if a destination
  12173. register is shared between the first and second MOV sets, it is more
  12174. efficient to turn the first one into a MOV instruction and place it
  12175. before the CMP if possible, but we won't know which registers are
  12176. shared until we've processed at least one list, so we might as well
  12177. make it the second one since that won't be modified again. }
  12178. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12179. begin
  12180. hp1 := fSecondMovBlock;
  12181. repeat
  12182. if not Assigned(hp1) then
  12183. InternalError(2018062902);
  12184. if (hp1.typ = ait_instruction) then
  12185. begin
  12186. { Extra safeguard }
  12187. if (taicpu(hp1).opcode <> A_MOV) then
  12188. InternalError(2018062903);
  12189. { Note: tsDoubleBranchDifferent is essentially identical to
  12190. tsBranching and the 2nd block is best left largely
  12191. untouched, but we need to evaluate which registers the MOVs
  12192. write to in order to track what would be complementary CMOV
  12193. pairs that can be further optimised. [Kit] }
  12194. if fState <> tsDoubleBranchDifferent then
  12195. begin
  12196. if taicpu(hp1).oper[0]^.typ = top_const then
  12197. begin
  12198. RegMatch := False;
  12199. for Count := 0 to ConstCount - 1 do
  12200. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12201. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12202. begin
  12203. RegMatch := True;
  12204. { If it's in RegisterTracking, then this register
  12205. is being used more than once and hence has
  12206. already had its value defined (it gets added to
  12207. UsedRegs through AllocRegBetween below) }
  12208. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12209. begin
  12210. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12211. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12212. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12213. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12214. ConstMovs[Count] := hp_new;
  12215. end
  12216. else
  12217. { We just need an instruction between hp_prev and hp1
  12218. where we know the register is marked as in use }
  12219. hp_new := fSecondMovBlock;
  12220. { Keep track of largest write for this register so it can be optimised later }
  12221. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12222. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12223. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12224. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12225. Break;
  12226. end;
  12227. if not RegMatch then
  12228. InternalError(2021100411);
  12229. end;
  12230. taicpu(hp1).opcode := A_CMOVcc;
  12231. taicpu(hp1).condition := condition;
  12232. end;
  12233. { Store these writes to search for duplicates later on }
  12234. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12235. Inc(Writes);
  12236. end;
  12237. fOptimizer.GetNextInstruction(hp1, hp1);
  12238. until (hp1 = fSecondMovBlockStop);
  12239. end;
  12240. { Now do the first set of MOVs }
  12241. hp1 := fFirstMovBlock;
  12242. repeat
  12243. if not Assigned(hp1) then
  12244. InternalError(2018062904);
  12245. if (hp1.typ = ait_instruction) then
  12246. begin
  12247. RegMatch := False;
  12248. { Extra safeguard }
  12249. if (taicpu(hp1).opcode <> A_MOV) then
  12250. InternalError(2018062905);
  12251. { Search through the RegWrites list to see if there are any
  12252. opposing CMOV pairs that write to the same register }
  12253. for Count := 0 to Writes - 1 do
  12254. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12255. begin
  12256. { We have a match. Keep this as a MOV }
  12257. { Move ahead in preparation }
  12258. fOptimizer.GetNextInstruction(hp1, hp1);
  12259. RegMatch := True;
  12260. Break;
  12261. end;
  12262. if RegMatch then
  12263. Continue;
  12264. if taicpu(hp1).oper[0]^.typ = top_const then
  12265. begin
  12266. for Count := 0 to ConstCount - 1 do
  12267. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12268. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12269. begin
  12270. RegMatch := True;
  12271. { If it's in RegisterTracking, then this register is
  12272. being used more than once and hence has already had
  12273. its value defined (it gets added to UsedRegs through
  12274. AllocRegBetween below) }
  12275. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12276. begin
  12277. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12278. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12279. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12280. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12281. ConstMovs[Count] := hp_new;
  12282. end
  12283. else
  12284. { We just need an instruction between hp_prev and hp1
  12285. where we know the register is marked as in use }
  12286. hp_new := fFirstMovBlock;
  12287. { Keep track of largest write for this register so it can be optimised later }
  12288. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12289. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12290. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12291. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12292. Break;
  12293. end;
  12294. if not RegMatch then
  12295. InternalError(2021100412);
  12296. end;
  12297. taicpu(hp1).opcode := A_CMOVcc;
  12298. taicpu(hp1).condition := inverted_condition;
  12299. if (fState = tsDoubleBranchDifferent) then
  12300. begin
  12301. { Store these writes to search for duplicates later on }
  12302. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12303. Inc(Writes);
  12304. end;
  12305. end;
  12306. fOptimizer.GetNextInstruction(hp1, hp1);
  12307. until (hp1 = fFirstMovBlockStop);
  12308. { Update initialisation MOVs to the smallest possible size }
  12309. for Count := 0 to ConstCount - 1 do
  12310. if Assigned(ConstMovs[Count]) then
  12311. begin
  12312. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12313. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12314. end;
  12315. case fState of
  12316. tsSimple:
  12317. begin
  12318. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12319. { No branch to delete }
  12320. end;
  12321. tsDetour:
  12322. begin
  12323. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12324. { Preserve jump }
  12325. end;
  12326. tsBranching, tsDoubleBranchDifferent:
  12327. begin
  12328. if (fState = tsBranching) then
  12329. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12330. else
  12331. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12332. taicpu(fSecondJump).opcode := A_JCC;
  12333. taicpu(fSecondJump).condition := inverted_condition;
  12334. end;
  12335. tsDouble, tsDoubleBranchSame:
  12336. begin
  12337. if (fState = tsDouble) then
  12338. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12339. else
  12340. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12341. { Delete second jump }
  12342. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12343. fOptimizer.RemoveInstruction(fSecondJump);
  12344. end;
  12345. tsDoubleSecondBranching:
  12346. begin
  12347. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12348. { Delete second jump, preserve third jump as conditional }
  12349. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12350. fOptimizer.RemoveInstruction(fSecondJump);
  12351. taicpu(fThirdJump).opcode := A_JCC;
  12352. taicpu(fThirdJump).condition := condition;
  12353. end;
  12354. else
  12355. InternalError(2023110720);
  12356. end;
  12357. { Now we can safely decrement the reference count }
  12358. tasmlabel(fLabel).decrefs;
  12359. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12360. { Remove the original jump }
  12361. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12362. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12363. fState := tsProcessed;
  12364. end;
  12365. {$endif 8086}
  12366. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12367. var
  12368. hp1,hp2: tai;
  12369. carryadd_opcode : TAsmOp;
  12370. symbol: TAsmSymbol;
  12371. increg, tmpreg: TRegister;
  12372. {$ifndef i8086}
  12373. CMOVTracking: PCMOVTracking;
  12374. hp3,hp4,hp5: tai;
  12375. {$endif i8086}
  12376. TempBool: Boolean;
  12377. begin
  12378. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12379. DoJumpOptimizations(p, TempBool) then
  12380. Exit(True);
  12381. result:=false;
  12382. if GetNextInstruction(p,hp1) then
  12383. begin
  12384. if (hp1.typ=ait_label) then
  12385. begin
  12386. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12387. Exit;
  12388. end
  12389. else if (hp1.typ<>ait_instruction) then
  12390. Exit;
  12391. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12392. if (
  12393. (
  12394. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12395. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12396. (Taicpu(hp1).oper[0]^.val=1)
  12397. ) or
  12398. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12399. ) and
  12400. GetNextInstruction(hp1,hp2) and
  12401. (hp2.typ = ait_label) and
  12402. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12403. { jb @@1 cmc
  12404. inc/dec operand --> adc/sbb operand,0
  12405. @@1:
  12406. ... and ...
  12407. jnb @@1
  12408. inc/dec operand --> adc/sbb operand,0
  12409. @@1: }
  12410. begin
  12411. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12412. begin
  12413. case taicpu(hp1).opcode of
  12414. A_INC,
  12415. A_ADD:
  12416. carryadd_opcode:=A_ADC;
  12417. A_DEC,
  12418. A_SUB:
  12419. carryadd_opcode:=A_SBB;
  12420. else
  12421. InternalError(2021011001);
  12422. end;
  12423. Taicpu(p).clearop(0);
  12424. Taicpu(p).ops:=0;
  12425. Taicpu(p).is_jmp:=false;
  12426. Taicpu(p).opcode:=A_CMC;
  12427. Taicpu(p).condition:=C_NONE;
  12428. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12429. Taicpu(hp1).ops:=2;
  12430. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12431. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12432. else
  12433. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12434. Taicpu(hp1).loadconst(0,0);
  12435. Taicpu(hp1).opcode:=carryadd_opcode;
  12436. result:=true;
  12437. exit;
  12438. end
  12439. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12440. begin
  12441. case taicpu(hp1).opcode of
  12442. A_INC,
  12443. A_ADD:
  12444. carryadd_opcode:=A_ADC;
  12445. A_DEC,
  12446. A_SUB:
  12447. carryadd_opcode:=A_SBB;
  12448. else
  12449. InternalError(2021011002);
  12450. end;
  12451. Taicpu(hp1).ops:=2;
  12452. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12453. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12454. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12455. else
  12456. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12457. Taicpu(hp1).loadconst(0,0);
  12458. Taicpu(hp1).opcode:=carryadd_opcode;
  12459. RemoveCurrentP(p, hp1);
  12460. result:=true;
  12461. exit;
  12462. end
  12463. {
  12464. jcc @@1 setcc tmpreg
  12465. inc/dec/add/sub operand -> (movzx tmpreg)
  12466. @@1: add/sub tmpreg,operand
  12467. While this increases code size slightly, it makes the code much faster if the
  12468. jump is unpredictable
  12469. }
  12470. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12471. begin
  12472. { search for an available register which is volatile }
  12473. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12474. if increg <> NR_NO then
  12475. begin
  12476. { We don't need to check if tmpreg is in hp1 or not, because
  12477. it will be marked as in use at p (if not, this is
  12478. indictive of a compiler bug). }
  12479. TAsmLabel(symbol).decrefs;
  12480. Taicpu(p).clearop(0);
  12481. Taicpu(p).ops:=1;
  12482. Taicpu(p).is_jmp:=false;
  12483. Taicpu(p).opcode:=A_SETcc;
  12484. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12485. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12486. Taicpu(p).loadreg(0,increg);
  12487. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12488. begin
  12489. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12490. R_SUBW:
  12491. begin
  12492. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12493. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12494. end;
  12495. R_SUBD:
  12496. begin
  12497. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12498. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12499. end;
  12500. {$ifdef x86_64}
  12501. R_SUBQ:
  12502. begin
  12503. { MOVZX doesn't have a 64-bit variant, because
  12504. the 32-bit version implicitly zeroes the
  12505. upper 32-bits of the destination register }
  12506. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12507. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12508. setsubreg(tmpreg, R_SUBQ);
  12509. end;
  12510. {$endif x86_64}
  12511. else
  12512. Internalerror(2020030601);
  12513. end;
  12514. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12515. asml.InsertAfter(hp2,p);
  12516. end
  12517. else
  12518. tmpreg := increg;
  12519. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12520. begin
  12521. Taicpu(hp1).ops:=2;
  12522. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12523. end;
  12524. Taicpu(hp1).loadreg(0,tmpreg);
  12525. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12526. Result := True;
  12527. { p is no longer a Jcc instruction, so exit }
  12528. Exit;
  12529. end;
  12530. end;
  12531. end;
  12532. { Detect the following:
  12533. jmp<cond> @Lbl1
  12534. jmp @Lbl2
  12535. ...
  12536. @Lbl1:
  12537. ret
  12538. Change to:
  12539. jmp<inv_cond> @Lbl2
  12540. ret
  12541. }
  12542. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12543. begin
  12544. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12545. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12546. MatchInstruction(hp2,A_RET,[S_NO]) then
  12547. begin
  12548. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12549. { Change label address to that of the unconditional jump }
  12550. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12551. TAsmLabel(symbol).DecRefs;
  12552. taicpu(hp1).opcode := A_RET;
  12553. taicpu(hp1).is_jmp := false;
  12554. taicpu(hp1).ops := taicpu(hp2).ops;
  12555. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12556. case taicpu(hp2).ops of
  12557. 0:
  12558. taicpu(hp1).clearop(0);
  12559. 1:
  12560. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12561. else
  12562. internalerror(2016041302);
  12563. end;
  12564. end;
  12565. {$ifndef i8086}
  12566. end
  12567. {
  12568. convert
  12569. j<c> .L1
  12570. mov 1,reg
  12571. jmp .L2
  12572. .L1
  12573. mov 0,reg
  12574. .L2
  12575. into
  12576. mov 0,reg
  12577. set<not(c)> reg
  12578. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12579. would destroy the flag contents
  12580. }
  12581. else if MatchInstruction(hp1,A_MOV,[]) and
  12582. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12583. {$ifdef i386}
  12584. (
  12585. { Under i386, ESI, EDI, EBP and ESP
  12586. don't have an 8-bit representation }
  12587. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12588. ) and
  12589. {$endif i386}
  12590. (taicpu(hp1).oper[0]^.val=1) and
  12591. GetNextInstruction(hp1,hp2) and
  12592. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12593. GetNextInstruction(hp2,hp3) and
  12594. (hp3.typ=ait_label) and
  12595. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12596. (tai_label(hp3).labsym.getrefs=1) and
  12597. GetNextInstruction(hp3,hp4) and
  12598. MatchInstruction(hp4,A_MOV,[]) and
  12599. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12600. (taicpu(hp4).oper[0]^.val=0) and
  12601. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12602. GetNextInstruction(hp4,hp5) and
  12603. (hp5.typ=ait_label) and
  12604. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12605. (tai_label(hp5).labsym.getrefs=1) then
  12606. begin
  12607. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12608. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12609. { remove last label }
  12610. RemoveInstruction(hp5);
  12611. { remove second label }
  12612. RemoveInstruction(hp3);
  12613. { remove jmp }
  12614. RemoveInstruction(hp2);
  12615. if taicpu(hp1).opsize=S_B then
  12616. RemoveInstruction(hp1)
  12617. else
  12618. taicpu(hp1).loadconst(0,0);
  12619. taicpu(hp4).opcode:=A_SETcc;
  12620. taicpu(hp4).opsize:=S_B;
  12621. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12622. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12623. taicpu(hp4).opercnt:=1;
  12624. taicpu(hp4).ops:=1;
  12625. taicpu(hp4).freeop(1);
  12626. RemoveCurrentP(p);
  12627. Result:=true;
  12628. exit;
  12629. end
  12630. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12631. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12632. begin
  12633. { check for
  12634. jCC xxx
  12635. <several movs>
  12636. xxx:
  12637. Also spot:
  12638. Jcc xxx
  12639. <several movs>
  12640. jmp xxx
  12641. Change to:
  12642. <several cmovs with inverted condition>
  12643. jmp xxx (only for the 2nd case)
  12644. }
  12645. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12646. if CMOVTracking^.State <> tsInvalid then
  12647. begin
  12648. CMovTracking^.Process(p);
  12649. Result := True;
  12650. end;
  12651. CMOVTracking^.Done;
  12652. {$endif i8086}
  12653. end;
  12654. end;
  12655. end;
  12656. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12657. var
  12658. hp1,hp2,hp3: tai;
  12659. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12660. NewSize: TOpSize;
  12661. NewRegSize: TSubRegister;
  12662. Limit: TCgInt;
  12663. SwapOper: POper;
  12664. begin
  12665. result:=false;
  12666. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12667. GetNextInstruction(p,hp1) and
  12668. (hp1.typ = ait_instruction);
  12669. if reg_and_hp1_is_instr and
  12670. (
  12671. (taicpu(hp1).opcode <> A_LEA) or
  12672. { If the LEA instruction can be converted into an arithmetic instruction,
  12673. it may be possible to then fold it. }
  12674. (
  12675. { If the flags register is in use, don't change the instruction
  12676. to an ADD otherwise this will scramble the flags. [Kit] }
  12677. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12678. ConvertLEA(taicpu(hp1))
  12679. )
  12680. ) and
  12681. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12682. GetNextInstruction(hp1,hp2) and
  12683. MatchInstruction(hp2,A_MOV,[]) and
  12684. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12685. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12686. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12687. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12688. {$ifdef i386}
  12689. { not all registers have byte size sub registers on i386 }
  12690. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12691. {$endif i386}
  12692. (((taicpu(hp1).ops=2) and
  12693. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12694. ((taicpu(hp1).ops=1) and
  12695. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12696. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12697. begin
  12698. { change movsX/movzX reg/ref, reg2
  12699. add/sub/or/... reg3/$const, reg2
  12700. mov reg2 reg/ref
  12701. to add/sub/or/... reg3/$const, reg/ref }
  12702. { by example:
  12703. movswl %si,%eax movswl %si,%eax p
  12704. decl %eax addl %edx,%eax hp1
  12705. movw %ax,%si movw %ax,%si hp2
  12706. ->
  12707. movswl %si,%eax movswl %si,%eax p
  12708. decw %eax addw %edx,%eax hp1
  12709. movw %ax,%si movw %ax,%si hp2
  12710. }
  12711. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12712. {
  12713. ->
  12714. movswl %si,%eax movswl %si,%eax p
  12715. decw %si addw %dx,%si hp1
  12716. movw %ax,%si movw %ax,%si hp2
  12717. }
  12718. case taicpu(hp1).ops of
  12719. 1:
  12720. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12721. 2:
  12722. begin
  12723. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12724. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12725. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12726. end;
  12727. else
  12728. internalerror(2008042702);
  12729. end;
  12730. {
  12731. ->
  12732. decw %si addw %dx,%si p
  12733. }
  12734. DebugMsg(SPeepholeOptimization + 'var3',p);
  12735. RemoveCurrentP(p, hp1);
  12736. RemoveInstruction(hp2);
  12737. Result := True;
  12738. Exit;
  12739. end;
  12740. if reg_and_hp1_is_instr and
  12741. (taicpu(hp1).opcode = A_MOV) and
  12742. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12743. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12744. {$ifdef x86_64}
  12745. { check for implicit extension to 64 bit }
  12746. or
  12747. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12748. (taicpu(hp1).opsize=S_Q) and
  12749. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12750. )
  12751. {$endif x86_64}
  12752. )
  12753. then
  12754. begin
  12755. { change
  12756. movx %reg1,%reg2
  12757. mov %reg2,%reg3
  12758. dealloc %reg2
  12759. into
  12760. movx %reg,%reg3
  12761. }
  12762. TransferUsedRegs(TmpUsedRegs);
  12763. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12764. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12765. begin
  12766. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12767. {$ifdef x86_64}
  12768. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12769. (taicpu(hp1).opsize=S_Q) then
  12770. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12771. else
  12772. {$endif x86_64}
  12773. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12774. RemoveInstruction(hp1);
  12775. Result := True;
  12776. Exit;
  12777. end;
  12778. end;
  12779. if reg_and_hp1_is_instr and
  12780. ((taicpu(hp1).opcode=A_MOV) or
  12781. (taicpu(hp1).opcode=A_ADD) or
  12782. (taicpu(hp1).opcode=A_SUB) or
  12783. (taicpu(hp1).opcode=A_CMP) or
  12784. (taicpu(hp1).opcode=A_OR) or
  12785. (taicpu(hp1).opcode=A_XOR) or
  12786. (taicpu(hp1).opcode=A_AND)
  12787. ) and
  12788. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12789. begin
  12790. AndTest := (taicpu(hp1).opcode=A_AND) and
  12791. GetNextInstruction(hp1, hp2) and
  12792. (hp2.typ = ait_instruction) and
  12793. (
  12794. (
  12795. (taicpu(hp2).opcode=A_TEST) and
  12796. (
  12797. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12798. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12799. (
  12800. { If the AND and TEST instructions share a constant, this is also valid }
  12801. (taicpu(hp1).oper[0]^.typ = top_const) and
  12802. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12803. )
  12804. ) and
  12805. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12806. ) or
  12807. (
  12808. (taicpu(hp2).opcode=A_CMP) and
  12809. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12810. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12811. )
  12812. );
  12813. { change
  12814. movx (oper),%reg2
  12815. and $x,%reg2
  12816. test %reg2,%reg2
  12817. dealloc %reg2
  12818. into
  12819. op %reg1,%reg3
  12820. if the second op accesses only the bits stored in reg1
  12821. }
  12822. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12823. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12824. (taicpu(hp1).oper[0]^.typ = top_const) and
  12825. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12826. AndTest then
  12827. begin
  12828. { Check if the AND constant is in range }
  12829. case taicpu(p).opsize of
  12830. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12831. begin
  12832. NewSize := S_B;
  12833. Limit := $FF;
  12834. end;
  12835. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12836. begin
  12837. NewSize := S_W;
  12838. Limit := $FFFF;
  12839. end;
  12840. {$ifdef x86_64}
  12841. S_LQ:
  12842. begin
  12843. NewSize := S_L;
  12844. Limit := $FFFFFFFF;
  12845. end;
  12846. {$endif x86_64}
  12847. else
  12848. InternalError(2021120303);
  12849. end;
  12850. if (
  12851. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12852. { Check for negative operands }
  12853. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12854. ) and
  12855. GetNextInstruction(hp2,hp3) and
  12856. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12857. (taicpu(hp3).condition in [C_E,C_NE]) then
  12858. begin
  12859. TransferUsedRegs(TmpUsedRegs);
  12860. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12861. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12862. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12863. begin
  12864. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12865. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12866. taicpu(hp1).opcode := A_TEST;
  12867. taicpu(hp1).opsize := NewSize;
  12868. RemoveInstruction(hp2);
  12869. RemoveCurrentP(p, hp1);
  12870. Result:=true;
  12871. exit;
  12872. end;
  12873. end;
  12874. end;
  12875. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12876. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12877. (taicpu(hp1).opsize=S_B)) or
  12878. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12879. (taicpu(hp1).opsize=S_W))
  12880. {$ifdef x86_64}
  12881. or ((taicpu(p).opsize=S_LQ) and
  12882. (taicpu(hp1).opsize=S_L))
  12883. {$endif x86_64}
  12884. ) and
  12885. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12886. begin
  12887. { change
  12888. movx %reg1,%reg2
  12889. op %reg2,%reg3
  12890. dealloc %reg2
  12891. into
  12892. op %reg1,%reg3
  12893. if the second op accesses only the bits stored in reg1
  12894. }
  12895. TransferUsedRegs(TmpUsedRegs);
  12896. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12897. if AndTest then
  12898. begin
  12899. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12900. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12901. end
  12902. else
  12903. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12904. if not RegUsed then
  12905. begin
  12906. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12907. if taicpu(p).oper[0]^.typ=top_reg then
  12908. begin
  12909. case taicpu(hp1).opsize of
  12910. S_B:
  12911. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12912. S_W:
  12913. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12914. S_L:
  12915. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12916. else
  12917. Internalerror(2020102301);
  12918. end;
  12919. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12920. end
  12921. else
  12922. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12923. RemoveCurrentP(p);
  12924. if AndTest then
  12925. RemoveInstruction(hp2);
  12926. result:=true;
  12927. exit;
  12928. end;
  12929. end
  12930. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12931. (
  12932. { Bitwise operations only }
  12933. (taicpu(hp1).opcode=A_AND) or
  12934. (taicpu(hp1).opcode=A_TEST) or
  12935. (
  12936. (taicpu(hp1).oper[0]^.typ = top_const) and
  12937. (
  12938. (taicpu(hp1).opcode=A_OR) or
  12939. (taicpu(hp1).opcode=A_XOR)
  12940. )
  12941. )
  12942. ) and
  12943. (
  12944. (taicpu(hp1).oper[0]^.typ = top_const) or
  12945. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12946. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12947. ) then
  12948. begin
  12949. { change
  12950. movx %reg2,%reg2
  12951. op const,%reg2
  12952. into
  12953. op const,%reg2 (smaller version)
  12954. movx %reg2,%reg2
  12955. also change
  12956. movx %reg1,%reg2
  12957. and/test (oper),%reg2
  12958. dealloc %reg2
  12959. into
  12960. and/test (oper),%reg1
  12961. }
  12962. case taicpu(p).opsize of
  12963. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12964. begin
  12965. NewSize := S_B;
  12966. NewRegSize := R_SUBL;
  12967. Limit := $FF;
  12968. end;
  12969. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12970. begin
  12971. NewSize := S_W;
  12972. NewRegSize := R_SUBW;
  12973. Limit := $FFFF;
  12974. end;
  12975. {$ifdef x86_64}
  12976. S_LQ:
  12977. begin
  12978. NewSize := S_L;
  12979. NewRegSize := R_SUBD;
  12980. Limit := $FFFFFFFF;
  12981. end;
  12982. {$endif x86_64}
  12983. else
  12984. Internalerror(2021120302);
  12985. end;
  12986. TransferUsedRegs(TmpUsedRegs);
  12987. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12988. if AndTest then
  12989. begin
  12990. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12991. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12992. end
  12993. else
  12994. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12995. if
  12996. (
  12997. (taicpu(p).opcode = A_MOVZX) and
  12998. (
  12999. (taicpu(hp1).opcode=A_AND) or
  13000. (taicpu(hp1).opcode=A_TEST)
  13001. ) and
  13002. not (
  13003. { If both are references, then the final instruction will have
  13004. both operands as references, which is not allowed }
  13005. (taicpu(p).oper[0]^.typ = top_ref) and
  13006. (taicpu(hp1).oper[0]^.typ = top_ref)
  13007. ) and
  13008. not RegUsed
  13009. ) or
  13010. (
  13011. (
  13012. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13013. not RegUsed
  13014. ) and
  13015. (taicpu(p).oper[0]^.typ = top_reg) and
  13016. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13017. (taicpu(hp1).oper[0]^.typ = top_const) and
  13018. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13019. ) then
  13020. begin
  13021. {$if defined(i386) or defined(i8086)}
  13022. { If the target size is 8-bit, make sure we can actually encode it }
  13023. 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
  13024. Exit;
  13025. {$endif i386 or i8086}
  13026. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13027. taicpu(hp1).opsize := NewSize;
  13028. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13029. if AndTest then
  13030. begin
  13031. RemoveInstruction(hp2);
  13032. if not RegUsed then
  13033. begin
  13034. taicpu(hp1).opcode := A_TEST;
  13035. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13036. begin
  13037. { Make sure the reference is the second operand }
  13038. SwapOper := taicpu(hp1).oper[0];
  13039. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13040. taicpu(hp1).oper[1] := SwapOper;
  13041. end;
  13042. end;
  13043. end;
  13044. case taicpu(hp1).oper[0]^.typ of
  13045. top_reg:
  13046. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13047. top_const:
  13048. { For the AND/TEST case }
  13049. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13050. else
  13051. ;
  13052. end;
  13053. if RegUsed then
  13054. begin
  13055. AsmL.Remove(p);
  13056. AsmL.InsertAfter(p, hp1);
  13057. p := hp1;
  13058. end
  13059. else
  13060. RemoveCurrentP(p, hp1);
  13061. result:=true;
  13062. exit;
  13063. end;
  13064. end;
  13065. end;
  13066. if reg_and_hp1_is_instr and
  13067. (taicpu(p).oper[0]^.typ = top_reg) and
  13068. (
  13069. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13070. ) and
  13071. (taicpu(hp1).oper[0]^.typ = top_const) and
  13072. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13073. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13074. { Minimum shift value allowed is the bit difference between the sizes }
  13075. (taicpu(hp1).oper[0]^.val >=
  13076. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13077. 8 * (
  13078. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13079. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13080. )
  13081. ) then
  13082. begin
  13083. { For:
  13084. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13085. shl/sal ##, %reg1
  13086. Remove the movsx/movzx instruction if the shift overwrites the
  13087. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13088. }
  13089. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13090. RemoveCurrentP(p, hp1);
  13091. Result := True;
  13092. Exit;
  13093. end
  13094. else if reg_and_hp1_is_instr and
  13095. (taicpu(p).oper[0]^.typ = top_reg) and
  13096. (
  13097. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13098. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13099. ) and
  13100. (taicpu(hp1).oper[0]^.typ = top_const) and
  13101. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13102. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13103. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13104. (taicpu(hp1).oper[0]^.val <
  13105. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13106. 8 * (
  13107. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13108. )
  13109. ) then
  13110. begin
  13111. { For:
  13112. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13113. sar ##, %reg1 shr ##, %reg1
  13114. Move the shift to before the movx instruction if the shift value
  13115. is not too large.
  13116. }
  13117. asml.Remove(hp1);
  13118. asml.InsertBefore(hp1, p);
  13119. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13120. case taicpu(p).opsize of
  13121. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13122. taicpu(hp1).opsize := S_B;
  13123. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13124. taicpu(hp1).opsize := S_W;
  13125. {$ifdef x86_64}
  13126. S_LQ:
  13127. taicpu(hp1).opsize := S_L;
  13128. {$endif}
  13129. else
  13130. InternalError(2020112401);
  13131. end;
  13132. if (taicpu(hp1).opcode = A_SHR) then
  13133. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13134. else
  13135. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13136. Result := True;
  13137. end;
  13138. if reg_and_hp1_is_instr and
  13139. (taicpu(p).oper[0]^.typ = top_reg) and
  13140. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13141. (
  13142. (taicpu(hp1).opcode = taicpu(p).opcode)
  13143. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13144. {$ifdef x86_64}
  13145. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13146. {$endif x86_64}
  13147. ) then
  13148. begin
  13149. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13150. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13151. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13152. begin
  13153. {
  13154. For example:
  13155. movzbw %al,%ax
  13156. movzwl %ax,%eax
  13157. Compress into:
  13158. movzbl %al,%eax
  13159. }
  13160. RegUsed := False;
  13161. case taicpu(p).opsize of
  13162. S_BW:
  13163. case taicpu(hp1).opsize of
  13164. S_WL:
  13165. begin
  13166. taicpu(p).opsize := S_BL;
  13167. RegUsed := True;
  13168. end;
  13169. {$ifdef x86_64}
  13170. S_WQ:
  13171. begin
  13172. if taicpu(p).opcode = A_MOVZX then
  13173. begin
  13174. taicpu(p).opsize := S_BL;
  13175. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13176. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13177. end
  13178. else
  13179. taicpu(p).opsize := S_BQ;
  13180. RegUsed := True;
  13181. end;
  13182. {$endif x86_64}
  13183. else
  13184. ;
  13185. end;
  13186. {$ifdef x86_64}
  13187. S_BL:
  13188. case taicpu(hp1).opsize of
  13189. S_LQ:
  13190. begin
  13191. if taicpu(p).opcode = A_MOVZX then
  13192. begin
  13193. taicpu(p).opsize := S_BL;
  13194. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13195. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13196. end
  13197. else
  13198. taicpu(p).opsize := S_BQ;
  13199. RegUsed := True;
  13200. end;
  13201. else
  13202. ;
  13203. end;
  13204. S_WL:
  13205. case taicpu(hp1).opsize of
  13206. S_LQ:
  13207. begin
  13208. if taicpu(p).opcode = A_MOVZX then
  13209. begin
  13210. taicpu(p).opsize := S_WL;
  13211. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13212. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13213. end
  13214. else
  13215. taicpu(p).opsize := S_WQ;
  13216. RegUsed := True;
  13217. end;
  13218. else
  13219. ;
  13220. end;
  13221. {$endif x86_64}
  13222. else
  13223. ;
  13224. end;
  13225. if RegUsed then
  13226. begin
  13227. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13228. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13229. RemoveInstruction(hp1);
  13230. Result := True;
  13231. Exit;
  13232. end;
  13233. end;
  13234. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13235. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13236. GetNextInstruction(hp1, hp2) and
  13237. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13238. (
  13239. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13240. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13241. {$ifdef x86_64}
  13242. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13243. {$endif x86_64}
  13244. ) and
  13245. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13246. (
  13247. (
  13248. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13249. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13250. ) or
  13251. (
  13252. { Only allow the operands in reverse order for TEST instructions }
  13253. (taicpu(hp2).opcode = A_TEST) and
  13254. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13255. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13256. )
  13257. ) then
  13258. begin
  13259. {
  13260. For example:
  13261. movzbl %al,%eax
  13262. movzbl (ref),%edx
  13263. andl %edx,%eax
  13264. (%edx deallocated)
  13265. Change to:
  13266. andb (ref),%al
  13267. movzbl %al,%eax
  13268. Rules are:
  13269. - First two instructions have the same opcode and opsize
  13270. - First instruction's operands are the same super-register
  13271. - Second instruction operates on a different register
  13272. - Third instruction is AND, OR, XOR or TEST
  13273. - Third instruction's operands are the destination registers of the first two instructions
  13274. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13275. - Second instruction's destination register is deallocated afterwards
  13276. }
  13277. TransferUsedRegs(TmpUsedRegs);
  13278. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13279. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13280. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13281. begin
  13282. case taicpu(p).opsize of
  13283. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13284. NewSize := S_B;
  13285. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13286. NewSize := S_W;
  13287. {$ifdef x86_64}
  13288. S_LQ:
  13289. NewSize := S_L;
  13290. {$endif x86_64}
  13291. else
  13292. InternalError(2021120301);
  13293. end;
  13294. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13295. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13296. taicpu(hp2).opsize := NewSize;
  13297. RemoveInstruction(hp1);
  13298. { With TEST, it's best to keep the MOVX instruction at the top }
  13299. if (taicpu(hp2).opcode <> A_TEST) then
  13300. begin
  13301. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13302. asml.Remove(p);
  13303. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13304. asml.InsertAfter(p, hp2);
  13305. p := hp2;
  13306. end
  13307. else
  13308. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13309. Result := True;
  13310. Exit;
  13311. end;
  13312. end;
  13313. end;
  13314. if taicpu(p).opcode=A_MOVZX then
  13315. begin
  13316. { removes superfluous And's after movzx's }
  13317. if reg_and_hp1_is_instr and
  13318. (taicpu(hp1).opcode = A_AND) and
  13319. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13320. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13321. {$ifdef x86_64}
  13322. { check for implicit extension to 64 bit }
  13323. or
  13324. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13325. (taicpu(hp1).opsize=S_Q) and
  13326. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13327. )
  13328. {$endif x86_64}
  13329. )
  13330. then
  13331. begin
  13332. case taicpu(p).opsize Of
  13333. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13334. if (taicpu(hp1).oper[0]^.val = $ff) then
  13335. begin
  13336. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13337. RemoveInstruction(hp1);
  13338. Result:=true;
  13339. exit;
  13340. end;
  13341. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13342. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13343. begin
  13344. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13345. RemoveInstruction(hp1);
  13346. Result:=true;
  13347. exit;
  13348. end;
  13349. {$ifdef x86_64}
  13350. S_LQ:
  13351. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13352. begin
  13353. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13354. RemoveInstruction(hp1);
  13355. Result:=true;
  13356. exit;
  13357. end;
  13358. {$endif x86_64}
  13359. else
  13360. ;
  13361. end;
  13362. { we cannot get rid of the and, but can we get rid of the movz ?}
  13363. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13364. begin
  13365. case taicpu(p).opsize Of
  13366. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13367. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13368. begin
  13369. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13370. RemoveCurrentP(p,hp1);
  13371. Result:=true;
  13372. exit;
  13373. end;
  13374. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13375. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13376. begin
  13377. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13378. RemoveCurrentP(p,hp1);
  13379. Result:=true;
  13380. exit;
  13381. end;
  13382. {$ifdef x86_64}
  13383. S_LQ:
  13384. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13385. begin
  13386. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13387. RemoveCurrentP(p,hp1);
  13388. Result:=true;
  13389. exit;
  13390. end;
  13391. {$endif x86_64}
  13392. else
  13393. ;
  13394. end;
  13395. end;
  13396. end;
  13397. { changes some movzx constructs to faster synonyms (all examples
  13398. are given with eax/ax, but are also valid for other registers)}
  13399. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13400. begin
  13401. case taicpu(p).opsize of
  13402. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13403. (the machine code is equivalent to movzbl %al,%eax), but the
  13404. code generator still generates that assembler instruction and
  13405. it is silently converted. This should probably be checked.
  13406. [Kit] }
  13407. S_BW:
  13408. begin
  13409. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13410. (
  13411. not IsMOVZXAcceptable
  13412. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13413. or (
  13414. (cs_opt_size in current_settings.optimizerswitches) and
  13415. (taicpu(p).oper[1]^.reg = NR_AX)
  13416. )
  13417. ) then
  13418. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13419. begin
  13420. DebugMsg(SPeepholeOptimization + 'var7',p);
  13421. taicpu(p).opcode := A_AND;
  13422. taicpu(p).changeopsize(S_W);
  13423. taicpu(p).loadConst(0,$ff);
  13424. Result := True;
  13425. end
  13426. else if not IsMOVZXAcceptable and
  13427. GetNextInstruction(p, hp1) and
  13428. (tai(hp1).typ = ait_instruction) and
  13429. (taicpu(hp1).opcode = A_AND) and
  13430. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13431. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13432. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13433. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13434. begin
  13435. DebugMsg(SPeepholeOptimization + 'var8',p);
  13436. taicpu(p).opcode := A_MOV;
  13437. taicpu(p).changeopsize(S_W);
  13438. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13439. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13440. Result := True;
  13441. end;
  13442. end;
  13443. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13444. S_BL:
  13445. if not IsMOVZXAcceptable then
  13446. begin
  13447. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13448. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13449. begin
  13450. DebugMsg(SPeepholeOptimization + 'var9',p);
  13451. taicpu(p).opcode := A_AND;
  13452. taicpu(p).changeopsize(S_L);
  13453. taicpu(p).loadConst(0,$ff);
  13454. Result := True;
  13455. end
  13456. else if GetNextInstruction(p, hp1) and
  13457. (tai(hp1).typ = ait_instruction) and
  13458. (taicpu(hp1).opcode = A_AND) and
  13459. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13460. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13461. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13462. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13463. begin
  13464. DebugMsg(SPeepholeOptimization + 'var10',p);
  13465. taicpu(p).opcode := A_MOV;
  13466. taicpu(p).changeopsize(S_L);
  13467. { do not use R_SUBWHOLE
  13468. as movl %rdx,%eax
  13469. is invalid in assembler PM }
  13470. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13471. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13472. Result := True;
  13473. end;
  13474. end;
  13475. {$endif i8086}
  13476. S_WL:
  13477. if not IsMOVZXAcceptable then
  13478. begin
  13479. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13480. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13481. begin
  13482. DebugMsg(SPeepholeOptimization + 'var11',p);
  13483. taicpu(p).opcode := A_AND;
  13484. taicpu(p).changeopsize(S_L);
  13485. taicpu(p).loadConst(0,$ffff);
  13486. Result := True;
  13487. end
  13488. else if GetNextInstruction(p, hp1) and
  13489. (tai(hp1).typ = ait_instruction) and
  13490. (taicpu(hp1).opcode = A_AND) and
  13491. (taicpu(hp1).oper[0]^.typ = top_const) and
  13492. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13493. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13494. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13495. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13496. begin
  13497. DebugMsg(SPeepholeOptimization + 'var12',p);
  13498. taicpu(p).opcode := A_MOV;
  13499. taicpu(p).changeopsize(S_L);
  13500. { do not use R_SUBWHOLE
  13501. as movl %rdx,%eax
  13502. is invalid in assembler PM }
  13503. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13504. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13505. Result := True;
  13506. end;
  13507. end;
  13508. else
  13509. InternalError(2017050705);
  13510. end;
  13511. end
  13512. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13513. begin
  13514. if GetNextInstruction(p, hp1) and
  13515. (tai(hp1).typ = ait_instruction) and
  13516. (taicpu(hp1).opcode = A_AND) and
  13517. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13518. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13519. begin
  13520. case taicpu(p).opsize Of
  13521. S_BL:
  13522. if (taicpu(hp1).opsize <> S_L) or
  13523. (taicpu(hp1).oper[0]^.val > $FF) then
  13524. begin
  13525. DebugMsg(SPeepholeOptimization + 'var13',p);
  13526. taicpu(hp1).changeopsize(S_L);
  13527. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13528. Include(OptsToCheck, aoc_ForceNewIteration);
  13529. end;
  13530. S_WL:
  13531. if (taicpu(hp1).opsize <> S_L) or
  13532. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13533. begin
  13534. DebugMsg(SPeepholeOptimization + 'var14',p);
  13535. taicpu(hp1).changeopsize(S_L);
  13536. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13537. Include(OptsToCheck, aoc_ForceNewIteration);
  13538. end;
  13539. S_BW:
  13540. if (taicpu(hp1).opsize <> S_W) or
  13541. (taicpu(hp1).oper[0]^.val > $FF) then
  13542. begin
  13543. DebugMsg(SPeepholeOptimization + 'var15',p);
  13544. taicpu(hp1).changeopsize(S_W);
  13545. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13546. Include(OptsToCheck, aoc_ForceNewIteration);
  13547. end;
  13548. else
  13549. Internalerror(2017050704)
  13550. end;
  13551. end;
  13552. end;
  13553. end;
  13554. end;
  13555. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13556. var
  13557. hp1, hp2 : tai;
  13558. MaskLength : Cardinal;
  13559. MaskedBits : TCgInt;
  13560. ActiveReg : TRegister;
  13561. begin
  13562. Result:=false;
  13563. { There are no optimisations for reference targets }
  13564. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13565. Exit;
  13566. while GetNextInstruction(p, hp1) and
  13567. (hp1.typ = ait_instruction) do
  13568. begin
  13569. if (taicpu(p).oper[0]^.typ = top_const) then
  13570. begin
  13571. case taicpu(hp1).opcode of
  13572. A_AND:
  13573. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13574. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13575. { the second register must contain the first one, so compare their subreg types }
  13576. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13577. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13578. { change
  13579. and const1, reg
  13580. and const2, reg
  13581. to
  13582. and (const1 and const2), reg
  13583. }
  13584. begin
  13585. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13586. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13587. RemoveCurrentP(p, hp1);
  13588. Result:=true;
  13589. exit;
  13590. end;
  13591. A_CMP:
  13592. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13593. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13594. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13595. { Just check that the condition on the next instruction is compatible }
  13596. GetNextInstruction(hp1, hp2) and
  13597. (hp2.typ = ait_instruction) and
  13598. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13599. then
  13600. { change
  13601. and 2^n, reg
  13602. cmp 2^n, reg
  13603. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13604. to
  13605. and 2^n, reg
  13606. test reg, reg
  13607. j(~c) / set(~c) / cmov(~c)
  13608. }
  13609. begin
  13610. { Keep TEST instruction in, rather than remove it, because
  13611. it may trigger other optimisations such as MovAndTest2Test }
  13612. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13613. taicpu(hp1).opcode := A_TEST;
  13614. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13615. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13616. Result := True;
  13617. Exit;
  13618. end
  13619. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13620. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13621. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13622. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13623. { change
  13624. and $ff/$ff/$ffff, reg
  13625. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13626. dealloc reg
  13627. to
  13628. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13629. }
  13630. begin
  13631. TransferUsedRegs(TmpUsedRegs);
  13632. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13633. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13634. begin
  13635. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13636. case taicpu(p).oper[0]^.val of
  13637. $ff:
  13638. begin
  13639. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13640. taicpu(hp1).opsize:=S_B;
  13641. end;
  13642. $ffff:
  13643. begin
  13644. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13645. taicpu(hp1).opsize:=S_W;
  13646. end;
  13647. $ffffffff:
  13648. begin
  13649. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13650. taicpu(hp1).opsize:=S_L;
  13651. end;
  13652. else
  13653. Internalerror(2023030401);
  13654. end;
  13655. RemoveCurrentP(p);
  13656. Result := True;
  13657. Exit;
  13658. end;
  13659. end;
  13660. A_MOVZX:
  13661. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13662. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13663. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13664. (
  13665. (
  13666. (taicpu(p).opsize=S_W) and
  13667. (taicpu(hp1).opsize=S_BW)
  13668. ) or
  13669. (
  13670. (taicpu(p).opsize=S_L) and
  13671. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13672. )
  13673. {$ifdef x86_64}
  13674. or
  13675. (
  13676. (taicpu(p).opsize=S_Q) and
  13677. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13678. )
  13679. {$endif x86_64}
  13680. ) then
  13681. begin
  13682. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13683. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13684. ) or
  13685. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13686. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13687. then
  13688. begin
  13689. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13690. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13691. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13692. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13693. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13694. }
  13695. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13696. RemoveInstruction(hp1);
  13697. { See if there are other optimisations possible }
  13698. Continue;
  13699. end;
  13700. end;
  13701. A_SHL:
  13702. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13703. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13704. begin
  13705. {$ifopt R+}
  13706. {$define RANGE_WAS_ON}
  13707. {$R-}
  13708. {$endif}
  13709. { get length of potential and mask }
  13710. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13711. { really a mask? }
  13712. {$ifdef RANGE_WAS_ON}
  13713. {$R+}
  13714. {$endif}
  13715. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13716. { unmasked part shifted out? }
  13717. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13718. begin
  13719. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13720. RemoveCurrentP(p, hp1);
  13721. Result:=true;
  13722. exit;
  13723. end;
  13724. end;
  13725. A_SHR:
  13726. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13727. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13728. (taicpu(hp1).oper[0]^.val <= 63) then
  13729. begin
  13730. { Does SHR combined with the AND cover all the bits?
  13731. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13732. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13733. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13734. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13735. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13736. begin
  13737. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13738. RemoveCurrentP(p, hp1);
  13739. Result := True;
  13740. Exit;
  13741. end;
  13742. end;
  13743. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13744. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13745. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13746. begin
  13747. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13748. (
  13749. (
  13750. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13751. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13752. ) or (
  13753. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13754. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13755. {$ifdef x86_64}
  13756. ) or (
  13757. (taicpu(hp1).opsize = S_LQ) and
  13758. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13759. {$endif x86_64}
  13760. )
  13761. ) then
  13762. begin
  13763. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13764. begin
  13765. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13766. RemoveInstruction(hp1);
  13767. { See if there are other optimisations possible }
  13768. Continue;
  13769. end;
  13770. { The super-registers are the same though.
  13771. Note that this change by itself doesn't improve
  13772. code speed, but it opens up other optimisations. }
  13773. {$ifdef x86_64}
  13774. { Convert 64-bit register to 32-bit }
  13775. case taicpu(hp1).opsize of
  13776. S_BQ:
  13777. begin
  13778. taicpu(hp1).opsize := S_BL;
  13779. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13780. end;
  13781. S_WQ:
  13782. begin
  13783. taicpu(hp1).opsize := S_WL;
  13784. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13785. end
  13786. else
  13787. ;
  13788. end;
  13789. {$endif x86_64}
  13790. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13791. taicpu(hp1).opcode := A_MOVZX;
  13792. { See if there are other optimisations possible }
  13793. Continue;
  13794. end;
  13795. end;
  13796. else
  13797. ;
  13798. end;
  13799. end
  13800. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13801. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13802. begin
  13803. {$ifdef x86_64}
  13804. if (taicpu(p).opsize = S_Q) then
  13805. begin
  13806. { Never necessary }
  13807. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13808. RemoveCurrentP(p, hp1);
  13809. Result := True;
  13810. Exit;
  13811. end;
  13812. {$endif x86_64}
  13813. { Forward check to determine necessity of and %reg,%reg }
  13814. TransferUsedRegs(TmpUsedRegs);
  13815. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13816. { Saves on a bunch of dereferences }
  13817. ActiveReg := taicpu(p).oper[1]^.reg;
  13818. case taicpu(hp1).opcode of
  13819. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13820. if (
  13821. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13822. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13823. ) and
  13824. (
  13825. (taicpu(hp1).opcode <> A_MOV) or
  13826. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13827. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13828. ) and
  13829. not (
  13830. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13831. (taicpu(hp1).opcode = A_MOV) and
  13832. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13833. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13834. ) and
  13835. (
  13836. (
  13837. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13838. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13839. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13840. ) or
  13841. (
  13842. {$ifdef x86_64}
  13843. (
  13844. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13845. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13846. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13847. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13848. ) and
  13849. {$endif x86_64}
  13850. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13851. )
  13852. ) then
  13853. begin
  13854. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13855. RemoveCurrentP(p, hp1);
  13856. Result := True;
  13857. Exit;
  13858. end;
  13859. A_ADD,
  13860. A_AND,
  13861. A_BSF,
  13862. A_BSR,
  13863. A_BTC,
  13864. A_BTR,
  13865. A_BTS,
  13866. A_OR,
  13867. A_SUB,
  13868. A_XOR:
  13869. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13870. if (
  13871. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13872. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13873. ) and
  13874. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13875. begin
  13876. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13877. RemoveCurrentP(p, hp1);
  13878. Result := True;
  13879. Exit;
  13880. end;
  13881. A_CMP,
  13882. A_TEST:
  13883. if (
  13884. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13885. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13886. ) and
  13887. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13888. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13889. begin
  13890. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13891. RemoveCurrentP(p, hp1);
  13892. Result := True;
  13893. Exit;
  13894. end;
  13895. A_BSWAP,
  13896. A_NEG,
  13897. A_NOT:
  13898. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13899. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13900. begin
  13901. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13902. RemoveCurrentP(p, hp1);
  13903. Result := True;
  13904. Exit;
  13905. end;
  13906. else
  13907. ;
  13908. end;
  13909. end;
  13910. if (taicpu(hp1).is_jmp) and
  13911. (taicpu(hp1).opcode<>A_JMP) and
  13912. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13913. begin
  13914. { change
  13915. and x, reg
  13916. jxx
  13917. to
  13918. test x, reg
  13919. jxx
  13920. if reg is deallocated before the
  13921. jump, but only if it's a conditional jump (PFV)
  13922. }
  13923. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13924. taicpu(p).opcode := A_TEST;
  13925. Exit;
  13926. end;
  13927. Break;
  13928. end;
  13929. { Lone AND tests }
  13930. if (taicpu(p).oper[0]^.typ = top_const) then
  13931. begin
  13932. {
  13933. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13934. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13935. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13936. }
  13937. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13938. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13939. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13940. begin
  13941. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13942. if taicpu(p).opsize = S_L then
  13943. begin
  13944. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13945. Result := True;
  13946. end;
  13947. end;
  13948. end;
  13949. { Backward check to determine necessity of and %reg,%reg }
  13950. if (taicpu(p).oper[0]^.typ = top_reg) and
  13951. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13952. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13953. GetLastInstruction(p, hp2) and
  13954. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13955. { Check size of adjacent instruction to determine if the AND is
  13956. effectively a null operation }
  13957. (
  13958. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13959. { Note: Don't include S_Q }
  13960. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13961. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13962. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13963. ) then
  13964. begin
  13965. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13966. { If GetNextInstruction returned False, hp1 will be nil }
  13967. RemoveCurrentP(p, hp1);
  13968. Result := True;
  13969. Exit;
  13970. end;
  13971. end;
  13972. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13973. var
  13974. hp1, hp2: tai;
  13975. NewRef: TReference;
  13976. Distance: Cardinal;
  13977. TempTracking: TAllUsedRegs;
  13978. { This entire nested function is used in an if-statement below, but we
  13979. want to avoid all the used reg transfers and GetNextInstruction calls
  13980. until we really have to check }
  13981. function MemRegisterNotUsedLater: Boolean; inline;
  13982. var
  13983. hp2: tai;
  13984. begin
  13985. TransferUsedRegs(TmpUsedRegs);
  13986. hp2 := p;
  13987. repeat
  13988. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13989. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13990. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13991. end;
  13992. begin
  13993. Result := False;
  13994. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13995. (taicpu(p).oper[1]^.typ = top_reg) then
  13996. begin
  13997. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13998. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13999. (hp1.typ <> ait_instruction) or
  14000. not
  14001. (
  14002. (cs_opt_level3 in current_settings.optimizerswitches) or
  14003. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14004. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14005. ) then
  14006. Exit;
  14007. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14008. addq $x, %rax
  14009. movq %rax, %rdx
  14010. sarq $63, %rdx
  14011. (%rax still in use)
  14012. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14013. leaq $x(%rax),%rdx
  14014. addq $x, %rax
  14015. sarq $63, %rdx
  14016. ...which is okay since it breaks the dependency chain between
  14017. addq and movq, but if OptPass2MOV is called first:
  14018. addq $x, %rax
  14019. cqto
  14020. ...which is better in all ways, taking only 2 cycles to execute
  14021. and much smaller in code size.
  14022. }
  14023. { The extra register tracking is quite strenuous }
  14024. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14025. MatchInstruction(hp1, A_MOV, []) then
  14026. begin
  14027. { Update the register tracking to the MOV instruction }
  14028. CopyUsedRegs(TempTracking);
  14029. hp2 := p;
  14030. repeat
  14031. UpdateUsedRegs(tai(hp2.Next));
  14032. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14033. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14034. OptPass2ADD get called again }
  14035. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14036. begin
  14037. { Reset the tracking to the current instruction }
  14038. RestoreUsedRegs(TempTracking);
  14039. ReleaseUsedRegs(TempTracking);
  14040. Result := True;
  14041. Exit;
  14042. end;
  14043. { Reset the tracking to the current instruction }
  14044. RestoreUsedRegs(TempTracking);
  14045. ReleaseUsedRegs(TempTracking);
  14046. { If OptPass2MOV returned True, we don't need to set Result to
  14047. True if hp1 didn't change because the ADD instruction didn't
  14048. get modified and we'll be evaluating hp1 again when the
  14049. peephole optimizer reaches it }
  14050. end;
  14051. { Change:
  14052. add %reg2,%reg1
  14053. (%reg2 not modified in between)
  14054. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14055. To:
  14056. mov/s/z #(%reg1,%reg2),%reg1
  14057. }
  14058. if (taicpu(p).oper[0]^.typ = top_reg) and
  14059. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14060. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14061. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14062. (
  14063. (
  14064. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14065. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14066. { r/esp cannot be an index }
  14067. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14068. ) or (
  14069. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14070. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14071. )
  14072. ) and (
  14073. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14074. (
  14075. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14076. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14077. MemRegisterNotUsedLater
  14078. )
  14079. ) then
  14080. begin
  14081. if (
  14082. { Instructions are guaranteed to be adjacent on -O2 and under }
  14083. (cs_opt_level3 in current_settings.optimizerswitches) and
  14084. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14085. ) then
  14086. begin
  14087. { If the other register is used in between, move the MOV
  14088. instruction to right after the ADD instruction so a
  14089. saving can still be made }
  14090. Asml.Remove(hp1);
  14091. Asml.InsertAfter(hp1, p);
  14092. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14093. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14094. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14095. RemoveCurrentp(p, hp1);
  14096. end
  14097. else
  14098. begin
  14099. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14100. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14101. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14102. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14103. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14104. { hp1 may not be the immediate next instruction under -O3 }
  14105. RemoveCurrentp(p)
  14106. else
  14107. RemoveCurrentp(p, hp1);
  14108. end;
  14109. Result := True;
  14110. Exit;
  14111. end;
  14112. { Change:
  14113. addl/q $x,%reg1
  14114. movl/q %reg1,%reg2
  14115. To:
  14116. leal/q $x(%reg1),%reg2
  14117. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14118. Breaks the dependency chain.
  14119. }
  14120. if (taicpu(p).oper[0]^.typ = top_const) and
  14121. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14122. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14123. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14124. (
  14125. { Instructions are guaranteed to be adjacent on -O2 and under }
  14126. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14127. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14128. ) then
  14129. begin
  14130. TransferUsedRegs(TmpUsedRegs);
  14131. hp2 := p;
  14132. repeat
  14133. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14134. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14135. if (
  14136. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14137. not (cs_opt_size in current_settings.optimizerswitches) or
  14138. (
  14139. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14140. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14141. )
  14142. ) then
  14143. begin
  14144. { Change the MOV instruction to a LEA instruction, and update the
  14145. first operand }
  14146. reference_reset(NewRef, 1, []);
  14147. NewRef.base := taicpu(p).oper[1]^.reg;
  14148. NewRef.scalefactor := 1;
  14149. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14150. taicpu(hp1).opcode := A_LEA;
  14151. taicpu(hp1).loadref(0, NewRef);
  14152. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14153. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14154. begin
  14155. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14156. { Move what is now the LEA instruction to before the ADD instruction }
  14157. Asml.Remove(hp1);
  14158. Asml.InsertBefore(hp1, p);
  14159. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14160. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14161. p := hp1;
  14162. end
  14163. else
  14164. begin
  14165. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14166. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14167. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14168. { hp1 may not be the immediate next instruction under -O3 }
  14169. RemoveCurrentp(p)
  14170. else
  14171. RemoveCurrentp(p, hp1);
  14172. end;
  14173. Result := True;
  14174. end;
  14175. end;
  14176. end;
  14177. end;
  14178. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14179. var
  14180. SubReg: TSubRegister;
  14181. hp1, hp2: tai;
  14182. CallJmp: Boolean;
  14183. begin
  14184. Result := False;
  14185. CallJmp := False;
  14186. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14187. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14188. with taicpu(p).oper[0]^.ref^ do
  14189. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14190. if (offset = 0) then
  14191. begin
  14192. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14193. begin
  14194. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14195. taicpu(p).opcode := A_ADD;
  14196. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14197. Result := True;
  14198. end
  14199. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14200. begin
  14201. if (base <> NR_NO) then
  14202. begin
  14203. if (scalefactor <= 1) then
  14204. begin
  14205. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14206. taicpu(p).opcode := A_ADD;
  14207. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14208. Result := True;
  14209. end;
  14210. end
  14211. else
  14212. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14213. if (scalefactor in [2, 4, 8]) then
  14214. begin
  14215. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14216. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14217. taicpu(p).opcode := A_SHL;
  14218. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14219. Result := True;
  14220. end;
  14221. end;
  14222. end
  14223. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14224. lot of latency, so break off the offset if %reg3 is used soon
  14225. afterwards }
  14226. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14227. { If 3-component addresses don't have additional latency, don't
  14228. perform this optimisation }
  14229. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14230. GetNextInstruction(p, hp1) and
  14231. (hp1.typ = ait_instruction) and
  14232. (
  14233. (
  14234. { Permit jumps and calls since they have a larger degree of overhead }
  14235. (
  14236. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14237. (
  14238. { ... unless the register specifies the location }
  14239. (taicpu(hp1).ops > 0) and
  14240. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14241. )
  14242. ) and
  14243. (
  14244. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14245. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14246. )
  14247. )
  14248. or
  14249. (
  14250. { Check up to two instructions ahead }
  14251. GetNextInstruction(hp1, hp2) and
  14252. (hp2.typ = ait_instruction) and
  14253. (
  14254. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14255. (
  14256. { Same as above }
  14257. (taicpu(hp2).ops > 0) and
  14258. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14259. )
  14260. ) and
  14261. (
  14262. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14263. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14264. )
  14265. )
  14266. ) then
  14267. begin
  14268. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14269. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14270. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14271. offset := 0;
  14272. if Assigned(symbol) or Assigned(relsymbol) then
  14273. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14274. else
  14275. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14276. { Inserting before the next instruction rather than after the
  14277. current instruction gives more accurate register tracking }
  14278. asml.InsertBefore(hp2, hp1);
  14279. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14280. Result := True;
  14281. end;
  14282. end;
  14283. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14284. var
  14285. hp1, hp2: tai;
  14286. NewRef: TReference;
  14287. Distance: Cardinal;
  14288. TempTracking: TAllUsedRegs;
  14289. begin
  14290. Result := False;
  14291. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14292. MatchOpType(taicpu(p),top_const,top_reg) then
  14293. begin
  14294. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14295. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14296. (hp1.typ <> ait_instruction) or
  14297. not
  14298. (
  14299. (cs_opt_level3 in current_settings.optimizerswitches) or
  14300. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14301. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14302. ) then
  14303. Exit;
  14304. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14305. subq $x, %rax
  14306. movq %rax, %rdx
  14307. sarq $63, %rdx
  14308. (%rax still in use)
  14309. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14310. leaq $-x(%rax),%rdx
  14311. movq $x, %rax
  14312. sarq $63, %rdx
  14313. ...which is okay since it breaks the dependency chain between
  14314. subq and movq, but if OptPass2MOV is called first:
  14315. subq $x, %rax
  14316. cqto
  14317. ...which is better in all ways, taking only 2 cycles to execute
  14318. and much smaller in code size.
  14319. }
  14320. { The extra register tracking is quite strenuous }
  14321. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14322. MatchInstruction(hp1, A_MOV, []) then
  14323. begin
  14324. { Update the register tracking to the MOV instruction }
  14325. CopyUsedRegs(TempTracking);
  14326. hp2 := p;
  14327. repeat
  14328. UpdateUsedRegs(tai(hp2.Next));
  14329. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14330. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14331. OptPass2SUB get called again }
  14332. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14333. begin
  14334. { Reset the tracking to the current instruction }
  14335. RestoreUsedRegs(TempTracking);
  14336. ReleaseUsedRegs(TempTracking);
  14337. Result := True;
  14338. Exit;
  14339. end;
  14340. { Reset the tracking to the current instruction }
  14341. RestoreUsedRegs(TempTracking);
  14342. ReleaseUsedRegs(TempTracking);
  14343. { If OptPass2MOV returned True, we don't need to set Result to
  14344. True if hp1 didn't change because the SUB instruction didn't
  14345. get modified and we'll be evaluating hp1 again when the
  14346. peephole optimizer reaches it }
  14347. end;
  14348. { Change:
  14349. subl/q $x,%reg1
  14350. movl/q %reg1,%reg2
  14351. To:
  14352. leal/q $-x(%reg1),%reg2
  14353. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14354. Breaks the dependency chain and potentially permits the removal of
  14355. a CMP instruction if one follows.
  14356. }
  14357. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14358. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14359. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14360. (
  14361. { Instructions are guaranteed to be adjacent on -O2 and under }
  14362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14363. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14364. ) then
  14365. begin
  14366. TransferUsedRegs(TmpUsedRegs);
  14367. hp2 := p;
  14368. repeat
  14369. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14370. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14371. if (
  14372. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14373. not (cs_opt_size in current_settings.optimizerswitches) or
  14374. (
  14375. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14376. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14377. )
  14378. ) then
  14379. begin
  14380. { Change the MOV instruction to a LEA instruction, and update the
  14381. first operand }
  14382. reference_reset(NewRef, 1, []);
  14383. NewRef.base := taicpu(p).oper[1]^.reg;
  14384. NewRef.scalefactor := 1;
  14385. NewRef.offset := -taicpu(p).oper[0]^.val;
  14386. taicpu(hp1).opcode := A_LEA;
  14387. taicpu(hp1).loadref(0, NewRef);
  14388. TransferUsedRegs(TmpUsedRegs);
  14389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14390. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14391. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14392. begin
  14393. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14394. { Move what is now the LEA instruction to before the SUB instruction }
  14395. Asml.Remove(hp1);
  14396. Asml.InsertBefore(hp1, p);
  14397. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14398. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14399. p := hp1;
  14400. end
  14401. else
  14402. begin
  14403. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14404. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14405. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14406. { hp1 may not be the immediate next instruction under -O3 }
  14407. RemoveCurrentp(p)
  14408. else
  14409. RemoveCurrentp(p, hp1);
  14410. end;
  14411. Result := True;
  14412. end;
  14413. end;
  14414. end;
  14415. end;
  14416. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14417. begin
  14418. { we can skip all instructions not messing with the stack pointer }
  14419. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14420. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14421. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14422. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14423. ({(taicpu(hp1).ops=0) or }
  14424. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14425. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14426. ) and }
  14427. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14428. )
  14429. ) do
  14430. GetNextInstruction(hp1,hp1);
  14431. Result:=assigned(hp1);
  14432. end;
  14433. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14434. var
  14435. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14436. begin
  14437. Result:=false;
  14438. hp5:=nil;
  14439. hp6:=nil;
  14440. hp7:=nil;
  14441. hp8:=nil;
  14442. { replace
  14443. leal(q) x(<stackpointer>),<stackpointer>
  14444. <optional .seh_stackalloc ...>
  14445. <optional .seh_endprologue ...>
  14446. call procname
  14447. <optional NOP>
  14448. leal(q) -x(<stackpointer>),<stackpointer>
  14449. <optional VZEROUPPER>
  14450. ret
  14451. by
  14452. jmp procname
  14453. but do it only on level 4 because it destroys stack back traces
  14454. }
  14455. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14456. MatchOpType(taicpu(p),top_ref,top_reg) and
  14457. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14458. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14459. { the -8, -24, -40 are not required, but bail out early if possible,
  14460. higher values are unlikely }
  14461. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14462. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14463. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14464. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14465. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14466. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14467. GetNextInstruction(p, hp1) and
  14468. { Take a copy of hp1 }
  14469. SetAndTest(hp1, hp4) and
  14470. { trick to skip label }
  14471. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14472. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14473. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14474. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14475. SkipSimpleInstructions(hp1) and
  14476. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14477. GetNextInstruction(hp1, hp2) and
  14478. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14479. { skip nop instruction on win64 }
  14480. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14481. SetAndTest(hp2,hp6) and
  14482. GetNextInstruction(hp2,hp2) and
  14483. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14484. ) and
  14485. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14486. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14487. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14488. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14489. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14490. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14491. { Segment register will be NR_NO }
  14492. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14493. GetNextInstruction(hp2, hp3) and
  14494. { trick to skip label }
  14495. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14496. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14497. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14498. SetAndTest(hp3,hp5) and
  14499. GetNextInstruction(hp3,hp3) and
  14500. MatchInstruction(hp3,A_RET,[S_NO])
  14501. )
  14502. ) and
  14503. (taicpu(hp3).ops=0) then
  14504. begin
  14505. taicpu(hp1).opcode := A_JMP;
  14506. taicpu(hp1).is_jmp := true;
  14507. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14508. { search for the stackalloc directive and remove it }
  14509. hp7:=tai(p.next);
  14510. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14511. begin
  14512. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14513. begin
  14514. { sanity check }
  14515. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14516. Internalerror(2024012201);
  14517. hp8:=tai(hp7.next);
  14518. RemoveInstruction(tai(hp7));
  14519. hp7:=hp8;
  14520. break;
  14521. end
  14522. else
  14523. hp7:=tai(hp7.next);
  14524. end;
  14525. RemoveCurrentP(p, hp4);
  14526. RemoveInstruction(hp2);
  14527. RemoveInstruction(hp3);
  14528. { if there is a vzeroupper instruction then move it before the jmp }
  14529. if Assigned(hp5) then
  14530. begin
  14531. AsmL.Remove(hp5);
  14532. ASmL.InsertBefore(hp5,hp1)
  14533. end;
  14534. { remove nop on win64 }
  14535. if Assigned(hp6) then
  14536. RemoveInstruction(hp6);
  14537. Result:=true;
  14538. end;
  14539. end;
  14540. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14541. {$ifdef x86_64}
  14542. var
  14543. hp1, hp2, hp3, hp4, hp5: tai;
  14544. {$endif x86_64}
  14545. begin
  14546. Result:=false;
  14547. {$ifdef x86_64}
  14548. hp5:=nil;
  14549. { replace
  14550. push %rax
  14551. call procname
  14552. pop %rcx
  14553. ret
  14554. by
  14555. jmp procname
  14556. but do it only on level 4 because it destroys stack back traces
  14557. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14558. for all supported calling conventions
  14559. }
  14560. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14561. MatchOpType(taicpu(p),top_reg) and
  14562. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14563. GetNextInstruction(p, hp1) and
  14564. { Take a copy of hp1 }
  14565. SetAndTest(hp1, hp4) and
  14566. { trick to skip label }
  14567. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14568. SkipSimpleInstructions(hp1) and
  14569. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14570. GetNextInstruction(hp1, hp2) and
  14571. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14572. MatchOpType(taicpu(hp2),top_reg) and
  14573. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14574. GetNextInstruction(hp2, hp3) and
  14575. { trick to skip label }
  14576. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14577. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14578. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14579. SetAndTest(hp3,hp5) and
  14580. GetNextInstruction(hp3,hp3) and
  14581. MatchInstruction(hp3,A_RET,[S_NO])
  14582. )
  14583. ) and
  14584. (taicpu(hp3).ops=0) then
  14585. begin
  14586. taicpu(hp1).opcode := A_JMP;
  14587. taicpu(hp1).is_jmp := true;
  14588. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14589. RemoveCurrentP(p, hp4);
  14590. RemoveInstruction(hp2);
  14591. RemoveInstruction(hp3);
  14592. if Assigned(hp5) then
  14593. begin
  14594. AsmL.Remove(hp5);
  14595. ASmL.InsertBefore(hp5,hp1)
  14596. end;
  14597. Result:=true;
  14598. end;
  14599. {$endif x86_64}
  14600. end;
  14601. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14602. var
  14603. Value, RegName: string;
  14604. hp1: tai;
  14605. begin
  14606. Result:=false;
  14607. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14608. begin
  14609. case taicpu(p).oper[0]^.val of
  14610. 0:
  14611. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14612. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14613. (
  14614. { See if we can still convert the instruction }
  14615. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14616. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14617. ) then
  14618. begin
  14619. { change "mov $0,%reg" into "xor %reg,%reg" }
  14620. taicpu(p).opcode := A_XOR;
  14621. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14622. Result := True;
  14623. {$ifdef x86_64}
  14624. end
  14625. else if (taicpu(p).opsize = S_Q) then
  14626. begin
  14627. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14628. { The actual optimization }
  14629. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14630. taicpu(p).changeopsize(S_L);
  14631. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14632. Result := True;
  14633. end;
  14634. $1..$FFFFFFFF:
  14635. begin
  14636. { Code size reduction by J. Gareth "Kit" Moreton }
  14637. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14638. case taicpu(p).opsize of
  14639. S_Q:
  14640. begin
  14641. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14642. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14643. { The actual optimization }
  14644. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14645. taicpu(p).changeopsize(S_L);
  14646. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14647. Result := True;
  14648. end;
  14649. else
  14650. { Do nothing };
  14651. end;
  14652. {$endif x86_64}
  14653. end;
  14654. -1:
  14655. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14656. if (cs_opt_size in current_settings.optimizerswitches) and
  14657. (taicpu(p).opsize <> S_B) and
  14658. (
  14659. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14660. (
  14661. { See if we can still convert the instruction }
  14662. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14663. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14664. )
  14665. ) then
  14666. begin
  14667. { change "mov $-1,%reg" into "or $-1,%reg" }
  14668. { NOTES:
  14669. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14670. - This operation creates a false dependency on the register, so only do it when optimising for size
  14671. - 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
  14672. }
  14673. taicpu(p).opcode := A_OR;
  14674. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14675. Result := True;
  14676. end;
  14677. else
  14678. { Do nothing };
  14679. end;
  14680. end;
  14681. end;
  14682. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14683. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14684. begin
  14685. Result := False;
  14686. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14687. Exit;
  14688. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14689. so don't bother optimising }
  14690. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14691. Exit;
  14692. if (taicpu(p).oper[0]^.typ <> top_const) or
  14693. { If the value can fit into an 8-bit signed integer, a smaller
  14694. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14695. falls within this range }
  14696. (
  14697. (taicpu(p).oper[0]^.val > -128) and
  14698. (taicpu(p).oper[0]^.val <= 127)
  14699. ) then
  14700. Exit;
  14701. { If we're optimising for size, this is acceptable }
  14702. if (cs_opt_size in current_settings.optimizerswitches) then
  14703. Exit(True);
  14704. if (taicpu(p).oper[1]^.typ = top_reg) and
  14705. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14706. Exit(True);
  14707. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14708. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14709. Exit(True);
  14710. end;
  14711. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14712. var
  14713. hp1: tai;
  14714. Value: TCGInt;
  14715. begin
  14716. Result := False;
  14717. if MatchOpType(taicpu(p), top_const, top_reg) then
  14718. begin
  14719. { Detect:
  14720. andw x, %ax (0 <= x < $8000)
  14721. ...
  14722. movzwl %ax,%eax
  14723. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14724. }
  14725. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14726. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14727. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14728. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14729. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14730. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14731. begin
  14732. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14733. taicpu(hp1).opcode := A_CWDE;
  14734. taicpu(hp1).clearop(0);
  14735. taicpu(hp1).clearop(1);
  14736. taicpu(hp1).ops := 0;
  14737. { A change was made, but not with p, so don't set Result, but
  14738. notify the compiler that a change was made }
  14739. Include(OptsToCheck, aoc_ForceNewIteration);
  14740. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14741. end;
  14742. end;
  14743. { If "not x" is a power of 2 (popcnt = 1), change:
  14744. and $x, %reg/ref
  14745. To:
  14746. btr lb(x), %reg/ref
  14747. }
  14748. if IsBTXAcceptable(p) and
  14749. (
  14750. { Make sure a TEST doesn't follow that plays with the register }
  14751. not GetNextInstruction(p, hp1) or
  14752. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14753. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14754. ) then
  14755. begin
  14756. {$push}{$R-}{$Q-}
  14757. { Value is a sign-extended 32-bit integer - just correct it
  14758. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14759. checks to see if this operand is an immediate. }
  14760. Value := not taicpu(p).oper[0]^.val;
  14761. {$pop}
  14762. {$ifdef x86_64}
  14763. if taicpu(p).opsize = S_L then
  14764. {$endif x86_64}
  14765. Value := Value and $FFFFFFFF;
  14766. if (PopCnt(QWord(Value)) = 1) then
  14767. begin
  14768. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14769. taicpu(p).opcode := A_BTR;
  14770. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14771. Result := True;
  14772. Exit;
  14773. end;
  14774. end;
  14775. end;
  14776. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14777. begin
  14778. Result := False;
  14779. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14780. Exit;
  14781. { Convert:
  14782. movswl %ax,%eax -> cwtl
  14783. movslq %eax,%rax -> cdqe
  14784. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14785. refer to the same opcode and depends only on the assembler's
  14786. current operand-size attribute. [Kit]
  14787. }
  14788. with taicpu(p) do
  14789. case opsize of
  14790. S_WL:
  14791. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14792. begin
  14793. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14794. opcode := A_CWDE;
  14795. clearop(0);
  14796. clearop(1);
  14797. ops := 0;
  14798. Result := True;
  14799. end;
  14800. {$ifdef x86_64}
  14801. S_LQ:
  14802. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14803. begin
  14804. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14805. opcode := A_CDQE;
  14806. clearop(0);
  14807. clearop(1);
  14808. ops := 0;
  14809. Result := True;
  14810. end;
  14811. {$endif x86_64}
  14812. else
  14813. ;
  14814. end;
  14815. end;
  14816. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14817. var
  14818. hp1, hp2: tai;
  14819. IdentityMask, Shift: TCGInt;
  14820. LimitSize: Topsize;
  14821. DoNotMerge: Boolean;
  14822. begin
  14823. Result := False;
  14824. { All these optimisations work on "shr const,%reg" }
  14825. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14826. Exit;
  14827. DoNotMerge := False;
  14828. Shift := taicpu(p).oper[0]^.val;
  14829. LimitSize := taicpu(p).opsize;
  14830. hp1 := p;
  14831. repeat
  14832. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14833. Break;
  14834. { Detect:
  14835. shr x, %reg
  14836. and y, %reg
  14837. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14838. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14839. }
  14840. case taicpu(hp1).opcode of
  14841. A_AND:
  14842. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14843. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14844. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14845. begin
  14846. { Make sure the FLAGS register isn't in use }
  14847. TransferUsedRegs(TmpUsedRegs);
  14848. hp2 := p;
  14849. repeat
  14850. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14851. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14852. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14853. begin
  14854. { Generate the identity mask }
  14855. case taicpu(p).opsize of
  14856. S_B:
  14857. IdentityMask := $FF shr Shift;
  14858. S_W:
  14859. IdentityMask := $FFFF shr Shift;
  14860. S_L:
  14861. IdentityMask := $FFFFFFFF shr Shift;
  14862. {$ifdef x86_64}
  14863. S_Q:
  14864. { We need to force the operands to be unsigned 64-bit
  14865. integers otherwise the wrong value is generated }
  14866. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14867. {$endif x86_64}
  14868. else
  14869. InternalError(2022081501);
  14870. end;
  14871. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14872. begin
  14873. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14874. { All the possible 1 bits are covered, so we can remove the AND }
  14875. hp2 := tai(hp1.Previous);
  14876. RemoveInstruction(hp1);
  14877. { p wasn't actually changed, so don't set Result to True,
  14878. but a change was nonetheless made elsewhere }
  14879. Include(OptsToCheck, aoc_ForceNewIteration);
  14880. { Do another pass in case other AND or MOVZX instructions
  14881. follow }
  14882. hp1 := hp2;
  14883. Continue;
  14884. end;
  14885. end;
  14886. end;
  14887. A_TEST, A_CMP, A_Jcc:
  14888. { Skip over conditional jumps and relevant comparisons }
  14889. Continue;
  14890. A_MOVZX:
  14891. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14892. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14893. begin
  14894. { Since the original register is being read as is, subsequent
  14895. SHRs must not be merged at this point }
  14896. DoNotMerge := True;
  14897. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14898. begin
  14899. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14900. begin
  14901. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14902. { All the possible 1 bits are covered, so we can remove the AND }
  14903. hp2 := tai(hp1.Previous);
  14904. RemoveInstruction(hp1);
  14905. hp1 := hp2;
  14906. end
  14907. else { Different register target }
  14908. begin
  14909. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14910. taicpu(hp1).opcode := A_MOV;
  14911. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14912. case taicpu(hp1).opsize of
  14913. S_BW:
  14914. taicpu(hp1).opsize := S_W;
  14915. S_BL, S_WL:
  14916. taicpu(hp1).opsize := S_L;
  14917. else
  14918. InternalError(2022081503);
  14919. end;
  14920. end;
  14921. end
  14922. else if (Shift > 0) and
  14923. (taicpu(p).opsize = S_W) and
  14924. (taicpu(hp1).opsize = S_WL) and
  14925. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14926. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14927. begin
  14928. { Detect:
  14929. shr x, %ax (x > 0)
  14930. ...
  14931. movzwl %ax,%eax
  14932. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14933. }
  14934. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14935. taicpu(hp1).opcode := A_CWDE;
  14936. taicpu(hp1).clearop(0);
  14937. taicpu(hp1).clearop(1);
  14938. taicpu(hp1).ops := 0;
  14939. end;
  14940. { Move onto the next instruction }
  14941. Continue;
  14942. end;
  14943. A_SHL, A_SAL, A_SHR:
  14944. if (taicpu(hp1).opsize <= LimitSize) and
  14945. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14946. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14947. begin
  14948. { Make sure the sizes don't exceed the register size limit
  14949. (measured by the shift value falling below the limit) }
  14950. if taicpu(hp1).opsize < LimitSize then
  14951. LimitSize := taicpu(hp1).opsize;
  14952. if taicpu(hp1).opcode = A_SHR then
  14953. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14954. else
  14955. begin
  14956. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14957. DoNotMerge := True;
  14958. end;
  14959. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14960. Break;
  14961. { Since we've established that the combined shift is within
  14962. limits, we can actually combine the adjacent SHR
  14963. instructions even if they're different sizes }
  14964. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14965. begin
  14966. hp2 := tai(hp1.Previous);
  14967. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14968. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14969. RemoveInstruction(hp1);
  14970. hp1 := hp2;
  14971. end;
  14972. { Move onto the next instruction }
  14973. Continue;
  14974. end;
  14975. else
  14976. ;
  14977. end;
  14978. Break;
  14979. until False;
  14980. { Detect the following (looking backwards):
  14981. shr %cl,%reg
  14982. shr x, %reg
  14983. Swap the two SHR instructions to minimise a pipeline stall.
  14984. }
  14985. if GetLastInstruction(p, hp1) and
  14986. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14987. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14988. { First operand will be %cl }
  14989. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14990. { Just to be sure }
  14991. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14992. begin
  14993. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14994. { Moving the entries this way ensures the register tracking remains correct }
  14995. Asml.Remove(p);
  14996. Asml.InsertBefore(p, hp1);
  14997. p := hp1;
  14998. { Don't set Result to True because the current instruction is now
  14999. "shr %cl,%reg" and there's nothing more we can do with it }
  15000. end;
  15001. end;
  15002. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15003. var
  15004. hp1, hp2: tai;
  15005. Opposite, SecondOpposite: TAsmOp;
  15006. NewCond: TAsmCond;
  15007. begin
  15008. Result := False;
  15009. { Change:
  15010. add/sub 128,(dest)
  15011. To:
  15012. sub/add -128,(dest)
  15013. This generaally takes fewer bytes to encode because -128 can be stored
  15014. in a signed byte, whereas +128 cannot.
  15015. }
  15016. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15017. begin
  15018. if taicpu(p).opcode = A_ADD then
  15019. Opposite := A_SUB
  15020. else
  15021. Opposite := A_ADD;
  15022. { Be careful if the flags are in use, because the CF flag inverts
  15023. when changing from ADD to SUB and vice versa }
  15024. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15025. GetNextInstruction(p, hp1) then
  15026. begin
  15027. TransferUsedRegs(TmpUsedRegs);
  15028. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15029. hp2 := hp1;
  15030. { Scan ahead to check if everything's safe }
  15031. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15032. begin
  15033. if (hp1.typ <> ait_instruction) then
  15034. { Probably unsafe since the flags are still in use }
  15035. Exit;
  15036. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15037. { Stop searching at an unconditional jump }
  15038. Break;
  15039. if not
  15040. (
  15041. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15042. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15043. ) and
  15044. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15045. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15046. Exit;
  15047. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15048. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15049. { Move to the next instruction }
  15050. GetNextInstruction(hp1, hp1);
  15051. end;
  15052. while Assigned(hp2) and (hp2 <> hp1) do
  15053. begin
  15054. NewCond := C_None;
  15055. case taicpu(hp2).condition of
  15056. C_A, C_NBE:
  15057. NewCond := C_BE;
  15058. C_B, C_C, C_NAE:
  15059. NewCond := C_AE;
  15060. C_AE, C_NB, C_NC:
  15061. NewCond := C_B;
  15062. C_BE, C_NA:
  15063. NewCond := C_A;
  15064. else
  15065. { No change needed };
  15066. end;
  15067. if NewCond <> C_None then
  15068. begin
  15069. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15070. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15071. taicpu(hp2).condition := NewCond;
  15072. end
  15073. else
  15074. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15075. begin
  15076. { Because of the flipping of the carry bit, to ensure
  15077. the operation remains equivalent, ADC becomes SBB
  15078. and vice versa, and the constant is not-inverted.
  15079. If multiple ADCs or SBBs appear in a row, each one
  15080. changed causes the carry bit to invert, so they all
  15081. need to be flipped }
  15082. if taicpu(hp2).opcode = A_ADC then
  15083. SecondOpposite := A_SBB
  15084. else
  15085. SecondOpposite := A_ADC;
  15086. if taicpu(hp2).oper[0]^.typ <> top_const then
  15087. { Should have broken out of this optimisation already }
  15088. InternalError(2021112901);
  15089. 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]^) + ' -> ' +
  15090. 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);
  15091. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15092. taicpu(hp2).opcode := SecondOpposite;
  15093. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15094. end;
  15095. { Move to the next instruction }
  15096. GetNextInstruction(hp2, hp2);
  15097. end;
  15098. if (hp2 <> hp1) then
  15099. InternalError(2021111501);
  15100. end;
  15101. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15102. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15103. taicpu(p).opcode := Opposite;
  15104. taicpu(p).oper[0]^.val := -128;
  15105. { No further optimisations can be made on this instruction, so move
  15106. onto the next one to save time }
  15107. p := tai(p.Next);
  15108. UpdateUsedRegs(p);
  15109. Result := True;
  15110. Exit;
  15111. end;
  15112. { Detect:
  15113. add/sub %reg2,(dest)
  15114. add/sub x, (dest)
  15115. (dest can be a register or a reference)
  15116. Swap the instructions to minimise a pipeline stall. This reverses the
  15117. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15118. optimisations could be made.
  15119. }
  15120. if (taicpu(p).oper[0]^.typ = top_reg) and
  15121. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15122. (
  15123. (
  15124. (taicpu(p).oper[1]^.typ = top_reg) and
  15125. { We can try searching further ahead if we're writing to a register }
  15126. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15127. ) or
  15128. (
  15129. (taicpu(p).oper[1]^.typ = top_ref) and
  15130. GetNextInstruction(p, hp1)
  15131. )
  15132. ) and
  15133. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15134. (taicpu(hp1).oper[0]^.typ = top_const) and
  15135. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15136. begin
  15137. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15138. TransferUsedRegs(TmpUsedRegs);
  15139. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15140. hp2 := p;
  15141. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15142. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15143. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15144. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15145. begin
  15146. asml.remove(hp1);
  15147. asml.InsertBefore(hp1, p);
  15148. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15149. Result := True;
  15150. end;
  15151. end;
  15152. end;
  15153. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15154. var
  15155. hp1: tai;
  15156. begin
  15157. Result:=false;
  15158. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15159. while GetNextInstruction(p, hp1) and
  15160. TrySwapMovCmp(p, hp1) do
  15161. begin
  15162. if MatchInstruction(hp1, A_MOV, []) then
  15163. begin
  15164. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15165. begin
  15166. { A little hacky, but since CMP doesn't read the flags, only
  15167. modify them, it's safe if they get scrambled by MOV -> XOR }
  15168. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15169. Result := PostPeepholeOptMov(hp1);
  15170. {$ifdef x86_64}
  15171. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15172. { Used to shrink instruction size }
  15173. PostPeepholeOptXor(hp1);
  15174. {$endif x86_64}
  15175. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15176. end
  15177. else
  15178. begin
  15179. Result := PostPeepholeOptMov(hp1);
  15180. {$ifdef x86_64}
  15181. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15182. { Used to shrink instruction size }
  15183. PostPeepholeOptXor(hp1);
  15184. {$endif x86_64}
  15185. end;
  15186. end;
  15187. { Enabling this flag is actually a null operation, but it marks
  15188. the code as 'modified' during this pass }
  15189. Include(OptsToCheck, aoc_ForceNewIteration);
  15190. end;
  15191. { change "cmp $0, %reg" to "test %reg, %reg" }
  15192. if MatchOpType(taicpu(p),top_const,top_reg) and
  15193. (taicpu(p).oper[0]^.val = 0) then
  15194. begin
  15195. taicpu(p).opcode := A_TEST;
  15196. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15197. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15198. Result:=true;
  15199. end;
  15200. end;
  15201. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15202. var
  15203. IsTestConstX, IsValid : Boolean;
  15204. hp1,hp2 : tai;
  15205. begin
  15206. Result:=false;
  15207. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15208. if (taicpu(p).opcode = A_TEST) then
  15209. while GetNextInstruction(p, hp1) and
  15210. TrySwapMovCmp(p, hp1) do
  15211. begin
  15212. if MatchInstruction(hp1, A_MOV, []) then
  15213. begin
  15214. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15215. begin
  15216. { A little hacky, but since TEST doesn't read the flags, only
  15217. modify them, it's safe if they get scrambled by MOV -> XOR }
  15218. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15219. Result := PostPeepholeOptMov(hp1);
  15220. {$ifdef x86_64}
  15221. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15222. { Used to shrink instruction size }
  15223. PostPeepholeOptXor(hp1);
  15224. {$endif x86_64}
  15225. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15226. end
  15227. else
  15228. begin
  15229. Result := PostPeepholeOptMov(hp1);
  15230. {$ifdef x86_64}
  15231. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15232. { Used to shrink instruction size }
  15233. PostPeepholeOptXor(hp1);
  15234. {$endif x86_64}
  15235. end;
  15236. end;
  15237. { Enabling this flag is actually a null operation, but it marks
  15238. the code as 'modified' during this pass }
  15239. Include(OptsToCheck, aoc_ForceNewIteration);
  15240. end;
  15241. { If x is a power of 2 (popcnt = 1), change:
  15242. or $x, %reg/ref
  15243. To:
  15244. bts lb(x), %reg/ref
  15245. }
  15246. if (taicpu(p).opcode = A_OR) and
  15247. IsBTXAcceptable(p) and
  15248. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15249. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15250. (
  15251. { Don't optimise if a test instruction follows }
  15252. not GetNextInstruction(p, hp1) or
  15253. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15254. ) then
  15255. begin
  15256. 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);
  15257. taicpu(p).opcode := A_BTS;
  15258. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15259. Result := True;
  15260. Exit;
  15261. end;
  15262. { If x is a power of 2 (popcnt = 1), change:
  15263. test $x, %reg/ref
  15264. je / sete / cmove (or jne / setne)
  15265. To:
  15266. bt lb(x), %reg/ref
  15267. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15268. }
  15269. if (taicpu(p).opcode = A_TEST) and
  15270. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15271. (taicpu(p).oper[0]^.typ = top_const) and
  15272. (
  15273. (cs_opt_size in current_settings.optimizerswitches) or
  15274. (
  15275. (taicpu(p).oper[1]^.typ = top_reg) and
  15276. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15277. ) or
  15278. (
  15279. (taicpu(p).oper[1]^.typ <> top_reg) and
  15280. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15281. )
  15282. ) and
  15283. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15284. { For sizes less than S_L, the byte size is equal or larger with BT,
  15285. so don't bother optimising }
  15286. (taicpu(p).opsize >= S_L) then
  15287. begin
  15288. IsValid := True;
  15289. { Check the next set of instructions, watching the FLAGS register
  15290. and the conditions used }
  15291. TransferUsedRegs(TmpUsedRegs);
  15292. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15293. hp1 := p;
  15294. hp2 := nil;
  15295. while GetNextInstruction(hp1, hp1) do
  15296. begin
  15297. if not Assigned(hp2) then
  15298. { The first instruction after TEST }
  15299. hp2 := hp1;
  15300. if (hp1.typ <> ait_instruction) then
  15301. begin
  15302. { If the flags are no longer in use, everything is fine }
  15303. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15304. IsValid := False;
  15305. Break;
  15306. end;
  15307. case taicpu(hp1).condition of
  15308. C_None:
  15309. begin
  15310. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15311. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15312. { Something is not quite normal, so play safe and don't change }
  15313. IsValid := False;
  15314. Break;
  15315. end;
  15316. C_E, C_Z, C_NE, C_NZ:
  15317. { This is fine };
  15318. else
  15319. begin
  15320. { Unsupported condition }
  15321. IsValid := False;
  15322. Break;
  15323. end;
  15324. end;
  15325. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15326. end;
  15327. if IsValid then
  15328. begin
  15329. while hp2 <> hp1 do
  15330. begin
  15331. case taicpu(hp2).condition of
  15332. C_Z, C_E:
  15333. taicpu(hp2).condition := C_NC;
  15334. C_NZ, C_NE:
  15335. taicpu(hp2).condition := C_C;
  15336. else
  15337. { Should not get this by this point }
  15338. InternalError(2022110701);
  15339. end;
  15340. GetNextInstruction(hp2, hp2);
  15341. end;
  15342. 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);
  15343. taicpu(p).opcode := A_BT;
  15344. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15345. Result := True;
  15346. Exit;
  15347. end;
  15348. end;
  15349. { removes the line marked with (x) from the sequence
  15350. and/or/xor/add/sub/... $x, %y
  15351. test/or %y, %y | test $-1, %y (x)
  15352. j(n)z _Label
  15353. as the first instruction already adjusts the ZF
  15354. %y operand may also be a reference }
  15355. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15356. MatchOperand(taicpu(p).oper[0]^,-1);
  15357. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15358. GetLastInstruction(p, hp1) and
  15359. (tai(hp1).typ = ait_instruction) and
  15360. GetNextInstruction(p,hp2) and
  15361. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15362. case taicpu(hp1).opcode Of
  15363. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15364. { These two instructions set the zero flag if the result is zero }
  15365. A_POPCNT, A_LZCNT:
  15366. begin
  15367. if (
  15368. { With POPCNT, an input of zero will set the zero flag
  15369. because the population count of zero is zero }
  15370. (taicpu(hp1).opcode = A_POPCNT) and
  15371. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15372. (
  15373. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15374. { Faster than going through the second half of the 'or'
  15375. condition below }
  15376. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15377. )
  15378. ) or (
  15379. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15380. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15381. { and in case of carry for A(E)/B(E)/C/NC }
  15382. (
  15383. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15384. (
  15385. (taicpu(hp1).opcode <> A_ADD) and
  15386. (taicpu(hp1).opcode <> A_SUB) and
  15387. (taicpu(hp1).opcode <> A_LZCNT)
  15388. )
  15389. )
  15390. ) then
  15391. begin
  15392. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15393. RemoveCurrentP(p, hp2);
  15394. Result:=true;
  15395. Exit;
  15396. end;
  15397. end;
  15398. A_SHL, A_SAL, A_SHR, A_SAR:
  15399. begin
  15400. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15401. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15402. { therefore, it's only safe to do this optimization for }
  15403. { shifts by a (nonzero) constant }
  15404. (taicpu(hp1).oper[0]^.typ = top_const) and
  15405. (taicpu(hp1).oper[0]^.val <> 0) and
  15406. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15407. { and in case of carry for A(E)/B(E)/C/NC }
  15408. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15409. begin
  15410. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15411. RemoveCurrentP(p, hp2);
  15412. Result:=true;
  15413. Exit;
  15414. end;
  15415. end;
  15416. A_DEC, A_INC, A_NEG:
  15417. begin
  15418. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15419. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15420. { and in case of carry for A(E)/B(E)/C/NC }
  15421. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15422. begin
  15423. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15424. RemoveCurrentP(p, hp2);
  15425. Result:=true;
  15426. Exit;
  15427. end;
  15428. end;
  15429. A_ANDN, A_BZHI:
  15430. begin
  15431. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15432. { Only the zero and sign flags are consistent with what the result is }
  15433. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15434. begin
  15435. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15436. RemoveCurrentP(p, hp2);
  15437. Result:=true;
  15438. Exit;
  15439. end;
  15440. end;
  15441. A_BEXTR:
  15442. begin
  15443. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15444. { Only the zero flag is set }
  15445. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15446. begin
  15447. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15448. RemoveCurrentP(p, hp2);
  15449. Result:=true;
  15450. Exit;
  15451. end;
  15452. end;
  15453. else
  15454. ;
  15455. end; { case }
  15456. { change "test $-1,%reg" into "test %reg,%reg" }
  15457. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15458. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15459. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15460. if MatchInstruction(p, A_OR, []) and
  15461. { Can only match if they're both registers }
  15462. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15463. begin
  15464. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15465. taicpu(p).opcode := A_TEST;
  15466. { No need to set Result to True, as we've done all the optimisations we can }
  15467. end;
  15468. end;
  15469. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15470. var
  15471. hp1,hp3 : tai;
  15472. {$ifndef x86_64}
  15473. hp2 : taicpu;
  15474. {$endif x86_64}
  15475. begin
  15476. Result:=false;
  15477. hp3:=nil;
  15478. {$ifndef x86_64}
  15479. { don't do this on modern CPUs, this really hurts them due to
  15480. broken call/ret pairing }
  15481. if (current_settings.optimizecputype < cpu_Pentium2) and
  15482. not(cs_create_pic in current_settings.moduleswitches) and
  15483. GetNextInstruction(p, hp1) and
  15484. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15485. MatchOpType(taicpu(hp1),top_ref) and
  15486. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15487. begin
  15488. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15489. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15490. InsertLLItem(p.previous, p, hp2);
  15491. taicpu(p).opcode := A_JMP;
  15492. taicpu(p).is_jmp := true;
  15493. RemoveInstruction(hp1);
  15494. Result:=true;
  15495. end
  15496. else
  15497. {$endif x86_64}
  15498. { replace
  15499. call procname
  15500. ret
  15501. by
  15502. jmp procname
  15503. but do it only on level 4 because it destroys stack back traces
  15504. else if the subroutine is marked as no return, remove the ret
  15505. }
  15506. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15507. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15508. GetNextInstruction(p, hp1) and
  15509. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15510. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15511. SetAndTest(hp1,hp3) and
  15512. GetNextInstruction(hp1,hp1) and
  15513. MatchInstruction(hp1,A_RET,[S_NO])
  15514. )
  15515. ) and
  15516. (taicpu(hp1).ops=0) then
  15517. begin
  15518. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15519. { we might destroy stack alignment here if we do not do a call }
  15520. (target_info.stackalign<=sizeof(SizeUInt)) then
  15521. begin
  15522. taicpu(p).opcode := A_JMP;
  15523. taicpu(p).is_jmp := true;
  15524. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15525. end
  15526. else
  15527. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15528. RemoveInstruction(hp1);
  15529. if Assigned(hp3) then
  15530. begin
  15531. AsmL.Remove(hp3);
  15532. AsmL.InsertBefore(hp3,p)
  15533. end;
  15534. Result:=true;
  15535. end;
  15536. end;
  15537. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15538. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15539. begin
  15540. case OpSize of
  15541. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15542. Result := (Val <= $FF) and (Val >= -128);
  15543. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15544. Result := (Val <= $FFFF) and (Val >= -32768);
  15545. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15546. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15547. else
  15548. Result := True;
  15549. end;
  15550. end;
  15551. var
  15552. hp1, hp2 : tai;
  15553. SizeChange: Boolean;
  15554. PreMessage: string;
  15555. begin
  15556. Result := False;
  15557. if (taicpu(p).oper[0]^.typ = top_reg) and
  15558. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15559. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15560. begin
  15561. { Change (using movzbl %al,%eax as an example):
  15562. movzbl %al, %eax movzbl %al, %eax
  15563. cmpl x, %eax testl %eax,%eax
  15564. To:
  15565. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15566. movzbl %al, %eax movzbl %al, %eax
  15567. Smaller instruction and minimises pipeline stall as the CPU
  15568. doesn't have to wait for the register to get zero-extended. [Kit]
  15569. Also allow if the smaller of the two registers is being checked,
  15570. as this still removes the false dependency.
  15571. }
  15572. if
  15573. (
  15574. (
  15575. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15576. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15577. ) or (
  15578. { If MatchOperand returns True, they must both be registers }
  15579. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15580. )
  15581. ) and
  15582. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15583. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15584. begin
  15585. 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);
  15586. asml.Remove(hp1);
  15587. asml.InsertBefore(hp1, p);
  15588. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15589. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15590. begin
  15591. taicpu(hp1).opcode := A_TEST;
  15592. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15593. end;
  15594. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15595. case taicpu(p).opsize of
  15596. S_BW, S_BL:
  15597. begin
  15598. SizeChange := taicpu(hp1).opsize <> S_B;
  15599. taicpu(hp1).changeopsize(S_B);
  15600. end;
  15601. S_WL:
  15602. begin
  15603. SizeChange := taicpu(hp1).opsize <> S_W;
  15604. taicpu(hp1).changeopsize(S_W);
  15605. end
  15606. else
  15607. InternalError(2020112701);
  15608. end;
  15609. UpdateUsedRegs(tai(p.Next));
  15610. { Check if the register is used aferwards - if not, we can
  15611. remove the movzx instruction completely }
  15612. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15613. begin
  15614. { Hp1 is a better position than p for debugging purposes }
  15615. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15616. RemoveCurrentp(p, hp1);
  15617. Result := True;
  15618. end;
  15619. if SizeChange then
  15620. DebugMsg(SPeepholeOptimization + PreMessage +
  15621. 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)
  15622. else
  15623. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15624. Exit;
  15625. end;
  15626. { Change (using movzwl %ax,%eax as an example):
  15627. movzwl %ax, %eax
  15628. movb %al, (dest) (Register is smaller than read register in movz)
  15629. To:
  15630. movb %al, (dest) (Move one back to avoid a false dependency)
  15631. movzwl %ax, %eax
  15632. }
  15633. if (taicpu(hp1).opcode = A_MOV) and
  15634. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15635. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15636. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15637. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15638. begin
  15639. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15640. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15641. asml.Remove(hp1);
  15642. asml.InsertBefore(hp1, p);
  15643. if taicpu(hp1).oper[1]^.typ = top_reg then
  15644. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15645. { Check if the register is used aferwards - if not, we can
  15646. remove the movzx instruction completely }
  15647. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15648. begin
  15649. { Hp1 is a better position than p for debugging purposes }
  15650. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15651. RemoveCurrentp(p, hp1);
  15652. Result := True;
  15653. end;
  15654. Exit;
  15655. end;
  15656. end;
  15657. end;
  15658. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15659. var
  15660. hp1: tai;
  15661. {$ifdef x86_64}
  15662. PreMessage, RegName: string;
  15663. {$endif x86_64}
  15664. begin
  15665. Result := False;
  15666. { If x is a power of 2 (popcnt = 1), change:
  15667. xor $x, %reg/ref
  15668. To:
  15669. btc lb(x), %reg/ref
  15670. }
  15671. if IsBTXAcceptable(p) and
  15672. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15673. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15674. (
  15675. { Don't optimise if a test instruction follows }
  15676. not GetNextInstruction(p, hp1) or
  15677. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15678. ) then
  15679. begin
  15680. 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);
  15681. taicpu(p).opcode := A_BTC;
  15682. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15683. Result := True;
  15684. Exit;
  15685. end;
  15686. {$ifdef x86_64}
  15687. { Code size reduction by J. Gareth "Kit" Moreton }
  15688. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15689. as this removes the REX prefix }
  15690. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15691. Exit;
  15692. if taicpu(p).oper[0]^.typ <> top_reg then
  15693. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15694. InternalError(2018011500);
  15695. case taicpu(p).opsize of
  15696. S_Q:
  15697. begin
  15698. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15699. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15700. { The actual optimization }
  15701. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15702. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15703. taicpu(p).changeopsize(S_L);
  15704. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15705. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15706. end;
  15707. else
  15708. ;
  15709. end;
  15710. {$endif x86_64}
  15711. end;
  15712. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15713. var
  15714. XReg: TRegister;
  15715. begin
  15716. Result := False;
  15717. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15718. Smaller encoding and slightly faster on some platforms (also works for
  15719. ZMM-sized registers) }
  15720. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15721. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15722. begin
  15723. XReg := taicpu(p).oper[0]^.reg;
  15724. if (taicpu(p).oper[1]^.reg = XReg) then
  15725. begin
  15726. taicpu(p).changeopsize(S_XMM);
  15727. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15728. if (cs_opt_size in current_settings.optimizerswitches) then
  15729. begin
  15730. { Change input registers to %xmm0 to reduce size. Note that
  15731. there's a risk of a false dependency doing this, so only
  15732. optimise for size here }
  15733. XReg := NR_XMM0;
  15734. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15735. end
  15736. else
  15737. begin
  15738. setsubreg(XReg, R_SUBMMX);
  15739. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15740. end;
  15741. taicpu(p).oper[0]^.reg := XReg;
  15742. taicpu(p).oper[1]^.reg := XReg;
  15743. Result := True;
  15744. end;
  15745. end;
  15746. end;
  15747. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15748. var
  15749. OperIdx: Integer;
  15750. begin
  15751. for OperIdx := 0 to p.ops - 1 do
  15752. if p.oper[OperIdx]^.typ = top_ref then
  15753. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15754. end;
  15755. end.