aoptx86.pas 686 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2037. begin
  2038. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2039. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2040. begin
  2041. { vmova* reg1,reg2
  2042. vmova* reg2,reg3
  2043. dealloc reg2
  2044. =>
  2045. vmova* reg1,reg3 }
  2046. TransferUsedRegs(TmpUsedRegs);
  2047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2048. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2049. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2050. begin
  2051. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2052. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2053. RemoveInstruction(hp1);
  2054. result:=true;
  2055. exit;
  2056. end;
  2057. { special case:
  2058. vmova* reg1,<op>
  2059. vmova* <op>,reg1
  2060. =>
  2061. vmova* reg1,<op> }
  2062. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2063. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2064. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2065. ) then
  2066. begin
  2067. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2068. RemoveInstruction(hp1);
  2069. result:=true;
  2070. exit;
  2071. end
  2072. end
  2073. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2074. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2075. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2076. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2077. ) and
  2078. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2079. begin
  2080. { vmova* reg1,reg2
  2081. vmovs* reg2,<op>
  2082. dealloc reg2
  2083. =>
  2084. vmovs* reg1,reg3 }
  2085. TransferUsedRegs(TmpUsedRegs);
  2086. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2087. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2088. begin
  2089. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2090. taicpu(p).opcode:=taicpu(hp1).opcode;
  2091. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2092. RemoveInstruction(hp1);
  2093. result:=true;
  2094. exit;
  2095. end
  2096. end;
  2097. end;
  2098. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2099. begin
  2100. if MatchInstruction(hp1,[A_VFMADDPD,
  2101. A_VFMADD132PD,
  2102. A_VFMADD132PS,
  2103. A_VFMADD132SD,
  2104. A_VFMADD132SS,
  2105. A_VFMADD213PD,
  2106. A_VFMADD213PS,
  2107. A_VFMADD213SD,
  2108. A_VFMADD213SS,
  2109. A_VFMADD231PD,
  2110. A_VFMADD231PS,
  2111. A_VFMADD231SD,
  2112. A_VFMADD231SS,
  2113. A_VFMADDSUB132PD,
  2114. A_VFMADDSUB132PS,
  2115. A_VFMADDSUB213PD,
  2116. A_VFMADDSUB213PS,
  2117. A_VFMADDSUB231PD,
  2118. A_VFMADDSUB231PS,
  2119. A_VFMSUB132PD,
  2120. A_VFMSUB132PS,
  2121. A_VFMSUB132SD,
  2122. A_VFMSUB132SS,
  2123. A_VFMSUB213PD,
  2124. A_VFMSUB213PS,
  2125. A_VFMSUB213SD,
  2126. A_VFMSUB213SS,
  2127. A_VFMSUB231PD,
  2128. A_VFMSUB231PS,
  2129. A_VFMSUB231SD,
  2130. A_VFMSUB231SS,
  2131. A_VFMSUBADD132PD,
  2132. A_VFMSUBADD132PS,
  2133. A_VFMSUBADD213PD,
  2134. A_VFMSUBADD213PS,
  2135. A_VFMSUBADD231PD,
  2136. A_VFMSUBADD231PS,
  2137. A_VFNMADD132PD,
  2138. A_VFNMADD132PS,
  2139. A_VFNMADD132SD,
  2140. A_VFNMADD132SS,
  2141. A_VFNMADD213PD,
  2142. A_VFNMADD213PS,
  2143. A_VFNMADD213SD,
  2144. A_VFNMADD213SS,
  2145. A_VFNMADD231PD,
  2146. A_VFNMADD231PS,
  2147. A_VFNMADD231SD,
  2148. A_VFNMADD231SS,
  2149. A_VFNMSUB132PD,
  2150. A_VFNMSUB132PS,
  2151. A_VFNMSUB132SD,
  2152. A_VFNMSUB132SS,
  2153. A_VFNMSUB213PD,
  2154. A_VFNMSUB213PS,
  2155. A_VFNMSUB213SD,
  2156. A_VFNMSUB213SS,
  2157. A_VFNMSUB231PD,
  2158. A_VFNMSUB231PS,
  2159. A_VFNMSUB231SD,
  2160. A_VFNMSUB231SS],[S_NO]) and
  2161. { we mix single and double opperations here because we assume that the compiler
  2162. generates vmovapd only after double operations and vmovaps only after single operations }
  2163. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2164. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2165. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2173. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2174. RemoveCurrentP(p)
  2175. else
  2176. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2177. RemoveInstruction(hp2);
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_MOVAPS) and
  2182. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2183. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2184. ((taicpu(p).opcode=A_MOVAPD) and
  2185. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2186. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2187. ) and
  2188. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2189. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2191. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2192. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2193. { change
  2194. movapX reg,reg2
  2195. addsX/subsX/... reg3, reg2
  2196. movapX reg2,reg
  2197. to
  2198. addsX/subsX/... reg3,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+' '+
  2208. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2209. { we cannot eliminate the first move if
  2210. the operations uses the same register for source and dest }
  2211. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2212. { Remember that hp1 is not necessarily the immediate
  2213. next instruction }
  2214. RemoveCurrentP(p);
  2215. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2216. RemoveInstruction(hp2);
  2217. result:=true;
  2218. end;
  2219. end
  2220. else if (hp1.typ = ait_instruction) and
  2221. (((taicpu(p).opcode=A_VMOVAPD) and
  2222. (taicpu(hp1).opcode=A_VCOMISD)) or
  2223. ((taicpu(p).opcode=A_VMOVAPS) and
  2224. ((taicpu(hp1).opcode=A_VCOMISS))
  2225. )
  2226. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { change
  2228. movapX reg,reg1
  2229. vcomisX reg1,reg1
  2230. to
  2231. vcomisX reg,reg
  2232. }
  2233. begin
  2234. TransferUsedRegs(TmpUsedRegs);
  2235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2236. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2237. begin
  2238. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2239. debug_op2str(taicpu(p).opcode)+' '+
  2240. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2241. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2242. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2243. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2245. RemoveCurrentP(p);
  2246. result:=true;
  2247. exit;
  2248. end;
  2249. end
  2250. end;
  2251. end;
  2252. end;
  2253. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2254. var
  2255. hp1 : tai;
  2256. begin
  2257. result:=false;
  2258. { replace
  2259. V<Op>X %mreg1,%mreg2,%mreg3
  2260. VMovX %mreg3,%mreg4
  2261. dealloc %mreg3
  2262. by
  2263. V<Op>X %mreg1,%mreg2,%mreg4
  2264. ?
  2265. }
  2266. if GetNextInstruction(p,hp1) and
  2267. { we mix single and double operations here because we assume that the compiler
  2268. generates vmovapd only after double operations and vmovaps only after single operations }
  2269. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2270. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2271. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2275. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2276. begin
  2277. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2278. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2279. RemoveInstruction(hp1);
  2280. result:=true;
  2281. end;
  2282. end;
  2283. end;
  2284. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2285. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2286. begin
  2287. Result := False;
  2288. { For safety reasons, only check for exact register matches }
  2289. { Check base register }
  2290. if (ref.base = AOldReg) then
  2291. begin
  2292. ref.base := ANewReg;
  2293. Result := True;
  2294. end;
  2295. { Check index register }
  2296. if (ref.index = AOldReg) then
  2297. begin
  2298. ref.index := ANewReg;
  2299. Result := True;
  2300. end;
  2301. end;
  2302. { Replaces all references to AOldReg in an operand to ANewReg }
  2303. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2304. var
  2305. OldSupReg, NewSupReg: TSuperRegister;
  2306. OldSubReg, NewSubReg: TSubRegister;
  2307. OldRegType: TRegisterType;
  2308. ThisOper: POper;
  2309. begin
  2310. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2311. Result := False;
  2312. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2313. InternalError(2020011801);
  2314. OldSupReg := getsupreg(AOldReg);
  2315. OldSubReg := getsubreg(AOldReg);
  2316. OldRegType := getregtype(AOldReg);
  2317. NewSupReg := getsupreg(ANewReg);
  2318. NewSubReg := getsubreg(ANewReg);
  2319. if OldRegType <> getregtype(ANewReg) then
  2320. InternalError(2020011802);
  2321. if OldSubReg <> NewSubReg then
  2322. InternalError(2020011803);
  2323. case ThisOper^.typ of
  2324. top_reg:
  2325. if (
  2326. (ThisOper^.reg = AOldReg) or
  2327. (
  2328. (OldRegType = R_INTREGISTER) and
  2329. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2330. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2331. (
  2332. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2333. {$ifndef x86_64}
  2334. and (
  2335. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2336. don't have an 8-bit representation }
  2337. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2338. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2339. )
  2340. {$endif x86_64}
  2341. )
  2342. )
  2343. ) then
  2344. begin
  2345. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2346. Result := True;
  2347. end;
  2348. top_ref:
  2349. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2350. Result := True;
  2351. else
  2352. ;
  2353. end;
  2354. end;
  2355. { Replaces all references to AOldReg in an instruction to ANewReg }
  2356. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2357. const
  2358. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2359. var
  2360. OperIdx: Integer;
  2361. begin
  2362. Result := False;
  2363. for OperIdx := 0 to p.ops - 1 do
  2364. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2365. begin
  2366. { The shift and rotate instructions can only use CL }
  2367. if not (
  2368. (OperIdx = 0) and
  2369. { This second condition just helps to avoid unnecessarily
  2370. calling MatchInstruction for 10 different opcodes }
  2371. (p.oper[0]^.reg = NR_CL) and
  2372. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2373. ) then
  2374. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2375. end
  2376. else if p.oper[OperIdx]^.typ = top_ref then
  2377. { It's okay to replace registers in references that get written to }
  2378. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2379. end;
  2380. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2381. begin
  2382. Result :=
  2383. (ref^.index = NR_NO) and
  2384. (
  2385. {$ifdef x86_64}
  2386. (
  2387. (ref^.base = NR_RIP) and
  2388. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2389. ) or
  2390. {$endif x86_64}
  2391. (ref^.refaddr = addr_full) or
  2392. (ref^.base = NR_STACK_POINTER_REG) or
  2393. (ref^.base = current_procinfo.framepointer)
  2394. );
  2395. end;
  2396. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2397. var
  2398. l: asizeint;
  2399. begin
  2400. Result := False;
  2401. { Should have been checked previously }
  2402. if p.opcode <> A_LEA then
  2403. InternalError(2020072501);
  2404. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2405. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2406. not(cs_opt_size in current_settings.optimizerswitches) then
  2407. exit;
  2408. with p.oper[0]^.ref^ do
  2409. begin
  2410. if (base <> p.oper[1]^.reg) or
  2411. (index <> NR_NO) or
  2412. assigned(symbol) then
  2413. exit;
  2414. l:=offset;
  2415. if (l=1) and UseIncDec then
  2416. begin
  2417. p.opcode:=A_INC;
  2418. p.loadreg(0,p.oper[1]^.reg);
  2419. p.ops:=1;
  2420. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2421. end
  2422. else if (l=-1) and UseIncDec then
  2423. begin
  2424. p.opcode:=A_DEC;
  2425. p.loadreg(0,p.oper[1]^.reg);
  2426. p.ops:=1;
  2427. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2428. end
  2429. else
  2430. begin
  2431. if (l<0) and (l<>-2147483648) then
  2432. begin
  2433. p.opcode:=A_SUB;
  2434. p.loadConst(0,-l);
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2436. end
  2437. else
  2438. begin
  2439. p.opcode:=A_ADD;
  2440. p.loadConst(0,l);
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2442. end;
  2443. end;
  2444. end;
  2445. Result := True;
  2446. end;
  2447. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2448. var
  2449. CurrentReg, ReplaceReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2453. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2454. case hp.opcode of
  2455. A_FSTSW, A_FNSTSW,
  2456. A_IN, A_INS, A_OUT, A_OUTS,
  2457. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2458. { These routines have explicit operands, but they are restricted in
  2459. what they can be (e.g. IN and OUT can only read from AL, AX or
  2460. EAX. }
  2461. Exit;
  2462. A_IMUL:
  2463. begin
  2464. { The 1-operand version writes to implicit registers
  2465. The 2-operand version reads from the first operator, and reads
  2466. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2467. the 3-operand version reads from a register that it doesn't write to
  2468. }
  2469. case hp.ops of
  2470. 1:
  2471. if (
  2472. (
  2473. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2474. ) or
  2475. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2476. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2477. begin
  2478. Result := True;
  2479. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2480. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2481. end;
  2482. 2:
  2483. { Only modify the first parameter }
  2484. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2485. begin
  2486. Result := True;
  2487. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2488. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2489. end;
  2490. 3:
  2491. { Only modify the second parameter }
  2492. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2493. begin
  2494. Result := True;
  2495. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2496. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2497. end;
  2498. else
  2499. InternalError(2020012901);
  2500. end;
  2501. end;
  2502. else
  2503. if (hp.ops > 0) and
  2504. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. end;
  2511. end;
  2512. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2513. var
  2514. hp2: tai;
  2515. p_SourceReg, p_TargetReg: TRegister;
  2516. begin
  2517. Result := False;
  2518. { Backward optimisation. If we have:
  2519. func. %reg1,%reg2
  2520. mov %reg2,%reg3
  2521. (dealloc %reg2)
  2522. Change to:
  2523. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2524. Perform similar optimisations with 1, 3 and 4-operand instructions
  2525. that only have one output.
  2526. }
  2527. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2528. begin
  2529. p_SourceReg := taicpu(p).oper[0]^.reg;
  2530. p_TargetReg := taicpu(p).oper[1]^.reg;
  2531. TransferUsedRegs(TmpUsedRegs);
  2532. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2533. GetLastInstruction(p, hp2) and
  2534. (hp2.typ = ait_instruction) and
  2535. { Have to make sure it's an instruction that only reads from
  2536. the first operands and only writes (not reads or modifies) to
  2537. the last one; in essence, a pure function such as BSR, POPCNT
  2538. or ANDN }
  2539. (
  2540. (
  2541. (taicpu(hp2).ops = 1) and
  2542. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2543. ) or
  2544. (
  2545. (taicpu(hp2).ops = 2) and
  2546. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2547. ) or
  2548. (
  2549. (taicpu(hp2).ops = 3) and
  2550. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2551. ) or
  2552. (
  2553. (taicpu(hp2).ops = 4) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2555. )
  2556. ) and
  2557. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2558. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2559. begin
  2560. case taicpu(hp2).opcode of
  2561. A_FSTSW, A_FNSTSW,
  2562. A_IN, A_INS, A_OUT, A_OUTS,
  2563. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2564. { These routines have explicit operands, but they are restricted in
  2565. what they can be (e.g. IN and OUT can only read from AL, AX or
  2566. EAX. }
  2567. ;
  2568. else
  2569. begin
  2570. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2571. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2572. if not RegInInstruction(p_TargetReg, hp2) then
  2573. begin
  2574. { Since we're allocating from an earlier point, we
  2575. need to remove the register from the tracking }
  2576. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2577. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2578. end;
  2579. RemoveCurrentp(p, hp1);
  2580. { If the Func was another MOV instruction, we might get
  2581. "mov %reg,%reg" that doesn't get removed in Pass 2
  2582. otherwise, so deal with it here (also do something
  2583. similar with lea (%reg),%reg}
  2584. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2585. begin
  2586. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2587. if p = hp2 then
  2588. RemoveCurrentp(p)
  2589. else
  2590. RemoveInstruction(hp2);
  2591. end;
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. end;
  2596. end;
  2597. end;
  2598. end;
  2599. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2600. var
  2601. hp1, hp2, hp3: tai;
  2602. DoOptimisation, TempBool: Boolean;
  2603. {$ifdef x86_64}
  2604. NewConst: TCGInt;
  2605. {$endif x86_64}
  2606. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2607. begin
  2608. if taicpu(hp1).opcode = signed_movop then
  2609. begin
  2610. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2611. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2612. end
  2613. else
  2614. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2615. end;
  2616. function TryConstMerge(var p1, p2: tai): Boolean;
  2617. var
  2618. ThisRef: TReference;
  2619. begin
  2620. Result := False;
  2621. ThisRef := taicpu(p2).oper[1]^.ref^;
  2622. { Only permit writes to the stack, since we can guarantee alignment with that }
  2623. if (ThisRef.index = NR_NO) and
  2624. (
  2625. (ThisRef.base = NR_STACK_POINTER_REG) or
  2626. (ThisRef.base = current_procinfo.framepointer)
  2627. ) then
  2628. begin
  2629. case taicpu(p).opsize of
  2630. S_B:
  2631. begin
  2632. { Word writes must be on a 2-byte boundary }
  2633. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2634. begin
  2635. { Reduce offset of second reference to see if it is sequential with the first }
  2636. Dec(ThisRef.offset, 1);
  2637. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2638. begin
  2639. { Make sure the constants aren't represented as a
  2640. negative number, as these won't merge properly }
  2641. taicpu(p1).opsize := S_W;
  2642. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2643. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2644. RemoveInstruction(p2);
  2645. Result := True;
  2646. end;
  2647. end;
  2648. end;
  2649. S_W:
  2650. begin
  2651. { Longword writes must be on a 4-byte boundary }
  2652. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2653. begin
  2654. { Reduce offset of second reference to see if it is sequential with the first }
  2655. Dec(ThisRef.offset, 2);
  2656. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2657. begin
  2658. { Make sure the constants aren't represented as a
  2659. negative number, as these won't merge properly }
  2660. taicpu(p1).opsize := S_L;
  2661. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2662. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2663. RemoveInstruction(p2);
  2664. Result := True;
  2665. end;
  2666. end;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_L:
  2670. begin
  2671. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2672. see if the constants can be encoded this way. }
  2673. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2674. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2675. { Quadword writes must be on an 8-byte boundary }
  2676. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2677. begin
  2678. { Reduce offset of second reference to see if it is sequential with the first }
  2679. Dec(ThisRef.offset, 4);
  2680. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2681. begin
  2682. { Make sure the constants aren't represented as a
  2683. negative number, as these won't merge properly }
  2684. taicpu(p1).opsize := S_Q;
  2685. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2686. taicpu(p1).oper[0]^.val := NewConst;
  2687. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2688. RemoveInstruction(p2);
  2689. Result := True;
  2690. end;
  2691. end;
  2692. end;
  2693. {$endif x86_64}
  2694. else
  2695. ;
  2696. end;
  2697. end;
  2698. end;
  2699. var
  2700. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2701. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2702. NewSize: topsize; NewOffset: asizeint;
  2703. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2704. SourceRef, TargetRef: TReference;
  2705. MovAligned, MovUnaligned: TAsmOp;
  2706. ThisRef: TReference;
  2707. JumpTracking: TLinkedList;
  2708. begin
  2709. Result:=false;
  2710. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2711. { remove mov reg1,reg1? }
  2712. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2713. then
  2714. begin
  2715. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2716. { take care of the register (de)allocs following p }
  2717. RemoveCurrentP(p, hp1);
  2718. Result:=true;
  2719. exit;
  2720. end;
  2721. { All the next optimisations require a next instruction }
  2722. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2723. Exit;
  2724. { Prevent compiler warnings }
  2725. p_TargetReg := NR_NO;
  2726. if taicpu(p).oper[1]^.typ = top_reg then
  2727. begin
  2728. { Saves on a large number of dereferences }
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. { Look for:
  2731. mov %reg1,%reg2
  2732. ??? %reg2,r/m
  2733. Change to:
  2734. mov %reg1,%reg2
  2735. ??? %reg1,r/m
  2736. }
  2737. if taicpu(p).oper[0]^.typ = top_reg then
  2738. begin
  2739. if RegReadByInstruction(p_TargetReg, hp1) and
  2740. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2741. begin
  2742. { A change has occurred, just not in p }
  2743. Result := True;
  2744. TransferUsedRegs(TmpUsedRegs);
  2745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2746. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2747. { Just in case something didn't get modified (e.g. an
  2748. implicit register) }
  2749. not RegReadByInstruction(p_TargetReg, hp1) then
  2750. begin
  2751. { We can remove the original MOV }
  2752. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2753. RemoveCurrentp(p, hp1);
  2754. { UsedRegs got updated by RemoveCurrentp }
  2755. Result := True;
  2756. Exit;
  2757. end;
  2758. { If we know a MOV instruction has become a null operation, we might as well
  2759. get rid of it now to save time. }
  2760. if (taicpu(hp1).opcode = A_MOV) and
  2761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2763. { Just being a register is enough to confirm it's a null operation }
  2764. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2765. begin
  2766. Result := True;
  2767. { Speed-up to reduce a pipeline stall... if we had something like...
  2768. movl %eax,%edx
  2769. movw %dx,%ax
  2770. ... the second instruction would change to movw %ax,%ax, but
  2771. given that it is now %ax that's active rather than %eax,
  2772. penalties might occur due to a partial register write, so instead,
  2773. change it to a MOVZX instruction when optimising for speed.
  2774. }
  2775. if not (cs_opt_size in current_settings.optimizerswitches) and
  2776. IsMOVZXAcceptable and
  2777. (taicpu(hp1).opsize < taicpu(p).opsize)
  2778. {$ifdef x86_64}
  2779. { operations already implicitly set the upper 64 bits to zero }
  2780. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2781. {$endif x86_64}
  2782. then
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2785. case taicpu(p).opsize of
  2786. S_W:
  2787. if taicpu(hp1).opsize = S_B then
  2788. taicpu(hp1).opsize := S_BL
  2789. else
  2790. InternalError(2020012911);
  2791. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2792. case taicpu(hp1).opsize of
  2793. S_B:
  2794. taicpu(hp1).opsize := S_BL;
  2795. S_W:
  2796. taicpu(hp1).opsize := S_WL;
  2797. else
  2798. InternalError(2020012912);
  2799. end;
  2800. else
  2801. InternalError(2020012910);
  2802. end;
  2803. taicpu(hp1).opcode := A_MOVZX;
  2804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2805. end
  2806. else
  2807. begin
  2808. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2809. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2810. RemoveInstruction(hp1);
  2811. { The instruction after what was hp1 is now the immediate next instruction,
  2812. so we can continue to make optimisations if it's present }
  2813. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2814. Exit;
  2815. hp1 := hp2;
  2816. end;
  2817. end;
  2818. end;
  2819. end;
  2820. end;
  2821. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2822. overwrites the original destination register. e.g.
  2823. movl ###,%reg2d
  2824. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2825. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2826. }
  2827. if (taicpu(p).oper[1]^.typ = top_reg) and
  2828. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2830. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2831. begin
  2832. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2833. begin
  2834. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2835. case taicpu(p).oper[0]^.typ of
  2836. top_const:
  2837. { We have something like:
  2838. movb $x, %regb
  2839. movzbl %regb,%regd
  2840. Change to:
  2841. movl $x, %regd
  2842. }
  2843. begin
  2844. case taicpu(hp1).opsize of
  2845. S_BW:
  2846. begin
  2847. convert_mov_value(A_MOVSX, $FF);
  2848. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2849. taicpu(p).opsize := S_W;
  2850. end;
  2851. S_BL:
  2852. begin
  2853. convert_mov_value(A_MOVSX, $FF);
  2854. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2855. taicpu(p).opsize := S_L;
  2856. end;
  2857. S_WL:
  2858. begin
  2859. convert_mov_value(A_MOVSX, $FFFF);
  2860. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2861. taicpu(p).opsize := S_L;
  2862. end;
  2863. {$ifdef x86_64}
  2864. S_BQ:
  2865. begin
  2866. convert_mov_value(A_MOVSX, $FF);
  2867. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2868. taicpu(p).opsize := S_Q;
  2869. end;
  2870. S_WQ:
  2871. begin
  2872. convert_mov_value(A_MOVSX, $FFFF);
  2873. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2874. taicpu(p).opsize := S_Q;
  2875. end;
  2876. S_LQ:
  2877. begin
  2878. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2880. taicpu(p).opsize := S_Q;
  2881. end;
  2882. {$endif x86_64}
  2883. else
  2884. { If hp1 was a MOV instruction, it should have been
  2885. optimised already }
  2886. InternalError(2020021001);
  2887. end;
  2888. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2889. RemoveInstruction(hp1);
  2890. Result := True;
  2891. Exit;
  2892. end;
  2893. top_ref:
  2894. begin
  2895. { We have something like:
  2896. movb mem, %regb
  2897. movzbl %regb,%regd
  2898. Change to:
  2899. movzbl mem, %regd
  2900. }
  2901. ThisRef := taicpu(p).oper[0]^.ref^;
  2902. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2903. begin
  2904. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2905. taicpu(hp1).loadref(0, ThisRef);
  2906. { Make sure any registers in the references are properly tracked }
  2907. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2908. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2909. if (ThisRef.index <> NR_NO) then
  2910. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2911. RemoveCurrentP(p, hp1);
  2912. Result := True;
  2913. Exit;
  2914. end;
  2915. end;
  2916. else
  2917. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2918. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2919. Exit;
  2920. end;
  2921. end
  2922. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2923. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2924. optimised }
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2928. RemoveCurrentP(p, hp1);
  2929. Result := True;
  2930. Exit;
  2931. end;
  2932. end;
  2933. if (taicpu(hp1).opcode = A_AND) and
  2934. (taicpu(p).oper[1]^.typ = top_reg) and
  2935. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2936. begin
  2937. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2938. begin
  2939. case taicpu(p).opsize of
  2940. S_L:
  2941. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2942. begin
  2943. { Optimize out:
  2944. mov x, %reg
  2945. and ffffffffh, %reg
  2946. }
  2947. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2948. RemoveInstruction(hp1);
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. S_Q: { TODO: Confirm if this is even possible }
  2953. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2954. begin
  2955. { Optimize out:
  2956. mov x, %reg
  2957. and ffffffffffffffffh, %reg
  2958. }
  2959. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2960. RemoveInstruction(hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. else
  2965. ;
  2966. end;
  2967. if (
  2968. (taicpu(p).oper[0]^.typ=top_reg) or
  2969. (
  2970. (taicpu(p).oper[0]^.typ=top_ref) and
  2971. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2972. )
  2973. ) and
  2974. GetNextInstruction(hp1,hp2) and
  2975. MatchInstruction(hp2,A_TEST,[]) and
  2976. (
  2977. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2978. (
  2979. { If the register being tested is smaller than the one
  2980. that received a bitwise AND, permit it if the constant
  2981. fits into the smaller size }
  2982. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2983. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2984. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2985. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2986. (
  2987. (
  2988. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2989. (taicpu(hp1).oper[0]^.val <= $FF)
  2990. ) or
  2991. (
  2992. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2993. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2994. {$ifdef x86_64}
  2995. ) or
  2996. (
  2997. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2998. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2999. {$endif x86_64}
  3000. )
  3001. )
  3002. )
  3003. ) and
  3004. (
  3005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3006. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3007. ) and
  3008. GetNextInstruction(hp2,hp3) and
  3009. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3010. (taicpu(hp3).condition in [C_E,C_NE]) then
  3011. begin
  3012. TransferUsedRegs(TmpUsedRegs);
  3013. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3015. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3016. begin
  3017. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3018. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3019. taicpu(hp1).opcode:=A_TEST;
  3020. { Shrink the TEST instruction down to the smallest possible size }
  3021. case taicpu(hp1).oper[0]^.val of
  3022. 0..255:
  3023. if (taicpu(hp1).opsize <> S_B)
  3024. {$ifndef x86_64}
  3025. and (
  3026. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3027. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3028. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3029. )
  3030. {$endif x86_64}
  3031. then
  3032. begin
  3033. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3034. { Only print debug message if the TEST instruction
  3035. is a different size before and after }
  3036. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3037. taicpu(hp1).opsize := S_B;
  3038. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3040. end;
  3041. 256..65535:
  3042. if (taicpu(hp1).opsize <> S_W) then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3048. taicpu(hp1).opsize := S_W;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3051. end;
  3052. {$ifdef x86_64}
  3053. 65536..$7FFFFFFF:
  3054. if (taicpu(hp1).opsize <> S_L) then
  3055. begin
  3056. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3057. { Only print debug message if the TEST instruction
  3058. is a different size before and after }
  3059. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3060. taicpu(hp1).opsize := S_L;
  3061. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3063. end;
  3064. {$endif x86_64}
  3065. else
  3066. ;
  3067. end;
  3068. RemoveInstruction(hp2);
  3069. RemoveCurrentP(p, hp1);
  3070. Result:=true;
  3071. exit;
  3072. end;
  3073. end;
  3074. end
  3075. else if IsMOVZXAcceptable and
  3076. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3077. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3078. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3079. then
  3080. begin
  3081. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3082. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3083. case taicpu(p).opsize of
  3084. S_B:
  3085. if (taicpu(hp1).oper[0]^.val = $ff) then
  3086. begin
  3087. { Convert:
  3088. movb x, %regl movb x, %regl
  3089. andw ffh, %regw andl ffh, %regd
  3090. To:
  3091. movzbw x, %regd movzbl x, %regd
  3092. (Identical registers, just different sizes)
  3093. }
  3094. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3095. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3096. case taicpu(hp1).opsize of
  3097. S_W: NewSize := S_BW;
  3098. S_L: NewSize := S_BL;
  3099. {$ifdef x86_64}
  3100. S_Q: NewSize := S_BQ;
  3101. {$endif x86_64}
  3102. else
  3103. InternalError(2018011510);
  3104. end;
  3105. end
  3106. else
  3107. NewSize := S_NO;
  3108. S_W:
  3109. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3110. begin
  3111. { Convert:
  3112. movw x, %regw
  3113. andl ffffh, %regd
  3114. To:
  3115. movzwl x, %regd
  3116. (Identical registers, just different sizes)
  3117. }
  3118. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3119. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3120. case taicpu(hp1).opsize of
  3121. S_L: NewSize := S_WL;
  3122. {$ifdef x86_64}
  3123. S_Q: NewSize := S_WQ;
  3124. {$endif x86_64}
  3125. else
  3126. InternalError(2018011511);
  3127. end;
  3128. end
  3129. else
  3130. NewSize := S_NO;
  3131. else
  3132. NewSize := S_NO;
  3133. end;
  3134. if NewSize <> S_NO then
  3135. begin
  3136. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3137. { The actual optimization }
  3138. taicpu(p).opcode := A_MOVZX;
  3139. taicpu(p).changeopsize(NewSize);
  3140. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3141. { Safeguard if "and" is followed by a conditional command }
  3142. TransferUsedRegs(TmpUsedRegs);
  3143. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3144. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3145. begin
  3146. { At this point, the "and" command is effectively equivalent to
  3147. "test %reg,%reg". This will be handled separately by the
  3148. Peephole Optimizer. [Kit] }
  3149. DebugMsg(SPeepholeOptimization + PreMessage +
  3150. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3151. end
  3152. else
  3153. begin
  3154. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3155. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3156. RemoveInstruction(hp1);
  3157. end;
  3158. Result := True;
  3159. Exit;
  3160. end;
  3161. end;
  3162. end;
  3163. if (taicpu(hp1).opcode = A_OR) and
  3164. (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[0]^, 0) and
  3166. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3167. begin
  3168. { mov 0, %reg
  3169. or ###,%reg
  3170. Change to (only if the flags are not used):
  3171. mov ###,%reg
  3172. }
  3173. TransferUsedRegs(TmpUsedRegs);
  3174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3175. DoOptimisation := True;
  3176. { Even if the flags are used, we might be able to do the optimisation
  3177. if the conditions are predictable }
  3178. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3179. begin
  3180. { Only perform if ### = %reg (the same register) or equal to 0,
  3181. so %reg is guaranteed to still have a value of zero }
  3182. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3183. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3184. begin
  3185. hp2 := hp1;
  3186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3187. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3188. GetNextInstruction(hp2, hp3) do
  3189. begin
  3190. { Don't continue modifying if the flags state is getting changed }
  3191. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3192. Break;
  3193. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3194. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3195. begin
  3196. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3197. begin
  3198. { Condition is always true }
  3199. case taicpu(hp3).opcode of
  3200. A_Jcc:
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3203. { Check for jump shortcuts before we destroy the condition }
  3204. DoJumpOptimizations(hp3, TempBool);
  3205. MakeUnconditional(taicpu(hp3));
  3206. Result := True;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3211. taicpu(hp3).opcode := A_MOV;
  3212. taicpu(hp3).condition := C_None;
  3213. Result := True;
  3214. end;
  3215. A_SETcc:
  3216. begin
  3217. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3218. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3219. taicpu(hp3).opcode := A_MOV;
  3220. taicpu(hp3).ops := 2;
  3221. taicpu(hp3).condition := C_None;
  3222. taicpu(hp3).opsize := S_B;
  3223. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3224. taicpu(hp3).loadconst(0, 1);
  3225. Result := True;
  3226. end;
  3227. else
  3228. InternalError(2021090701);
  3229. end;
  3230. end
  3231. 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
  3232. begin
  3233. { Condition is always false }
  3234. case taicpu(hp3).opcode of
  3235. A_Jcc:
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3238. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3239. RemoveInstruction(hp3);
  3240. Result := True;
  3241. { Since hp3 was deleted, hp2 must not be updated }
  3242. Continue;
  3243. end;
  3244. A_CMOVcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3247. RemoveInstruction(hp3);
  3248. Result := True;
  3249. { Since hp3 was deleted, hp2 must not be updated }
  3250. Continue;
  3251. end;
  3252. A_SETcc:
  3253. begin
  3254. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3256. taicpu(hp3).opcode := A_MOV;
  3257. taicpu(hp3).ops := 2;
  3258. taicpu(hp3).condition := C_None;
  3259. taicpu(hp3).opsize := S_B;
  3260. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3261. taicpu(hp3).loadconst(0, 0);
  3262. Result := True;
  3263. end;
  3264. else
  3265. InternalError(2021090702);
  3266. end;
  3267. end
  3268. else
  3269. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3270. DoOptimisation := False;
  3271. end;
  3272. hp2 := hp3;
  3273. end;
  3274. { Flags are still in use - don't optimise }
  3275. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3276. DoOptimisation := False;
  3277. end
  3278. else
  3279. DoOptimisation := False;
  3280. end;
  3281. if DoOptimisation then
  3282. begin
  3283. {$ifdef x86_64}
  3284. { OR only supports 32-bit sign-extended constants for 64-bit
  3285. instructions, so compensate for this if the constant is
  3286. encoded as a value greater than or equal to 2^31 }
  3287. if (taicpu(hp1).opsize = S_Q) and
  3288. (taicpu(hp1).oper[0]^.typ = top_const) and
  3289. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3290. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3291. {$endif x86_64}
  3292. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3293. taicpu(hp1).opcode := A_MOV;
  3294. RemoveCurrentP(p, hp1);
  3295. Result := True;
  3296. Exit;
  3297. end;
  3298. end;
  3299. { Next instruction is also a MOV ? }
  3300. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3301. begin
  3302. if MatchOpType(taicpu(p), top_const, top_ref) and
  3303. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3304. TryConstMerge(p, hp1) then
  3305. begin
  3306. Result := True;
  3307. { In case we have four byte writes in a row, check for 2 more
  3308. right now so we don't have to wait for another iteration of
  3309. pass 1
  3310. }
  3311. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3312. case taicpu(p).opsize of
  3313. S_W:
  3314. begin
  3315. if GetNextInstruction(p, hp1) and
  3316. MatchInstruction(hp1, A_MOV, [S_B]) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2, A_MOV, [S_B]) and
  3320. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3321. { Try to merge the two bytes }
  3322. TryConstMerge(hp1, hp2) then
  3323. { Now try to merge the two words (hp2 will get deleted) }
  3324. TryConstMerge(p, hp1);
  3325. end;
  3326. S_L:
  3327. begin
  3328. { Though this only really benefits x86_64 and not i386, it
  3329. gets a potential optimisation done faster and hence
  3330. reduces the number of times OptPass1MOV is entered }
  3331. if GetNextInstruction(p, hp1) and
  3332. MatchInstruction(hp1, A_MOV, [S_W]) and
  3333. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3334. GetNextInstruction(hp1, hp2) and
  3335. MatchInstruction(hp2, A_MOV, [S_W]) and
  3336. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3337. { Try to merge the two words }
  3338. TryConstMerge(hp1, hp2) then
  3339. { This will always fail on i386, so don't bother
  3340. calling it unless we're doing x86_64 }
  3341. {$ifdef x86_64}
  3342. { Now try to merge the two longwords (hp2 will get deleted) }
  3343. TryConstMerge(p, hp1)
  3344. {$endif x86_64}
  3345. ;
  3346. end;
  3347. else
  3348. ;
  3349. end;
  3350. Exit;
  3351. end;
  3352. if (taicpu(p).oper[1]^.typ = top_reg) and
  3353. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3354. begin
  3355. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3356. TransferUsedRegs(TmpUsedRegs);
  3357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3358. { we have
  3359. mov x, %treg
  3360. mov %treg, y
  3361. }
  3362. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3363. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3364. { we've got
  3365. mov x, %treg
  3366. mov %treg, y
  3367. with %treg is not used after }
  3368. case taicpu(p).oper[0]^.typ Of
  3369. { top_reg is covered by DeepMOVOpt }
  3370. top_const:
  3371. begin
  3372. { change
  3373. mov const, %treg
  3374. mov %treg, y
  3375. to
  3376. mov const, y
  3377. }
  3378. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3379. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3380. begin
  3381. if taicpu(hp1).oper[1]^.typ=top_reg then
  3382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3383. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3385. RemoveInstruction(hp1);
  3386. Result:=true;
  3387. Exit;
  3388. end;
  3389. end;
  3390. top_ref:
  3391. case taicpu(hp1).oper[1]^.typ of
  3392. top_reg:
  3393. begin
  3394. { change
  3395. mov mem, %treg
  3396. mov %treg, %reg
  3397. to
  3398. mov mem, %reg"
  3399. }
  3400. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3401. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3402. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3403. RemoveInstruction(hp1);
  3404. Result:=true;
  3405. Exit;
  3406. end;
  3407. top_ref:
  3408. begin
  3409. {$ifdef x86_64}
  3410. { Look for the following to simplify:
  3411. mov x(mem1), %reg
  3412. mov %reg, y(mem2)
  3413. mov x+8(mem1), %reg
  3414. mov %reg, y+8(mem2)
  3415. Change to:
  3416. movdqu x(mem1), %xmmreg
  3417. movdqu %xmmreg, y(mem2)
  3418. ...but only as long as the memory blocks don't overlap
  3419. }
  3420. SourceRef := taicpu(p).oper[0]^.ref^;
  3421. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3422. if (taicpu(p).opsize = S_Q) and
  3423. GetNextInstruction(hp1, hp2) and
  3424. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3425. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3426. begin
  3427. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3429. Inc(SourceRef.offset, 8);
  3430. if UseAVX then
  3431. begin
  3432. MovAligned := A_VMOVDQA;
  3433. MovUnaligned := A_VMOVDQU;
  3434. end
  3435. else
  3436. begin
  3437. MovAligned := A_MOVDQA;
  3438. MovUnaligned := A_MOVDQU;
  3439. end;
  3440. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3441. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3442. begin
  3443. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3444. Inc(TargetRef.offset, 8);
  3445. if GetNextInstruction(hp2, hp3) and
  3446. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3447. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3448. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3449. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3450. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3451. begin
  3452. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3453. if NewMMReg <> NR_NO then
  3454. begin
  3455. { Remember that the offsets are 8 ahead }
  3456. if ((SourceRef.offset mod 16) = 8) and
  3457. (
  3458. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3459. (SourceRef.base = current_procinfo.framepointer) or
  3460. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3461. ) then
  3462. taicpu(p).opcode := MovAligned
  3463. else
  3464. taicpu(p).opcode := MovUnaligned;
  3465. taicpu(p).opsize := S_XMM;
  3466. taicpu(p).oper[1]^.reg := NewMMReg;
  3467. if ((TargetRef.offset mod 16) = 8) and
  3468. (
  3469. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3470. (TargetRef.base = current_procinfo.framepointer) or
  3471. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3472. ) then
  3473. taicpu(hp1).opcode := MovAligned
  3474. else
  3475. taicpu(hp1).opcode := MovUnaligned;
  3476. taicpu(hp1).opsize := S_XMM;
  3477. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3478. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3479. RemoveInstruction(hp2);
  3480. RemoveInstruction(hp3);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. end;
  3485. end
  3486. else
  3487. begin
  3488. { See if the next references are 8 less rather than 8 greater }
  3489. Dec(SourceRef.offset, 16); { -8 the other way }
  3490. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3491. begin
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3493. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3494. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3495. GetNextInstruction(hp2, hp3) and
  3496. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3497. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3498. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3499. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3500. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3501. begin
  3502. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3503. if NewMMReg <> NR_NO then
  3504. begin
  3505. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3506. if ((SourceRef.offset mod 16) = 0) and
  3507. (
  3508. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3509. (SourceRef.base = current_procinfo.framepointer) or
  3510. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3511. ) then
  3512. taicpu(hp2).opcode := MovAligned
  3513. else
  3514. taicpu(hp2).opcode := MovUnaligned;
  3515. taicpu(hp2).opsize := S_XMM;
  3516. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3517. if ((TargetRef.offset mod 16) = 0) and
  3518. (
  3519. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3520. (TargetRef.base = current_procinfo.framepointer) or
  3521. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3522. ) then
  3523. taicpu(hp3).opcode := MovAligned
  3524. else
  3525. taicpu(hp3).opcode := MovUnaligned;
  3526. taicpu(hp3).opsize := S_XMM;
  3527. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3528. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3529. RemoveInstruction(hp1);
  3530. RemoveCurrentP(p, hp2);
  3531. Result := True;
  3532. Exit;
  3533. end;
  3534. end;
  3535. end;
  3536. end;
  3537. end;
  3538. {$endif x86_64}
  3539. end;
  3540. else
  3541. { The write target should be a reg or a ref }
  3542. InternalError(2021091601);
  3543. end;
  3544. else
  3545. ;
  3546. end
  3547. else
  3548. { %treg is used afterwards, but all eventualities
  3549. other than the first MOV instruction being a constant
  3550. are covered by DeepMOVOpt, so only check for that }
  3551. if (taicpu(p).oper[0]^.typ = top_const) and
  3552. (
  3553. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3554. not (cs_opt_size in current_settings.optimizerswitches) or
  3555. (taicpu(hp1).opsize = S_B)
  3556. ) and
  3557. (
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3559. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3560. ) then
  3561. begin
  3562. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3563. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3564. end;
  3565. end;
  3566. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3567. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3568. { mov reg1, mem1 or mov mem1, reg1
  3569. mov mem2, reg2 mov reg2, mem2}
  3570. begin
  3571. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3572. { mov reg1, mem1 or mov mem1, reg1
  3573. mov mem2, reg1 mov reg2, mem1}
  3574. begin
  3575. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3576. { Removes the second statement from
  3577. mov reg1, mem1/reg2
  3578. mov mem1/reg2, reg1 }
  3579. begin
  3580. if taicpu(p).oper[0]^.typ=top_reg then
  3581. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3582. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3583. RemoveInstruction(hp1);
  3584. Result:=true;
  3585. exit;
  3586. end
  3587. else
  3588. begin
  3589. TransferUsedRegs(TmpUsedRegs);
  3590. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3591. if (taicpu(p).oper[1]^.typ = top_ref) and
  3592. { mov reg1, mem1
  3593. mov mem2, reg1 }
  3594. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3595. GetNextInstruction(hp1, hp2) and
  3596. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3597. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3598. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3599. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3600. { change to
  3601. mov reg1, mem1 mov reg1, mem1
  3602. mov mem2, reg1 cmp reg1, mem2
  3603. cmp mem1, reg1
  3604. }
  3605. begin
  3606. RemoveInstruction(hp2);
  3607. taicpu(hp1).opcode := A_CMP;
  3608. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3609. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3612. end;
  3613. end;
  3614. end
  3615. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3616. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3617. begin
  3618. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3621. end
  3622. else
  3623. begin
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. if GetNextInstruction(hp1, hp2) and
  3626. MatchOpType(taicpu(p),top_ref,top_reg) and
  3627. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3628. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3629. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3631. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3634. { mov mem1, %reg1
  3635. mov %reg1, mem2
  3636. mov mem2, reg2
  3637. to:
  3638. mov mem1, reg2
  3639. mov reg2, mem2}
  3640. begin
  3641. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3642. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3643. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3644. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3645. RemoveInstruction(hp2);
  3646. Result := True;
  3647. end
  3648. {$ifdef i386}
  3649. { this is enabled for i386 only, as the rules to create the reg sets below
  3650. are too complicated for x86-64, so this makes this code too error prone
  3651. on x86-64
  3652. }
  3653. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3654. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3655. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3656. { mov mem1, reg1 mov mem1, reg1
  3657. mov reg1, mem2 mov reg1, mem2
  3658. mov mem2, reg2 mov mem2, reg1
  3659. to: to:
  3660. mov mem1, reg1 mov mem1, reg1
  3661. mov mem1, reg2 mov reg1, mem2
  3662. mov reg1, mem2
  3663. or (if mem1 depends on reg1
  3664. and/or if mem2 depends on reg2)
  3665. to:
  3666. mov mem1, reg1
  3667. mov reg1, mem2
  3668. mov reg1, reg2
  3669. }
  3670. begin
  3671. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3672. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3673. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3674. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3675. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3676. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3677. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3678. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3679. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3680. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3681. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3682. end
  3683. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3684. begin
  3685. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3686. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3687. end
  3688. else
  3689. begin
  3690. RemoveInstruction(hp2);
  3691. end
  3692. {$endif i386}
  3693. ;
  3694. end;
  3695. end
  3696. { movl [mem1],reg1
  3697. movl [mem1],reg2
  3698. to
  3699. movl [mem1],reg1
  3700. movl reg1,reg2
  3701. }
  3702. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3703. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3704. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3705. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3706. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3707. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3708. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3709. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3710. begin
  3711. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3712. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3713. end;
  3714. { movl const1,[mem1]
  3715. movl [mem1],reg1
  3716. to
  3717. movl const1,reg1
  3718. movl reg1,[mem1]
  3719. }
  3720. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3721. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3722. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3723. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3724. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3725. begin
  3726. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3727. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3728. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3729. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3730. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3731. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3732. Result:=true;
  3733. exit;
  3734. end;
  3735. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3736. { Change:
  3737. movl %reg1,%reg2
  3738. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3739. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3740. To:
  3741. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3742. movl x(%reg1),%reg1
  3743. movl %reg1,%regX
  3744. }
  3745. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3746. begin
  3747. p_SourceReg := taicpu(p).oper[0]^.reg;
  3748. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3749. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3750. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3751. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3755. begin
  3756. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3757. if RegInRef(p_TargetReg, SourceRef) and
  3758. { If %reg1 also appears in the second reference, then it will
  3759. not refer to the same memory block as the first reference }
  3760. not RegInRef(p_SourceReg, SourceRef) then
  3761. begin
  3762. { Check to see if the references match if %reg2 is changed to %reg1 }
  3763. if SourceRef.base = p_TargetReg then
  3764. SourceRef.base := p_SourceReg;
  3765. if SourceRef.index = p_TargetReg then
  3766. SourceRef.index := p_SourceReg;
  3767. { RefsEqual also checks to ensure both references are non-volatile }
  3768. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3769. begin
  3770. taicpu(hp2).loadreg(0, p_SourceReg);
  3771. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3772. Result := True;
  3773. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3774. begin
  3775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3776. RemoveCurrentP(p, hp1);
  3777. Exit;
  3778. end
  3779. else
  3780. begin
  3781. { Check to see if %reg2 is no longer in use }
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3786. begin
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3788. RemoveCurrentP(p, hp1);
  3789. Exit;
  3790. end;
  3791. end;
  3792. { If we reach this point, p and hp1 weren't actually modified,
  3793. so we can do a bit more work on this pass }
  3794. end;
  3795. end;
  3796. end;
  3797. end;
  3798. end;
  3799. {$ifdef x86_64}
  3800. { Change:
  3801. movl %reg1l,%reg2l
  3802. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3803. To:
  3804. movl %reg1l,%reg2l
  3805. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3806. If %reg1 = %reg3, convert to:
  3807. movl %reg1l,%reg2l
  3808. andl %reg1l,%reg1l
  3809. }
  3810. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3811. MatchOpType(taicpu(p), top_reg, top_reg) and
  3812. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3813. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3814. begin
  3815. TransferUsedRegs(TmpUsedRegs);
  3816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3817. taicpu(hp1).opsize := S_L;
  3818. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3821. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3822. begin
  3823. { %reg1 = %reg3 }
  3824. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3825. taicpu(hp1).opcode := A_AND;
  3826. end
  3827. else
  3828. begin
  3829. { %reg1 <> %reg3 }
  3830. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3831. end;
  3832. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3835. RemoveCurrentP(p, hp1);
  3836. Result := True;
  3837. Exit;
  3838. end
  3839. else
  3840. begin
  3841. { Initial instruction wasn't actually changed }
  3842. Include(OptsToCheck, aoc_ForceNewIteration);
  3843. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3844. appears below since %reg1 has technically changed }
  3845. if taicpu(hp1).opcode = A_AND then
  3846. Exit;
  3847. end;
  3848. end;
  3849. {$endif x86_64}
  3850. { search further than the next instruction for a mov (as long as it's not a jump) }
  3851. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3852. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3853. (taicpu(p).oper[1]^.typ = top_reg) and
  3854. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3855. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3856. begin
  3857. { we work with hp2 here, so hp1 can be still used later on when
  3858. checking for GetNextInstruction_p }
  3859. hp3 := hp1;
  3860. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3861. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3862. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3863. TransferUsedRegs(TmpUsedRegs);
  3864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3865. if NotFirstIteration then
  3866. JumpTracking := TLinkedList.Create
  3867. else
  3868. JumpTracking := nil;
  3869. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3870. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3871. (hp2.typ=ait_instruction) do
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_POP:
  3875. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3876. begin
  3877. if not CrossJump and
  3878. not RegUsedBetween(p_TargetReg, p, hp2) then
  3879. begin
  3880. { We can remove the original MOV since the register
  3881. wasn't used between it and its popping from the stack }
  3882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3883. RemoveCurrentp(p, hp1);
  3884. Result := True;
  3885. JumpTracking.Free;
  3886. Exit;
  3887. end;
  3888. { Can't go any further }
  3889. Break;
  3890. end;
  3891. A_MOV:
  3892. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3893. ((taicpu(p).oper[0]^.typ=top_const) or
  3894. ((taicpu(p).oper[0]^.typ=top_reg) and
  3895. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3896. )
  3897. ) then
  3898. begin
  3899. { we have
  3900. mov x, %treg
  3901. mov %treg, y
  3902. }
  3903. { We don't need to call UpdateUsedRegs for every instruction between
  3904. p and hp2 because the register we're concerned about will not
  3905. become deallocated (otherwise GetNextInstructionUsingReg would
  3906. have stopped at an earlier instruction). [Kit] }
  3907. TempRegUsed :=
  3908. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3909. RegReadByInstruction(p_TargetReg, hp3) or
  3910. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3911. case taicpu(p).oper[0]^.typ Of
  3912. top_reg:
  3913. begin
  3914. { change
  3915. mov %reg, %treg
  3916. mov %treg, y
  3917. to
  3918. mov %reg, y
  3919. }
  3920. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3921. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3922. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3923. begin
  3924. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3925. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3926. if TempRegUsed then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3929. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3930. { Set the start of the next GetNextInstructionUsingRegCond search
  3931. to start at the entry right before hp2 (which is about to be removed) }
  3932. hp3 := tai(hp2.Previous);
  3933. RemoveInstruction(hp2);
  3934. Include(OptsToCheck, aoc_ForceNewIteration);
  3935. { See if there's more we can optimise }
  3936. Continue;
  3937. end
  3938. else
  3939. begin
  3940. RemoveInstruction(hp2);
  3941. { We can remove the original MOV too }
  3942. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3943. RemoveCurrentP(p, hp1);
  3944. Result:=true;
  3945. JumpTracking.Free;
  3946. Exit;
  3947. end;
  3948. end
  3949. else
  3950. begin
  3951. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3952. taicpu(hp2).loadReg(0, p_SourceReg);
  3953. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3954. { Check to see if the register also appears in the reference }
  3955. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3956. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3957. { Don't remove the first instruction if the temporary register is in use }
  3958. if not TempRegUsed and
  3959. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3960. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3963. RemoveCurrentP(p, hp1);
  3964. Result:=true;
  3965. JumpTracking.Free;
  3966. Exit;
  3967. end;
  3968. { No need to set Result to True here. If there's another instruction later
  3969. on that can be optimised, it will be detected when the main Pass 1 loop
  3970. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3971. end;
  3972. end;
  3973. top_const:
  3974. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3975. begin
  3976. { change
  3977. mov const, %treg
  3978. mov %treg, y
  3979. to
  3980. mov const, y
  3981. }
  3982. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3983. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3984. begin
  3985. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3986. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3987. if TempRegUsed then
  3988. begin
  3989. { Don't remove the first instruction if the temporary register is in use }
  3990. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3991. { No need to set Result to True. If there's another instruction later on
  3992. that can be optimised, it will be detected when the main Pass 1 loop
  3993. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3994. end
  3995. else
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3998. RemoveCurrentP(p, hp1);
  3999. Result:=true;
  4000. Exit;
  4001. end;
  4002. end;
  4003. end;
  4004. else
  4005. Internalerror(2019103001);
  4006. end;
  4007. end
  4008. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4009. begin
  4010. if not CrossJump and
  4011. not RegUsedBetween(p_TargetReg, p, hp2) and
  4012. not RegReadByInstruction(p_TargetReg, hp2) then
  4013. begin
  4014. { Register is not used before it is overwritten }
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4016. RemoveCurrentp(p, hp1);
  4017. Result := True;
  4018. Exit;
  4019. end;
  4020. if (taicpu(p).oper[0]^.typ = top_const) and
  4021. (taicpu(hp2).oper[0]^.typ = top_const) then
  4022. begin
  4023. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4024. begin
  4025. { Same value - register hasn't changed }
  4026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4027. RemoveInstruction(hp2);
  4028. Include(OptsToCheck, aoc_ForceNewIteration);
  4029. { See if there's more we can optimise }
  4030. Continue;
  4031. end;
  4032. end;
  4033. {$ifdef x86_64}
  4034. end
  4035. { Change:
  4036. movl %reg1l,%reg2l
  4037. ...
  4038. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4039. To:
  4040. movl %reg1l,%reg2l
  4041. ...
  4042. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4043. If %reg1 = %reg3, convert to:
  4044. movl %reg1l,%reg2l
  4045. ...
  4046. andl %reg1l,%reg1l
  4047. }
  4048. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4049. (taicpu(p).oper[0]^.typ = top_reg) and
  4050. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4051. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4052. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4053. begin
  4054. TempRegUsed :=
  4055. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4056. RegReadByInstruction(p_TargetReg, hp3) or
  4057. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4058. taicpu(hp2).opsize := S_L;
  4059. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4060. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4062. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4063. begin
  4064. { %reg1 = %reg3 }
  4065. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4066. taicpu(hp2).opcode := A_AND;
  4067. end
  4068. else
  4069. begin
  4070. { %reg1 <> %reg3 }
  4071. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4072. end;
  4073. if not TempRegUsed then
  4074. begin
  4075. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4076. RemoveCurrentP(p, hp1);
  4077. Result := True;
  4078. Exit;
  4079. end
  4080. else
  4081. begin
  4082. { Initial instruction wasn't actually changed }
  4083. Include(OptsToCheck, aoc_ForceNewIteration);
  4084. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4085. appears below since %reg1 has technically changed }
  4086. if taicpu(hp2).opcode = A_AND then
  4087. Break;
  4088. end;
  4089. {$endif x86_64}
  4090. end;
  4091. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4092. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4093. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4094. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4095. begin
  4096. {
  4097. Change from:
  4098. mov ###, %reg
  4099. ...
  4100. movs/z %reg,%reg (Same register, just different sizes)
  4101. To:
  4102. movs/z ###, %reg (Longer version)
  4103. ...
  4104. (remove)
  4105. }
  4106. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4107. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4108. { Keep the first instruction as mov if ### is a constant }
  4109. if taicpu(p).oper[0]^.typ = top_const then
  4110. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4111. else
  4112. begin
  4113. taicpu(p).opcode := taicpu(hp2).opcode;
  4114. taicpu(p).opsize := taicpu(hp2).opsize;
  4115. end;
  4116. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4117. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. JumpTracking.Free;
  4121. Exit;
  4122. end;
  4123. else
  4124. { Move down to the if-block below };
  4125. end;
  4126. { Also catches MOV/S/Z instructions that aren't modified }
  4127. if taicpu(p).oper[0]^.typ = top_reg then
  4128. begin
  4129. p_SourceReg := taicpu(p).oper[0]^.reg;
  4130. if
  4131. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4132. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4133. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4134. begin
  4135. Result := True;
  4136. { Just in case something didn't get modified (e.g. an
  4137. implicit register). Also, if it does read from this
  4138. register, then there's no longer an advantage to
  4139. changing the register on subsequent instructions.}
  4140. if not RegReadByInstruction(p_TargetReg, hp2) then
  4141. begin
  4142. { If a conditional jump was crossed, do not delete
  4143. the original MOV no matter what }
  4144. if not CrossJump and
  4145. { RegEndOfLife returns True if the register is
  4146. deallocated before the next instruction or has
  4147. been loaded with a new value }
  4148. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4149. begin
  4150. { We can remove the original MOV }
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4152. RemoveCurrentp(p, hp1);
  4153. JumpTracking.Free;
  4154. Result := True;
  4155. Exit;
  4156. end;
  4157. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4158. begin
  4159. { See if there's more we can optimise }
  4160. hp3 := hp2;
  4161. Continue;
  4162. end;
  4163. end;
  4164. end;
  4165. end;
  4166. { Break out of the while loop under normal circumstances }
  4167. Break;
  4168. end;
  4169. JumpTracking.Free;
  4170. end;
  4171. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4172. (taicpu(p).oper[1]^.typ = top_reg) and
  4173. (taicpu(p).opsize = S_L) and
  4174. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4175. (hp2.typ = ait_instruction) and
  4176. (taicpu(hp2).opcode = A_AND) and
  4177. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4178. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4179. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4180. ) then
  4181. begin
  4182. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4183. begin
  4184. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4185. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4186. begin
  4187. { Optimize out:
  4188. mov x, %reg
  4189. and ffffffffh, %reg
  4190. }
  4191. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4192. RemoveInstruction(hp2);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. end;
  4197. end;
  4198. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4199. x >= RetOffset) as it doesn't do anything (it writes either to a
  4200. parameter or to the temporary storage room for the function
  4201. result)
  4202. }
  4203. if IsExitCode(hp1) and
  4204. (taicpu(p).oper[1]^.typ = top_ref) and
  4205. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4206. (
  4207. (
  4208. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4209. not (
  4210. assigned(current_procinfo.procdef.funcretsym) and
  4211. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4212. )
  4213. ) or
  4214. { Also discard writes to the stack that are below the base pointer,
  4215. as this is temporary storage rather than a function result on the
  4216. stack, say. }
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4219. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4220. )
  4221. ) then
  4222. begin
  4223. RemoveCurrentp(p, hp1);
  4224. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4225. RemoveLastDeallocForFuncRes(p);
  4226. Result:=true;
  4227. exit;
  4228. end;
  4229. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4230. begin
  4231. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4232. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4233. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4234. begin
  4235. { change
  4236. mov reg1, mem1
  4237. test/cmp x, mem1
  4238. to
  4239. mov reg1, mem1
  4240. test/cmp x, reg1
  4241. }
  4242. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4243. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if DoMovCmpMemOpt(p, hp1) then
  4249. begin
  4250. Result := True;
  4251. Exit;
  4252. end;
  4253. end;
  4254. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4255. { If the flags register is in use, don't change the instruction to an
  4256. ADD otherwise this will scramble the flags. [Kit] }
  4257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4258. begin
  4259. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4260. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4261. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4262. ) or
  4263. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4264. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4265. )
  4266. ) then
  4267. { mov reg1,ref
  4268. lea reg2,[reg1,reg2]
  4269. to
  4270. add reg2,ref}
  4271. begin
  4272. TransferUsedRegs(TmpUsedRegs);
  4273. { reg1 may not be used afterwards }
  4274. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4275. begin
  4276. Taicpu(hp1).opcode:=A_ADD;
  4277. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4278. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4279. RemoveCurrentp(p, hp1);
  4280. result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. { If the LEA instruction can be converted into an arithmetic instruction,
  4285. it may be possible to then fold it in the next optimisation, otherwise
  4286. there's nothing more that can be optimised here. }
  4287. if not ConvertLEA(taicpu(hp1)) then
  4288. Exit;
  4289. end;
  4290. if (taicpu(p).oper[1]^.typ = top_reg) and
  4291. (hp1.typ = ait_instruction) and
  4292. GetNextInstruction(hp1, hp2) and
  4293. MatchInstruction(hp2,A_MOV,[]) and
  4294. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4295. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4296. (
  4297. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4298. {$ifdef x86_64}
  4299. or
  4300. (
  4301. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4302. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4303. )
  4304. {$endif x86_64}
  4305. ) then
  4306. begin
  4307. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4308. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4309. { change movsX/movzX reg/ref, reg2
  4310. add/sub/or/... reg3/$const, reg2
  4311. mov reg2 reg/ref
  4312. dealloc reg2
  4313. to
  4314. add/sub/or/... reg3/$const, reg/ref }
  4315. begin
  4316. TransferUsedRegs(TmpUsedRegs);
  4317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4318. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4319. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4320. begin
  4321. { by example:
  4322. movswl %si,%eax movswl %si,%eax p
  4323. decl %eax addl %edx,%eax hp1
  4324. movw %ax,%si movw %ax,%si hp2
  4325. ->
  4326. movswl %si,%eax movswl %si,%eax p
  4327. decw %eax addw %edx,%eax hp1
  4328. movw %ax,%si movw %ax,%si hp2
  4329. }
  4330. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4331. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4332. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4333. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4334. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4335. {
  4336. ->
  4337. movswl %si,%eax movswl %si,%eax p
  4338. decw %si addw %dx,%si hp1
  4339. movw %ax,%si movw %ax,%si hp2
  4340. }
  4341. case taicpu(hp1).ops of
  4342. 1:
  4343. begin
  4344. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4345. if taicpu(hp1).oper[0]^.typ=top_reg then
  4346. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4347. end;
  4348. 2:
  4349. begin
  4350. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4351. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4352. (taicpu(hp1).opcode<>A_SHL) and
  4353. (taicpu(hp1).opcode<>A_SHR) and
  4354. (taicpu(hp1).opcode<>A_SAR) then
  4355. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4356. end;
  4357. else
  4358. internalerror(2008042701);
  4359. end;
  4360. {
  4361. ->
  4362. decw %si addw %dx,%si p
  4363. }
  4364. RemoveInstruction(hp2);
  4365. RemoveCurrentP(p, hp1);
  4366. Result:=True;
  4367. Exit;
  4368. end;
  4369. end;
  4370. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4371. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4372. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4373. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4374. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4375. )
  4376. {$ifdef i386}
  4377. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4378. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4379. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4380. {$endif i386}
  4381. then
  4382. { change movsX/movzX reg/ref, reg2
  4383. add/sub/or/... regX/$const, reg2
  4384. mov reg2, reg3
  4385. dealloc reg2
  4386. to
  4387. movsX/movzX reg/ref, reg3
  4388. add/sub/or/... reg3/$const, reg3
  4389. }
  4390. begin
  4391. TransferUsedRegs(TmpUsedRegs);
  4392. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4394. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4395. begin
  4396. { by example:
  4397. movswl %si,%eax movswl %si,%eax p
  4398. decl %eax addl %edx,%eax hp1
  4399. movw %ax,%si movw %ax,%si hp2
  4400. ->
  4401. movswl %si,%eax movswl %si,%eax p
  4402. decw %eax addw %edx,%eax hp1
  4403. movw %ax,%si movw %ax,%si hp2
  4404. }
  4405. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4406. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4407. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4408. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4409. { limit size of constants as well to avoid assembler errors, but
  4410. check opsize to avoid overflow when left shifting the 1 }
  4411. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4412. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4413. {$ifdef x86_64}
  4414. { Be careful of, for example:
  4415. movl %reg1,%reg2
  4416. addl %reg3,%reg2
  4417. movq %reg2,%reg4
  4418. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4419. }
  4420. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4421. begin
  4422. taicpu(hp2).changeopsize(S_L);
  4423. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4424. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4425. end;
  4426. {$endif x86_64}
  4427. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4428. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4429. if taicpu(p).oper[0]^.typ=top_reg then
  4430. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4431. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4432. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4433. {
  4434. ->
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decw %si addw %dx,%si hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. }
  4439. case taicpu(hp1).ops of
  4440. 1:
  4441. begin
  4442. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4443. if taicpu(hp1).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. 2:
  4447. begin
  4448. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4449. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4450. (taicpu(hp1).opcode<>A_SHL) and
  4451. (taicpu(hp1).opcode<>A_SHR) and
  4452. (taicpu(hp1).opcode<>A_SAR) then
  4453. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4454. end;
  4455. else
  4456. internalerror(2018111801);
  4457. end;
  4458. {
  4459. ->
  4460. decw %si addw %dx,%si p
  4461. }
  4462. RemoveInstruction(hp2);
  4463. end;
  4464. end;
  4465. end;
  4466. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4467. GetNextInstruction(hp1, hp2) and
  4468. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4469. MatchOperand(Taicpu(p).oper[0]^,0) and
  4470. (Taicpu(p).oper[1]^.typ = top_reg) and
  4471. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4472. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4473. { mov reg1,0
  4474. bts reg1,operand1 --> mov reg1,operand2
  4475. or reg1,operand2 bts reg1,operand1}
  4476. begin
  4477. Taicpu(hp2).opcode:=A_MOV;
  4478. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4479. asml.remove(hp1);
  4480. insertllitem(hp2,hp2.next,hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4487. GetNextInstruction(hp1, hp2) and
  4488. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4489. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4490. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4491. { change
  4492. mov reg1,reg2
  4493. sub reg3,reg2
  4494. cmp reg3,reg1
  4495. into
  4496. mov reg1,reg2
  4497. sub reg3,reg2
  4498. }
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4501. RemoveInstruction(hp2);
  4502. Result:=true;
  4503. exit;
  4504. end;
  4505. {
  4506. mov ref,reg0
  4507. <op> reg0,reg1
  4508. dealloc reg0
  4509. to
  4510. <op> ref,reg1
  4511. }
  4512. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4513. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4515. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4516. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4517. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4518. begin
  4519. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4520. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4521. RemoveCurrentp(p, hp1);
  4522. Result:=true;
  4523. exit;
  4524. end;
  4525. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4526. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4527. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4529. begin
  4530. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4531. {$ifdef x86_64}
  4532. { Convert:
  4533. movq x(ref),%reg64
  4534. shrq y,%reg64
  4535. To:
  4536. movl x+4(ref),%reg32
  4537. shrl y-32,%reg32 (Remove if y = 32)
  4538. }
  4539. if (taicpu(p).opsize = S_Q) and
  4540. (taicpu(hp1).opcode = A_SHR) and
  4541. (taicpu(hp1).oper[0]^.val >= 32) then
  4542. begin
  4543. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4544. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4545. { Convert to 32-bit }
  4546. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4547. taicpu(p).opsize := S_L;
  4548. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4549. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4550. if (taicpu(hp1).oper[0]^.val = 32) then
  4551. begin
  4552. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4553. RemoveInstruction(hp1);
  4554. end
  4555. else
  4556. begin
  4557. { This will potentially open up more arithmetic operations since
  4558. the peephole optimizer now has a big hint that only the lower
  4559. 32 bits are currently in use (and opcodes are smaller in size) }
  4560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4561. taicpu(hp1).opsize := S_L;
  4562. Dec(taicpu(hp1).oper[0]^.val, 32);
  4563. DebugMsg(SPeepholeOptimization + PreMessage +
  4564. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4565. end;
  4566. Result := True;
  4567. Exit;
  4568. end;
  4569. {$endif x86_64}
  4570. { Convert:
  4571. movl x(ref),%reg
  4572. shrl $24,%reg
  4573. To:
  4574. movzbl x+3(ref),%reg
  4575. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4576. Also accept sar instead of shr, but convert to movsx instead of movzx
  4577. }
  4578. if taicpu(hp1).opcode = A_SHR then
  4579. MovUnaligned := A_MOVZX
  4580. else
  4581. MovUnaligned := A_MOVSX;
  4582. NewSize := S_NO;
  4583. NewOffset := 0;
  4584. case taicpu(p).opsize of
  4585. S_B:
  4586. { No valid combinations };
  4587. S_W:
  4588. if (taicpu(hp1).oper[0]^.val = 8) then
  4589. begin
  4590. NewSize := S_BW;
  4591. NewOffset := 1;
  4592. end;
  4593. S_L:
  4594. case taicpu(hp1).oper[0]^.val of
  4595. 16:
  4596. begin
  4597. NewSize := S_WL;
  4598. NewOffset := 2;
  4599. end;
  4600. 24:
  4601. begin
  4602. NewSize := S_BL;
  4603. NewOffset := 3;
  4604. end;
  4605. else
  4606. ;
  4607. end;
  4608. {$ifdef x86_64}
  4609. S_Q:
  4610. case taicpu(hp1).oper[0]^.val of
  4611. 32:
  4612. begin
  4613. if taicpu(hp1).opcode = A_SAR then
  4614. begin
  4615. { 32-bit to 64-bit is a distinct instruction }
  4616. MovUnaligned := A_MOVSXD;
  4617. NewSize := S_LQ;
  4618. NewOffset := 4;
  4619. end
  4620. else
  4621. { Should have been handled by MovShr2Mov above }
  4622. InternalError(2022081811);
  4623. end;
  4624. 48:
  4625. begin
  4626. NewSize := S_WQ;
  4627. NewOffset := 6;
  4628. end;
  4629. 56:
  4630. begin
  4631. NewSize := S_BQ;
  4632. NewOffset := 7;
  4633. end;
  4634. else
  4635. ;
  4636. end;
  4637. {$endif x86_64}
  4638. else
  4639. InternalError(2022081810);
  4640. end;
  4641. if (NewSize <> S_NO) and
  4642. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4643. begin
  4644. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4645. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4646. debug_op2str(MovUnaligned);
  4647. {$ifdef x86_64}
  4648. if MovUnaligned <> A_MOVSXD then
  4649. { Don't add size suffix for MOVSXD }
  4650. {$endif x86_64}
  4651. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4652. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4653. taicpu(p).opcode := MovUnaligned;
  4654. taicpu(p).opsize := NewSize;
  4655. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4656. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4657. RemoveInstruction(hp1);
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. { Backward optimisation shared with OptPass2MOV }
  4663. if FuncMov2Func(p, hp1) then
  4664. begin
  4665. Result := True;
  4666. Exit;
  4667. end;
  4668. end;
  4669. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4670. var
  4671. hp1 : tai;
  4672. begin
  4673. Result:=false;
  4674. if taicpu(p).ops <> 2 then
  4675. exit;
  4676. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4677. GetNextInstruction(p,hp1) then
  4678. begin
  4679. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4680. (taicpu(hp1).ops = 2) then
  4681. begin
  4682. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4683. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4684. { movXX reg1, mem1 or movXX mem1, reg1
  4685. movXX mem2, reg2 movXX reg2, mem2}
  4686. begin
  4687. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4688. { movXX reg1, mem1 or movXX mem1, reg1
  4689. movXX mem2, reg1 movXX reg2, mem1}
  4690. begin
  4691. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4692. begin
  4693. { Removes the second statement from
  4694. movXX reg1, mem1/reg2
  4695. movXX mem1/reg2, reg1
  4696. }
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4699. { Removes the second statement from
  4700. movXX mem1/reg1, reg2
  4701. movXX reg2, mem1/reg1
  4702. }
  4703. if (taicpu(p).oper[1]^.typ=top_reg) and
  4704. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4705. begin
  4706. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4707. RemoveInstruction(hp1);
  4708. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4709. Result:=true;
  4710. exit;
  4711. end
  4712. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4713. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4716. RemoveInstruction(hp1);
  4717. Result:=true;
  4718. exit;
  4719. end;
  4720. end
  4721. end;
  4722. end;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4727. var
  4728. hp1 : tai;
  4729. begin
  4730. result:=false;
  4731. { replace
  4732. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4733. MovX %mreg2,%mreg1
  4734. dealloc %mreg2
  4735. by
  4736. <Op>X %mreg2,%mreg1
  4737. ?
  4738. }
  4739. if GetNextInstruction(p,hp1) and
  4740. { we mix single and double opperations here because we assume that the compiler
  4741. generates vmovapd only after double operations and vmovaps only after single operations }
  4742. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4745. (taicpu(p).oper[0]^.typ=top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. end;
  4757. end;
  4758. end;
  4759. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4760. var
  4761. hp1, p_label, p_dist, hp1_dist: tai;
  4762. JumpLabel, JumpLabel_dist: TAsmLabel;
  4763. FirstValue, SecondValue: TCGInt;
  4764. TempBool: Boolean;
  4765. begin
  4766. Result := False;
  4767. if (taicpu(p).oper[0]^.typ = top_const) and
  4768. (taicpu(p).oper[0]^.val <> -1) then
  4769. begin
  4770. { Convert unsigned maximum constants to -1 to aid optimisation }
  4771. case taicpu(p).opsize of
  4772. S_B:
  4773. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4774. begin
  4775. taicpu(p).oper[0]^.val := -1;
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. S_W:
  4780. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4781. begin
  4782. taicpu(p).oper[0]^.val := -1;
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. S_L:
  4787. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. {$ifdef x86_64}
  4794. S_Q:
  4795. { Storing anything greater than $7FFFFFFF is not possible so do
  4796. nothing };
  4797. {$endif x86_64}
  4798. else
  4799. InternalError(2021121001);
  4800. end;
  4801. end;
  4802. if GetNextInstruction(p, hp1) and
  4803. TrySwapMovCmp(p, hp1) then
  4804. begin
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. if MatchInstruction(hp1, A_Jcc, []) then
  4809. begin
  4810. TempBool := True;
  4811. if DoJumpOptimizations(hp1, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(hp1) then
  4816. begin
  4817. if (hp1.typ in [ait_align]) then
  4818. SkipAligns(hp1, hp1);
  4819. { CollapseZeroDistJump will be set to the label after the
  4820. jump if it optimises, whether or not it's live or dead }
  4821. if (hp1.typ in [ait_label]) and
  4822. not (tai_label(hp1).labsym.is_used) then
  4823. GetNextInstruction(hp1, hp1);
  4824. end;
  4825. TransferUsedRegs(TmpUsedRegs);
  4826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4827. if not Assigned(hp1) or
  4828. (
  4829. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4830. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4831. ) then
  4832. begin
  4833. { No more conditional jumps; conditional statement is no longer required }
  4834. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4835. RemoveCurrentP(p);
  4836. end;
  4837. Exit;
  4838. end;
  4839. end;
  4840. { Search for:
  4841. test $x,(reg/ref)
  4842. jne @lbl1
  4843. test $y,(reg/ref) (same register or reference)
  4844. jne @lbl1
  4845. Change to:
  4846. test $(x or y),(reg/ref)
  4847. jne @lbl1
  4848. (Note, this doesn't work with je instead of jne)
  4849. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4850. Also search for:
  4851. test $x,(reg/ref)
  4852. je @lbl1
  4853. test $y,(reg/ref)
  4854. je/jne @lbl2
  4855. If (x or y) = x, then the second jump is deterministic
  4856. }
  4857. if (
  4858. (
  4859. (taicpu(p).oper[0]^.typ = top_const) or
  4860. (
  4861. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4862. (taicpu(p).oper[0]^.typ = top_reg) and
  4863. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4864. )
  4865. ) and
  4866. MatchInstruction(hp1, A_JCC, [])
  4867. ) then
  4868. begin
  4869. if (taicpu(p).oper[0]^.typ = top_reg) and
  4870. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4871. FirstValue := -1
  4872. else
  4873. FirstValue := taicpu(p).oper[0]^.val;
  4874. { If we have several test/jne's in a row, it might be the case that
  4875. the second label doesn't go to the same location, but the one
  4876. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4877. so accommodate for this with a while loop.
  4878. }
  4879. hp1_dist := hp1;
  4880. if GetNextInstruction(hp1, p_dist) and
  4881. (p_dist.typ = ait_instruction) and
  4882. (
  4883. (
  4884. (taicpu(p_dist).opcode = A_TEST) and
  4885. (
  4886. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4887. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4888. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4889. )
  4890. ) or
  4891. (
  4892. { cmp 0,%reg = test %reg,%reg }
  4893. (taicpu(p_dist).opcode = A_CMP) and
  4894. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4895. )
  4896. ) and
  4897. { Make sure the destination operands are actually the same }
  4898. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4899. GetNextInstruction(p_dist, hp1_dist) and
  4900. MatchInstruction(hp1_dist, A_JCC, []) then
  4901. begin
  4902. if
  4903. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4904. (
  4905. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4906. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4907. ) then
  4908. SecondValue := -1
  4909. else
  4910. SecondValue := taicpu(p_dist).oper[0]^.val;
  4911. { If both of the TEST constants are identical, delete the second
  4912. TEST that is unnecessary. }
  4913. if (FirstValue = SecondValue) then
  4914. begin
  4915. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4916. RemoveInstruction(p_dist);
  4917. { Don't let the flags register become deallocated and reallocated between the jumps }
  4918. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4919. Result := True;
  4920. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4921. begin
  4922. { Since the second jump's condition is a subset of the first, we
  4923. know it will never branch because the first jump dominates it.
  4924. Get it out of the way now rather than wait for the jump
  4925. optimisations for a speed boost. }
  4926. if IsJumpToLabel(taicpu(hp1_dist)) then
  4927. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4928. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4929. RemoveInstruction(hp1_dist);
  4930. end
  4931. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4932. begin
  4933. { If the inverse of the first condition is a subset of the second,
  4934. the second one will definitely branch if the first one doesn't }
  4935. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4936. MakeUnconditional(taicpu(hp1_dist));
  4937. RemoveDeadCodeAfterJump(hp1_dist);
  4938. end;
  4939. Exit;
  4940. end;
  4941. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4942. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4943. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4944. then the second jump will never branch, so it can also be
  4945. removed regardless of where it goes }
  4946. (
  4947. (FirstValue = -1) or
  4948. (SecondValue = -1) or
  4949. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4950. ) then
  4951. begin
  4952. { Same jump location... can be a register since nothing's changed }
  4953. { If any of the entries are equivalent to test %reg,%reg, then the
  4954. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4955. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4956. if IsJumpToLabel(taicpu(hp1_dist)) then
  4957. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4958. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4959. RemoveInstruction(hp1_dist);
  4960. { Only remove the second test if no jumps or other conditional instructions follow }
  4961. TransferUsedRegs(TmpUsedRegs);
  4962. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4963. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4964. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4965. RemoveInstruction(p_dist);
  4966. Result := True;
  4967. Exit;
  4968. end;
  4969. end;
  4970. end;
  4971. { Search for:
  4972. test %reg,%reg
  4973. j(c1) @lbl1
  4974. ...
  4975. @lbl:
  4976. test %reg,%reg (same register)
  4977. j(c2) @lbl2
  4978. If c2 is a subset of c1, change to:
  4979. test %reg,%reg
  4980. j(c1) @lbl2
  4981. (@lbl1 may become a dead label as a result)
  4982. }
  4983. if (taicpu(p).oper[1]^.typ = top_reg) and
  4984. (taicpu(p).oper[0]^.typ = top_reg) and
  4985. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4986. MatchInstruction(hp1, A_JCC, []) and
  4987. IsJumpToLabel(taicpu(hp1)) then
  4988. begin
  4989. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4990. p_label := nil;
  4991. if Assigned(JumpLabel) then
  4992. p_label := getlabelwithsym(JumpLabel);
  4993. if Assigned(p_label) and
  4994. GetNextInstruction(p_label, p_dist) and
  4995. MatchInstruction(p_dist, A_TEST, []) and
  4996. { It's fine if the second test uses smaller sub-registers }
  4997. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4998. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4999. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5000. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5001. GetNextInstruction(p_dist, hp1_dist) and
  5002. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5003. begin
  5004. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5005. if JumpLabel = JumpLabel_dist then
  5006. { This is an infinite loop }
  5007. Exit;
  5008. { Best optimisation when the first condition is a subset (or equal) of the second }
  5009. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5010. begin
  5011. { Any registers used here will already be allocated }
  5012. if Assigned(JumpLabel) then
  5013. JumpLabel.DecRefs;
  5014. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5015. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5016. Result := True;
  5017. Exit;
  5018. end;
  5019. end;
  5020. end;
  5021. end;
  5022. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5023. var
  5024. hp1, hp2: tai;
  5025. ActiveReg: TRegister;
  5026. OldOffset: asizeint;
  5027. ThisConst: TCGInt;
  5028. function RegDeallocated: Boolean;
  5029. begin
  5030. TransferUsedRegs(TmpUsedRegs);
  5031. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5032. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5033. end;
  5034. begin
  5035. result:=false;
  5036. hp1 := nil;
  5037. { replace
  5038. addX const,%reg1
  5039. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5040. dealloc %reg1
  5041. by
  5042. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5043. }
  5044. if MatchOpType(taicpu(p),top_const,top_reg) then
  5045. begin
  5046. ActiveReg := taicpu(p).oper[1]^.reg;
  5047. { Ensures the entire register was updated }
  5048. if (taicpu(p).opsize >= S_L) and
  5049. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5050. MatchInstruction(hp1,A_LEA,[]) and
  5051. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5052. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5053. (
  5054. { Cover the case where the register in the reference is also the destination register }
  5055. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5056. (
  5057. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5058. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5059. RegDeallocated
  5060. )
  5061. ) then
  5062. begin
  5063. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5064. {$push}
  5065. {$R-}{$Q-}
  5066. { Explicitly disable overflow checking for these offset calculation
  5067. as those do not matter for the final result }
  5068. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5069. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5070. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5071. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5072. {$pop}
  5073. {$ifdef x86_64}
  5074. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5075. begin
  5076. { Overflow; abort }
  5077. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5078. end
  5079. else
  5080. {$endif x86_64}
  5081. begin
  5082. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5083. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5084. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5085. RemoveCurrentP(p, hp1)
  5086. else
  5087. RemoveCurrentP(p);
  5088. result:=true;
  5089. Exit;
  5090. end;
  5091. end;
  5092. if (
  5093. { Save calling GetNextInstructionUsingReg again }
  5094. Assigned(hp1) or
  5095. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5096. ) and
  5097. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5098. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5099. begin
  5100. if taicpu(hp1).oper[0]^.typ = top_const then
  5101. begin
  5102. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5103. if taicpu(hp1).opcode = A_ADD then
  5104. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5105. else
  5106. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5107. Result := True;
  5108. { Handle any overflows }
  5109. case taicpu(p).opsize of
  5110. S_B:
  5111. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5112. S_W:
  5113. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5114. S_L:
  5115. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5116. {$ifdef x86_64}
  5117. S_Q:
  5118. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5119. { Overflow; abort }
  5120. Result := False
  5121. else
  5122. taicpu(p).oper[0]^.val := ThisConst;
  5123. {$endif x86_64}
  5124. else
  5125. InternalError(2021102610);
  5126. end;
  5127. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5128. if Result then
  5129. begin
  5130. if (taicpu(p).oper[0]^.val < 0) and
  5131. (
  5132. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5133. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5134. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5135. ) then
  5136. begin
  5137. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5138. taicpu(p).opcode := A_SUB;
  5139. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5140. end
  5141. else
  5142. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5143. RemoveInstruction(hp1);
  5144. end;
  5145. end
  5146. else
  5147. begin
  5148. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5149. TransferUsedRegs(TmpUsedRegs);
  5150. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5151. hp2 := p;
  5152. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5153. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5154. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5155. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5156. begin
  5157. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5158. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5159. Asml.Remove(p);
  5160. Asml.InsertAfter(p, hp1);
  5161. p := hp1;
  5162. Result := True;
  5163. Exit;
  5164. end;
  5165. end;
  5166. end;
  5167. if DoArithCombineOpt(p) then
  5168. Result:=true;
  5169. end;
  5170. end;
  5171. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5172. var
  5173. hp1, hp2: tai;
  5174. ref: Integer;
  5175. saveref: treference;
  5176. offsetcalc: Int64;
  5177. TempReg: TRegister;
  5178. Multiple: TCGInt;
  5179. Adjacent, IntermediateRegDiscarded: Boolean;
  5180. begin
  5181. Result:=false;
  5182. { play save and throw an error if LEA uses a seg register prefix,
  5183. this is most likely an error somewhere else }
  5184. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5185. internalerror(2022022001);
  5186. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5187. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5188. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5189. (
  5190. { do not mess with leas accessing the stack pointer
  5191. unless it's a null operation }
  5192. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5193. (
  5194. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5195. (taicpu(p).oper[0]^.ref^.offset = 0)
  5196. )
  5197. ) and
  5198. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5199. begin
  5200. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5201. begin
  5202. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5203. begin
  5204. taicpu(p).opcode := A_MOV;
  5205. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5206. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5207. end
  5208. else
  5209. begin
  5210. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5211. RemoveCurrentP(p);
  5212. end;
  5213. Result:=true;
  5214. exit;
  5215. end
  5216. else if (
  5217. { continue to use lea to adjust the stack pointer,
  5218. it is the recommended way, but only if not optimizing for size }
  5219. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5220. (cs_opt_size in current_settings.optimizerswitches)
  5221. ) and
  5222. { If the flags register is in use, don't change the instruction
  5223. to an ADD otherwise this will scramble the flags. [Kit] }
  5224. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5225. ConvertLEA(taicpu(p)) then
  5226. begin
  5227. Result:=true;
  5228. exit;
  5229. end;
  5230. end;
  5231. { Don't optimise if the stack or frame pointer is the destination register }
  5232. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5233. Exit;
  5234. if GetNextInstruction(p,hp1) and
  5235. (hp1.typ=ait_instruction) then
  5236. begin
  5237. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5238. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5239. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5240. begin
  5241. TransferUsedRegs(TmpUsedRegs);
  5242. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5243. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5244. begin
  5245. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5246. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5247. RemoveInstruction(hp1);
  5248. result:=true;
  5249. exit;
  5250. end;
  5251. end;
  5252. { changes
  5253. lea <ref1>, reg1
  5254. <op> ...,<ref. with reg1>,...
  5255. to
  5256. <op> ...,<ref1>,... }
  5257. { find a reference which uses reg1 }
  5258. 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
  5259. ref:=0
  5260. 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
  5261. ref:=1
  5262. else
  5263. ref:=-1;
  5264. if (ref<>-1) and
  5265. { reg1 must be either the base or the index }
  5266. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5267. begin
  5268. { reg1 can be removed from the reference }
  5269. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5270. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5271. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5272. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5273. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5274. else
  5275. Internalerror(2019111201);
  5276. { check if the can insert all data of the lea into the second instruction }
  5277. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5278. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5279. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5280. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5281. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5282. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5283. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5284. {$ifdef x86_64}
  5285. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5286. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5287. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5288. )
  5289. {$endif x86_64}
  5290. then
  5291. begin
  5292. { reg1 might not used by the second instruction after it is remove from the reference }
  5293. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5294. begin
  5295. TransferUsedRegs(TmpUsedRegs);
  5296. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5297. { reg1 is not updated so it might not be used afterwards }
  5298. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5301. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5302. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5303. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5304. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5305. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5306. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5307. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5308. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5309. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5310. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5311. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5312. RemoveCurrentP(p, hp1);
  5313. result:=true;
  5314. exit;
  5315. end
  5316. end;
  5317. end;
  5318. { recover }
  5319. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5320. end;
  5321. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5322. if Adjacent or
  5323. { Check further ahead (up to 2 instructions ahead for -O2) }
  5324. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5325. begin
  5326. { Check common LEA/LEA conditions }
  5327. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5328. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5329. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5330. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5331. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5332. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5333. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5334. (
  5335. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5336. calling it (since it calls GetNextInstruction) }
  5337. Adjacent or
  5338. (
  5339. (
  5340. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5341. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5342. ) and (
  5343. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5344. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5345. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5346. )
  5347. )
  5348. ) then
  5349. begin
  5350. TransferUsedRegs(TmpUsedRegs);
  5351. hp2 := p;
  5352. repeat
  5353. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5354. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5355. IntermediateRegDiscarded :=
  5356. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5357. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5358. { changes
  5359. lea offset1(regX,scale), reg1
  5360. lea offset2(reg1,reg1), reg2
  5361. to
  5362. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5363. and
  5364. lea offset1(regX,scale1), reg1
  5365. lea offset2(reg1,scale2), reg2
  5366. to
  5367. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5368. and
  5369. lea offset1(regX,scale1), reg1
  5370. lea offset2(reg3,reg1,scale2), reg2
  5371. to
  5372. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5373. ... so long as the final scale does not exceed 8
  5374. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5375. }
  5376. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5377. (
  5378. { Don't optimise if size is a concern and the intermediate register remains in use }
  5379. IntermediateRegDiscarded or
  5380. not (cs_opt_size in current_settings.optimizerswitches)
  5381. ) and
  5382. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5383. (
  5384. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5385. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5386. ) and (
  5387. (
  5388. { lea (reg1,scale2), reg2 variant }
  5389. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5390. (
  5391. Adjacent or
  5392. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5393. ) and
  5394. (
  5395. (
  5396. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5397. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5398. ) or (
  5399. { lea (regX,regX), reg1 variant }
  5400. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5401. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5402. )
  5403. )
  5404. ) or (
  5405. { lea (reg1,reg1), reg1 variant }
  5406. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5407. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5408. )
  5409. ) then
  5410. begin
  5411. { Make everything homogeneous to make calculations easier }
  5412. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5413. begin
  5414. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5415. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5416. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5417. else
  5418. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5419. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5420. end;
  5421. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5422. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5423. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5424. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5425. begin
  5426. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5427. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5428. begin
  5429. { Put the register to change in the index register }
  5430. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5431. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5432. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5433. end;
  5434. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5435. begin
  5436. { Just to prevent miscalculations }
  5437. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5438. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5439. else
  5440. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5441. end
  5442. else
  5443. begin
  5444. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5445. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5446. end;
  5447. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5448. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5449. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5450. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5451. if IntermediateRegDiscarded then
  5452. begin
  5453. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5454. RemoveCurrentP(p);
  5455. end
  5456. else
  5457. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5458. result:=true;
  5459. exit;
  5460. end;
  5461. end;
  5462. { changes
  5463. lea offset1(regX), reg1
  5464. lea offset2(reg1), reg2
  5465. to
  5466. lea offset1+offset2(regX), reg2 }
  5467. if (
  5468. { Don't optimise if size is a concern and the intermediate register remains in use }
  5469. IntermediateRegDiscarded or
  5470. not (cs_opt_size in current_settings.optimizerswitches)
  5471. ) and
  5472. (
  5473. (
  5474. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5475. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5476. ) or (
  5477. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5478. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5479. (
  5480. (
  5481. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5482. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5483. ) or (
  5484. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5485. (
  5486. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5487. (
  5488. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5489. (
  5490. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5491. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5492. )
  5493. )
  5494. )
  5495. )
  5496. )
  5497. )
  5498. ) then
  5499. begin
  5500. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5501. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5502. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5503. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5504. begin
  5505. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5506. begin
  5507. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5508. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5509. { if the register is used as index and base, we have to increase for base as well
  5510. and adapt base }
  5511. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5512. begin
  5513. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5514. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5515. end;
  5516. end
  5517. else
  5518. begin
  5519. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5520. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5521. end;
  5522. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5523. begin
  5524. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5525. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5526. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5527. end;
  5528. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5529. if IntermediateRegDiscarded then
  5530. begin
  5531. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5532. RemoveCurrentP(p);
  5533. end
  5534. else
  5535. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5536. result:=true;
  5537. exit;
  5538. end;
  5539. end;
  5540. end;
  5541. { Change:
  5542. leal/q $x(%reg1),%reg2
  5543. ...
  5544. shll/q $y,%reg2
  5545. To:
  5546. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5547. }
  5548. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5549. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5550. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5551. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5552. (taicpu(hp1).oper[0]^.val <= 3) then
  5553. begin
  5554. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5555. TransferUsedRegs(TmpUsedRegs);
  5556. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5557. if
  5558. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5559. (this works even if scalefactor is zero) }
  5560. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5561. { Ensure offset doesn't go out of bounds }
  5562. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5563. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5564. (
  5565. (
  5566. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5567. (
  5568. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5569. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5570. (
  5571. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5572. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5573. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5574. )
  5575. )
  5576. ) or (
  5577. (
  5578. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5579. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5580. ) and
  5581. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5582. )
  5583. ) then
  5584. begin
  5585. repeat
  5586. with taicpu(p).oper[0]^.ref^ do
  5587. begin
  5588. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5589. if index = base then
  5590. begin
  5591. if Multiple > 4 then
  5592. { Optimisation will no longer work because resultant
  5593. scale factor will exceed 8 }
  5594. Break;
  5595. base := NR_NO;
  5596. scalefactor := 2;
  5597. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5598. end
  5599. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5600. begin
  5601. { Scale factor only works on the index register }
  5602. index := base;
  5603. base := NR_NO;
  5604. end;
  5605. { For safety }
  5606. if scalefactor <= 1 then
  5607. begin
  5608. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5609. scalefactor := Multiple;
  5610. end
  5611. else
  5612. begin
  5613. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5614. scalefactor := scalefactor * Multiple;
  5615. end;
  5616. offset := offset * Multiple;
  5617. end;
  5618. RemoveInstruction(hp1);
  5619. Result := True;
  5620. Exit;
  5621. { This repeat..until loop exists for the benefit of Break }
  5622. until True;
  5623. end;
  5624. end;
  5625. end;
  5626. end;
  5627. end;
  5628. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5629. var
  5630. hp1 : tai;
  5631. SubInstr: Boolean;
  5632. ThisConst: TCGInt;
  5633. const
  5634. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5635. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5636. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5637. begin
  5638. Result := False;
  5639. if taicpu(p).oper[0]^.typ <> top_const then
  5640. { Should have been confirmed before calling }
  5641. InternalError(2021102601);
  5642. SubInstr := (taicpu(p).opcode = A_SUB);
  5643. if GetLastInstruction(p, hp1) and
  5644. (hp1.typ = ait_instruction) and
  5645. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5646. begin
  5647. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5648. { Bad size }
  5649. InternalError(2022042001);
  5650. case taicpu(hp1).opcode Of
  5651. A_INC:
  5652. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5653. begin
  5654. if SubInstr then
  5655. ThisConst := taicpu(p).oper[0]^.val - 1
  5656. else
  5657. ThisConst := taicpu(p).oper[0]^.val + 1;
  5658. end
  5659. else
  5660. Exit;
  5661. A_DEC:
  5662. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5663. begin
  5664. if SubInstr then
  5665. ThisConst := taicpu(p).oper[0]^.val + 1
  5666. else
  5667. ThisConst := taicpu(p).oper[0]^.val - 1;
  5668. end
  5669. else
  5670. Exit;
  5671. A_SUB:
  5672. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5673. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5674. begin
  5675. if SubInstr then
  5676. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5677. else
  5678. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5679. end
  5680. else
  5681. Exit;
  5682. A_ADD:
  5683. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5684. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5685. begin
  5686. if SubInstr then
  5687. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5688. else
  5689. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5690. end
  5691. else
  5692. Exit;
  5693. else
  5694. Exit;
  5695. end;
  5696. { Check that the values are in range }
  5697. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5698. { Overflow; abort }
  5699. Exit;
  5700. if (ThisConst = 0) then
  5701. begin
  5702. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5703. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5704. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5705. RemoveInstruction(hp1);
  5706. hp1 := tai(p.next);
  5707. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5708. if not GetLastInstruction(hp1, p) then
  5709. p := hp1;
  5710. end
  5711. else
  5712. begin
  5713. if taicpu(hp1).opercnt=1 then
  5714. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5715. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5716. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5717. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5718. else
  5719. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5720. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5721. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5722. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5723. RemoveInstruction(hp1);
  5724. taicpu(p).loadconst(0, ThisConst);
  5725. end;
  5726. Result := True;
  5727. end;
  5728. end;
  5729. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5730. var
  5731. hp2: tai;
  5732. begin
  5733. Result := False;
  5734. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5735. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5736. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5737. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5738. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5739. (
  5740. (
  5741. (taicpu(hp1).opcode = A_TEST)
  5742. ) or (
  5743. (taicpu(hp1).opcode = A_CMP) and
  5744. { A sanity check more than anything }
  5745. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5746. )
  5747. ) then
  5748. begin
  5749. { change
  5750. mov mem, %reg
  5751. ...
  5752. cmp/test x, %reg / test %reg,%reg
  5753. (reg deallocated)
  5754. to
  5755. cmp/test x, mem / cmp 0, mem
  5756. }
  5757. TransferUsedRegs(TmpUsedRegs);
  5758. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5759. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5760. begin
  5761. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5762. if (taicpu(hp1).opcode = A_TEST) and
  5763. (
  5764. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5765. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5766. ) then
  5767. begin
  5768. taicpu(hp1).opcode := A_CMP;
  5769. taicpu(hp1).loadconst(0, 0);
  5770. end;
  5771. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5772. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5773. RemoveCurrentP(p);
  5774. if (p <> hp1) then
  5775. begin
  5776. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5777. hp2 := p;
  5778. repeat
  5779. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5780. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5781. end;
  5782. { Make sure the flags are allocated across the CMP instruction }
  5783. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5784. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5785. Result := True;
  5786. Exit;
  5787. end;
  5788. end;
  5789. end;
  5790. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5791. var
  5792. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5793. ThisReg, SecondReg: TRegister;
  5794. JumpLoc: TAsmLabel;
  5795. NewSize: TOpSize;
  5796. begin
  5797. Result := False;
  5798. {
  5799. Convert:
  5800. j<c> .L1
  5801. .L2:
  5802. mov 1,reg
  5803. jmp .L3 (or ret, although it might not be a RET yet)
  5804. .L1:
  5805. mov 0,reg
  5806. jmp .L3 (or ret)
  5807. ( As long as .L3 <> .L1 or .L2)
  5808. To:
  5809. mov 0,reg
  5810. set<not(c)> reg
  5811. jmp .L3 (or ret)
  5812. .L2:
  5813. mov 1,reg
  5814. jmp .L3 (or ret)
  5815. .L1:
  5816. mov 0,reg
  5817. jmp .L3 (or ret)
  5818. }
  5819. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5820. Exit;
  5821. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5822. if GetNextInstruction(hp_label, hp2) and
  5823. MatchInstruction(hp2,A_MOV,[]) and
  5824. (taicpu(hp2).oper[0]^.typ = top_const) and
  5825. (
  5826. (
  5827. (taicpu(hp2).oper[1]^.typ = top_reg)
  5828. {$ifdef i386}
  5829. { Under i386, ESI, EDI, EBP and ESP
  5830. don't have an 8-bit representation }
  5831. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5832. {$endif i386}
  5833. ) or (
  5834. {$ifdef i386}
  5835. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5836. {$endif i386}
  5837. (taicpu(hp2).opsize = S_B)
  5838. )
  5839. ) and
  5840. GetNextInstruction(hp2, hp3) and
  5841. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5842. (
  5843. (taicpu(hp3).opcode=A_RET) or
  5844. (
  5845. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5846. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5847. )
  5848. ) and
  5849. GetNextInstruction(hp3, hp4) and
  5850. SkipAligns(hp4, hp4) and
  5851. (hp4.typ=ait_label) and
  5852. (tai_label(hp4).labsym=JumpLoc) and
  5853. (
  5854. not (cs_opt_size in current_settings.optimizerswitches) or
  5855. { If the initial jump is the label's only reference, then it will
  5856. become a dead label if the other conditions are met and hence
  5857. remove at least 2 instructions, including a jump }
  5858. (JumpLoc.getrefs = 1)
  5859. ) and
  5860. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5861. that will be optimised out }
  5862. GetNextInstruction(hp4, hp5) and
  5863. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5864. (taicpu(hp5).oper[0]^.typ = top_const) and
  5865. (
  5866. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5867. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5868. ) and
  5869. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5870. GetNextInstruction(hp5,hp6) and
  5871. (
  5872. (hp6.typ<>ait_label) or
  5873. SkipLabels(hp6, hp6)
  5874. ) and
  5875. (hp6.typ=ait_instruction) then
  5876. begin
  5877. { First, let's look at the two jumps that are hp3 and hp6 }
  5878. if not
  5879. (
  5880. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5881. (
  5882. (taicpu(hp6).opcode=A_RET) or
  5883. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5884. )
  5885. ) then
  5886. { If condition is False, then the JMP/RET instructions matched conventionally }
  5887. begin
  5888. { See if one of the jumps can be instantly converted into a RET }
  5889. if (taicpu(hp3).opcode=A_JMP) then
  5890. begin
  5891. { Reuse hp5 }
  5892. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5893. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5894. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5895. Exit;
  5896. if MatchInstruction(hp5, A_RET, []) then
  5897. begin
  5898. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5899. ConvertJumpToRET(hp3, hp5);
  5900. Result := True;
  5901. end
  5902. else
  5903. Exit;
  5904. end;
  5905. if (taicpu(hp6).opcode=A_JMP) then
  5906. begin
  5907. { Reuse hp5 }
  5908. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5909. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5910. Exit;
  5911. if MatchInstruction(hp5, A_RET, []) then
  5912. begin
  5913. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5914. ConvertJumpToRET(hp6, hp5);
  5915. Result := True;
  5916. end
  5917. else
  5918. Exit;
  5919. end;
  5920. if not
  5921. (
  5922. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5923. (
  5924. (taicpu(hp6).opcode=A_RET) or
  5925. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5926. )
  5927. ) then
  5928. { Still doesn't match }
  5929. Exit;
  5930. end;
  5931. if (taicpu(hp2).oper[0]^.val = 1) then
  5932. begin
  5933. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5934. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5935. end
  5936. else
  5937. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5938. if taicpu(hp2).opsize=S_B then
  5939. begin
  5940. if taicpu(hp2).oper[1]^.typ = top_reg then
  5941. begin
  5942. SecondReg := taicpu(hp2).oper[1]^.reg;
  5943. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5944. end
  5945. else
  5946. begin
  5947. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5948. SecondReg := NR_NO;
  5949. end;
  5950. hp_pos := p;
  5951. hp_allocstart := hp4;
  5952. end
  5953. else
  5954. begin
  5955. { Will be a register because the size can't be S_B otherwise }
  5956. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5957. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5958. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5959. if (cs_opt_size in current_settings.optimizerswitches) then
  5960. begin
  5961. { Favour using MOVZX when optimising for size }
  5962. case taicpu(hp2).opsize of
  5963. S_W:
  5964. NewSize := S_BW;
  5965. S_L:
  5966. NewSize := S_BL;
  5967. {$ifdef x86_64}
  5968. S_Q:
  5969. begin
  5970. NewSize := S_BL;
  5971. { Will implicitly zero-extend to 64-bit }
  5972. setsubreg(SecondReg, R_SUBD);
  5973. end;
  5974. {$endif x86_64}
  5975. else
  5976. InternalError(2022101301);
  5977. end;
  5978. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5979. { Inserting it right before p will guarantee that the flags are also tracked }
  5980. Asml.InsertBefore(hp5, p);
  5981. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5982. hp_pos := hp5;
  5983. hp_allocstart := hp4;
  5984. end
  5985. else
  5986. begin
  5987. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5988. { Inserting it right before p will guarantee that the flags are also tracked }
  5989. Asml.InsertBefore(hp5, p);
  5990. hp_pos := p;
  5991. hp_allocstart := hp5;
  5992. end;
  5993. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5994. end;
  5995. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5996. taicpu(hp4).condition := taicpu(p).condition;
  5997. asml.InsertBefore(hp4, hp_pos);
  5998. if taicpu(hp3).is_jmp then
  5999. begin
  6000. JumpLoc.decrefs;
  6001. MakeUnconditional(taicpu(p));
  6002. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6003. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6004. end
  6005. else
  6006. ConvertJumpToRET(p, hp3);
  6007. if SecondReg <> NR_NO then
  6008. { Ensure the destination register is allocated over this region }
  6009. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6010. if (JumpLoc.getrefs = 0) then
  6011. RemoveDeadCodeAfterJump(hp3);
  6012. Result:=true;
  6013. exit;
  6014. end;
  6015. end;
  6016. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6017. var
  6018. hp1, hp2: tai;
  6019. ActiveReg: TRegister;
  6020. OldOffset: asizeint;
  6021. ThisConst: TCGInt;
  6022. function RegDeallocated: Boolean;
  6023. begin
  6024. TransferUsedRegs(TmpUsedRegs);
  6025. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6026. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6027. end;
  6028. begin
  6029. Result:=false;
  6030. hp1 := nil;
  6031. { replace
  6032. subX const,%reg1
  6033. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6034. dealloc %reg1
  6035. by
  6036. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6037. }
  6038. if MatchOpType(taicpu(p),top_const,top_reg) then
  6039. begin
  6040. ActiveReg := taicpu(p).oper[1]^.reg;
  6041. { Ensures the entire register was updated }
  6042. if (taicpu(p).opsize >= S_L) and
  6043. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6044. MatchInstruction(hp1,A_LEA,[]) and
  6045. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6046. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6047. (
  6048. { Cover the case where the register in the reference is also the destination register }
  6049. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6050. (
  6051. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6052. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6053. RegDeallocated
  6054. )
  6055. ) then
  6056. begin
  6057. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6058. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6059. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6060. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6061. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6062. {$ifdef x86_64}
  6063. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6064. begin
  6065. { Overflow; abort }
  6066. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6067. end
  6068. else
  6069. {$endif x86_64}
  6070. begin
  6071. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6072. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6073. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6074. RemoveCurrentP(p, hp1)
  6075. else
  6076. RemoveCurrentP(p);
  6077. result:=true;
  6078. Exit;
  6079. end;
  6080. end;
  6081. if (
  6082. { Save calling GetNextInstructionUsingReg again }
  6083. Assigned(hp1) or
  6084. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6085. ) and
  6086. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6087. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6088. begin
  6089. if taicpu(hp1).oper[0]^.typ = top_const then
  6090. begin
  6091. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6092. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6093. Result := True;
  6094. { Handle any overflows }
  6095. case taicpu(p).opsize of
  6096. S_B:
  6097. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6098. S_W:
  6099. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6100. S_L:
  6101. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6102. {$ifdef x86_64}
  6103. S_Q:
  6104. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6105. { Overflow; abort }
  6106. Result := False
  6107. else
  6108. taicpu(p).oper[0]^.val := ThisConst;
  6109. {$endif x86_64}
  6110. else
  6111. InternalError(2021102611);
  6112. end;
  6113. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6114. if Result then
  6115. begin
  6116. if (taicpu(p).oper[0]^.val < 0) and
  6117. (
  6118. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6119. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6120. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6121. ) then
  6122. begin
  6123. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6124. taicpu(p).opcode := A_SUB;
  6125. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6126. end
  6127. else
  6128. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6129. RemoveInstruction(hp1);
  6130. end;
  6131. end
  6132. else
  6133. begin
  6134. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6135. TransferUsedRegs(TmpUsedRegs);
  6136. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6137. hp2 := p;
  6138. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6139. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6140. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6141. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6142. begin
  6143. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6144. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6145. Asml.Remove(p);
  6146. Asml.InsertAfter(p, hp1);
  6147. p := hp1;
  6148. Result := True;
  6149. Exit;
  6150. end;
  6151. end;
  6152. end;
  6153. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6154. { * change "sub/add const1, reg" or "dec reg" followed by
  6155. "sub const2, reg" to one "sub ..., reg" }
  6156. {$ifdef i386}
  6157. if (taicpu(p).oper[0]^.val = 2) and
  6158. (ActiveReg = NR_ESP) and
  6159. { Don't do the sub/push optimization if the sub }
  6160. { comes from setting up the stack frame (JM) }
  6161. (not(GetLastInstruction(p,hp1)) or
  6162. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6163. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6164. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6165. begin
  6166. hp1 := tai(p.next);
  6167. while Assigned(hp1) and
  6168. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6169. not RegReadByInstruction(NR_ESP,hp1) and
  6170. not RegModifiedByInstruction(NR_ESP,hp1) do
  6171. hp1 := tai(hp1.next);
  6172. if Assigned(hp1) and
  6173. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6174. begin
  6175. taicpu(hp1).changeopsize(S_L);
  6176. if taicpu(hp1).oper[0]^.typ=top_reg then
  6177. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6178. hp1 := tai(p.next);
  6179. RemoveCurrentp(p, hp1);
  6180. Result:=true;
  6181. exit;
  6182. end;
  6183. end;
  6184. {$endif i386}
  6185. if DoArithCombineOpt(p) then
  6186. Result:=true;
  6187. end;
  6188. end;
  6189. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6190. var
  6191. TmpBool1,TmpBool2 : Boolean;
  6192. tmpref : treference;
  6193. hp1,hp2: tai;
  6194. mask, shiftval: tcgint;
  6195. begin
  6196. Result:=false;
  6197. { All these optimisations work on "shl/sal const,%reg" }
  6198. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6199. Exit;
  6200. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6201. (taicpu(p).oper[0]^.val <= 3) then
  6202. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6203. begin
  6204. { should we check the next instruction? }
  6205. TmpBool1 := True;
  6206. { have we found an add/sub which could be
  6207. integrated in the lea? }
  6208. TmpBool2 := False;
  6209. reference_reset(tmpref,2,[]);
  6210. TmpRef.index := taicpu(p).oper[1]^.reg;
  6211. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6212. while TmpBool1 and
  6213. GetNextInstruction(p, hp1) and
  6214. (tai(hp1).typ = ait_instruction) and
  6215. ((((taicpu(hp1).opcode = A_ADD) or
  6216. (taicpu(hp1).opcode = A_SUB)) and
  6217. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6218. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6219. (((taicpu(hp1).opcode = A_INC) or
  6220. (taicpu(hp1).opcode = A_DEC)) and
  6221. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6222. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6223. ((taicpu(hp1).opcode = A_LEA) and
  6224. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6225. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6226. (not GetNextInstruction(hp1,hp2) or
  6227. not instrReadsFlags(hp2)) Do
  6228. begin
  6229. TmpBool1 := False;
  6230. if taicpu(hp1).opcode=A_LEA then
  6231. begin
  6232. if (TmpRef.base = NR_NO) and
  6233. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6234. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6235. { Segment register isn't a concern here }
  6236. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6237. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6238. begin
  6239. TmpBool1 := True;
  6240. TmpBool2 := True;
  6241. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6242. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6243. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6244. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6245. RemoveInstruction(hp1);
  6246. end
  6247. end
  6248. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6249. begin
  6250. TmpBool1 := True;
  6251. TmpBool2 := True;
  6252. case taicpu(hp1).opcode of
  6253. A_ADD:
  6254. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6255. A_SUB:
  6256. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6257. else
  6258. internalerror(2019050536);
  6259. end;
  6260. RemoveInstruction(hp1);
  6261. end
  6262. else
  6263. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6264. (((taicpu(hp1).opcode = A_ADD) and
  6265. (TmpRef.base = NR_NO)) or
  6266. (taicpu(hp1).opcode = A_INC) or
  6267. (taicpu(hp1).opcode = A_DEC)) then
  6268. begin
  6269. TmpBool1 := True;
  6270. TmpBool2 := True;
  6271. case taicpu(hp1).opcode of
  6272. A_ADD:
  6273. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6274. A_INC:
  6275. inc(TmpRef.offset);
  6276. A_DEC:
  6277. dec(TmpRef.offset);
  6278. else
  6279. internalerror(2019050535);
  6280. end;
  6281. RemoveInstruction(hp1);
  6282. end;
  6283. end;
  6284. if TmpBool2
  6285. {$ifndef x86_64}
  6286. or
  6287. ((current_settings.optimizecputype < cpu_Pentium2) and
  6288. (taicpu(p).oper[0]^.val <= 3) and
  6289. not(cs_opt_size in current_settings.optimizerswitches))
  6290. {$endif x86_64}
  6291. then
  6292. begin
  6293. if not(TmpBool2) and
  6294. (taicpu(p).oper[0]^.val=1) then
  6295. begin
  6296. taicpu(p).opcode := A_ADD;
  6297. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6298. end
  6299. else
  6300. begin
  6301. taicpu(p).opcode := A_LEA;
  6302. taicpu(p).loadref(0, TmpRef);
  6303. end;
  6304. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6305. Result := True;
  6306. end;
  6307. end
  6308. {$ifndef x86_64}
  6309. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6310. begin
  6311. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6312. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6313. (unlike shl, which is only Tairable in the U pipe) }
  6314. if taicpu(p).oper[0]^.val=1 then
  6315. begin
  6316. taicpu(p).opcode := A_ADD;
  6317. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6318. Result := True;
  6319. end
  6320. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6321. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6322. else if (taicpu(p).opsize = S_L) and
  6323. (taicpu(p).oper[0]^.val<= 3) then
  6324. begin
  6325. reference_reset(tmpref,2,[]);
  6326. TmpRef.index := taicpu(p).oper[1]^.reg;
  6327. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6328. taicpu(p).opcode := A_LEA;
  6329. taicpu(p).loadref(0, TmpRef);
  6330. Result := True;
  6331. end;
  6332. end
  6333. {$endif x86_64}
  6334. else if
  6335. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6336. (
  6337. (
  6338. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6339. SetAndTest(hp1, hp2)
  6340. {$ifdef x86_64}
  6341. ) or
  6342. (
  6343. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6344. GetNextInstruction(hp1, hp2) and
  6345. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6346. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6347. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6348. {$endif x86_64}
  6349. )
  6350. ) and
  6351. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6352. begin
  6353. { Change:
  6354. shl x, %reg1
  6355. mov -(1<<x), %reg2
  6356. and %reg2, %reg1
  6357. Or:
  6358. shl x, %reg1
  6359. and -(1<<x), %reg1
  6360. To just:
  6361. shl x, %reg1
  6362. Since the and operation only zeroes bits that are already zero from the shl operation
  6363. }
  6364. case taicpu(p).oper[0]^.val of
  6365. 8:
  6366. mask:=$FFFFFFFFFFFFFF00;
  6367. 16:
  6368. mask:=$FFFFFFFFFFFF0000;
  6369. 32:
  6370. mask:=$FFFFFFFF00000000;
  6371. 63:
  6372. { Constant pre-calculated to prevent overflow errors with Int64 }
  6373. mask:=$8000000000000000;
  6374. else
  6375. begin
  6376. if taicpu(p).oper[0]^.val >= 64 then
  6377. { Shouldn't happen realistically, since the register
  6378. is guaranteed to be set to zero at this point }
  6379. mask := 0
  6380. else
  6381. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6382. end;
  6383. end;
  6384. if taicpu(hp1).oper[0]^.val = mask then
  6385. begin
  6386. { Everything checks out, perform the optimisation, as long as
  6387. the FLAGS register isn't being used}
  6388. TransferUsedRegs(TmpUsedRegs);
  6389. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6390. {$ifdef x86_64}
  6391. if (hp1 <> hp2) then
  6392. begin
  6393. { "shl/mov/and" version }
  6394. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6395. { Don't do the optimisation if the FLAGS register is in use }
  6396. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6397. begin
  6398. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6399. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6400. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6401. begin
  6402. RemoveInstruction(hp1);
  6403. Result := True;
  6404. end;
  6405. { Only set Result to True if the 'mov' instruction was removed }
  6406. RemoveInstruction(hp2);
  6407. end;
  6408. end
  6409. else
  6410. {$endif x86_64}
  6411. begin
  6412. { "shl/and" version }
  6413. { Don't do the optimisation if the FLAGS register is in use }
  6414. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6415. begin
  6416. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6417. RemoveInstruction(hp1);
  6418. Result := True;
  6419. end;
  6420. end;
  6421. Exit;
  6422. end
  6423. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6424. begin
  6425. { Even if the mask doesn't allow for its removal, we might be
  6426. able to optimise the mask for the "shl/and" version, which
  6427. may permit other peephole optimisations }
  6428. {$ifdef DEBUG_AOPTCPU}
  6429. mask := taicpu(hp1).oper[0]^.val and mask;
  6430. if taicpu(hp1).oper[0]^.val <> mask then
  6431. begin
  6432. DebugMsg(
  6433. SPeepholeOptimization +
  6434. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6435. ' to $' + debug_tostr(mask) +
  6436. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6437. taicpu(hp1).oper[0]^.val := mask;
  6438. end;
  6439. {$else DEBUG_AOPTCPU}
  6440. { If debugging is off, just set the operand even if it's the same }
  6441. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6442. {$endif DEBUG_AOPTCPU}
  6443. end;
  6444. end;
  6445. {
  6446. change
  6447. shl/sal const,reg
  6448. <op> ...(...,reg,1),...
  6449. into
  6450. <op> ...(...,reg,1 shl const),...
  6451. if const in 1..3
  6452. }
  6453. if MatchOpType(taicpu(p), top_const, top_reg) and
  6454. (taicpu(p).oper[0]^.val in [1..3]) and
  6455. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6456. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6457. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6458. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6459. MatchOpType(taicpu(hp1),top_ref))
  6460. ) and
  6461. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6462. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6463. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6464. begin
  6465. TransferUsedRegs(TmpUsedRegs);
  6466. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6467. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6468. begin
  6469. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6470. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6471. RemoveCurrentP(p);
  6472. Result:=true;
  6473. exit;
  6474. end;
  6475. end;
  6476. if MatchOpType(taicpu(p), top_const, top_reg) and
  6477. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6478. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6479. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6480. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6481. begin
  6482. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6483. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6484. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6485. {$ifdef x86_64}
  6486. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6487. {$endif x86_64}
  6488. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6489. begin
  6490. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6491. taicpu(hp1).opcode:=A_MOV;
  6492. taicpu(hp1).oper[0]^.val:=0;
  6493. end
  6494. else
  6495. begin
  6496. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6497. taicpu(hp1).oper[0]^.val:=shiftval;
  6498. end;
  6499. RemoveCurrentP(p);
  6500. Result:=true;
  6501. exit;
  6502. end;
  6503. end;
  6504. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6505. begin
  6506. case shr_size of
  6507. S_B:
  6508. { No valid combinations }
  6509. Result := False;
  6510. S_W:
  6511. Result := (Shift >= 8) and (movz_size = S_BW);
  6512. S_L:
  6513. Result :=
  6514. (Shift >= 24) { Any opsize is valid for this shift } or
  6515. ((Shift >= 16) and (movz_size = S_WL));
  6516. {$ifdef x86_64}
  6517. S_Q:
  6518. Result :=
  6519. (Shift >= 56) { Any opsize is valid for this shift } or
  6520. ((Shift >= 48) and (movz_size = S_WL));
  6521. {$endif x86_64}
  6522. else
  6523. InternalError(2022081510);
  6524. end;
  6525. end;
  6526. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6527. var
  6528. hp1, hp2: tai;
  6529. Shift: TCGInt;
  6530. LimitSize: Topsize;
  6531. DoNotMerge: Boolean;
  6532. begin
  6533. Result := False;
  6534. { All these optimisations work on "shr const,%reg" }
  6535. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6536. Exit;
  6537. DoNotMerge := False;
  6538. Shift := taicpu(p).oper[0]^.val;
  6539. LimitSize := taicpu(p).opsize;
  6540. hp1 := p;
  6541. repeat
  6542. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6543. Exit;
  6544. case taicpu(hp1).opcode of
  6545. A_TEST, A_CMP, A_Jcc:
  6546. { Skip over conditional jumps and relevant comparisons }
  6547. Continue;
  6548. A_MOVZX:
  6549. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6550. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6551. begin
  6552. { Since the original register is being read as is, subsequent
  6553. SHRs must not be merged at this point }
  6554. DoNotMerge := True;
  6555. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6556. begin
  6557. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6558. begin
  6559. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6560. taicpu(hp1).opcode := A_MOV;
  6561. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6562. case taicpu(hp1).opsize of
  6563. S_BW:
  6564. taicpu(hp1).opsize := S_W;
  6565. S_BL, S_WL:
  6566. taicpu(hp1).opsize := S_L;
  6567. else
  6568. InternalError(2022081503);
  6569. end;
  6570. { p itself hasn't changed, so no need to set Result to True }
  6571. Include(OptsToCheck, aoc_ForceNewIteration);
  6572. { See if there's anything afterwards that can be
  6573. optimised, since the input register hasn't changed }
  6574. Continue;
  6575. end;
  6576. { NOTE: If the MOVZX instruction reads and writes the same
  6577. register, defer this to the post-peephole optimisation stage }
  6578. Exit;
  6579. end;
  6580. end;
  6581. A_SHL, A_SAL, A_SHR:
  6582. if (taicpu(hp1).opsize <= LimitSize) and
  6583. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6584. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6585. begin
  6586. { Make sure the sizes don't exceed the register size limit
  6587. (measured by the shift value falling below the limit) }
  6588. if taicpu(hp1).opsize < LimitSize then
  6589. LimitSize := taicpu(hp1).opsize;
  6590. if taicpu(hp1).opcode = A_SHR then
  6591. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6592. else
  6593. begin
  6594. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6595. DoNotMerge := True;
  6596. end;
  6597. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6598. Exit;
  6599. { Since we've established that the combined shift is within
  6600. limits, we can actually combine the adjacent SHR
  6601. instructions even if they're different sizes }
  6602. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6603. begin
  6604. hp2 := tai(hp1.Previous);
  6605. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6606. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6607. RemoveInstruction(hp1);
  6608. hp1 := hp2;
  6609. { Though p has changed, only the constant has, and its
  6610. effects can still be detected on the next iteration of
  6611. the repeat..until loop }
  6612. Include(OptsToCheck, aoc_ForceNewIteration);
  6613. end;
  6614. { Move onto the next instruction }
  6615. Continue;
  6616. end;
  6617. else
  6618. ;
  6619. end;
  6620. Break;
  6621. until False;
  6622. end;
  6623. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6624. var
  6625. CurrentRef: TReference;
  6626. FullReg: TRegister;
  6627. hp1, hp2: tai;
  6628. begin
  6629. Result := False;
  6630. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6631. Exit;
  6632. { We assume you've checked if the operand is actually a reference by
  6633. this point. If it isn't, you'll most likely get an access violation }
  6634. CurrentRef := first_mov.oper[1]^.ref^;
  6635. { Memory must be aligned }
  6636. if (CurrentRef.offset mod 4) <> 0 then
  6637. Exit;
  6638. Inc(CurrentRef.offset);
  6639. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6640. if MatchOperand(second_mov.oper[0]^, 0) and
  6641. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6642. GetNextInstruction(second_mov, hp1) and
  6643. (hp1.typ = ait_instruction) and
  6644. (taicpu(hp1).opcode = A_MOV) and
  6645. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6646. (taicpu(hp1).oper[0]^.val = 0) then
  6647. begin
  6648. Inc(CurrentRef.offset);
  6649. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6650. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6651. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6652. begin
  6653. case taicpu(hp1).opsize of
  6654. S_B:
  6655. if GetNextInstruction(hp1, hp2) and
  6656. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6657. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6658. (taicpu(hp2).oper[0]^.val = 0) then
  6659. begin
  6660. Inc(CurrentRef.offset);
  6661. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6662. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6663. (taicpu(hp2).opsize = S_B) then
  6664. begin
  6665. RemoveInstruction(hp1);
  6666. RemoveInstruction(hp2);
  6667. first_mov.opsize := S_L;
  6668. if first_mov.oper[0]^.typ = top_reg then
  6669. begin
  6670. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6671. { Reuse second_mov as a MOVZX instruction }
  6672. second_mov.opcode := A_MOVZX;
  6673. second_mov.opsize := S_BL;
  6674. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6675. second_mov.loadreg(1, FullReg);
  6676. first_mov.oper[0]^.reg := FullReg;
  6677. asml.Remove(second_mov);
  6678. asml.InsertBefore(second_mov, first_mov);
  6679. end
  6680. else
  6681. { It's a value }
  6682. begin
  6683. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6684. RemoveInstruction(second_mov);
  6685. end;
  6686. Result := True;
  6687. Exit;
  6688. end;
  6689. end;
  6690. S_W:
  6691. begin
  6692. RemoveInstruction(hp1);
  6693. first_mov.opsize := S_L;
  6694. if first_mov.oper[0]^.typ = top_reg then
  6695. begin
  6696. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6697. { Reuse second_mov as a MOVZX instruction }
  6698. second_mov.opcode := A_MOVZX;
  6699. second_mov.opsize := S_BL;
  6700. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6701. second_mov.loadreg(1, FullReg);
  6702. first_mov.oper[0]^.reg := FullReg;
  6703. asml.Remove(second_mov);
  6704. asml.InsertBefore(second_mov, first_mov);
  6705. end
  6706. else
  6707. { It's a value }
  6708. begin
  6709. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6710. RemoveInstruction(second_mov);
  6711. end;
  6712. Result := True;
  6713. Exit;
  6714. end;
  6715. else
  6716. ;
  6717. end;
  6718. end;
  6719. end;
  6720. end;
  6721. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6722. { returns true if a "continue" should be done after this optimization }
  6723. var
  6724. hp1, hp2, hp3: tai;
  6725. begin
  6726. Result := false;
  6727. hp3 := nil;
  6728. if MatchOpType(taicpu(p),top_ref) and
  6729. GetNextInstruction(p, hp1) and
  6730. (hp1.typ = ait_instruction) and
  6731. (((taicpu(hp1).opcode = A_FLD) and
  6732. (taicpu(p).opcode = A_FSTP)) or
  6733. ((taicpu(p).opcode = A_FISTP) and
  6734. (taicpu(hp1).opcode = A_FILD))) and
  6735. MatchOpType(taicpu(hp1),top_ref) and
  6736. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6737. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6738. begin
  6739. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6740. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6741. GetNextInstruction(hp1, hp2) and
  6742. (((hp2.typ = ait_instruction) and
  6743. IsExitCode(hp2) and
  6744. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6745. not(assigned(current_procinfo.procdef.funcretsym) and
  6746. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6747. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6748. { fstp <temp>
  6749. fld <temp>
  6750. <dealloc> <temp>
  6751. }
  6752. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6753. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6754. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6755. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6756. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6757. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6758. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6759. )
  6760. )
  6761. ) then
  6762. begin
  6763. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6764. RemoveInstruction(hp1);
  6765. RemoveCurrentP(p, hp2);
  6766. { first case: exit code }
  6767. if hp2.typ = ait_instruction then
  6768. RemoveLastDeallocForFuncRes(p);
  6769. Result := true;
  6770. end
  6771. else
  6772. { we can do this only in fast math mode as fstp is rounding ...
  6773. ... still disabled as it breaks the compiler and/or rtl }
  6774. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6775. { ... or if another fstp equal to the first one follows }
  6776. GetNextInstruction(hp1,hp2) and
  6777. (hp2.typ = ait_instruction) and
  6778. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6779. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6780. begin
  6781. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6782. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6783. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6784. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6785. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6786. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6787. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6788. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6789. ) then
  6790. begin
  6791. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6792. RemoveCurrentP(p,hp2);
  6793. RemoveInstruction(hp1);
  6794. Result := true;
  6795. end
  6796. else if { fst can't store an extended/comp value }
  6797. (taicpu(p).opsize <> S_FX) and
  6798. (taicpu(p).opsize <> S_IQ) then
  6799. begin
  6800. if (taicpu(p).opcode = A_FSTP) then
  6801. taicpu(p).opcode := A_FST
  6802. else
  6803. taicpu(p).opcode := A_FIST;
  6804. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6805. RemoveInstruction(hp1);
  6806. Result := true;
  6807. end;
  6808. end;
  6809. end;
  6810. end;
  6811. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6812. var
  6813. hp1, hp2, hp3: tai;
  6814. begin
  6815. result:=false;
  6816. if MatchOpType(taicpu(p),top_reg) and
  6817. GetNextInstruction(p, hp1) and
  6818. (hp1.typ = Ait_Instruction) and
  6819. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6820. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6821. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6822. { change to
  6823. fld reg fxxx reg,st
  6824. fxxxp st, st1 (hp1)
  6825. Remark: non commutative operations must be reversed!
  6826. }
  6827. begin
  6828. case taicpu(hp1).opcode Of
  6829. A_FMULP,A_FADDP,
  6830. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6831. begin
  6832. case taicpu(hp1).opcode Of
  6833. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6834. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6835. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6836. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6837. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6838. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6839. else
  6840. internalerror(2019050534);
  6841. end;
  6842. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6843. taicpu(hp1).oper[1]^.reg := NR_ST;
  6844. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6845. RemoveCurrentP(p, hp1);
  6846. Result:=true;
  6847. exit;
  6848. end;
  6849. else
  6850. ;
  6851. end;
  6852. end
  6853. else
  6854. if MatchOpType(taicpu(p),top_ref) and
  6855. GetNextInstruction(p, hp2) and
  6856. (hp2.typ = Ait_Instruction) and
  6857. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6858. (taicpu(p).opsize in [S_FS, S_FL]) and
  6859. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6860. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6861. if GetLastInstruction(p, hp1) and
  6862. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6863. MatchOpType(taicpu(hp1),top_ref) and
  6864. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6865. if ((taicpu(hp2).opcode = A_FMULP) or
  6866. (taicpu(hp2).opcode = A_FADDP)) then
  6867. { change to
  6868. fld/fst mem1 (hp1) fld/fst mem1
  6869. fld mem1 (p) fadd/
  6870. faddp/ fmul st, st
  6871. fmulp st, st1 (hp2) }
  6872. begin
  6873. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6874. RemoveCurrentP(p, hp1);
  6875. if (taicpu(hp2).opcode = A_FADDP) then
  6876. taicpu(hp2).opcode := A_FADD
  6877. else
  6878. taicpu(hp2).opcode := A_FMUL;
  6879. taicpu(hp2).oper[1]^.reg := NR_ST;
  6880. end
  6881. else
  6882. { change to
  6883. fld/fst mem1 (hp1) fld/fst mem1
  6884. fld mem1 (p) fld st
  6885. }
  6886. begin
  6887. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6888. taicpu(p).changeopsize(S_FL);
  6889. taicpu(p).loadreg(0,NR_ST);
  6890. end
  6891. else
  6892. begin
  6893. case taicpu(hp2).opcode Of
  6894. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6895. { change to
  6896. fld/fst mem1 (hp1) fld/fst mem1
  6897. fld mem2 (p) fxxx mem2
  6898. fxxxp st, st1 (hp2) }
  6899. begin
  6900. case taicpu(hp2).opcode Of
  6901. A_FADDP: taicpu(p).opcode := A_FADD;
  6902. A_FMULP: taicpu(p).opcode := A_FMUL;
  6903. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6904. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6905. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6906. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6907. else
  6908. internalerror(2019050533);
  6909. end;
  6910. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6911. RemoveInstruction(hp2);
  6912. end
  6913. else
  6914. ;
  6915. end
  6916. end
  6917. end;
  6918. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6919. begin
  6920. Result := condition_in(cond1, cond2) or
  6921. { Not strictly subsets due to the actual flags checked, but because we're
  6922. comparing integers, E is a subset of AE and GE and their aliases }
  6923. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6924. end;
  6925. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6926. var
  6927. v: TCGInt;
  6928. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6929. FirstMatch, TempBool: Boolean;
  6930. NewReg: TRegister;
  6931. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6932. begin
  6933. Result:=false;
  6934. { All these optimisations need a next instruction }
  6935. if not GetNextInstruction(p, hp1) then
  6936. Exit;
  6937. { Search for:
  6938. cmp ###,###
  6939. j(c1) @lbl1
  6940. ...
  6941. @lbl:
  6942. cmp ###,### (same comparison as above)
  6943. j(c2) @lbl2
  6944. If c1 is a subset of c2, change to:
  6945. cmp ###,###
  6946. j(c1) @lbl2
  6947. (@lbl1 may become a dead label as a result)
  6948. }
  6949. { Also handle cases where there are multiple jumps in a row }
  6950. p_jump := hp1;
  6951. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6952. begin
  6953. if IsJumpToLabel(taicpu(p_jump)) then
  6954. begin
  6955. { Do jump optimisations first in case the condition becomes
  6956. unnecessary }
  6957. TempBool := True;
  6958. if DoJumpOptimizations(p_jump, TempBool) or
  6959. not TempBool then
  6960. begin
  6961. if Assigned(p_jump) then
  6962. begin
  6963. hp1 := p_jump;
  6964. if (p_jump.typ in [ait_align]) then
  6965. SkipAligns(p_jump, p_jump);
  6966. { CollapseZeroDistJump will be set to the label after the
  6967. jump if it optimises, whether or not it's live or dead }
  6968. if (p_jump.typ in [ait_label]) and
  6969. not (tai_label(p_jump).labsym.is_used) then
  6970. GetNextInstruction(p_jump, p_jump);
  6971. end;
  6972. TransferUsedRegs(TmpUsedRegs);
  6973. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6974. if not Assigned(p_jump) or
  6975. (
  6976. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6977. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6978. ) then
  6979. begin
  6980. { No more conditional jumps; conditional statement is no longer required }
  6981. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6982. RemoveCurrentP(p);
  6983. Result := True;
  6984. Exit;
  6985. end;
  6986. hp1 := p_jump;
  6987. Include(OptsToCheck, aoc_ForceNewIteration);
  6988. Continue;
  6989. end;
  6990. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6991. if GetNextInstruction(p_jump, hp2) and
  6992. (
  6993. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6994. not TempBool
  6995. ) then
  6996. begin
  6997. hp1 := p_jump;
  6998. Include(OptsToCheck, aoc_ForceNewIteration);
  6999. Continue;
  7000. end;
  7001. p_label := nil;
  7002. if Assigned(JumpLabel) then
  7003. p_label := getlabelwithsym(JumpLabel);
  7004. if Assigned(p_label) and
  7005. GetNextInstruction(p_label, p_dist) and
  7006. MatchInstruction(p_dist, A_CMP, []) and
  7007. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7008. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7009. GetNextInstruction(p_dist, hp1_dist) and
  7010. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7011. begin
  7012. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7013. if JumpLabel = JumpLabel_dist then
  7014. { This is an infinite loop }
  7015. Exit;
  7016. { Best optimisation when the first condition is a subset (or equal) of the second }
  7017. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7018. begin
  7019. { Any registers used here will already be allocated }
  7020. if Assigned(JumpLabel) then
  7021. JumpLabel.DecRefs;
  7022. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7023. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7024. Result := True;
  7025. { Don't exit yet. Since p and p_jump haven't actually been
  7026. removed, we can check for more on this iteration }
  7027. end
  7028. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7029. GetNextInstruction(hp1_dist, hp1_label) and
  7030. SkipAligns(hp1_label, hp1_label) and
  7031. (hp1_label.typ = ait_label) then
  7032. begin
  7033. JumpLabel_far := tai_label(hp1_label).labsym;
  7034. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7035. { This is an infinite loop }
  7036. Exit;
  7037. if Assigned(JumpLabel_far) then
  7038. begin
  7039. { In this situation, if the first jump branches, the second one will never,
  7040. branch so change the destination label to after the second jump }
  7041. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7042. if Assigned(JumpLabel) then
  7043. JumpLabel.DecRefs;
  7044. JumpLabel_far.IncRefs;
  7045. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7046. Result := True;
  7047. { Don't exit yet. Since p and p_jump haven't actually been
  7048. removed, we can check for more on this iteration }
  7049. Continue;
  7050. end;
  7051. end;
  7052. end;
  7053. end;
  7054. { Search for:
  7055. cmp ###,###
  7056. j(c1) @lbl1
  7057. cmp ###,### (same as first)
  7058. Remove second cmp
  7059. }
  7060. if GetNextInstruction(p_jump, hp2) and
  7061. (
  7062. (
  7063. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7064. (
  7065. (
  7066. MatchOpType(taicpu(p), top_const, top_reg) and
  7067. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7068. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7069. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7070. ) or (
  7071. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7072. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7073. )
  7074. )
  7075. ) or (
  7076. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7077. MatchOperand(taicpu(p).oper[0]^, 0) and
  7078. (taicpu(p).oper[1]^.typ = top_reg) and
  7079. MatchInstruction(hp2, A_TEST, []) and
  7080. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7081. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7082. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7083. )
  7084. ) then
  7085. begin
  7086. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7087. RemoveInstruction(hp2);
  7088. Result := True;
  7089. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7090. end;
  7091. GetNextInstruction(p_jump, p_jump);
  7092. end;
  7093. if (
  7094. { Don't call GetNextInstruction again if we already have it }
  7095. (hp1 = p_jump) or
  7096. GetNextInstruction(p, hp1)
  7097. ) and
  7098. MatchInstruction(hp1, A_Jcc, []) and
  7099. IsJumpToLabel(taicpu(hp1)) and
  7100. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7101. GetNextInstruction(hp1, hp2) then
  7102. begin
  7103. {
  7104. cmp x, y (or "cmp y, x")
  7105. je @lbl
  7106. mov x, y
  7107. @lbl:
  7108. (x and y can be constants, registers or references)
  7109. Change to:
  7110. mov x, y (x and y will always be equal in the end)
  7111. @lbl: (may beceome a dead label)
  7112. Also:
  7113. cmp x, y (or "cmp y, x")
  7114. jne @lbl
  7115. mov x, y
  7116. @lbl:
  7117. (x and y can be constants, registers or references)
  7118. Change to:
  7119. Absolutely nothing! (Except @lbl if it's still live)
  7120. }
  7121. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7122. (
  7123. (
  7124. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7125. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7126. ) or (
  7127. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7128. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7129. )
  7130. ) and
  7131. GetNextInstruction(hp2, hp1_label) and
  7132. SkipAligns(hp1_label, hp1_label) and
  7133. (hp1_label.typ = ait_label) and
  7134. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7135. begin
  7136. tai_label(hp1_label).labsym.DecRefs;
  7137. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7138. begin
  7139. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7140. RemoveInstruction(hp2);
  7141. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7142. end
  7143. else
  7144. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7145. RemoveInstruction(hp1);
  7146. RemoveCurrentp(p, hp2);
  7147. Result := True;
  7148. Exit;
  7149. end;
  7150. {
  7151. Try to optimise the following:
  7152. cmp $x,### ($x and $y can be registers or constants)
  7153. je @lbl1 (only reference)
  7154. cmp $y,### (### are identical)
  7155. @Lbl:
  7156. sete %reg1
  7157. Change to:
  7158. cmp $x,###
  7159. sete %reg2 (allocate new %reg2)
  7160. cmp $y,###
  7161. sete %reg1
  7162. orb %reg2,%reg1
  7163. (dealloc %reg2)
  7164. This adds an instruction (so don't perform under -Os), but it removes
  7165. a conditional branch.
  7166. }
  7167. if not (cs_opt_size in current_settings.optimizerswitches) and
  7168. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7169. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7170. { The first operand of CMP instructions can only be a register or
  7171. immediate anyway, so no need to check }
  7172. GetNextInstruction(hp2, p_label) and
  7173. (p_label.typ = ait_label) and
  7174. (tai_label(p_label).labsym.getrefs = 1) and
  7175. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7176. GetNextInstruction(p_label, p_dist) and
  7177. MatchInstruction(p_dist, A_SETcc, []) and
  7178. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7179. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7180. begin
  7181. TransferUsedRegs(TmpUsedRegs);
  7182. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7183. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7184. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7185. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7186. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7187. { Get the instruction after the SETcc instruction so we can
  7188. allocate a new register over the entire range }
  7189. GetNextInstruction(p_dist, hp1_dist) then
  7190. begin
  7191. { Register can appear in p if it's not used afterwards, so only
  7192. allocate between hp1 and hp1_dist }
  7193. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7194. if NewReg <> NR_NO then
  7195. begin
  7196. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7197. { Change the jump instruction into a SETcc instruction }
  7198. taicpu(hp1).opcode := A_SETcc;
  7199. taicpu(hp1).opsize := S_B;
  7200. taicpu(hp1).loadreg(0, NewReg);
  7201. { This is now a dead label }
  7202. tai_label(p_label).labsym.decrefs;
  7203. { Prefer adding before the next instruction so the FLAGS
  7204. register is deallicated first }
  7205. AsmL.InsertBefore(
  7206. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7207. hp1_dist
  7208. );
  7209. Result := True;
  7210. { Don't exit yet, as p wasn't changed and hp1, while
  7211. modified, is still intact and might be optimised by the
  7212. SETcc optimisation below }
  7213. end;
  7214. end;
  7215. end;
  7216. end;
  7217. if taicpu(p).oper[0]^.typ = top_const then
  7218. begin
  7219. if (taicpu(p).oper[0]^.val = 0) and
  7220. (taicpu(p).oper[1]^.typ = top_reg) and
  7221. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7222. begin
  7223. hp2 := p;
  7224. FirstMatch := True;
  7225. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7226. anything meaningful once it's converted to "test %reg,%reg";
  7227. additionally, some jumps will always (or never) branch, so
  7228. evaluate every jump immediately following the
  7229. comparison, optimising the conditions if possible.
  7230. Similarly with SETcc... those that are always set to 0 or 1
  7231. are changed to MOV instructions }
  7232. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7233. (
  7234. GetNextInstruction(hp2, hp1) and
  7235. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7236. ) do
  7237. begin
  7238. FirstMatch := False;
  7239. case taicpu(hp1).condition of
  7240. C_B, C_C, C_NAE, C_O:
  7241. { For B/NAE:
  7242. Will never branch since an unsigned integer can never be below zero
  7243. For C/O:
  7244. Result cannot overflow because 0 is being subtracted
  7245. }
  7246. begin
  7247. if taicpu(hp1).opcode = A_Jcc then
  7248. begin
  7249. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7250. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7251. RemoveInstruction(hp1);
  7252. { Since hp1 was deleted, hp2 must not be updated }
  7253. Continue;
  7254. end
  7255. else
  7256. begin
  7257. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7258. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7259. taicpu(hp1).opcode := A_MOV;
  7260. taicpu(hp1).ops := 2;
  7261. taicpu(hp1).condition := C_None;
  7262. taicpu(hp1).opsize := S_B;
  7263. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7264. taicpu(hp1).loadconst(0, 0);
  7265. end;
  7266. end;
  7267. C_BE, C_NA:
  7268. begin
  7269. { Will only branch if equal to zero }
  7270. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7271. taicpu(hp1).condition := C_E;
  7272. end;
  7273. C_A, C_NBE:
  7274. begin
  7275. { Will only branch if not equal to zero }
  7276. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7277. taicpu(hp1).condition := C_NE;
  7278. end;
  7279. C_AE, C_NB, C_NC, C_NO:
  7280. begin
  7281. { Will always branch }
  7282. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7283. if taicpu(hp1).opcode = A_Jcc then
  7284. begin
  7285. MakeUnconditional(taicpu(hp1));
  7286. { Any jumps/set that follow will now be dead code }
  7287. RemoveDeadCodeAfterJump(taicpu(hp1));
  7288. Break;
  7289. end
  7290. else
  7291. begin
  7292. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7293. taicpu(hp1).opcode := A_MOV;
  7294. taicpu(hp1).ops := 2;
  7295. taicpu(hp1).condition := C_None;
  7296. taicpu(hp1).opsize := S_B;
  7297. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7298. taicpu(hp1).loadconst(0, 1);
  7299. end;
  7300. end;
  7301. C_None:
  7302. InternalError(2020012201);
  7303. C_P, C_PE, C_NP, C_PO:
  7304. { We can't handle parity checks and they should never be generated
  7305. after a general-purpose CMP (it's used in some floating-point
  7306. comparisons that don't use CMP) }
  7307. InternalError(2020012202);
  7308. else
  7309. { Zero/Equality, Sign, their complements and all of the
  7310. signed comparisons do not need to be converted };
  7311. end;
  7312. hp2 := hp1;
  7313. end;
  7314. { Convert the instruction to a TEST }
  7315. taicpu(p).opcode := A_TEST;
  7316. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7317. Result := True;
  7318. Exit;
  7319. end
  7320. else if (taicpu(p).oper[0]^.val = 1) and
  7321. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7322. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7323. begin
  7324. { Convert; To:
  7325. cmp $1,r/m cmp $0,r/m
  7326. jl @lbl jle @lbl
  7327. (Also do inverted conditions)
  7328. }
  7329. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7330. taicpu(p).oper[0]^.val := 0;
  7331. if taicpu(hp1).condition in [C_L, C_NGE] then
  7332. taicpu(hp1).condition := C_LE
  7333. else
  7334. taicpu(hp1).condition := C_NLE;
  7335. { If the instruction is now "cmp $0,%reg", convert it to a
  7336. TEST (and effectively do the work of the "cmp $0,%reg" in
  7337. the block above)
  7338. }
  7339. if (taicpu(p).oper[1]^.typ = top_reg) then
  7340. begin
  7341. taicpu(p).opcode := A_TEST;
  7342. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7343. end;
  7344. Result := True;
  7345. Exit;
  7346. end
  7347. else if (taicpu(p).oper[1]^.typ = top_reg)
  7348. {$ifdef x86_64}
  7349. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7350. {$endif x86_64}
  7351. then
  7352. begin
  7353. { cmp register,$8000 neg register
  7354. je target --> jo target
  7355. .... only if register is deallocated before jump.}
  7356. case Taicpu(p).opsize of
  7357. S_B: v:=$80;
  7358. S_W: v:=$8000;
  7359. S_L: v:=qword($80000000);
  7360. else
  7361. internalerror(2013112905);
  7362. end;
  7363. if (taicpu(p).oper[0]^.val=v) and
  7364. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7365. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7366. begin
  7367. TransferUsedRegs(TmpUsedRegs);
  7368. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7369. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7370. begin
  7371. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7372. Taicpu(p).opcode:=A_NEG;
  7373. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7374. Taicpu(p).clearop(1);
  7375. Taicpu(p).ops:=1;
  7376. if Taicpu(hp1).condition=C_E then
  7377. Taicpu(hp1).condition:=C_O
  7378. else
  7379. Taicpu(hp1).condition:=C_NO;
  7380. Result:=true;
  7381. exit;
  7382. end;
  7383. end;
  7384. end;
  7385. end;
  7386. if TrySwapMovCmp(p, hp1) then
  7387. begin
  7388. Result := True;
  7389. Exit;
  7390. end;
  7391. end;
  7392. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7393. var
  7394. hp1: tai;
  7395. begin
  7396. {
  7397. remove the second (v)pxor from
  7398. pxor reg,reg
  7399. ...
  7400. pxor reg,reg
  7401. }
  7402. Result:=false;
  7403. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7404. MatchOpType(taicpu(p),top_reg,top_reg) and
  7405. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7406. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7407. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7408. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7409. begin
  7410. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7411. RemoveInstruction(hp1);
  7412. Result:=true;
  7413. Exit;
  7414. end
  7415. {
  7416. replace
  7417. pxor reg1,reg1
  7418. movapd/s reg1,reg2
  7419. dealloc reg1
  7420. by
  7421. pxor reg2,reg2
  7422. }
  7423. else if GetNextInstruction(p,hp1) and
  7424. { we mix single and double opperations here because we assume that the compiler
  7425. generates vmovapd only after double operations and vmovaps only after single operations }
  7426. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7427. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7428. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7429. (taicpu(p).oper[0]^.typ=top_reg) then
  7430. begin
  7431. TransferUsedRegs(TmpUsedRegs);
  7432. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7433. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7434. begin
  7435. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7436. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7437. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7438. RemoveInstruction(hp1);
  7439. result:=true;
  7440. end;
  7441. end;
  7442. end;
  7443. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7444. var
  7445. hp1: tai;
  7446. begin
  7447. {
  7448. remove the second (v)pxor from
  7449. (v)pxor reg,reg
  7450. ...
  7451. (v)pxor reg,reg
  7452. }
  7453. Result:=false;
  7454. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7455. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7456. begin
  7457. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7458. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7459. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7460. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7461. begin
  7462. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7463. RemoveInstruction(hp1);
  7464. Result:=true;
  7465. Exit;
  7466. end;
  7467. {$ifdef x86_64}
  7468. {
  7469. replace
  7470. vpxor reg1,reg1,reg1
  7471. vmov reg,mem
  7472. by
  7473. movq $0,mem
  7474. }
  7475. if GetNextInstruction(p,hp1) and
  7476. MatchInstruction(hp1,A_VMOVSD,[]) and
  7477. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7478. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7479. begin
  7480. TransferUsedRegs(TmpUsedRegs);
  7481. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7482. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7483. begin
  7484. taicpu(hp1).loadconst(0,0);
  7485. taicpu(hp1).opcode:=A_MOV;
  7486. taicpu(hp1).opsize:=S_Q;
  7487. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7488. RemoveCurrentP(p);
  7489. result:=true;
  7490. Exit;
  7491. end;
  7492. end;
  7493. {$endif x86_64}
  7494. end
  7495. {
  7496. replace
  7497. vpxor reg1,reg1,reg2
  7498. by
  7499. vpxor reg2,reg2,reg2
  7500. to avoid unncessary data dependencies
  7501. }
  7502. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7503. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7504. begin
  7505. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7506. { avoid unncessary data dependency }
  7507. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7508. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7509. result:=true;
  7510. exit;
  7511. end;
  7512. Result:=OptPass1VOP(p);
  7513. end;
  7514. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7515. var
  7516. hp1 : tai;
  7517. begin
  7518. result:=false;
  7519. { replace
  7520. IMul const,%mreg1,%mreg2
  7521. Mov %reg2,%mreg3
  7522. dealloc %mreg3
  7523. by
  7524. Imul const,%mreg1,%mreg23
  7525. }
  7526. if (taicpu(p).ops=3) and
  7527. GetNextInstruction(p,hp1) and
  7528. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7529. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7530. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7531. begin
  7532. TransferUsedRegs(TmpUsedRegs);
  7533. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7534. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7535. begin
  7536. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7537. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7538. RemoveInstruction(hp1);
  7539. result:=true;
  7540. end;
  7541. end;
  7542. end;
  7543. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7544. var
  7545. hp1 : tai;
  7546. begin
  7547. result:=false;
  7548. { replace
  7549. IMul %reg0,%reg1,%reg2
  7550. Mov %reg2,%reg3
  7551. dealloc %reg2
  7552. by
  7553. Imul %reg0,%reg1,%reg3
  7554. }
  7555. if GetNextInstruction(p,hp1) and
  7556. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7557. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7558. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7559. begin
  7560. TransferUsedRegs(TmpUsedRegs);
  7561. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7562. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7563. begin
  7564. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7565. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7566. RemoveInstruction(hp1);
  7567. result:=true;
  7568. end;
  7569. end;
  7570. end;
  7571. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7572. var
  7573. hp1: tai;
  7574. begin
  7575. Result:=false;
  7576. { get rid of
  7577. (v)cvtss2sd reg0,<reg1,>reg2
  7578. (v)cvtss2sd reg2,<reg2,>reg0
  7579. }
  7580. if GetNextInstruction(p,hp1) and
  7581. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7582. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7583. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7584. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7585. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7586. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7587. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7588. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7589. )
  7590. ) then
  7591. begin
  7592. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7593. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7594. begin
  7595. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7596. RemoveCurrentP(p);
  7597. RemoveInstruction(hp1);
  7598. end
  7599. else
  7600. begin
  7601. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7602. if taicpu(hp1).opcode=A_CVTSD2SS then
  7603. begin
  7604. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7605. taicpu(p).opcode:=A_MOVAPS;
  7606. end
  7607. else
  7608. begin
  7609. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7610. taicpu(p).opcode:=A_VMOVAPS;
  7611. end;
  7612. taicpu(p).ops:=2;
  7613. RemoveInstruction(hp1);
  7614. end;
  7615. Result:=true;
  7616. Exit;
  7617. end;
  7618. end;
  7619. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7620. var
  7621. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7622. ThisReg: TRegister;
  7623. begin
  7624. Result := False;
  7625. if not GetNextInstruction(p,hp1) then
  7626. Exit;
  7627. {
  7628. convert
  7629. j<c> .L1
  7630. mov 1,reg
  7631. jmp .L2
  7632. .L1
  7633. mov 0,reg
  7634. .L2
  7635. into
  7636. mov 0,reg
  7637. set<not(c)> reg
  7638. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7639. would destroy the flag contents
  7640. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7641. executed at the same time as a previous comparison.
  7642. set<not(c)> reg
  7643. movzx reg, reg
  7644. }
  7645. if MatchInstruction(hp1,A_MOV,[]) and
  7646. (taicpu(hp1).oper[0]^.typ = top_const) and
  7647. (
  7648. (
  7649. (taicpu(hp1).oper[1]^.typ = top_reg)
  7650. {$ifdef i386}
  7651. { Under i386, ESI, EDI, EBP and ESP
  7652. don't have an 8-bit representation }
  7653. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7654. {$endif i386}
  7655. ) or (
  7656. {$ifdef i386}
  7657. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7658. {$endif i386}
  7659. (taicpu(hp1).opsize = S_B)
  7660. )
  7661. ) and
  7662. GetNextInstruction(hp1,hp2) and
  7663. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7664. GetNextInstruction(hp2,hp3) and
  7665. SkipAligns(hp3, hp3) and
  7666. (hp3.typ=ait_label) and
  7667. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7668. GetNextInstruction(hp3,hp4) and
  7669. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7670. (taicpu(hp4).oper[0]^.typ = top_const) and
  7671. (
  7672. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7673. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7674. ) and
  7675. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7676. GetNextInstruction(hp4,hp5) and
  7677. SkipAligns(hp5, hp5) and
  7678. (hp5.typ=ait_label) and
  7679. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7680. begin
  7681. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7682. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7683. tai_label(hp3).labsym.DecRefs;
  7684. { If this isn't the only reference to the middle label, we can
  7685. still make a saving - only that the first jump and everything
  7686. that follows will remain. }
  7687. if (tai_label(hp3).labsym.getrefs = 0) then
  7688. begin
  7689. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7690. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7691. else
  7692. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7693. { remove jump, first label and second MOV (also catching any aligns) }
  7694. repeat
  7695. if not GetNextInstruction(hp2, hp3) then
  7696. InternalError(2021040810);
  7697. RemoveInstruction(hp2);
  7698. hp2 := hp3;
  7699. until hp2 = hp5;
  7700. { Don't decrement reference count before the removal loop
  7701. above, otherwise GetNextInstruction won't stop on the
  7702. the label }
  7703. tai_label(hp5).labsym.DecRefs;
  7704. end
  7705. else
  7706. begin
  7707. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7708. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7709. else
  7710. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7711. end;
  7712. taicpu(p).opcode:=A_SETcc;
  7713. taicpu(p).opsize:=S_B;
  7714. taicpu(p).is_jmp:=False;
  7715. if taicpu(hp1).opsize=S_B then
  7716. begin
  7717. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7718. if taicpu(hp1).oper[1]^.typ = top_reg then
  7719. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7720. RemoveInstruction(hp1);
  7721. end
  7722. else
  7723. begin
  7724. { Will be a register because the size can't be S_B otherwise }
  7725. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7726. taicpu(p).loadreg(0, ThisReg);
  7727. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7728. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7729. begin
  7730. case taicpu(hp1).opsize of
  7731. S_W:
  7732. taicpu(hp1).opsize := S_BW;
  7733. S_L:
  7734. taicpu(hp1).opsize := S_BL;
  7735. {$ifdef x86_64}
  7736. S_Q:
  7737. begin
  7738. taicpu(hp1).opsize := S_BL;
  7739. { Change the destination register to 32-bit }
  7740. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7741. end;
  7742. {$endif x86_64}
  7743. else
  7744. InternalError(2021040820);
  7745. end;
  7746. taicpu(hp1).opcode := A_MOVZX;
  7747. taicpu(hp1).loadreg(0, ThisReg);
  7748. end
  7749. else
  7750. begin
  7751. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7752. { hp1 is already a MOV instruction with the correct register }
  7753. taicpu(hp1).loadconst(0, 0);
  7754. { Inserting it right before p will guarantee that the flags are also tracked }
  7755. asml.Remove(hp1);
  7756. asml.InsertBefore(hp1, p);
  7757. end;
  7758. end;
  7759. Result:=true;
  7760. exit;
  7761. end
  7762. else if (hp1.typ = ait_label) then
  7763. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7764. end;
  7765. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7766. var
  7767. hp1, hp2, hp3: tai;
  7768. SourceRef, TargetRef: TReference;
  7769. CurrentReg: TRegister;
  7770. begin
  7771. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7772. if not UseAVX then
  7773. InternalError(2021100501);
  7774. Result := False;
  7775. { Look for the following to simplify:
  7776. vmovdqa/u x(mem1), %xmmreg
  7777. vmovdqa/u %xmmreg, y(mem2)
  7778. vmovdqa/u x+16(mem1), %xmmreg
  7779. vmovdqa/u %xmmreg, y+16(mem2)
  7780. Change to:
  7781. vmovdqa/u x(mem1), %ymmreg
  7782. vmovdqa/u %ymmreg, y(mem2)
  7783. vpxor %ymmreg, %ymmreg, %ymmreg
  7784. ( The VPXOR instruction is to zero the upper half, thus removing the
  7785. need to call the potentially expensive VZEROUPPER instruction. Other
  7786. peephole optimisations can remove VPXOR if it's unnecessary )
  7787. }
  7788. TransferUsedRegs(TmpUsedRegs);
  7789. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7790. { NOTE: In the optimisations below, if the references dictate that an
  7791. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7792. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7793. if (taicpu(p).opsize = S_XMM) and
  7794. MatchOpType(taicpu(p), top_ref, top_reg) and
  7795. GetNextInstruction(p, hp1) and
  7796. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7797. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7798. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7799. begin
  7800. SourceRef := taicpu(p).oper[0]^.ref^;
  7801. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7802. if GetNextInstruction(hp1, hp2) and
  7803. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7804. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7805. begin
  7806. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7807. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7808. Inc(SourceRef.offset, 16);
  7809. { Reuse the register in the first block move }
  7810. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7811. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7812. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7813. begin
  7814. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7815. Inc(TargetRef.offset, 16);
  7816. if GetNextInstruction(hp2, hp3) and
  7817. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7818. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7819. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7820. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7821. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7822. begin
  7823. { Update the register tracking to the new size }
  7824. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7825. { Remember that the offsets are 16 ahead }
  7826. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7827. if not (
  7828. ((SourceRef.offset mod 32) = 16) and
  7829. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7830. ) then
  7831. taicpu(p).opcode := A_VMOVDQU;
  7832. taicpu(p).opsize := S_YMM;
  7833. taicpu(p).oper[1]^.reg := CurrentReg;
  7834. if not (
  7835. ((TargetRef.offset mod 32) = 16) and
  7836. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7837. ) then
  7838. taicpu(hp1).opcode := A_VMOVDQU;
  7839. taicpu(hp1).opsize := S_YMM;
  7840. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7841. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7842. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7843. if (pi_uses_ymm in current_procinfo.flags) then
  7844. RemoveInstruction(hp2)
  7845. else
  7846. begin
  7847. taicpu(hp2).opcode := A_VPXOR;
  7848. taicpu(hp2).opsize := S_YMM;
  7849. taicpu(hp2).loadreg(0, CurrentReg);
  7850. taicpu(hp2).loadreg(1, CurrentReg);
  7851. taicpu(hp2).loadreg(2, CurrentReg);
  7852. taicpu(hp2).ops := 3;
  7853. end;
  7854. RemoveInstruction(hp3);
  7855. Result := True;
  7856. Exit;
  7857. end;
  7858. end
  7859. else
  7860. begin
  7861. { See if the next references are 16 less rather than 16 greater }
  7862. Dec(SourceRef.offset, 32); { -16 the other way }
  7863. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7864. begin
  7865. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7866. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7867. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7868. GetNextInstruction(hp2, hp3) and
  7869. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7870. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7871. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7872. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7873. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7874. begin
  7875. { Update the register tracking to the new size }
  7876. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7877. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7878. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7879. if not(
  7880. ((SourceRef.offset mod 32) = 0) and
  7881. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7882. ) then
  7883. taicpu(hp2).opcode := A_VMOVDQU;
  7884. taicpu(hp2).opsize := S_YMM;
  7885. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7886. if not (
  7887. ((TargetRef.offset mod 32) = 0) and
  7888. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7889. ) then
  7890. taicpu(hp3).opcode := A_VMOVDQU;
  7891. taicpu(hp3).opsize := S_YMM;
  7892. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7893. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7894. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7895. if (pi_uses_ymm in current_procinfo.flags) then
  7896. RemoveInstruction(hp1)
  7897. else
  7898. begin
  7899. taicpu(hp1).opcode := A_VPXOR;
  7900. taicpu(hp1).opsize := S_YMM;
  7901. taicpu(hp1).loadreg(0, CurrentReg);
  7902. taicpu(hp1).loadreg(1, CurrentReg);
  7903. taicpu(hp1).loadreg(2, CurrentReg);
  7904. taicpu(hp1).ops := 3;
  7905. Asml.Remove(hp1);
  7906. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7907. end;
  7908. RemoveCurrentP(p, hp2);
  7909. Result := True;
  7910. Exit;
  7911. end;
  7912. end;
  7913. end;
  7914. end;
  7915. end;
  7916. end;
  7917. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7918. var
  7919. hp2, hp3, first_assignment: tai;
  7920. IncCount, OperIdx: Integer;
  7921. OrigLabel: TAsmLabel;
  7922. begin
  7923. Count := 0;
  7924. Result := False;
  7925. first_assignment := nil;
  7926. if (LoopCount >= 20) then
  7927. begin
  7928. { Guard against infinite loops }
  7929. Exit;
  7930. end;
  7931. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7932. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7933. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7934. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7935. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7936. Exit;
  7937. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7938. {
  7939. change
  7940. jmp .L1
  7941. ...
  7942. .L1:
  7943. mov ##, ## ( multiple movs possible )
  7944. jmp/ret
  7945. into
  7946. mov ##, ##
  7947. jmp/ret
  7948. }
  7949. if not Assigned(hp1) then
  7950. begin
  7951. hp1 := GetLabelWithSym(OrigLabel);
  7952. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7953. Exit;
  7954. end;
  7955. hp2 := hp1;
  7956. while Assigned(hp2) do
  7957. begin
  7958. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7959. SkipLabels(hp2,hp2);
  7960. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7961. Break;
  7962. case taicpu(hp2).opcode of
  7963. A_MOVSD:
  7964. begin
  7965. if taicpu(hp2).ops = 0 then
  7966. { Wrong MOVSD }
  7967. Break;
  7968. Inc(Count);
  7969. if Count >= 5 then
  7970. { Too many to be worthwhile }
  7971. Break;
  7972. GetNextInstruction(hp2, hp2);
  7973. Continue;
  7974. end;
  7975. A_MOV,
  7976. A_MOVD,
  7977. A_MOVQ,
  7978. A_MOVSX,
  7979. {$ifdef x86_64}
  7980. A_MOVSXD,
  7981. {$endif x86_64}
  7982. A_MOVZX,
  7983. A_MOVAPS,
  7984. A_MOVUPS,
  7985. A_MOVSS,
  7986. A_MOVAPD,
  7987. A_MOVUPD,
  7988. A_MOVDQA,
  7989. A_MOVDQU,
  7990. A_VMOVSS,
  7991. A_VMOVAPS,
  7992. A_VMOVUPS,
  7993. A_VMOVSD,
  7994. A_VMOVAPD,
  7995. A_VMOVUPD,
  7996. A_VMOVDQA,
  7997. A_VMOVDQU:
  7998. begin
  7999. Inc(Count);
  8000. if Count >= 5 then
  8001. { Too many to be worthwhile }
  8002. Break;
  8003. GetNextInstruction(hp2, hp2);
  8004. Continue;
  8005. end;
  8006. A_JMP:
  8007. begin
  8008. { Guard against infinite loops }
  8009. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8010. Exit;
  8011. { Analyse this jump first in case it also duplicates assignments }
  8012. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8013. begin
  8014. { Something did change! }
  8015. Result := True;
  8016. Inc(Count, IncCount);
  8017. if Count >= 5 then
  8018. begin
  8019. { Too many to be worthwhile }
  8020. Exit;
  8021. end;
  8022. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8023. Break;
  8024. end;
  8025. Result := True;
  8026. Break;
  8027. end;
  8028. A_RET:
  8029. begin
  8030. Result := True;
  8031. Break;
  8032. end;
  8033. else
  8034. Break;
  8035. end;
  8036. end;
  8037. if Result then
  8038. begin
  8039. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8040. if Count = 0 then
  8041. begin
  8042. Result := False;
  8043. Exit;
  8044. end;
  8045. hp3 := p;
  8046. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8047. while True do
  8048. begin
  8049. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8050. SkipLabels(hp1,hp1);
  8051. if (hp1.typ <> ait_instruction) then
  8052. InternalError(2021040720);
  8053. case taicpu(hp1).opcode of
  8054. A_JMP:
  8055. begin
  8056. { Change the original jump to the new destination }
  8057. OrigLabel.decrefs;
  8058. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8059. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8060. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8061. if not Assigned(first_assignment) then
  8062. InternalError(2021040810)
  8063. else
  8064. p := first_assignment;
  8065. Exit;
  8066. end;
  8067. A_RET:
  8068. begin
  8069. { Now change the jump into a RET instruction }
  8070. ConvertJumpToRET(p, hp1);
  8071. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8072. if not Assigned(first_assignment) then
  8073. InternalError(2021040811)
  8074. else
  8075. p := first_assignment;
  8076. Exit;
  8077. end;
  8078. else
  8079. begin
  8080. { Duplicate the MOV instruction }
  8081. hp3:=tai(hp1.getcopy);
  8082. if first_assignment = nil then
  8083. first_assignment := hp3;
  8084. asml.InsertBefore(hp3, p);
  8085. { Make sure the compiler knows about any final registers written here }
  8086. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8087. with taicpu(hp3).oper[OperIdx]^ do
  8088. begin
  8089. case typ of
  8090. top_ref:
  8091. begin
  8092. if (ref^.base <> NR_NO) and
  8093. (getsupreg(ref^.base) <> RS_ESP) and
  8094. (getsupreg(ref^.base) <> RS_EBP)
  8095. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8096. then
  8097. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8098. if (ref^.index <> NR_NO) and
  8099. (getsupreg(ref^.index) <> RS_ESP) and
  8100. (getsupreg(ref^.index) <> RS_EBP)
  8101. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8102. (ref^.index <> ref^.base) then
  8103. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8104. end;
  8105. top_reg:
  8106. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8107. else
  8108. ;
  8109. end;
  8110. end;
  8111. end;
  8112. end;
  8113. if not GetNextInstruction(hp1, hp1) then
  8114. { Should have dropped out earlier }
  8115. InternalError(2021040710);
  8116. end;
  8117. end;
  8118. end;
  8119. const
  8120. WriteOp: array[0..3] of set of TInsChange = (
  8121. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8122. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8123. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8124. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8125. RegWriteFlags: array[0..7] of set of TInsChange = (
  8126. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8127. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8128. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8129. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8130. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8131. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8132. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8133. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8134. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8135. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8136. var
  8137. hp2: tai;
  8138. X: Integer;
  8139. begin
  8140. { If we have something like:
  8141. op ###,###
  8142. mov ###,###
  8143. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8144. interfere in regards to what they write to.
  8145. NOTE: p must be a 2-operand instruction
  8146. }
  8147. Result := False;
  8148. if (hp1.typ <> ait_instruction) or
  8149. taicpu(hp1).is_jmp or
  8150. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8151. Exit;
  8152. { NOP is a pipeline fence, likely marking the beginning of the function
  8153. epilogue, so drop out. Similarly, drop out if POP or RET are
  8154. encountered }
  8155. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8156. Exit;
  8157. if (taicpu(hp1).opcode = A_MOVSD) and
  8158. (taicpu(hp1).ops = 0) then
  8159. { Wrong MOVSD }
  8160. Exit;
  8161. { Check for writes to specific registers first }
  8162. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8163. for X := 0 to 7 do
  8164. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8165. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8166. Exit;
  8167. for X := 0 to taicpu(hp1).ops - 1 do
  8168. begin
  8169. { Check to see if this operand writes to something }
  8170. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8171. { And matches something in the CMP/TEST instruction }
  8172. (
  8173. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8174. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8175. (
  8176. { If it's a register, make sure the register written to doesn't
  8177. appear in the cmp instruction as part of a reference }
  8178. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8179. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8180. )
  8181. ) then
  8182. Exit;
  8183. end;
  8184. { Check p to make sure it doesn't write to something that affects hp1 }
  8185. { Check for writes to specific registers first }
  8186. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8187. for X := 0 to 7 do
  8188. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8189. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8190. Exit;
  8191. for X := 0 to taicpu(p).ops - 1 do
  8192. begin
  8193. { Check to see if this operand writes to something }
  8194. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8195. { And matches something in hp1 }
  8196. (taicpu(p).oper[X]^.typ = top_reg) and
  8197. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8198. Exit;
  8199. end;
  8200. { The instruction can be safely moved }
  8201. asml.Remove(hp1);
  8202. { Try to insert after the last instructions where the FLAGS register is not
  8203. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8204. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8205. asml.InsertBefore(hp1, hp2)
  8206. { Failing that, try to insert after the last instructions where the
  8207. FLAGS register is not yet in use }
  8208. else if GetLastInstruction(p, hp2) and
  8209. (
  8210. (hp2.typ <> ait_instruction) or
  8211. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8212. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8213. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8214. ) then
  8215. asml.InsertAfter(hp1, hp2)
  8216. else
  8217. { Note, if p.Previous is nil (even if it should logically never be the
  8218. case), FindRegAllocBackward immediately exits with False and so we
  8219. safely land here (we can't just pass p because FindRegAllocBackward
  8220. immediately exits on an instruction). [Kit] }
  8221. asml.InsertBefore(hp1, p);
  8222. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8223. { We can't trust UsedRegs because we're looking backwards, although we
  8224. know the registers are allocated after p at the very least, so manually
  8225. create tai_regalloc objects if needed }
  8226. for X := 0 to taicpu(hp1).ops - 1 do
  8227. case taicpu(hp1).oper[X]^.typ of
  8228. top_reg:
  8229. begin
  8230. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8231. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8232. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8233. end;
  8234. top_ref:
  8235. begin
  8236. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8237. begin
  8238. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8239. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8240. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8241. end;
  8242. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8243. begin
  8244. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8245. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8246. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8247. end;
  8248. end;
  8249. else
  8250. ;
  8251. end;
  8252. Result := True;
  8253. end;
  8254. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8255. var
  8256. hp2: tai;
  8257. X: Integer;
  8258. begin
  8259. { If we have something like:
  8260. cmp ###,%reg1
  8261. mov 0,%reg2
  8262. And no modified registers are shared, move the instruction to before
  8263. the comparison as this means it can be optimised without worrying
  8264. about the FLAGS register. (CMP/MOV is generated by
  8265. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8266. As long as the second instruction doesn't use the flags or one of the
  8267. registers used by CMP or TEST (also check any references that use the
  8268. registers), then it can be moved prior to the comparison.
  8269. }
  8270. Result := False;
  8271. if not TrySwapMovOp(p, hp1) then
  8272. Exit;
  8273. if taicpu(hp1).opcode = A_LEA then
  8274. { The flags will be overwritten by the CMP/TEST instruction }
  8275. ConvertLEA(taicpu(hp1));
  8276. Result := True;
  8277. { Can we move it one further back? }
  8278. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8279. { Check to see if CMP/TEST is a comparison against zero }
  8280. (
  8281. (
  8282. (taicpu(p).opcode = A_CMP) and
  8283. MatchOperand(taicpu(p).oper[0]^, 0)
  8284. ) or
  8285. (
  8286. (taicpu(p).opcode = A_TEST) and
  8287. (
  8288. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8289. MatchOperand(taicpu(p).oper[0]^, -1)
  8290. )
  8291. )
  8292. ) and
  8293. { These instructions set the zero flag if the result is zero }
  8294. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8295. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8296. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8297. TrySwapMovOp(hp2, hp1);
  8298. end;
  8299. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8300. function IsXCHGAcceptable: Boolean; inline;
  8301. begin
  8302. { Always accept if optimising for size }
  8303. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8304. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8305. than 3, so it becomes a saving compared to three MOVs with two of
  8306. them able to execute simultaneously. [Kit] }
  8307. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8308. end;
  8309. var
  8310. NewRef: TReference;
  8311. hp1, hp2, hp3, hp4: Tai;
  8312. {$ifndef x86_64}
  8313. OperIdx: Integer;
  8314. {$endif x86_64}
  8315. NewInstr : Taicpu;
  8316. NewAligh : Tai_align;
  8317. DestLabel: TAsmLabel;
  8318. TempTracking: TAllUsedRegs;
  8319. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8320. var
  8321. NextInstr: tai;
  8322. begin
  8323. Result := False;
  8324. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8325. if not GetNextInstruction(InputInstr, NextInstr) or
  8326. (
  8327. { The FLAGS register isn't always tracked properly, so do not
  8328. perform this optimisation if a conditional statement follows }
  8329. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8330. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8331. ) then
  8332. begin
  8333. reference_reset(NewRef, 1, []);
  8334. NewRef.base := taicpu(p).oper[0]^.reg;
  8335. NewRef.scalefactor := 1;
  8336. if taicpu(InputInstr).opcode = A_ADD then
  8337. begin
  8338. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8339. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8340. end
  8341. else
  8342. begin
  8343. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8344. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8345. end;
  8346. taicpu(p).opcode := A_LEA;
  8347. taicpu(p).loadref(0, NewRef);
  8348. RemoveInstruction(InputInstr);
  8349. Result := True;
  8350. end;
  8351. end;
  8352. begin
  8353. Result:=false;
  8354. { This optimisation adds an instruction, so only do it for speed }
  8355. if not (cs_opt_size in current_settings.optimizerswitches) and
  8356. MatchOpType(taicpu(p), top_const, top_reg) and
  8357. (taicpu(p).oper[0]^.val = 0) then
  8358. begin
  8359. { To avoid compiler warning }
  8360. DestLabel := nil;
  8361. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8362. InternalError(2021040750);
  8363. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8364. Exit;
  8365. case hp1.typ of
  8366. ait_align,
  8367. ait_label:
  8368. begin
  8369. { Change:
  8370. mov $0,%reg mov $0,%reg
  8371. @Lbl1: @Lbl1:
  8372. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8373. je @Lbl2 jne @Lbl2
  8374. To: To:
  8375. mov $0,%reg mov $0,%reg
  8376. jmp @Lbl2 jmp @Lbl3
  8377. (align) (align)
  8378. @Lbl1: @Lbl1:
  8379. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8380. je @Lbl2 je @Lbl2
  8381. @Lbl3: <-- Only if label exists
  8382. (Not if it's optimised for size)
  8383. }
  8384. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8385. Exit;
  8386. if (hp2.typ = ait_instruction) and
  8387. (
  8388. { Register sizes must exactly match }
  8389. (
  8390. (taicpu(hp2).opcode = A_CMP) and
  8391. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8392. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8393. ) or (
  8394. (taicpu(hp2).opcode = A_TEST) and
  8395. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8396. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8397. )
  8398. ) and GetNextInstruction(hp2, hp3) and
  8399. (hp3.typ = ait_instruction) and
  8400. (taicpu(hp3).opcode = A_JCC) and
  8401. (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
  8402. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8403. begin
  8404. { Check condition of jump }
  8405. { Always true? }
  8406. if condition_in(C_E, taicpu(hp3).condition) then
  8407. begin
  8408. { Copy label symbol and obtain matching label entry for the
  8409. conditional jump, as this will be our destination}
  8410. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8411. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8412. Result := True;
  8413. end
  8414. { Always false? }
  8415. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8416. begin
  8417. { This is only worth it if there's a jump to take }
  8418. case hp2.typ of
  8419. ait_instruction:
  8420. begin
  8421. if taicpu(hp2).opcode = A_JMP then
  8422. begin
  8423. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8424. { An unconditional jump follows the conditional jump which will always be false,
  8425. so use this jump's destination for the new jump }
  8426. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8427. Result := True;
  8428. end
  8429. else if taicpu(hp2).opcode = A_JCC then
  8430. begin
  8431. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8432. if condition_in(C_E, taicpu(hp2).condition) then
  8433. begin
  8434. { A second conditional jump follows the conditional jump which will always be false,
  8435. while the second jump is always True, so use this jump's destination for the new jump }
  8436. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8437. Result := True;
  8438. end;
  8439. { Don't risk it if the jump isn't always true (Result remains False) }
  8440. end;
  8441. end;
  8442. else
  8443. { If anything else don't optimise };
  8444. end;
  8445. end;
  8446. if Result then
  8447. begin
  8448. { Just so we have something to insert as a paremeter}
  8449. reference_reset(NewRef, 1, []);
  8450. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8451. { Now actually load the correct parameter (this also
  8452. increases the reference count) }
  8453. NewInstr.loadsymbol(0, DestLabel, 0);
  8454. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8455. begin
  8456. { Get instruction before original label (may not be p under -O3) }
  8457. if not GetLastInstruction(hp1, hp2) then
  8458. { Shouldn't fail here }
  8459. InternalError(2021040701);
  8460. { Before the aligns too }
  8461. while (hp2.typ = ait_align) do
  8462. if not GetLastInstruction(hp2, hp2) then
  8463. { Shouldn't fail here }
  8464. InternalError(2021040702);
  8465. end
  8466. else
  8467. hp2 := p;
  8468. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8469. AsmL.InsertAfter(NewInstr, hp2);
  8470. { Add new alignment field }
  8471. (* AsmL.InsertAfter(
  8472. cai_align.create_max(
  8473. current_settings.alignment.jumpalign,
  8474. current_settings.alignment.jumpalignskipmax
  8475. ),
  8476. NewInstr
  8477. ); *)
  8478. end;
  8479. Exit;
  8480. end;
  8481. end;
  8482. else
  8483. ;
  8484. end;
  8485. end;
  8486. if not GetNextInstruction(p, hp1) then
  8487. Exit;
  8488. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8489. and DoMovCmpMemOpt(p, hp1) then
  8490. begin
  8491. Result := True;
  8492. Exit;
  8493. end
  8494. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8495. begin
  8496. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8497. further, but we can't just put this jump optimisation in pass 1
  8498. because it tends to perform worse when conditional jumps are
  8499. nearby (e.g. when converting CMOV instructions). [Kit] }
  8500. CopyUsedRegs(TempTracking);
  8501. UpdateUsedRegs(tai(p.Next));
  8502. if OptPass2JMP(hp1) then
  8503. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8504. Result := OptPass1MOV(p);
  8505. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8506. returned True and the instruction is still a MOV, thus checking
  8507. the optimisations below }
  8508. { If OptPass2JMP returned False, no optimisations were done to
  8509. the jump and there are no further optimisations that can be done
  8510. to the MOV instruction on this pass }
  8511. { Restore register state }
  8512. RestoreUsedRegs(TempTracking);
  8513. ReleaseUsedRegs(TempTracking);
  8514. end
  8515. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8516. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8517. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8518. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8519. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8520. begin
  8521. { Change:
  8522. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8523. addl/q $x,%reg2 subl/q $x,%reg2
  8524. To:
  8525. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8526. }
  8527. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8528. { be lazy, checking separately for sub would be slightly better }
  8529. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8530. begin
  8531. TransferUsedRegs(TmpUsedRegs);
  8532. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8533. if TryMovArith2Lea(hp1) then
  8534. begin
  8535. Result := True;
  8536. Exit;
  8537. end
  8538. end
  8539. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8540. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8541. { Same as above, but also adds or subtracts to %reg2 in between.
  8542. It's still valid as long as the flags aren't in use }
  8543. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8544. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8545. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8546. { be lazy, checking separately for sub would be slightly better }
  8547. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8548. begin
  8549. TransferUsedRegs(TmpUsedRegs);
  8550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8551. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8552. if TryMovArith2Lea(hp2) then
  8553. begin
  8554. Result := True;
  8555. Exit;
  8556. end;
  8557. end;
  8558. end
  8559. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8560. {$ifdef x86_64}
  8561. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8562. {$else x86_64}
  8563. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8564. {$endif x86_64}
  8565. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8566. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8567. { mov reg1, reg2 mov reg1, reg2
  8568. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8569. begin
  8570. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8571. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8572. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8573. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8574. TransferUsedRegs(TmpUsedRegs);
  8575. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8576. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8577. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8578. then
  8579. begin
  8580. RemoveCurrentP(p, hp1);
  8581. Result:=true;
  8582. end;
  8583. exit;
  8584. end
  8585. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8586. IsXCHGAcceptable and
  8587. { XCHG doesn't support 8-byte registers }
  8588. (taicpu(p).opsize <> S_B) and
  8589. MatchInstruction(hp1, A_MOV, []) and
  8590. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8591. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8592. GetNextInstruction(hp1, hp2) and
  8593. MatchInstruction(hp2, A_MOV, []) and
  8594. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8595. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8596. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8597. begin
  8598. { mov %reg1,%reg2
  8599. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8600. mov %reg2,%reg3
  8601. (%reg2 not used afterwards)
  8602. Note that xchg takes 3 cycles to execute, and generally mov's take
  8603. only one cycle apiece, but the first two mov's can be executed in
  8604. parallel, only taking 2 cycles overall. Older processors should
  8605. therefore only optimise for size. [Kit]
  8606. }
  8607. TransferUsedRegs(TmpUsedRegs);
  8608. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8609. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8610. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8611. begin
  8612. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8613. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8614. taicpu(hp1).opcode := A_XCHG;
  8615. RemoveCurrentP(p, hp1);
  8616. RemoveInstruction(hp2);
  8617. Result := True;
  8618. Exit;
  8619. end;
  8620. end
  8621. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8622. MatchInstruction(hp1, A_SAR, []) then
  8623. begin
  8624. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8625. begin
  8626. { the use of %edx also covers the opsize being S_L }
  8627. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8628. begin
  8629. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8630. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8631. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8632. begin
  8633. { Change:
  8634. movl %eax,%edx
  8635. sarl $31,%edx
  8636. To:
  8637. cltd
  8638. }
  8639. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8640. RemoveInstruction(hp1);
  8641. taicpu(p).opcode := A_CDQ;
  8642. taicpu(p).opsize := S_NO;
  8643. taicpu(p).clearop(1);
  8644. taicpu(p).clearop(0);
  8645. taicpu(p).ops:=0;
  8646. Result := True;
  8647. end
  8648. else if (cs_opt_size in current_settings.optimizerswitches) and
  8649. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8650. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8651. begin
  8652. { Change:
  8653. movl %edx,%eax
  8654. sarl $31,%edx
  8655. To:
  8656. movl %edx,%eax
  8657. cltd
  8658. Note that this creates a dependency between the two instructions,
  8659. so only perform if optimising for size.
  8660. }
  8661. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8662. taicpu(hp1).opcode := A_CDQ;
  8663. taicpu(hp1).opsize := S_NO;
  8664. taicpu(hp1).clearop(1);
  8665. taicpu(hp1).clearop(0);
  8666. taicpu(hp1).ops:=0;
  8667. end;
  8668. {$ifndef x86_64}
  8669. end
  8670. { Don't bother if CMOV is supported, because a more optimal
  8671. sequence would have been generated for the Abs() intrinsic }
  8672. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8673. { the use of %eax also covers the opsize being S_L }
  8674. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8675. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8676. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8677. GetNextInstruction(hp1, hp2) and
  8678. MatchInstruction(hp2, A_XOR, [S_L]) and
  8679. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8680. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8681. GetNextInstruction(hp2, hp3) and
  8682. MatchInstruction(hp3, A_SUB, [S_L]) and
  8683. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8684. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8685. begin
  8686. { Change:
  8687. movl %eax,%edx
  8688. sarl $31,%eax
  8689. xorl %eax,%edx
  8690. subl %eax,%edx
  8691. (Instruction that uses %edx)
  8692. (%eax deallocated)
  8693. (%edx deallocated)
  8694. To:
  8695. cltd
  8696. xorl %edx,%eax <-- Note the registers have swapped
  8697. subl %edx,%eax
  8698. (Instruction that uses %eax) <-- %eax rather than %edx
  8699. }
  8700. TransferUsedRegs(TmpUsedRegs);
  8701. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8702. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8703. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8704. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8705. begin
  8706. if GetNextInstruction(hp3, hp4) and
  8707. not RegModifiedByInstruction(NR_EDX, hp4) and
  8708. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8709. begin
  8710. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8711. taicpu(p).opcode := A_CDQ;
  8712. taicpu(p).clearop(1);
  8713. taicpu(p).clearop(0);
  8714. taicpu(p).ops:=0;
  8715. RemoveInstruction(hp1);
  8716. taicpu(hp2).loadreg(0, NR_EDX);
  8717. taicpu(hp2).loadreg(1, NR_EAX);
  8718. taicpu(hp3).loadreg(0, NR_EDX);
  8719. taicpu(hp3).loadreg(1, NR_EAX);
  8720. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8721. { Convert references in the following instruction (hp4) from %edx to %eax }
  8722. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8723. with taicpu(hp4).oper[OperIdx]^ do
  8724. case typ of
  8725. top_reg:
  8726. if getsupreg(reg) = RS_EDX then
  8727. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8728. top_ref:
  8729. begin
  8730. if getsupreg(reg) = RS_EDX then
  8731. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8732. if getsupreg(reg) = RS_EDX then
  8733. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8734. end;
  8735. else
  8736. ;
  8737. end;
  8738. end;
  8739. end;
  8740. {$else x86_64}
  8741. end;
  8742. end
  8743. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8744. { the use of %rdx also covers the opsize being S_Q }
  8745. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8746. begin
  8747. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8748. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8749. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8750. begin
  8751. { Change:
  8752. movq %rax,%rdx
  8753. sarq $63,%rdx
  8754. To:
  8755. cqto
  8756. }
  8757. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8758. RemoveInstruction(hp1);
  8759. taicpu(p).opcode := A_CQO;
  8760. taicpu(p).opsize := S_NO;
  8761. taicpu(p).clearop(1);
  8762. taicpu(p).clearop(0);
  8763. taicpu(p).ops:=0;
  8764. Result := True;
  8765. end
  8766. else if (cs_opt_size in current_settings.optimizerswitches) and
  8767. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8768. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8769. begin
  8770. { Change:
  8771. movq %rdx,%rax
  8772. sarq $63,%rdx
  8773. To:
  8774. movq %rdx,%rax
  8775. cqto
  8776. Note that this creates a dependency between the two instructions,
  8777. so only perform if optimising for size.
  8778. }
  8779. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8780. taicpu(hp1).opcode := A_CQO;
  8781. taicpu(hp1).opsize := S_NO;
  8782. taicpu(hp1).clearop(1);
  8783. taicpu(hp1).clearop(0);
  8784. taicpu(hp1).ops:=0;
  8785. {$endif x86_64}
  8786. end;
  8787. end;
  8788. end
  8789. else if MatchInstruction(hp1, A_MOV, []) and
  8790. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8791. { Though "GetNextInstruction" could be factored out, along with
  8792. the instructions that depend on hp2, it is an expensive call that
  8793. should be delayed for as long as possible, hence we do cheaper
  8794. checks first that are likely to be False. [Kit] }
  8795. begin
  8796. if (
  8797. (
  8798. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8799. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8800. (
  8801. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8802. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8803. )
  8804. ) or
  8805. (
  8806. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8807. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8808. (
  8809. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8810. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8811. )
  8812. )
  8813. ) and
  8814. GetNextInstruction(hp1, hp2) and
  8815. MatchInstruction(hp2, A_SAR, []) and
  8816. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8817. begin
  8818. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8819. begin
  8820. { Change:
  8821. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8822. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8823. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8824. To:
  8825. movl r/m,%eax <- Note the change in register
  8826. cltd
  8827. }
  8828. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8829. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8830. taicpu(p).loadreg(1, NR_EAX);
  8831. taicpu(hp1).opcode := A_CDQ;
  8832. taicpu(hp1).clearop(1);
  8833. taicpu(hp1).clearop(0);
  8834. taicpu(hp1).ops:=0;
  8835. RemoveInstruction(hp2);
  8836. (*
  8837. {$ifdef x86_64}
  8838. end
  8839. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8840. { This code sequence does not get generated - however it might become useful
  8841. if and when 128-bit signed integer types make an appearance, so the code
  8842. is kept here for when it is eventually needed. [Kit] }
  8843. (
  8844. (
  8845. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8846. (
  8847. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8848. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8849. )
  8850. ) or
  8851. (
  8852. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8853. (
  8854. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8855. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8856. )
  8857. )
  8858. ) and
  8859. GetNextInstruction(hp1, hp2) and
  8860. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8861. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8862. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8863. begin
  8864. { Change:
  8865. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8866. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8867. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8868. To:
  8869. movq r/m,%rax <- Note the change in register
  8870. cqto
  8871. }
  8872. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8873. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8874. taicpu(p).loadreg(1, NR_RAX);
  8875. taicpu(hp1).opcode := A_CQO;
  8876. taicpu(hp1).clearop(1);
  8877. taicpu(hp1).clearop(0);
  8878. taicpu(hp1).ops:=0;
  8879. RemoveInstruction(hp2);
  8880. {$endif x86_64}
  8881. *)
  8882. end;
  8883. end;
  8884. {$ifdef x86_64}
  8885. end
  8886. else if (taicpu(p).opsize = S_L) and
  8887. (taicpu(p).oper[1]^.typ = top_reg) and
  8888. (
  8889. MatchInstruction(hp1, A_MOV,[]) and
  8890. (taicpu(hp1).opsize = S_L) and
  8891. (taicpu(hp1).oper[1]^.typ = top_reg)
  8892. ) and (
  8893. GetNextInstruction(hp1, hp2) and
  8894. (tai(hp2).typ=ait_instruction) and
  8895. (taicpu(hp2).opsize = S_Q) and
  8896. (
  8897. (
  8898. MatchInstruction(hp2, A_ADD,[]) and
  8899. (taicpu(hp2).opsize = S_Q) and
  8900. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8901. (
  8902. (
  8903. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8904. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8905. ) or (
  8906. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8907. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8908. )
  8909. )
  8910. ) or (
  8911. MatchInstruction(hp2, A_LEA,[]) and
  8912. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8913. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8914. (
  8915. (
  8916. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8917. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8918. ) or (
  8919. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8920. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8921. )
  8922. ) and (
  8923. (
  8924. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8925. ) or (
  8926. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8927. )
  8928. )
  8929. )
  8930. )
  8931. ) and (
  8932. GetNextInstruction(hp2, hp3) and
  8933. MatchInstruction(hp3, A_SHR,[]) and
  8934. (taicpu(hp3).opsize = S_Q) and
  8935. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8936. (taicpu(hp3).oper[0]^.val = 1) and
  8937. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8938. ) then
  8939. begin
  8940. { Change movl x, reg1d movl x, reg1d
  8941. movl y, reg2d movl y, reg2d
  8942. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8943. shrq $1, reg1q shrq $1, reg1q
  8944. ( reg1d and reg2d can be switched around in the first two instructions )
  8945. To movl x, reg1d
  8946. addl y, reg1d
  8947. rcrl $1, reg1d
  8948. This corresponds to the common expression (x + y) shr 1, where
  8949. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8950. smaller code, but won't account for x + y causing an overflow). [Kit]
  8951. }
  8952. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8953. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8954. { Change first MOV command to have the same register as the final output }
  8955. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8956. else
  8957. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8958. { Change second MOV command to an ADD command. This is easier than
  8959. converting the existing command because it means we don't have to
  8960. touch 'y', which might be a complicated reference, and also the
  8961. fact that the third command might either be ADD or LEA. [Kit] }
  8962. taicpu(hp1).opcode := A_ADD;
  8963. { Delete old ADD/LEA instruction }
  8964. RemoveInstruction(hp2);
  8965. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8966. taicpu(hp3).opcode := A_RCR;
  8967. taicpu(hp3).changeopsize(S_L);
  8968. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8969. {$endif x86_64}
  8970. end;
  8971. if FuncMov2Func(p, hp1) then
  8972. begin
  8973. Result := True;
  8974. Exit;
  8975. end;
  8976. end;
  8977. {$push}
  8978. {$q-}{$r-}
  8979. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8980. var
  8981. ThisReg: TRegister;
  8982. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8983. TargetSubReg: TSubRegister;
  8984. hp1, hp2: tai;
  8985. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8986. { Store list of found instructions so we don't have to call
  8987. GetNextInstructionUsingReg multiple times }
  8988. InstrList: array of taicpu;
  8989. InstrMax, Index: Integer;
  8990. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8991. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8992. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8993. WorkingValue: TCgInt;
  8994. PreMessage: string;
  8995. { Data flow analysis }
  8996. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8997. BitwiseOnly, OrXorUsed,
  8998. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8999. function CheckOverflowConditions: Boolean;
  9000. begin
  9001. Result := True;
  9002. if (TestValSignedMax > SignedUpperLimit) then
  9003. UpperSignedOverflow := True;
  9004. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9005. LowerSignedOverflow := True;
  9006. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9007. LowerUnsignedOverflow := True;
  9008. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9009. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9010. begin
  9011. { Absolute overflow }
  9012. Result := False;
  9013. Exit;
  9014. end;
  9015. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9016. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9017. ShiftDownOverflow := True;
  9018. if (TestValMin < 0) or (TestValMax < 0) then
  9019. begin
  9020. LowerUnsignedOverflow := True;
  9021. UpperUnsignedOverflow := True;
  9022. end;
  9023. end;
  9024. function AdjustInitialLoadAndSize: Boolean;
  9025. begin
  9026. Result := False;
  9027. if not p_removed then
  9028. begin
  9029. if TargetSize = MinSize then
  9030. begin
  9031. { Convert the input MOVZX to a MOV }
  9032. if (taicpu(p).oper[0]^.typ = top_reg) and
  9033. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9034. begin
  9035. { Or remove it completely! }
  9036. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9037. RemoveCurrentP(p);
  9038. p_removed := True;
  9039. end
  9040. else
  9041. begin
  9042. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9043. taicpu(p).opcode := A_MOV;
  9044. taicpu(p).oper[1]^.reg := ThisReg;
  9045. taicpu(p).opsize := TargetSize;
  9046. end;
  9047. Result := True;
  9048. end
  9049. else if TargetSize <> MaxSize then
  9050. begin
  9051. case MaxSize of
  9052. S_L:
  9053. if TargetSize = S_W then
  9054. begin
  9055. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9056. taicpu(p).opsize := S_BW;
  9057. taicpu(p).oper[1]^.reg := ThisReg;
  9058. Result := True;
  9059. end
  9060. else
  9061. InternalError(2020112341);
  9062. S_W:
  9063. if TargetSize = S_L then
  9064. begin
  9065. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9066. taicpu(p).opsize := S_BL;
  9067. taicpu(p).oper[1]^.reg := ThisReg;
  9068. Result := True;
  9069. end
  9070. else
  9071. InternalError(2020112342);
  9072. else
  9073. ;
  9074. end;
  9075. end
  9076. else if not hp1_removed and not RegInUse then
  9077. begin
  9078. { If we have something like:
  9079. movzbl (oper),%regd
  9080. add x, %regd
  9081. movzbl %regb, %regd
  9082. We can reduce the register size to the input of the final
  9083. movzbl instruction. Overflows won't have any effect.
  9084. }
  9085. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9086. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9087. begin
  9088. TargetSize := S_B;
  9089. setsubreg(ThisReg, R_SUBL);
  9090. Result := True;
  9091. end
  9092. else if (taicpu(p).opsize = S_WL) and
  9093. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9094. begin
  9095. TargetSize := S_W;
  9096. setsubreg(ThisReg, R_SUBW);
  9097. Result := True;
  9098. end;
  9099. if Result then
  9100. begin
  9101. { Convert the input MOVZX to a MOV }
  9102. if (taicpu(p).oper[0]^.typ = top_reg) and
  9103. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9104. begin
  9105. { Or remove it completely! }
  9106. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9107. RemoveCurrentP(p);
  9108. p_removed := True;
  9109. end
  9110. else
  9111. begin
  9112. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9113. taicpu(p).opcode := A_MOV;
  9114. taicpu(p).oper[1]^.reg := ThisReg;
  9115. taicpu(p).opsize := TargetSize;
  9116. end;
  9117. end;
  9118. end;
  9119. end;
  9120. end;
  9121. procedure AdjustFinalLoad;
  9122. begin
  9123. if not LowerUnsignedOverflow then
  9124. begin
  9125. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9126. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9127. begin
  9128. { Convert the output MOVZX to a MOV }
  9129. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9130. begin
  9131. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9132. if (MinSize = S_B) or
  9133. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9134. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9135. begin
  9136. { Remove it completely! }
  9137. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9138. { Be careful; if p = hp1 and p was also removed, p
  9139. will become a dangling pointer }
  9140. if p = hp1 then
  9141. begin
  9142. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9143. p_removed := True;
  9144. end
  9145. else
  9146. RemoveInstruction(hp1);
  9147. hp1_removed := True;
  9148. end;
  9149. end
  9150. else
  9151. begin
  9152. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9153. taicpu(hp1).opcode := A_MOV;
  9154. taicpu(hp1).oper[0]^.reg := ThisReg;
  9155. taicpu(hp1).opsize := TargetSize;
  9156. end;
  9157. end
  9158. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9159. begin
  9160. { Need to change the size of the output }
  9161. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9162. taicpu(hp1).oper[0]^.reg := ThisReg;
  9163. taicpu(hp1).opsize := S_BL;
  9164. end;
  9165. end;
  9166. end;
  9167. function CompressInstructions: Boolean;
  9168. var
  9169. LocalIndex: Integer;
  9170. begin
  9171. Result := False;
  9172. { The objective here is to try to find a combination that
  9173. removes one of the MOV/Z instructions. }
  9174. if (
  9175. (taicpu(p).oper[0]^.typ <> top_reg) or
  9176. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9177. ) and
  9178. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9179. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9180. begin
  9181. { Make a preference to remove the second MOVZX instruction }
  9182. case taicpu(hp1).opsize of
  9183. S_BL, S_WL:
  9184. begin
  9185. TargetSize := S_L;
  9186. TargetSubReg := R_SUBD;
  9187. end;
  9188. S_BW:
  9189. begin
  9190. TargetSize := S_W;
  9191. TargetSubReg := R_SUBW;
  9192. end;
  9193. else
  9194. InternalError(2020112302);
  9195. end;
  9196. end
  9197. else
  9198. begin
  9199. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9200. begin
  9201. { Exceeded lower bound but not upper bound }
  9202. TargetSize := MaxSize;
  9203. end
  9204. else if not LowerUnsignedOverflow then
  9205. begin
  9206. { Size didn't exceed lower bound }
  9207. TargetSize := MinSize;
  9208. end
  9209. else
  9210. Exit;
  9211. end;
  9212. case TargetSize of
  9213. S_B:
  9214. TargetSubReg := R_SUBL;
  9215. S_W:
  9216. TargetSubReg := R_SUBW;
  9217. S_L:
  9218. TargetSubReg := R_SUBD;
  9219. else
  9220. InternalError(2020112350);
  9221. end;
  9222. { Update the register to its new size }
  9223. setsubreg(ThisReg, TargetSubReg);
  9224. RegInUse := False;
  9225. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9226. begin
  9227. { Check to see if the active register is used afterwards;
  9228. if not, we can change it and make a saving. }
  9229. TransferUsedRegs(TmpUsedRegs);
  9230. { The target register may be marked as in use to cross
  9231. a jump to a distant label, so exclude it }
  9232. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9233. hp2 := p;
  9234. repeat
  9235. { Explicitly check for the excluded register (don't include the first
  9236. instruction as it may be reading from here }
  9237. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9238. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9239. begin
  9240. RegInUse := True;
  9241. Break;
  9242. end;
  9243. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9244. if not GetNextInstruction(hp2, hp2) then
  9245. InternalError(2020112340);
  9246. until (hp2 = hp1);
  9247. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9248. { We might still be able to get away with this }
  9249. RegInUse := not
  9250. (
  9251. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9252. (hp2.typ = ait_instruction) and
  9253. (
  9254. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9255. instruction that doesn't actually contain ThisReg }
  9256. (cs_opt_level3 in current_settings.optimizerswitches) or
  9257. RegInInstruction(ThisReg, hp2)
  9258. ) and
  9259. RegLoadedWithNewValue(ThisReg, hp2)
  9260. );
  9261. if not RegInUse then
  9262. begin
  9263. { Force the register size to the same as this instruction so it can be removed}
  9264. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9265. begin
  9266. TargetSize := S_L;
  9267. TargetSubReg := R_SUBD;
  9268. end
  9269. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9270. begin
  9271. TargetSize := S_W;
  9272. TargetSubReg := R_SUBW;
  9273. end;
  9274. ThisReg := taicpu(hp1).oper[1]^.reg;
  9275. setsubreg(ThisReg, TargetSubReg);
  9276. RegChanged := True;
  9277. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9278. TransferUsedRegs(TmpUsedRegs);
  9279. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9280. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9281. if p = hp1 then
  9282. begin
  9283. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9284. p_removed := True;
  9285. end
  9286. else
  9287. RemoveInstruction(hp1);
  9288. hp1_removed := True;
  9289. { Instruction will become "mov %reg,%reg" }
  9290. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9291. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9292. begin
  9293. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9294. RemoveCurrentP(p);
  9295. p_removed := True;
  9296. end
  9297. else
  9298. taicpu(p).oper[1]^.reg := ThisReg;
  9299. Result := True;
  9300. end
  9301. else
  9302. begin
  9303. if TargetSize <> MaxSize then
  9304. begin
  9305. { Since the register is in use, we have to force it to
  9306. MaxSize otherwise part of it may become undefined later on }
  9307. TargetSize := MaxSize;
  9308. case TargetSize of
  9309. S_B:
  9310. TargetSubReg := R_SUBL;
  9311. S_W:
  9312. TargetSubReg := R_SUBW;
  9313. S_L:
  9314. TargetSubReg := R_SUBD;
  9315. else
  9316. InternalError(2020112351);
  9317. end;
  9318. setsubreg(ThisReg, TargetSubReg);
  9319. end;
  9320. AdjustFinalLoad;
  9321. end;
  9322. end
  9323. else
  9324. AdjustFinalLoad;
  9325. Result := AdjustInitialLoadAndSize or Result;
  9326. { Now go through every instruction we found and change the
  9327. size. If TargetSize = MaxSize, then almost no changes are
  9328. needed and Result can remain False if it hasn't been set
  9329. yet.
  9330. If RegChanged is True, then the register requires changing
  9331. and so the point about TargetSize = MaxSize doesn't apply. }
  9332. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9333. begin
  9334. for LocalIndex := 0 to InstrMax do
  9335. begin
  9336. { If p_removed is true, then the original MOV/Z was removed
  9337. and removing the AND instruction may not be safe if it
  9338. appears first }
  9339. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9340. InternalError(2020112310);
  9341. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9342. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9343. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9344. InstrList[LocalIndex].opsize := TargetSize;
  9345. end;
  9346. Result := True;
  9347. end;
  9348. end;
  9349. begin
  9350. Result := False;
  9351. p_removed := False;
  9352. hp1_removed := False;
  9353. ThisReg := taicpu(p).oper[1]^.reg;
  9354. { Check for:
  9355. movs/z ###,%ecx (or %cx or %rcx)
  9356. ...
  9357. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9358. (dealloc %ecx)
  9359. Change to:
  9360. mov ###,%cl (if ### = %cl, then remove completely)
  9361. ...
  9362. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9363. }
  9364. if (getsupreg(ThisReg) = RS_ECX) and
  9365. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9366. (hp1.typ = ait_instruction) and
  9367. (
  9368. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9369. instruction that doesn't actually contain ECX }
  9370. (cs_opt_level3 in current_settings.optimizerswitches) or
  9371. RegInInstruction(NR_ECX, hp1) or
  9372. (
  9373. { It's common for the shift/rotate's read/write register to be
  9374. initialised in between, so under -O2 and under, search ahead
  9375. one more instruction
  9376. }
  9377. GetNextInstruction(hp1, hp1) and
  9378. (hp1.typ = ait_instruction) and
  9379. RegInInstruction(NR_ECX, hp1)
  9380. )
  9381. ) and
  9382. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9383. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9384. begin
  9385. TransferUsedRegs(TmpUsedRegs);
  9386. hp2 := p;
  9387. repeat
  9388. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9389. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9390. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9391. begin
  9392. case taicpu(p).opsize of
  9393. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9394. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9395. begin
  9396. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9397. RemoveCurrentP(p);
  9398. end
  9399. else
  9400. begin
  9401. taicpu(p).opcode := A_MOV;
  9402. taicpu(p).opsize := S_B;
  9403. taicpu(p).oper[1]^.reg := NR_CL;
  9404. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9405. end;
  9406. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9407. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9408. begin
  9409. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9410. RemoveCurrentP(p);
  9411. end
  9412. else
  9413. begin
  9414. taicpu(p).opcode := A_MOV;
  9415. taicpu(p).opsize := S_W;
  9416. taicpu(p).oper[1]^.reg := NR_CX;
  9417. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9418. end;
  9419. {$ifdef x86_64}
  9420. S_LQ:
  9421. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9422. begin
  9423. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9424. RemoveCurrentP(p);
  9425. end
  9426. else
  9427. begin
  9428. taicpu(p).opcode := A_MOV;
  9429. taicpu(p).opsize := S_L;
  9430. taicpu(p).oper[1]^.reg := NR_ECX;
  9431. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9432. end;
  9433. {$endif x86_64}
  9434. else
  9435. InternalError(2021120401);
  9436. end;
  9437. Result := True;
  9438. Exit;
  9439. end;
  9440. end;
  9441. { This is anything but quick! }
  9442. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9443. Exit;
  9444. SetLength(InstrList, 0);
  9445. InstrMax := -1;
  9446. case taicpu(p).opsize of
  9447. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9448. begin
  9449. {$if defined(i386) or defined(i8086)}
  9450. { If the target size is 8-bit, make sure we can actually encode it }
  9451. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9452. Exit;
  9453. {$endif i386 or i8086}
  9454. LowerLimit := $FF;
  9455. SignedLowerLimit := $7F;
  9456. SignedLowerLimitBottom := -128;
  9457. MinSize := S_B;
  9458. if taicpu(p).opsize = S_BW then
  9459. begin
  9460. MaxSize := S_W;
  9461. UpperLimit := $FFFF;
  9462. SignedUpperLimit := $7FFF;
  9463. SignedUpperLimitBottom := -32768;
  9464. end
  9465. else
  9466. begin
  9467. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9468. MaxSize := S_L;
  9469. UpperLimit := $FFFFFFFF;
  9470. SignedUpperLimit := $7FFFFFFF;
  9471. SignedUpperLimitBottom := -2147483648;
  9472. end;
  9473. end;
  9474. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9475. begin
  9476. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9477. LowerLimit := $FFFF;
  9478. SignedLowerLimit := $7FFF;
  9479. SignedLowerLimitBottom := -32768;
  9480. UpperLimit := $FFFFFFFF;
  9481. SignedUpperLimit := $7FFFFFFF;
  9482. SignedUpperLimitBottom := -2147483648;
  9483. MinSize := S_W;
  9484. MaxSize := S_L;
  9485. end;
  9486. {$ifdef x86_64}
  9487. S_LQ:
  9488. begin
  9489. { Both the lower and upper limits are set to 32-bit. If a limit
  9490. is breached, then optimisation is impossible }
  9491. LowerLimit := $FFFFFFFF;
  9492. SignedLowerLimit := $7FFFFFFF;
  9493. SignedLowerLimitBottom := -2147483648;
  9494. UpperLimit := $FFFFFFFF;
  9495. SignedUpperLimit := $7FFFFFFF;
  9496. SignedUpperLimitBottom := -2147483648;
  9497. MinSize := S_L;
  9498. MaxSize := S_L;
  9499. end;
  9500. {$endif x86_64}
  9501. else
  9502. InternalError(2020112301);
  9503. end;
  9504. TestValMin := 0;
  9505. TestValMax := LowerLimit;
  9506. TestValSignedMax := SignedLowerLimit;
  9507. TryShiftDownLimit := LowerLimit;
  9508. TryShiftDown := S_NO;
  9509. ShiftDownOverflow := False;
  9510. RegChanged := False;
  9511. BitwiseOnly := True;
  9512. OrXorUsed := False;
  9513. UpperSignedOverflow := False;
  9514. LowerSignedOverflow := False;
  9515. UpperUnsignedOverflow := False;
  9516. LowerUnsignedOverflow := False;
  9517. hp1 := p;
  9518. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9519. (hp1.typ = ait_instruction) and
  9520. (
  9521. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9522. instruction that doesn't actually contain ThisReg }
  9523. (cs_opt_level3 in current_settings.optimizerswitches) or
  9524. { This allows this Movx optimisation to work through the SETcc instructions
  9525. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9526. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9527. skip over these SETcc instructions). }
  9528. (taicpu(hp1).opcode = A_SETcc) or
  9529. RegInInstruction(ThisReg, hp1)
  9530. ) do
  9531. begin
  9532. case taicpu(hp1).opcode of
  9533. A_INC,A_DEC:
  9534. begin
  9535. { Has to be an exact match on the register }
  9536. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9537. Break;
  9538. if taicpu(hp1).opcode = A_INC then
  9539. begin
  9540. Inc(TestValMin);
  9541. Inc(TestValMax);
  9542. Inc(TestValSignedMax);
  9543. end
  9544. else
  9545. begin
  9546. Dec(TestValMin);
  9547. Dec(TestValMax);
  9548. Dec(TestValSignedMax);
  9549. end;
  9550. end;
  9551. A_TEST, A_CMP:
  9552. begin
  9553. if (
  9554. { Too high a risk of non-linear behaviour that breaks DFA
  9555. here, unless it's cmp $0,%reg, which is equivalent to
  9556. test %reg,%reg }
  9557. OrXorUsed and
  9558. (taicpu(hp1).opcode = A_CMP) and
  9559. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9560. ) or
  9561. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9562. { Has to be an exact match on the register }
  9563. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9564. (
  9565. { Permit "test %reg,%reg" }
  9566. (taicpu(hp1).opcode = A_TEST) and
  9567. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9568. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9569. ) or
  9570. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9571. { Make sure the comparison value is not smaller than the
  9572. smallest allowed signed value for the minimum size (e.g.
  9573. -128 for 8-bit) }
  9574. not (
  9575. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9576. { Is it in the negative range? }
  9577. (
  9578. (taicpu(hp1).oper[0]^.val < 0) and
  9579. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9580. )
  9581. ) then
  9582. Break;
  9583. { Check to see if the active register is used afterwards }
  9584. TransferUsedRegs(TmpUsedRegs);
  9585. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9586. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9587. begin
  9588. { Make sure the comparison or any previous instructions
  9589. hasn't pushed the test values outside of the range of
  9590. MinSize }
  9591. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9592. begin
  9593. { Exceeded lower bound but not upper bound }
  9594. Exit;
  9595. end
  9596. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9597. begin
  9598. { Size didn't exceed lower bound }
  9599. TargetSize := MinSize;
  9600. end
  9601. else
  9602. Break;
  9603. case TargetSize of
  9604. S_B:
  9605. TargetSubReg := R_SUBL;
  9606. S_W:
  9607. TargetSubReg := R_SUBW;
  9608. S_L:
  9609. TargetSubReg := R_SUBD;
  9610. else
  9611. InternalError(2021051002);
  9612. end;
  9613. if TargetSize <> MaxSize then
  9614. begin
  9615. { Update the register to its new size }
  9616. setsubreg(ThisReg, TargetSubReg);
  9617. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9618. taicpu(hp1).oper[1]^.reg := ThisReg;
  9619. taicpu(hp1).opsize := TargetSize;
  9620. { Convert the input MOVZX to a MOV if necessary }
  9621. AdjustInitialLoadAndSize;
  9622. if (InstrMax >= 0) then
  9623. begin
  9624. for Index := 0 to InstrMax do
  9625. begin
  9626. { If p_removed is true, then the original MOV/Z was removed
  9627. and removing the AND instruction may not be safe if it
  9628. appears first }
  9629. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9630. InternalError(2020112311);
  9631. if InstrList[Index].oper[0]^.typ = top_reg then
  9632. InstrList[Index].oper[0]^.reg := ThisReg;
  9633. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9634. InstrList[Index].opsize := MinSize;
  9635. end;
  9636. end;
  9637. Result := True;
  9638. end;
  9639. Exit;
  9640. end;
  9641. end;
  9642. A_SETcc:
  9643. begin
  9644. { This allows this Movx optimisation to work through the SETcc instructions
  9645. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9646. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9647. skip over these SETcc instructions). }
  9648. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9649. { Of course, break out if the current register is used }
  9650. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9651. Break
  9652. else
  9653. { We must use Continue so the instruction doesn't get added
  9654. to InstrList }
  9655. Continue;
  9656. end;
  9657. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9658. begin
  9659. if
  9660. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9661. { Has to be an exact match on the register }
  9662. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9663. (
  9664. (
  9665. (taicpu(hp1).oper[0]^.typ = top_const) and
  9666. (
  9667. (
  9668. (taicpu(hp1).opcode = A_SHL) and
  9669. (
  9670. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9671. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9672. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9673. )
  9674. ) or (
  9675. (taicpu(hp1).opcode <> A_SHL) and
  9676. (
  9677. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9678. { Is it in the negative range? }
  9679. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9680. )
  9681. )
  9682. )
  9683. ) or (
  9684. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9685. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9686. )
  9687. ) then
  9688. Break;
  9689. { Only process OR and XOR if there are only bitwise operations,
  9690. since otherwise they can too easily fool the data flow
  9691. analysis (they can cause non-linear behaviour) }
  9692. case taicpu(hp1).opcode of
  9693. A_ADD:
  9694. begin
  9695. if OrXorUsed then
  9696. { Too high a risk of non-linear behaviour that breaks DFA here }
  9697. Break
  9698. else
  9699. BitwiseOnly := False;
  9700. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9701. begin
  9702. TestValMin := TestValMin * 2;
  9703. TestValMax := TestValMax * 2;
  9704. TestValSignedMax := TestValSignedMax * 2;
  9705. end
  9706. else
  9707. begin
  9708. WorkingValue := taicpu(hp1).oper[0]^.val;
  9709. TestValMin := TestValMin + WorkingValue;
  9710. TestValMax := TestValMax + WorkingValue;
  9711. TestValSignedMax := TestValSignedMax + WorkingValue;
  9712. end;
  9713. end;
  9714. A_SUB:
  9715. begin
  9716. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9717. begin
  9718. TestValMin := 0;
  9719. TestValMax := 0;
  9720. TestValSignedMax := 0;
  9721. end
  9722. else
  9723. begin
  9724. if OrXorUsed then
  9725. { Too high a risk of non-linear behaviour that breaks DFA here }
  9726. Break
  9727. else
  9728. BitwiseOnly := False;
  9729. WorkingValue := taicpu(hp1).oper[0]^.val;
  9730. TestValMin := TestValMin - WorkingValue;
  9731. TestValMax := TestValMax - WorkingValue;
  9732. TestValSignedMax := TestValSignedMax - WorkingValue;
  9733. end;
  9734. end;
  9735. A_AND:
  9736. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9737. begin
  9738. { we might be able to go smaller if AND appears first }
  9739. if InstrMax = -1 then
  9740. case MinSize of
  9741. S_B:
  9742. ;
  9743. S_W:
  9744. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9745. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9746. begin
  9747. TryShiftDown := S_B;
  9748. TryShiftDownLimit := $FF;
  9749. end;
  9750. S_L:
  9751. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9752. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9753. begin
  9754. TryShiftDown := S_B;
  9755. TryShiftDownLimit := $FF;
  9756. end
  9757. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9758. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9759. begin
  9760. TryShiftDown := S_W;
  9761. TryShiftDownLimit := $FFFF;
  9762. end;
  9763. else
  9764. InternalError(2020112320);
  9765. end;
  9766. WorkingValue := taicpu(hp1).oper[0]^.val;
  9767. TestValMin := TestValMin and WorkingValue;
  9768. TestValMax := TestValMax and WorkingValue;
  9769. TestValSignedMax := TestValSignedMax and WorkingValue;
  9770. end;
  9771. A_OR:
  9772. begin
  9773. if not BitwiseOnly then
  9774. Break;
  9775. OrXorUsed := True;
  9776. WorkingValue := taicpu(hp1).oper[0]^.val;
  9777. TestValMin := TestValMin or WorkingValue;
  9778. TestValMax := TestValMax or WorkingValue;
  9779. TestValSignedMax := TestValSignedMax or WorkingValue;
  9780. end;
  9781. A_XOR:
  9782. begin
  9783. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9784. begin
  9785. TestValMin := 0;
  9786. TestValMax := 0;
  9787. TestValSignedMax := 0;
  9788. end
  9789. else
  9790. begin
  9791. if not BitwiseOnly then
  9792. Break;
  9793. OrXorUsed := True;
  9794. WorkingValue := taicpu(hp1).oper[0]^.val;
  9795. TestValMin := TestValMin xor WorkingValue;
  9796. TestValMax := TestValMax xor WorkingValue;
  9797. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9798. end;
  9799. end;
  9800. A_SHL:
  9801. begin
  9802. BitwiseOnly := False;
  9803. WorkingValue := taicpu(hp1).oper[0]^.val;
  9804. TestValMin := TestValMin shl WorkingValue;
  9805. TestValMax := TestValMax shl WorkingValue;
  9806. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9807. end;
  9808. A_SHR,
  9809. { The first instruction was MOVZX, so the value won't be negative }
  9810. A_SAR:
  9811. begin
  9812. if InstrMax <> -1 then
  9813. BitwiseOnly := False
  9814. else
  9815. { we might be able to go smaller if SHR appears first }
  9816. case MinSize of
  9817. S_B:
  9818. ;
  9819. S_W:
  9820. if (taicpu(hp1).oper[0]^.val >= 8) then
  9821. begin
  9822. TryShiftDown := S_B;
  9823. TryShiftDownLimit := $FF;
  9824. TryShiftDownSignedLimit := $7F;
  9825. TryShiftDownSignedLimitLower := -128;
  9826. end;
  9827. S_L:
  9828. if (taicpu(hp1).oper[0]^.val >= 24) then
  9829. begin
  9830. TryShiftDown := S_B;
  9831. TryShiftDownLimit := $FF;
  9832. TryShiftDownSignedLimit := $7F;
  9833. TryShiftDownSignedLimitLower := -128;
  9834. end
  9835. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9836. begin
  9837. TryShiftDown := S_W;
  9838. TryShiftDownLimit := $FFFF;
  9839. TryShiftDownSignedLimit := $7FFF;
  9840. TryShiftDownSignedLimitLower := -32768;
  9841. end;
  9842. else
  9843. InternalError(2020112321);
  9844. end;
  9845. WorkingValue := taicpu(hp1).oper[0]^.val;
  9846. if taicpu(hp1).opcode = A_SAR then
  9847. begin
  9848. TestValMin := SarInt64(TestValMin, WorkingValue);
  9849. TestValMax := SarInt64(TestValMax, WorkingValue);
  9850. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9851. end
  9852. else
  9853. begin
  9854. TestValMin := TestValMin shr WorkingValue;
  9855. TestValMax := TestValMax shr WorkingValue;
  9856. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9857. end;
  9858. end;
  9859. else
  9860. InternalError(2020112303);
  9861. end;
  9862. end;
  9863. (*
  9864. A_IMUL:
  9865. case taicpu(hp1).ops of
  9866. 2:
  9867. begin
  9868. if not MatchOpType(hp1, top_reg, top_reg) or
  9869. { Has to be an exact match on the register }
  9870. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9871. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9872. Break;
  9873. TestValMin := TestValMin * TestValMin;
  9874. TestValMax := TestValMax * TestValMax;
  9875. TestValSignedMax := TestValSignedMax * TestValMax;
  9876. end;
  9877. 3:
  9878. begin
  9879. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9880. { Has to be an exact match on the register }
  9881. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9882. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9883. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9884. { Is it in the negative range? }
  9885. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9886. Break;
  9887. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9888. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9889. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9890. end;
  9891. else
  9892. Break;
  9893. end;
  9894. A_IDIV:
  9895. case taicpu(hp1).ops of
  9896. 3:
  9897. begin
  9898. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9899. { Has to be an exact match on the register }
  9900. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9901. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9902. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9903. { Is it in the negative range? }
  9904. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9905. Break;
  9906. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9907. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9908. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9909. end;
  9910. else
  9911. Break;
  9912. end;
  9913. *)
  9914. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9915. begin
  9916. { If there are no instructions in between, then we might be able to make a saving }
  9917. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9918. Break;
  9919. { We have something like:
  9920. movzbw %dl,%dx
  9921. ...
  9922. movswl %dx,%edx
  9923. Change the latter to a zero-extension then enter the
  9924. A_MOVZX case branch.
  9925. }
  9926. {$ifdef x86_64}
  9927. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9928. begin
  9929. { this becomes a zero extension from 32-bit to 64-bit, but
  9930. the upper 32 bits are already zero, so just delete the
  9931. instruction }
  9932. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9933. RemoveInstruction(hp1);
  9934. Result := True;
  9935. Exit;
  9936. end
  9937. else
  9938. {$endif x86_64}
  9939. begin
  9940. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9941. taicpu(hp1).opcode := A_MOVZX;
  9942. {$ifdef x86_64}
  9943. case taicpu(hp1).opsize of
  9944. S_BQ:
  9945. begin
  9946. taicpu(hp1).opsize := S_BL;
  9947. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9948. end;
  9949. S_WQ:
  9950. begin
  9951. taicpu(hp1).opsize := S_WL;
  9952. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9953. end;
  9954. S_LQ:
  9955. begin
  9956. taicpu(hp1).opcode := A_MOV;
  9957. taicpu(hp1).opsize := S_L;
  9958. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9959. { In this instance, we need to break out because the
  9960. instruction is no longer MOVZX or MOVSXD }
  9961. Result := True;
  9962. Exit;
  9963. end;
  9964. else
  9965. ;
  9966. end;
  9967. {$endif x86_64}
  9968. Result := CompressInstructions;
  9969. Exit;
  9970. end;
  9971. end;
  9972. A_MOVZX:
  9973. begin
  9974. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9975. Break;
  9976. if (InstrMax = -1) then
  9977. begin
  9978. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9979. begin
  9980. { Optimise around i40003 }
  9981. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9982. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9983. {$ifndef x86_64}
  9984. and (
  9985. (taicpu(p).oper[0]^.typ <> top_reg) or
  9986. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9987. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9988. )
  9989. {$endif not x86_64}
  9990. then
  9991. begin
  9992. if (taicpu(p).oper[0]^.typ = top_reg) then
  9993. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9994. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9995. taicpu(p).opsize := S_BL;
  9996. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9997. RemoveInstruction(hp1);
  9998. Result := True;
  9999. Exit;
  10000. end;
  10001. end
  10002. else
  10003. begin
  10004. { Will return false if the second parameter isn't ThisReg
  10005. (can happen on -O2 and under) }
  10006. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10007. begin
  10008. { The two MOVZX instructions are adjacent, so remove the first one }
  10009. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10010. RemoveCurrentP(p);
  10011. Result := True;
  10012. Exit;
  10013. end;
  10014. Break;
  10015. end;
  10016. end;
  10017. Result := CompressInstructions;
  10018. Exit;
  10019. end;
  10020. else
  10021. { This includes ADC, SBB and IDIV }
  10022. Break;
  10023. end;
  10024. if not CheckOverflowConditions then
  10025. Break;
  10026. { Contains highest index (so instruction count - 1) }
  10027. Inc(InstrMax);
  10028. if InstrMax > High(InstrList) then
  10029. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10030. InstrList[InstrMax] := taicpu(hp1);
  10031. end;
  10032. end;
  10033. {$pop}
  10034. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10035. var
  10036. hp1 : tai;
  10037. begin
  10038. Result:=false;
  10039. if (taicpu(p).ops >= 2) and
  10040. ((taicpu(p).oper[0]^.typ = top_const) or
  10041. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10042. (taicpu(p).oper[1]^.typ = top_reg) and
  10043. ((taicpu(p).ops = 2) or
  10044. ((taicpu(p).oper[2]^.typ = top_reg) and
  10045. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10046. GetLastInstruction(p,hp1) and
  10047. MatchInstruction(hp1,A_MOV,[]) and
  10048. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10049. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10050. begin
  10051. TransferUsedRegs(TmpUsedRegs);
  10052. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10053. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10054. { change
  10055. mov reg1,reg2
  10056. imul y,reg2 to imul y,reg1,reg2 }
  10057. begin
  10058. taicpu(p).ops := 3;
  10059. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10060. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10061. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10062. RemoveInstruction(hp1);
  10063. result:=true;
  10064. end;
  10065. end;
  10066. end;
  10067. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10068. var
  10069. ThisLabel: TAsmLabel;
  10070. begin
  10071. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10072. ThisLabel.decrefs;
  10073. taicpu(p).condition := C_None;
  10074. taicpu(p).opcode := A_RET;
  10075. taicpu(p).is_jmp := false;
  10076. taicpu(p).ops := taicpu(ret_p).ops;
  10077. case taicpu(ret_p).ops of
  10078. 0:
  10079. taicpu(p).clearop(0);
  10080. 1:
  10081. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10082. else
  10083. internalerror(2016041301);
  10084. end;
  10085. { If the original label is now dead, it might turn out that the label
  10086. immediately follows p. As a result, everything beyond it, which will
  10087. be just some final register configuration and a RET instruction, is
  10088. now dead code. [Kit] }
  10089. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10090. running RemoveDeadCodeAfterJump for each RET instruction, because
  10091. this optimisation rarely happens and most RETs appear at the end of
  10092. routines where there is nothing that can be stripped. [Kit] }
  10093. if not ThisLabel.is_used then
  10094. RemoveDeadCodeAfterJump(p);
  10095. end;
  10096. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10097. var
  10098. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10099. Unconditional, PotentialModified: Boolean;
  10100. OperPtr: POper;
  10101. NewRef: TReference;
  10102. InstrList: array of taicpu;
  10103. InstrMax, Index: Integer;
  10104. const
  10105. {$ifdef DEBUG_AOPTCPU}
  10106. SNoFlags: shortstring = ' so the flags aren''t modified';
  10107. {$else DEBUG_AOPTCPU}
  10108. SNoFlags = '';
  10109. {$endif DEBUG_AOPTCPU}
  10110. begin
  10111. Result:=false;
  10112. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10113. begin
  10114. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10115. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10116. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10117. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10118. GetNextInstruction(hp1, hp2) and
  10119. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10120. { Change from: To:
  10121. set(C) %reg j(~C) label
  10122. test %reg,%reg/cmp $0,%reg
  10123. je label
  10124. set(C) %reg j(C) label
  10125. test %reg,%reg/cmp $0,%reg
  10126. jne label
  10127. (Also do something similar with sete/setne instead of je/jne)
  10128. }
  10129. begin
  10130. { Before we do anything else, we need to check the instructions
  10131. in between SETcc and TEST to make sure they don't modify the
  10132. FLAGS register - if -O2 or under, there won't be any
  10133. instructions between SET and TEST }
  10134. TransferUsedRegs(TmpUsedRegs);
  10135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10136. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10137. begin
  10138. next := p;
  10139. SetLength(InstrList, 0);
  10140. InstrMax := -1;
  10141. PotentialModified := False;
  10142. { Make a note of every instruction that modifies the FLAGS
  10143. register }
  10144. while GetNextInstruction(next, next) and (next <> hp1) do
  10145. begin
  10146. if next.typ <> ait_instruction then
  10147. { GetNextInstructionUsingReg should have returned False }
  10148. InternalError(2021051701);
  10149. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10150. begin
  10151. case taicpu(next).opcode of
  10152. A_SETcc,
  10153. A_CMOVcc,
  10154. A_Jcc:
  10155. begin
  10156. if PotentialModified then
  10157. { Not safe because the flags were modified earlier }
  10158. Exit
  10159. else
  10160. { Condition is the same as the initial SETcc, so this is safe
  10161. (don't add to instruction list though) }
  10162. Continue;
  10163. end;
  10164. A_ADD:
  10165. begin
  10166. if (taicpu(next).opsize = S_B) or
  10167. { LEA doesn't support 8-bit operands }
  10168. (taicpu(next).oper[1]^.typ <> top_reg) or
  10169. { Must write to a register }
  10170. (taicpu(next).oper[0]^.typ = top_ref) then
  10171. { Require a constant or a register }
  10172. Exit;
  10173. PotentialModified := True;
  10174. end;
  10175. A_SUB:
  10176. begin
  10177. if (taicpu(next).opsize = S_B) or
  10178. { LEA doesn't support 8-bit operands }
  10179. (taicpu(next).oper[1]^.typ <> top_reg) or
  10180. { Must write to a register }
  10181. (taicpu(next).oper[0]^.typ <> top_const) or
  10182. (taicpu(next).oper[0]^.val = $80000000) then
  10183. { Can't subtract a register with LEA - also
  10184. check that the value isn't -2^31, as this
  10185. can't be negated }
  10186. Exit;
  10187. PotentialModified := True;
  10188. end;
  10189. A_SAL,
  10190. A_SHL:
  10191. begin
  10192. if (taicpu(next).opsize = S_B) or
  10193. { LEA doesn't support 8-bit operands }
  10194. (taicpu(next).oper[1]^.typ <> top_reg) or
  10195. { Must write to a register }
  10196. (taicpu(next).oper[0]^.typ <> top_const) or
  10197. (taicpu(next).oper[0]^.val < 0) or
  10198. (taicpu(next).oper[0]^.val > 3) then
  10199. Exit;
  10200. PotentialModified := True;
  10201. end;
  10202. A_IMUL:
  10203. begin
  10204. if (taicpu(next).ops <> 3) or
  10205. (taicpu(next).oper[1]^.typ <> top_reg) or
  10206. { Must write to a register }
  10207. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10208. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10209. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10210. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10211. Exit
  10212. else
  10213. PotentialModified := True;
  10214. end;
  10215. else
  10216. { Don't know how to change this, so abort }
  10217. Exit;
  10218. end;
  10219. { Contains highest index (so instruction count - 1) }
  10220. Inc(InstrMax);
  10221. if InstrMax > High(InstrList) then
  10222. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10223. InstrList[InstrMax] := taicpu(next);
  10224. end;
  10225. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10226. end;
  10227. if not Assigned(next) or (next <> hp1) then
  10228. { It should be equal to hp1 }
  10229. InternalError(2021051702);
  10230. { Cycle through each instruction and check to see if we can
  10231. change them to versions that don't modify the flags }
  10232. if (InstrMax >= 0) then
  10233. begin
  10234. for Index := 0 to InstrMax do
  10235. case InstrList[Index].opcode of
  10236. A_ADD:
  10237. begin
  10238. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10239. InstrList[Index].opcode := A_LEA;
  10240. reference_reset(NewRef, 1, []);
  10241. NewRef.base := InstrList[Index].oper[1]^.reg;
  10242. if InstrList[Index].oper[0]^.typ = top_reg then
  10243. begin
  10244. NewRef.index := InstrList[Index].oper[0]^.reg;
  10245. NewRef.scalefactor := 1;
  10246. end
  10247. else
  10248. NewRef.offset := InstrList[Index].oper[0]^.val;
  10249. InstrList[Index].loadref(0, NewRef);
  10250. end;
  10251. A_SUB:
  10252. begin
  10253. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10254. InstrList[Index].opcode := A_LEA;
  10255. reference_reset(NewRef, 1, []);
  10256. NewRef.base := InstrList[Index].oper[1]^.reg;
  10257. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10258. InstrList[Index].loadref(0, NewRef);
  10259. end;
  10260. A_SHL,
  10261. A_SAL:
  10262. begin
  10263. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10264. InstrList[Index].opcode := A_LEA;
  10265. reference_reset(NewRef, 1, []);
  10266. NewRef.index := InstrList[Index].oper[1]^.reg;
  10267. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10268. InstrList[Index].loadref(0, NewRef);
  10269. end;
  10270. A_IMUL:
  10271. begin
  10272. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10273. InstrList[Index].opcode := A_LEA;
  10274. reference_reset(NewRef, 1, []);
  10275. NewRef.index := InstrList[Index].oper[1]^.reg;
  10276. case InstrList[Index].oper[0]^.val of
  10277. 2, 4, 8:
  10278. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10279. else {3, 5 and 9}
  10280. begin
  10281. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10282. NewRef.base := InstrList[Index].oper[1]^.reg;
  10283. end;
  10284. end;
  10285. InstrList[Index].loadref(0, NewRef);
  10286. end;
  10287. else
  10288. InternalError(2021051710);
  10289. end;
  10290. end;
  10291. { Mark the FLAGS register as used across this whole block }
  10292. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10293. end;
  10294. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10295. JumpC := taicpu(hp2).condition;
  10296. Unconditional := False;
  10297. if conditions_equal(JumpC, C_E) then
  10298. SetC := inverse_cond(taicpu(p).condition)
  10299. else if conditions_equal(JumpC, C_NE) then
  10300. SetC := taicpu(p).condition
  10301. else
  10302. { We've got something weird here (and inefficent) }
  10303. begin
  10304. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10305. SetC := C_NONE;
  10306. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10307. if condition_in(C_AE, JumpC) then
  10308. Unconditional := True
  10309. else
  10310. { Not sure what to do with this jump - drop out }
  10311. Exit;
  10312. end;
  10313. RemoveInstruction(hp1);
  10314. if Unconditional then
  10315. MakeUnconditional(taicpu(hp2))
  10316. else
  10317. begin
  10318. if SetC = C_NONE then
  10319. InternalError(2018061402);
  10320. taicpu(hp2).SetCondition(SetC);
  10321. end;
  10322. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10323. TmpUsedRegs }
  10324. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10325. begin
  10326. RemoveCurrentp(p, hp2);
  10327. if taicpu(hp2).opcode = A_SETcc then
  10328. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10329. else
  10330. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10331. end
  10332. else
  10333. if taicpu(hp2).opcode = A_SETcc then
  10334. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10335. else
  10336. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10337. Result := True;
  10338. end
  10339. else if
  10340. { Make sure the instructions are adjacent }
  10341. (
  10342. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10343. GetNextInstruction(p, hp1)
  10344. ) and
  10345. MatchInstruction(hp1, A_MOV, [S_B]) and
  10346. { Writing to memory is allowed }
  10347. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10348. begin
  10349. {
  10350. Watch out for sequences such as:
  10351. set(c)b %regb
  10352. movb %regb,(ref)
  10353. movb $0,1(ref)
  10354. movb $0,2(ref)
  10355. movb $0,3(ref)
  10356. Much more efficient to turn it into:
  10357. movl $0,%regl
  10358. set(c)b %regb
  10359. movl %regl,(ref)
  10360. Or:
  10361. set(c)b %regb
  10362. movzbl %regb,%regl
  10363. movl %regl,(ref)
  10364. }
  10365. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10366. GetNextInstruction(hp1, hp2) and
  10367. MatchInstruction(hp2, A_MOV, [S_B]) and
  10368. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10369. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10370. begin
  10371. { Don't do anything else except set Result to True }
  10372. end
  10373. else
  10374. begin
  10375. if taicpu(p).oper[0]^.typ = top_reg then
  10376. begin
  10377. TransferUsedRegs(TmpUsedRegs);
  10378. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10379. end;
  10380. { If it's not a register, it's a memory address }
  10381. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10382. begin
  10383. { Even if the register is still in use, we can minimise the
  10384. pipeline stall by changing the MOV into another SETcc. }
  10385. taicpu(hp1).opcode := A_SETcc;
  10386. taicpu(hp1).condition := taicpu(p).condition;
  10387. if taicpu(hp1).oper[1]^.typ = top_ref then
  10388. begin
  10389. { Swapping the operand pointers like this is probably a
  10390. bit naughty, but it is far faster than using loadoper
  10391. to transfer the reference from oper[1] to oper[0] if
  10392. you take into account the extra procedure calls and
  10393. the memory allocation and deallocation required }
  10394. OperPtr := taicpu(hp1).oper[1];
  10395. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10396. taicpu(hp1).oper[0] := OperPtr;
  10397. end
  10398. else
  10399. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10400. taicpu(hp1).clearop(1);
  10401. taicpu(hp1).ops := 1;
  10402. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10403. end
  10404. else
  10405. begin
  10406. if taicpu(hp1).oper[1]^.typ = top_reg then
  10407. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10408. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10409. RemoveInstruction(hp1);
  10410. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10411. end
  10412. end;
  10413. Result := True;
  10414. end;
  10415. end;
  10416. end;
  10417. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10418. var
  10419. hp1: tai;
  10420. Count: Integer;
  10421. OrigLabel: TAsmLabel;
  10422. begin
  10423. result := False;
  10424. { Sometimes, the optimisations below can permit this }
  10425. RemoveDeadCodeAfterJump(p);
  10426. 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
  10427. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10428. begin
  10429. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10430. { Also a side-effect of optimisations }
  10431. if CollapseZeroDistJump(p, OrigLabel) then
  10432. begin
  10433. Result := True;
  10434. Exit;
  10435. end;
  10436. hp1 := GetLabelWithSym(OrigLabel);
  10437. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10438. begin
  10439. if taicpu(hp1).opcode = A_RET then
  10440. begin
  10441. {
  10442. change
  10443. jmp .L1
  10444. ...
  10445. .L1:
  10446. ret
  10447. into
  10448. ret
  10449. }
  10450. begin
  10451. ConvertJumpToRET(p, hp1);
  10452. result:=true;
  10453. end;
  10454. end
  10455. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10456. not (cs_opt_size in current_settings.optimizerswitches) and
  10457. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10458. begin
  10459. Result := True;
  10460. Exit;
  10461. end;
  10462. end;
  10463. end;
  10464. end;
  10465. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10466. begin
  10467. Result := assigned(p) and
  10468. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10469. (taicpu(p).oper[1]^.typ = top_reg) and
  10470. (
  10471. (taicpu(p).oper[0]^.typ = top_reg) or
  10472. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10473. it is not expected that this can cause a seg. violation }
  10474. (
  10475. (taicpu(p).oper[0]^.typ = top_ref) and
  10476. { TODO: Can we detect which references become constants at this
  10477. stage so we don't have to do a blanket ban? }
  10478. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10479. (
  10480. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10481. (
  10482. { If the reference also appears in the condition, then we know it's safe, otherwise
  10483. any kind of access violation would have occurred already }
  10484. Assigned(cond_p) and
  10485. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10486. (cond_p.typ = ait_instruction) and
  10487. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10488. { Just consider 2-operand comparison instructions for now to be safe }
  10489. (taicpu(cond_p).ops = 2) and
  10490. (
  10491. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10492. (
  10493. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10494. { Don't risk identical registers but different offsets, as we may have constructs
  10495. such as buffer streams with things like length fields that indicate whether
  10496. any more data follows. And there are probably some contrived examples where
  10497. writing to offsets behind the one being read also lead to access violations }
  10498. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10499. (
  10500. { Check that we're not modifying a register that appears in the reference }
  10501. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10502. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10503. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10504. )
  10505. )
  10506. )
  10507. )
  10508. )
  10509. )
  10510. );
  10511. end;
  10512. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10513. begin
  10514. { Update integer registers, ignoring deallocations }
  10515. repeat
  10516. while assigned(p) and
  10517. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10518. (p.typ = ait_label) or
  10519. ((p.typ = ait_marker) and
  10520. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10521. p := tai(p.next);
  10522. while assigned(p) and
  10523. (p.typ=ait_RegAlloc) Do
  10524. begin
  10525. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10526. begin
  10527. case tai_regalloc(p).ratype of
  10528. ra_alloc :
  10529. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10530. else
  10531. ;
  10532. end;
  10533. end;
  10534. p := tai(p.next);
  10535. end;
  10536. until not(assigned(p)) or
  10537. (not(p.typ in SkipInstr) and
  10538. not((p.typ = ait_label) and
  10539. labelCanBeSkipped(tai_label(p))));
  10540. end;
  10541. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10542. var
  10543. hp1,hp2: tai;
  10544. carryadd_opcode : TAsmOp;
  10545. symbol: TAsmSymbol;
  10546. increg, tmpreg: TRegister;
  10547. {$ifndef i8086}
  10548. { Code and variables specific to CMOV optimisations }
  10549. hp3,hp4,hp5,
  10550. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10551. l, c, w, x : Longint;
  10552. condition, second_condition : TAsmCond;
  10553. FoundMatchingJump, RegMatch: Boolean;
  10554. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10555. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10556. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10557. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10558. new register to store the constant }
  10559. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10560. var
  10561. RegSize: TSubRegister;
  10562. CurrentVal: TCGInt;
  10563. NewReg: TRegister;
  10564. X: ShortInt;
  10565. begin
  10566. Result := False;
  10567. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10568. Exit;
  10569. if StoredCount >= MAX_CMOV_REGISTERS then
  10570. { Arrays are full }
  10571. Exit;
  10572. { Remember that CMOV can't encode 8-bit registers }
  10573. case taicpu(p).opsize of
  10574. S_W:
  10575. RegSize := R_SUBW;
  10576. S_L:
  10577. RegSize := R_SUBD;
  10578. S_Q:
  10579. RegSize := R_SUBQ;
  10580. else
  10581. InternalError(2021100401);
  10582. end;
  10583. { See if the value has already been reserved for another CMOV instruction }
  10584. CurrentVal := taicpu(p).oper[0]^.val;
  10585. for X := 0 to StoredCount - 1 do
  10586. if ConstVals[X] = CurrentVal then
  10587. begin
  10588. ConstRegs[StoredCount] := ConstRegs[X];
  10589. ConstVals[StoredCount] := CurrentVal;
  10590. Result := True;
  10591. Inc(StoredCount);
  10592. { Don't increase CMOVCount this time, since we're re-using a register }
  10593. Exit;
  10594. end;
  10595. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10596. if NewReg = NR_NO then
  10597. { No free registers }
  10598. Exit;
  10599. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10600. up vying for the same register }
  10601. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10602. ConstRegs[StoredCount] := NewReg;
  10603. ConstVals[StoredCount] := CurrentVal;
  10604. Inc(StoredCount);
  10605. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10606. MOV required adds complexity and will cause diminishing returns
  10607. sooner than normal. This is more of an approximate weighting than
  10608. anything else. }
  10609. Inc(CMOVCount);
  10610. Result := True;
  10611. end;
  10612. {$endif i8086}
  10613. begin
  10614. result:=false;
  10615. if GetNextInstruction(p,hp1) then
  10616. begin
  10617. if (hp1.typ=ait_label) then
  10618. begin
  10619. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10620. Exit;
  10621. end
  10622. else if (hp1.typ<>ait_instruction) then
  10623. Exit;
  10624. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10625. if (
  10626. (
  10627. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10628. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10629. (Taicpu(hp1).oper[0]^.val=1)
  10630. ) or
  10631. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10632. ) and
  10633. GetNextInstruction(hp1,hp2) and
  10634. SkipAligns(hp2, hp2) and
  10635. (hp2.typ = ait_label) and
  10636. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10637. { jb @@1 cmc
  10638. inc/dec operand --> adc/sbb operand,0
  10639. @@1:
  10640. ... and ...
  10641. jnb @@1
  10642. inc/dec operand --> adc/sbb operand,0
  10643. @@1: }
  10644. begin
  10645. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10646. begin
  10647. case taicpu(hp1).opcode of
  10648. A_INC,
  10649. A_ADD:
  10650. carryadd_opcode:=A_ADC;
  10651. A_DEC,
  10652. A_SUB:
  10653. carryadd_opcode:=A_SBB;
  10654. else
  10655. InternalError(2021011001);
  10656. end;
  10657. Taicpu(p).clearop(0);
  10658. Taicpu(p).ops:=0;
  10659. Taicpu(p).is_jmp:=false;
  10660. Taicpu(p).opcode:=A_CMC;
  10661. Taicpu(p).condition:=C_NONE;
  10662. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10663. Taicpu(hp1).ops:=2;
  10664. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10665. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10666. else
  10667. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10668. Taicpu(hp1).loadconst(0,0);
  10669. Taicpu(hp1).opcode:=carryadd_opcode;
  10670. result:=true;
  10671. exit;
  10672. end
  10673. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10674. begin
  10675. case taicpu(hp1).opcode of
  10676. A_INC,
  10677. A_ADD:
  10678. carryadd_opcode:=A_ADC;
  10679. A_DEC,
  10680. A_SUB:
  10681. carryadd_opcode:=A_SBB;
  10682. else
  10683. InternalError(2021011002);
  10684. end;
  10685. Taicpu(hp1).ops:=2;
  10686. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10687. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10688. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10689. else
  10690. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10691. Taicpu(hp1).loadconst(0,0);
  10692. Taicpu(hp1).opcode:=carryadd_opcode;
  10693. RemoveCurrentP(p, hp1);
  10694. result:=true;
  10695. exit;
  10696. end
  10697. {
  10698. jcc @@1 setcc tmpreg
  10699. inc/dec/add/sub operand -> (movzx tmpreg)
  10700. @@1: add/sub tmpreg,operand
  10701. While this increases code size slightly, it makes the code much faster if the
  10702. jump is unpredictable
  10703. }
  10704. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10705. begin
  10706. { search for an available register which is volatile }
  10707. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10708. if increg <> NR_NO then
  10709. begin
  10710. { We don't need to check if tmpreg is in hp1 or not, because
  10711. it will be marked as in use at p (if not, this is
  10712. indictive of a compiler bug). }
  10713. TAsmLabel(symbol).decrefs;
  10714. Taicpu(p).clearop(0);
  10715. Taicpu(p).ops:=1;
  10716. Taicpu(p).is_jmp:=false;
  10717. Taicpu(p).opcode:=A_SETcc;
  10718. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10719. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10720. Taicpu(p).loadreg(0,increg);
  10721. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10722. begin
  10723. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10724. R_SUBW:
  10725. begin
  10726. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10727. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10728. end;
  10729. R_SUBD:
  10730. begin
  10731. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10732. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10733. end;
  10734. {$ifdef x86_64}
  10735. R_SUBQ:
  10736. begin
  10737. { MOVZX doesn't have a 64-bit variant, because
  10738. the 32-bit version implicitly zeroes the
  10739. upper 32-bits of the destination register }
  10740. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10741. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10742. setsubreg(tmpreg, R_SUBQ);
  10743. end;
  10744. {$endif x86_64}
  10745. else
  10746. Internalerror(2020030601);
  10747. end;
  10748. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10749. asml.InsertAfter(hp2,p);
  10750. end
  10751. else
  10752. tmpreg := increg;
  10753. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10754. begin
  10755. Taicpu(hp1).ops:=2;
  10756. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10757. end;
  10758. Taicpu(hp1).loadreg(0,tmpreg);
  10759. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10760. Result := True;
  10761. { p is no longer a Jcc instruction, so exit }
  10762. Exit;
  10763. end;
  10764. end;
  10765. end;
  10766. { Detect the following:
  10767. jmp<cond> @Lbl1
  10768. jmp @Lbl2
  10769. ...
  10770. @Lbl1:
  10771. ret
  10772. Change to:
  10773. jmp<inv_cond> @Lbl2
  10774. ret
  10775. }
  10776. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10777. begin
  10778. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10779. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10780. MatchInstruction(hp2,A_RET,[S_NO]) then
  10781. begin
  10782. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10783. { Change label address to that of the unconditional jump }
  10784. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10785. TAsmLabel(symbol).DecRefs;
  10786. taicpu(hp1).opcode := A_RET;
  10787. taicpu(hp1).is_jmp := false;
  10788. taicpu(hp1).ops := taicpu(hp2).ops;
  10789. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10790. case taicpu(hp2).ops of
  10791. 0:
  10792. taicpu(hp1).clearop(0);
  10793. 1:
  10794. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10795. else
  10796. internalerror(2016041302);
  10797. end;
  10798. end;
  10799. {$ifndef i8086}
  10800. end
  10801. {
  10802. convert
  10803. j<c> .L1
  10804. mov 1,reg
  10805. jmp .L2
  10806. .L1
  10807. mov 0,reg
  10808. .L2
  10809. into
  10810. mov 0,reg
  10811. set<not(c)> reg
  10812. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10813. would destroy the flag contents
  10814. }
  10815. else if MatchInstruction(hp1,A_MOV,[]) and
  10816. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10817. {$ifdef i386}
  10818. (
  10819. { Under i386, ESI, EDI, EBP and ESP
  10820. don't have an 8-bit representation }
  10821. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10822. ) and
  10823. {$endif i386}
  10824. (taicpu(hp1).oper[0]^.val=1) and
  10825. GetNextInstruction(hp1,hp2) and
  10826. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10827. GetNextInstruction(hp2,hp3) and
  10828. { skip align }
  10829. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10830. (hp3.typ=ait_label) and
  10831. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10832. (tai_label(hp3).labsym.getrefs=1) and
  10833. GetNextInstruction(hp3,hp4) and
  10834. MatchInstruction(hp4,A_MOV,[]) and
  10835. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10836. (taicpu(hp4).oper[0]^.val=0) and
  10837. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10838. GetNextInstruction(hp4,hp5) and
  10839. (hp5.typ=ait_label) and
  10840. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10841. (tai_label(hp5).labsym.getrefs=1) then
  10842. begin
  10843. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10844. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10845. { remove last label }
  10846. RemoveInstruction(hp5);
  10847. { remove second label }
  10848. RemoveInstruction(hp3);
  10849. { if align is present remove it }
  10850. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10851. RemoveInstruction(hp3);
  10852. { remove jmp }
  10853. RemoveInstruction(hp2);
  10854. if taicpu(hp1).opsize=S_B then
  10855. RemoveInstruction(hp1)
  10856. else
  10857. taicpu(hp1).loadconst(0,0);
  10858. taicpu(hp4).opcode:=A_SETcc;
  10859. taicpu(hp4).opsize:=S_B;
  10860. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10861. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10862. taicpu(hp4).opercnt:=1;
  10863. taicpu(hp4).ops:=1;
  10864. taicpu(hp4).freeop(1);
  10865. RemoveCurrentP(p);
  10866. Result:=true;
  10867. exit;
  10868. end
  10869. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10870. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10871. begin
  10872. { check for
  10873. jCC xxx
  10874. <several movs>
  10875. xxx:
  10876. Also spot:
  10877. Jcc xxx
  10878. <several movs>
  10879. jmp xxx
  10880. Change to:
  10881. <several cmovs with inverted condition>
  10882. jmp xxx (only for the 2nd case)
  10883. }
  10884. hp2 := p;
  10885. hp_lblxxx := hp1;
  10886. hp_flagalloc := nil;
  10887. hp_stop := nil;
  10888. FoundMatchingJump := False;
  10889. { Remember the first instruction in the first block of MOVs }
  10890. hpmov1 := hp1;
  10891. TransferUsedRegs(TmpUsedRegs);
  10892. while assigned(hp_lblxxx) and
  10893. { stop on labels }
  10894. (hp_lblxxx.typ <> ait_label) do
  10895. begin
  10896. { Keep track of all integer registers that are used }
  10897. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10898. if hp_lblxxx.typ = ait_instruction then
  10899. begin
  10900. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10901. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10902. begin
  10903. hp_stop := hp_lblxxx;
  10904. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10905. begin
  10906. { We found Jcc xxx; <several movs>; Jmp xxx }
  10907. FoundMatchingJump := True;
  10908. Break;
  10909. end;
  10910. { If it's not the jump we're looking for, it's
  10911. possibly the "if..else" variant }
  10912. end
  10913. { Check to see if we have a valid MOV instruction instead }
  10914. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10915. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10916. Break
  10917. else
  10918. { This will be a valid MOV }
  10919. hp_stop := hp_lblxxx;
  10920. end;
  10921. hp2 := hp_lblxxx;
  10922. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10923. end;
  10924. { Just make sure the last MOV is included if there's no jump }
  10925. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10926. hp_stop := hp_lblxxx;
  10927. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10928. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10929. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10930. jmp yyy; xxx:; movs; yyy:" variation }
  10931. if assigned(hp_lblxxx) and
  10932. (
  10933. { If we found JMP xxx, we don't actually need a label
  10934. (hp_lblxxx is the JMP instruction instead) }
  10935. FoundMatchingJump or
  10936. { Make sure we actually have the right label }
  10937. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10938. ) then
  10939. begin
  10940. { Use TmpUsedRegs to track registers that we reserve }
  10941. { When allocating temporary registers, try to look one
  10942. instruction back, as defining them before a CMP or TEST
  10943. instruction will be faster, and also avoid picking a
  10944. register that was only just deallocated }
  10945. if GetLastInstruction(p, hp_prev) and
  10946. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  10947. begin
  10948. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10949. for l := 0 to 1 do
  10950. with taicpu(hp_prev).oper[l]^ do
  10951. case typ of
  10952. top_reg:
  10953. if getregtype(reg) = R_INTREGISTER then
  10954. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10955. top_ref:
  10956. begin
  10957. if
  10958. {$ifdef x86_64}
  10959. (ref^.base <> NR_RIP) and
  10960. {$endif x86_64}
  10961. (ref^.base <> NR_NO) then
  10962. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10963. if (ref^.index <> NR_NO) then
  10964. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10965. end
  10966. else
  10967. ;
  10968. end;
  10969. { When inserting instructions before hp_prev, try to insert
  10970. them before the allocation of the FLAGS register }
  10971. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10972. { If not found, set it equal to hp_prev so it's something sensible }
  10973. hp_flagalloc := hp_prev;
  10974. hp_prev2 := nil;
  10975. { When dealing with a comparison against zero, take
  10976. note of the instruction before it to see if we can
  10977. move instructions further back in order to benefit
  10978. PostPeepholeOptTestOr.
  10979. }
  10980. if (
  10981. (
  10982. (taicpu(hp_prev).opcode = A_CMP) and
  10983. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10984. ) or
  10985. (
  10986. (taicpu(hp_prev).opcode = A_TEST) and
  10987. (
  10988. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10989. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10990. )
  10991. )
  10992. ) and
  10993. GetLastInstruction(hp_prev, hp_prev2) then
  10994. begin
  10995. if (hp_prev2.typ = ait_instruction) and
  10996. { These instructions set the zero flag if the result is zero }
  10997. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10998. begin
  10999. { Also mark all the registers in this previous instruction
  11000. as 'in use', even if they've just been deallocated }
  11001. for l := 0 to 1 do
  11002. with taicpu(hp_prev2).oper[l]^ do
  11003. case typ of
  11004. top_reg:
  11005. if getregtype(reg) = R_INTREGISTER then
  11006. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11007. top_ref:
  11008. begin
  11009. if
  11010. {$ifdef x86_64}
  11011. (ref^.base <> NR_RIP) and
  11012. {$endif x86_64}
  11013. (ref^.base <> NR_NO) then
  11014. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11015. if (ref^.index <> NR_NO) then
  11016. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11017. end
  11018. else
  11019. ;
  11020. end;
  11021. end
  11022. else
  11023. { Unsuitable instruction }
  11024. hp_prev2 := nil;
  11025. end;
  11026. end
  11027. else
  11028. begin
  11029. hp_prev := p;
  11030. { When inserting instructions before hp_prev, try to insert
  11031. them before the allocation of the FLAGS register }
  11032. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11033. { If not found, set it equal to p so it's something sensible }
  11034. hp_flagalloc := p;
  11035. hp_prev2 := nil;
  11036. end;
  11037. l := 0;
  11038. c := 0;
  11039. { Initialise RegWrites, ConstRegs and ConstVals }
  11040. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11041. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11042. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11043. while assigned(hp1) and
  11044. { Stop on the label we found }
  11045. (hp1 <> hp_lblxxx) do
  11046. begin
  11047. case hp1.typ of
  11048. ait_instruction:
  11049. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11050. begin
  11051. if CanBeCMOV(hp1, hp_prev) then
  11052. Inc(l)
  11053. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11054. { CMOV with constants grows the code size }
  11055. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11056. begin
  11057. { Register was reserved by TryCMOVConst and
  11058. stored on ConstRegs[c] }
  11059. end
  11060. else
  11061. Break;
  11062. end
  11063. else
  11064. Break;
  11065. else
  11066. ;
  11067. end;
  11068. GetNextInstruction(hp1,hp1);
  11069. end;
  11070. if (hp1 = hp_lblxxx) then
  11071. begin
  11072. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11073. begin
  11074. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11075. TmpUsedRegs[R_INTREGISTER].Clear;
  11076. x := 0;
  11077. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11078. condition := inverse_cond(taicpu(p).condition);
  11079. UpdateUsedRegs(tai(p.next));
  11080. hp1 := hpmov1;
  11081. repeat
  11082. if not Assigned(hp1) then
  11083. InternalError(2018062900);
  11084. if (hp1.typ = ait_instruction) then
  11085. begin
  11086. { Extra safeguard }
  11087. if (taicpu(hp1).opcode <> A_MOV) then
  11088. InternalError(2018062901);
  11089. if taicpu(hp1).oper[0]^.typ = top_const then
  11090. begin
  11091. if x >= MAX_CMOV_REGISTERS then
  11092. InternalError(2021100410);
  11093. { If it's in TmpUsedRegs, then this register
  11094. is being used more than once and hence has
  11095. already had its value defined (it gets
  11096. added to UsedRegs through AllocRegBetween
  11097. below) }
  11098. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11099. begin
  11100. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11101. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11102. asml.InsertBefore(hp_new, hp_flagalloc);
  11103. if Assigned(hp_prev2) then
  11104. TrySwapMovOp(hp_prev2, hp_new);
  11105. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11106. end
  11107. else
  11108. { We just need an instruction between hp_prev and hp1
  11109. where we know the register is marked as in use }
  11110. hp_new := hpmov1;
  11111. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11112. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11113. Inc(x);
  11114. end;
  11115. taicpu(hp1).opcode := A_CMOVcc;
  11116. taicpu(hp1).condition := condition;
  11117. end;
  11118. UpdateUsedRegs(tai(hp1.next));
  11119. GetNextInstruction(hp1, hp1);
  11120. until (hp1 = hp_lblxxx);
  11121. hp2 := hp_lblxxx;
  11122. repeat
  11123. if not Assigned(hp2) then
  11124. InternalError(2018062910);
  11125. case hp2.typ of
  11126. ait_label:
  11127. { What we expected - break out of the loop (it won't be a dead label at the top of
  11128. a cluster because that was optimised at an earlier stage) }
  11129. Break;
  11130. ait_align:
  11131. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11132. begin
  11133. hp2 := tai(hp2.Next);
  11134. Continue;
  11135. end;
  11136. ait_instruction:
  11137. begin
  11138. if taicpu(hp2).opcode<>A_JMP then
  11139. InternalError(2018062912);
  11140. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11141. Break;
  11142. end
  11143. else
  11144. begin
  11145. { Might be a comment or temporary allocation entry }
  11146. if not (hp2.typ in SkipInstr) then
  11147. InternalError(2018062911);
  11148. hp2 := tai(hp2.Next);
  11149. Continue;
  11150. end;
  11151. end;
  11152. until False;
  11153. { Now we can safely decrement the reference count }
  11154. tasmlabel(symbol).decrefs;
  11155. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11156. { Remove the original jump }
  11157. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11158. if hp2.typ=ait_instruction then
  11159. begin
  11160. p := hp2;
  11161. Result := True;
  11162. end
  11163. else
  11164. begin
  11165. UpdateUsedRegs(tai(hp2.next));
  11166. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11167. { Remove the label if this is its final reference }
  11168. if (tasmlabel(symbol).getrefs=0) then
  11169. begin
  11170. { Make sure the aligns get stripped too }
  11171. hp1 := tai(hp_lblxxx.Previous);
  11172. while Assigned(hp1) and (hp1.typ = ait_align) do
  11173. begin
  11174. hp_lblxxx := hp1;
  11175. hp1 := tai(hp_lblxxx.Previous);
  11176. end;
  11177. StripLabelFast(hp_lblxxx);
  11178. end;
  11179. end;
  11180. Exit;
  11181. end;
  11182. end
  11183. else if assigned(hp_lblxxx) and
  11184. { check further for
  11185. jCC xxx
  11186. <several movs 1>
  11187. jmp yyy
  11188. xxx:
  11189. <several movs 2>
  11190. yyy:
  11191. }
  11192. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11193. { hp1 should be pointing to jmp yyy }
  11194. MatchInstruction(hp1, A_JMP, []) and
  11195. { real label and jump, no further references to the
  11196. label are allowed }
  11197. (TAsmLabel(symbol).getrefs=1) and
  11198. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11199. begin
  11200. hp_jump := hp1;
  11201. { Don't set c to zero }
  11202. l := 0;
  11203. w := 0;
  11204. GetNextInstruction(hp_lblxxx, hpmov2);
  11205. hp2 := hp_lblxxx;
  11206. hp_lblyyy := hpmov2;
  11207. while assigned(hp_lblyyy) and
  11208. { stop on labels }
  11209. (hp_lblyyy.typ <> ait_label) do
  11210. begin
  11211. { Keep track of all integer registers that are used }
  11212. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11213. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11214. Break;
  11215. hp2 := hp_lblyyy;
  11216. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11217. end;
  11218. { Analyse the second batch of MOVs to see if the setup is valid }
  11219. hp1 := hpmov2;
  11220. while assigned(hp1) and
  11221. (hp1 <> hp_lblyyy) do
  11222. begin
  11223. case hp1.typ of
  11224. ait_instruction:
  11225. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11226. begin
  11227. if CanBeCMOV(hp1, hp_prev) then
  11228. Inc(l)
  11229. else if not (cs_opt_size in current_settings.optimizerswitches)
  11230. { CMOV with constants grows the code size }
  11231. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11232. begin
  11233. { Register was reserved by TryCMOVConst and
  11234. stored on ConstRegs[c] }
  11235. end
  11236. else
  11237. Break;
  11238. end
  11239. else
  11240. Break;
  11241. else
  11242. ;
  11243. end;
  11244. GetNextInstruction(hp1,hp1);
  11245. end;
  11246. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11247. TmpUsedRegs[R_INTREGISTER].Clear;
  11248. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11249. (hp1 = hp_lblyyy) and
  11250. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11251. begin
  11252. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11253. second_condition := taicpu(p).condition;
  11254. condition := inverse_cond(taicpu(p).condition);
  11255. UpdateUsedRegs(tai(p.next));
  11256. { Scan through the first set of MOVs to update UsedRegs,
  11257. but don't process them yet }
  11258. hp1 := hpmov1;
  11259. repeat
  11260. if not Assigned(hp1) then
  11261. InternalError(2018062901);
  11262. UpdateUsedRegs(tai(hp1.next));
  11263. GetNextInstruction(hp1, hp1);
  11264. until (hp1 = hp_lblxxx);
  11265. UpdateUsedRegs(tai(hp_lblxxx.next));
  11266. { Process the second set of MOVs first,
  11267. because if a destination register is
  11268. shared between the first and second MOV
  11269. sets, it is more efficient to turn the
  11270. first one into a MOV instruction and place
  11271. it before the CMP if possible, but we
  11272. won't know which registers are shared
  11273. until we've processed at least one list,
  11274. so we might as well make it the second
  11275. one since that won't be modified again. }
  11276. hp1 := hpmov2;
  11277. repeat
  11278. if not Assigned(hp1) then
  11279. InternalError(2018062902);
  11280. if (hp1.typ = ait_instruction) then
  11281. begin
  11282. { Extra safeguard }
  11283. if (taicpu(hp1).opcode <> A_MOV) then
  11284. InternalError(2018062903);
  11285. if taicpu(hp1).oper[0]^.typ = top_const then
  11286. begin
  11287. RegMatch := False;
  11288. for x := 0 to c - 1 do
  11289. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11290. begin
  11291. RegMatch := True;
  11292. { If it's in TmpUsedRegs, then this register
  11293. is being used more than once and hence has
  11294. already had its value defined (it gets
  11295. added to UsedRegs through AllocRegBetween
  11296. below) }
  11297. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11298. begin
  11299. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11300. asml.InsertBefore(hp_new, hp_flagalloc);
  11301. if Assigned(hp_prev2) then
  11302. TrySwapMovOp(hp_prev2, hp_new);
  11303. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11304. end
  11305. else
  11306. { We just need an instruction between hp_prev and hp1
  11307. where we know the register is marked as in use }
  11308. hp_new := hpmov2;
  11309. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11310. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11311. Break;
  11312. end;
  11313. if not RegMatch then
  11314. InternalError(2021100411);
  11315. end;
  11316. taicpu(hp1).opcode := A_CMOVcc;
  11317. taicpu(hp1).condition := second_condition;
  11318. { Store these writes to search for
  11319. duplicates later on }
  11320. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11321. Inc(w);
  11322. end;
  11323. UpdateUsedRegs(tai(hp1.next));
  11324. GetNextInstruction(hp1, hp1);
  11325. until (hp1 = hp_lblyyy);
  11326. { Now do the first set of MOVs }
  11327. hp1 := hpmov1;
  11328. repeat
  11329. if not Assigned(hp1) then
  11330. InternalError(2018062904);
  11331. if (hp1.typ = ait_instruction) then
  11332. begin
  11333. RegMatch := False;
  11334. { Extra safeguard }
  11335. if (taicpu(hp1).opcode <> A_MOV) then
  11336. InternalError(2018062905);
  11337. { Search through the RegWrites list to see
  11338. if there are any opposing CMOV pairs that
  11339. write to the same register }
  11340. for x := 0 to w - 1 do
  11341. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11342. begin
  11343. { We have a match. Keep this as a MOV }
  11344. { Move ahead in preparation }
  11345. GetNextInstruction(hp1, hp1);
  11346. RegMatch := True;
  11347. Break;
  11348. end;
  11349. if RegMatch then
  11350. Continue;
  11351. if taicpu(hp1).oper[0]^.typ = top_const then
  11352. begin
  11353. RegMatch := False;
  11354. for x := 0 to c - 1 do
  11355. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11356. begin
  11357. RegMatch := True;
  11358. { If it's in TmpUsedRegs, then this register
  11359. is being used more than once and hence has
  11360. already had its value defined (it gets
  11361. added to UsedRegs through AllocRegBetween
  11362. below) }
  11363. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11364. begin
  11365. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11366. asml.InsertBefore(hp_new, hp_flagalloc);
  11367. if Assigned(hp_prev2) then
  11368. TrySwapMovOp(hp_prev2, hp_new);
  11369. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11370. end
  11371. else
  11372. { We just need an instruction between hp_prev and hp1
  11373. where we know the register is marked as in use }
  11374. hp_new := hpmov1;
  11375. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11376. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11377. Break;
  11378. end;
  11379. if not RegMatch then
  11380. InternalError(2021100412);
  11381. end;
  11382. taicpu(hp1).opcode := A_CMOVcc;
  11383. taicpu(hp1).condition := condition;
  11384. end;
  11385. GetNextInstruction(hp1, hp1);
  11386. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11387. UpdateUsedRegs(tai(hp_jump.next));
  11388. UpdateUsedRegs(tai(hp_lblyyy.next));
  11389. { Get first instruction after label }
  11390. hp1 := p;
  11391. GetNextInstruction(hp_lblyyy, p);
  11392. { Don't dereference yet, as doing so will cause
  11393. GetNextInstruction to skip the label and
  11394. optional align marker. [Kit] }
  11395. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11396. { remove Jcc }
  11397. RemoveInstruction(hp1);
  11398. { Now we can safely decrement it }
  11399. tasmlabel(symbol).decrefs;
  11400. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11401. { Make sure the aligns get stripped too }
  11402. hp1 := tai(hp_lblxxx.Previous);
  11403. while Assigned(hp1) and (hp1.typ = ait_align) do
  11404. begin
  11405. hp_lblxxx := hp1;
  11406. hp1 := tai(hp_lblxxx.Previous);
  11407. end;
  11408. StripLabelFast(hp_lblxxx);
  11409. { remove jmp }
  11410. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11411. RemoveInstruction(hp_jump);
  11412. { As before, now we can safely decrement it }
  11413. TAsmLabel(symbol).decrefs;
  11414. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11415. if TAsmLabel(symbol).getrefs = 0 then
  11416. begin
  11417. { Make sure the aligns get stripped too }
  11418. hp1 := tai(hp_lblyyy.Previous);
  11419. while Assigned(hp1) and (hp1.typ = ait_align) do
  11420. begin
  11421. hp_lblyyy := hp1;
  11422. hp1 := tai(hp_lblyyy.Previous);
  11423. end;
  11424. StripLabelFast(hp_lblyyy);
  11425. end;
  11426. if Assigned(p) then
  11427. result := True;
  11428. exit;
  11429. end;
  11430. end;
  11431. end;
  11432. {$endif i8086}
  11433. end;
  11434. end;
  11435. end;
  11436. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11437. var
  11438. hp1,hp2,hp3: tai;
  11439. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11440. NewSize: TOpSize;
  11441. NewRegSize: TSubRegister;
  11442. Limit: TCgInt;
  11443. SwapOper: POper;
  11444. begin
  11445. result:=false;
  11446. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11447. GetNextInstruction(p,hp1) and
  11448. (hp1.typ = ait_instruction);
  11449. if reg_and_hp1_is_instr and
  11450. (
  11451. (taicpu(hp1).opcode <> A_LEA) or
  11452. { If the LEA instruction can be converted into an arithmetic instruction,
  11453. it may be possible to then fold it. }
  11454. (
  11455. { If the flags register is in use, don't change the instruction
  11456. to an ADD otherwise this will scramble the flags. [Kit] }
  11457. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11458. ConvertLEA(taicpu(hp1))
  11459. )
  11460. ) and
  11461. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11462. GetNextInstruction(hp1,hp2) and
  11463. MatchInstruction(hp2,A_MOV,[]) and
  11464. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11465. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11466. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11467. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11468. {$ifdef i386}
  11469. { not all registers have byte size sub registers on i386 }
  11470. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11471. {$endif i386}
  11472. (((taicpu(hp1).ops=2) and
  11473. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11474. ((taicpu(hp1).ops=1) and
  11475. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11476. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11477. begin
  11478. { change movsX/movzX reg/ref, reg2
  11479. add/sub/or/... reg3/$const, reg2
  11480. mov reg2 reg/ref
  11481. to add/sub/or/... reg3/$const, reg/ref }
  11482. { by example:
  11483. movswl %si,%eax movswl %si,%eax p
  11484. decl %eax addl %edx,%eax hp1
  11485. movw %ax,%si movw %ax,%si hp2
  11486. ->
  11487. movswl %si,%eax movswl %si,%eax p
  11488. decw %eax addw %edx,%eax hp1
  11489. movw %ax,%si movw %ax,%si hp2
  11490. }
  11491. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11492. {
  11493. ->
  11494. movswl %si,%eax movswl %si,%eax p
  11495. decw %si addw %dx,%si hp1
  11496. movw %ax,%si movw %ax,%si hp2
  11497. }
  11498. case taicpu(hp1).ops of
  11499. 1:
  11500. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11501. 2:
  11502. begin
  11503. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11504. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11505. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11506. end;
  11507. else
  11508. internalerror(2008042702);
  11509. end;
  11510. {
  11511. ->
  11512. decw %si addw %dx,%si p
  11513. }
  11514. DebugMsg(SPeepholeOptimization + 'var3',p);
  11515. RemoveCurrentP(p, hp1);
  11516. RemoveInstruction(hp2);
  11517. Result := True;
  11518. Exit;
  11519. end;
  11520. if reg_and_hp1_is_instr and
  11521. (taicpu(hp1).opcode = A_MOV) and
  11522. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11523. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11524. {$ifdef x86_64}
  11525. { check for implicit extension to 64 bit }
  11526. or
  11527. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11528. (taicpu(hp1).opsize=S_Q) and
  11529. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11530. )
  11531. {$endif x86_64}
  11532. )
  11533. then
  11534. begin
  11535. { change
  11536. movx %reg1,%reg2
  11537. mov %reg2,%reg3
  11538. dealloc %reg2
  11539. into
  11540. movx %reg,%reg3
  11541. }
  11542. TransferUsedRegs(TmpUsedRegs);
  11543. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11544. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11545. begin
  11546. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11547. {$ifdef x86_64}
  11548. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11549. (taicpu(hp1).opsize=S_Q) then
  11550. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11551. else
  11552. {$endif x86_64}
  11553. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11554. RemoveInstruction(hp1);
  11555. Result := True;
  11556. Exit;
  11557. end;
  11558. end;
  11559. if reg_and_hp1_is_instr and
  11560. ((taicpu(hp1).opcode=A_MOV) or
  11561. (taicpu(hp1).opcode=A_ADD) or
  11562. (taicpu(hp1).opcode=A_SUB) or
  11563. (taicpu(hp1).opcode=A_CMP) or
  11564. (taicpu(hp1).opcode=A_OR) or
  11565. (taicpu(hp1).opcode=A_XOR) or
  11566. (taicpu(hp1).opcode=A_AND)
  11567. ) and
  11568. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11569. begin
  11570. AndTest := (taicpu(hp1).opcode=A_AND) and
  11571. GetNextInstruction(hp1, hp2) and
  11572. (hp2.typ = ait_instruction) and
  11573. (
  11574. (
  11575. (taicpu(hp2).opcode=A_TEST) and
  11576. (
  11577. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11578. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11579. (
  11580. { If the AND and TEST instructions share a constant, this is also valid }
  11581. (taicpu(hp1).oper[0]^.typ = top_const) and
  11582. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11583. )
  11584. ) and
  11585. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11586. ) or
  11587. (
  11588. (taicpu(hp2).opcode=A_CMP) and
  11589. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11590. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11591. )
  11592. );
  11593. { change
  11594. movx (oper),%reg2
  11595. and $x,%reg2
  11596. test %reg2,%reg2
  11597. dealloc %reg2
  11598. into
  11599. op %reg1,%reg3
  11600. if the second op accesses only the bits stored in reg1
  11601. }
  11602. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11603. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11604. (taicpu(hp1).oper[0]^.typ = top_const) and
  11605. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11606. AndTest then
  11607. begin
  11608. { Check if the AND constant is in range }
  11609. case taicpu(p).opsize of
  11610. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11611. begin
  11612. NewSize := S_B;
  11613. Limit := $FF;
  11614. end;
  11615. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11616. begin
  11617. NewSize := S_W;
  11618. Limit := $FFFF;
  11619. end;
  11620. {$ifdef x86_64}
  11621. S_LQ:
  11622. begin
  11623. NewSize := S_L;
  11624. Limit := $FFFFFFFF;
  11625. end;
  11626. {$endif x86_64}
  11627. else
  11628. InternalError(2021120303);
  11629. end;
  11630. if (
  11631. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11632. { Check for negative operands }
  11633. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11634. ) and
  11635. GetNextInstruction(hp2,hp3) and
  11636. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11637. (taicpu(hp3).condition in [C_E,C_NE]) then
  11638. begin
  11639. TransferUsedRegs(TmpUsedRegs);
  11640. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11641. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11642. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11643. begin
  11644. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11645. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11646. taicpu(hp1).opcode := A_TEST;
  11647. taicpu(hp1).opsize := NewSize;
  11648. RemoveInstruction(hp2);
  11649. RemoveCurrentP(p, hp1);
  11650. Result:=true;
  11651. exit;
  11652. end;
  11653. end;
  11654. end;
  11655. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11656. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11657. (taicpu(hp1).opsize=S_B)) or
  11658. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11659. (taicpu(hp1).opsize=S_W))
  11660. {$ifdef x86_64}
  11661. or ((taicpu(p).opsize=S_LQ) and
  11662. (taicpu(hp1).opsize=S_L))
  11663. {$endif x86_64}
  11664. ) and
  11665. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11666. begin
  11667. { change
  11668. movx %reg1,%reg2
  11669. op %reg2,%reg3
  11670. dealloc %reg2
  11671. into
  11672. op %reg1,%reg3
  11673. if the second op accesses only the bits stored in reg1
  11674. }
  11675. TransferUsedRegs(TmpUsedRegs);
  11676. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11677. if AndTest then
  11678. begin
  11679. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11680. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11681. end
  11682. else
  11683. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11684. if not RegUsed then
  11685. begin
  11686. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11687. if taicpu(p).oper[0]^.typ=top_reg then
  11688. begin
  11689. case taicpu(hp1).opsize of
  11690. S_B:
  11691. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11692. S_W:
  11693. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11694. S_L:
  11695. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11696. else
  11697. Internalerror(2020102301);
  11698. end;
  11699. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11700. end
  11701. else
  11702. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11703. RemoveCurrentP(p);
  11704. if AndTest then
  11705. RemoveInstruction(hp2);
  11706. result:=true;
  11707. exit;
  11708. end;
  11709. end
  11710. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11711. (
  11712. { Bitwise operations only }
  11713. (taicpu(hp1).opcode=A_AND) or
  11714. (taicpu(hp1).opcode=A_TEST) or
  11715. (
  11716. (taicpu(hp1).oper[0]^.typ = top_const) and
  11717. (
  11718. (taicpu(hp1).opcode=A_OR) or
  11719. (taicpu(hp1).opcode=A_XOR)
  11720. )
  11721. )
  11722. ) and
  11723. (
  11724. (taicpu(hp1).oper[0]^.typ = top_const) or
  11725. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11726. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11727. ) then
  11728. begin
  11729. { change
  11730. movx %reg2,%reg2
  11731. op const,%reg2
  11732. into
  11733. op const,%reg2 (smaller version)
  11734. movx %reg2,%reg2
  11735. also change
  11736. movx %reg1,%reg2
  11737. and/test (oper),%reg2
  11738. dealloc %reg2
  11739. into
  11740. and/test (oper),%reg1
  11741. }
  11742. case taicpu(p).opsize of
  11743. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11744. begin
  11745. NewSize := S_B;
  11746. NewRegSize := R_SUBL;
  11747. Limit := $FF;
  11748. end;
  11749. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11750. begin
  11751. NewSize := S_W;
  11752. NewRegSize := R_SUBW;
  11753. Limit := $FFFF;
  11754. end;
  11755. {$ifdef x86_64}
  11756. S_LQ:
  11757. begin
  11758. NewSize := S_L;
  11759. NewRegSize := R_SUBD;
  11760. Limit := $FFFFFFFF;
  11761. end;
  11762. {$endif x86_64}
  11763. else
  11764. Internalerror(2021120302);
  11765. end;
  11766. TransferUsedRegs(TmpUsedRegs);
  11767. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11768. if AndTest then
  11769. begin
  11770. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11771. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11772. end
  11773. else
  11774. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11775. if
  11776. (
  11777. (taicpu(p).opcode = A_MOVZX) and
  11778. (
  11779. (taicpu(hp1).opcode=A_AND) or
  11780. (taicpu(hp1).opcode=A_TEST)
  11781. ) and
  11782. not (
  11783. { If both are references, then the final instruction will have
  11784. both operands as references, which is not allowed }
  11785. (taicpu(p).oper[0]^.typ = top_ref) and
  11786. (taicpu(hp1).oper[0]^.typ = top_ref)
  11787. ) and
  11788. not RegUsed
  11789. ) or
  11790. (
  11791. (
  11792. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11793. not RegUsed
  11794. ) and
  11795. (taicpu(p).oper[0]^.typ = top_reg) and
  11796. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11797. (taicpu(hp1).oper[0]^.typ = top_const) and
  11798. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11799. ) then
  11800. begin
  11801. {$if defined(i386) or defined(i8086)}
  11802. { If the target size is 8-bit, make sure we can actually encode it }
  11803. 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
  11804. Exit;
  11805. {$endif i386 or i8086}
  11806. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11807. taicpu(hp1).opsize := NewSize;
  11808. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11809. if AndTest then
  11810. begin
  11811. RemoveInstruction(hp2);
  11812. if not RegUsed then
  11813. begin
  11814. taicpu(hp1).opcode := A_TEST;
  11815. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11816. begin
  11817. { Make sure the reference is the second operand }
  11818. SwapOper := taicpu(hp1).oper[0];
  11819. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11820. taicpu(hp1).oper[1] := SwapOper;
  11821. end;
  11822. end;
  11823. end;
  11824. case taicpu(hp1).oper[0]^.typ of
  11825. top_reg:
  11826. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11827. top_const:
  11828. { For the AND/TEST case }
  11829. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11830. else
  11831. ;
  11832. end;
  11833. if RegUsed then
  11834. begin
  11835. AsmL.Remove(p);
  11836. AsmL.InsertAfter(p, hp1);
  11837. p := hp1;
  11838. end
  11839. else
  11840. RemoveCurrentP(p, hp1);
  11841. result:=true;
  11842. exit;
  11843. end;
  11844. end;
  11845. end;
  11846. if reg_and_hp1_is_instr and
  11847. (taicpu(p).oper[0]^.typ = top_reg) and
  11848. (
  11849. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11850. ) and
  11851. (taicpu(hp1).oper[0]^.typ = top_const) and
  11852. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11853. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11854. { Minimum shift value allowed is the bit difference between the sizes }
  11855. (taicpu(hp1).oper[0]^.val >=
  11856. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11857. 8 * (
  11858. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11859. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11860. )
  11861. ) then
  11862. begin
  11863. { For:
  11864. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11865. shl/sal ##, %reg1
  11866. Remove the movsx/movzx instruction if the shift overwrites the
  11867. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11868. }
  11869. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11870. RemoveCurrentP(p, hp1);
  11871. Result := True;
  11872. Exit;
  11873. end
  11874. else if reg_and_hp1_is_instr and
  11875. (taicpu(p).oper[0]^.typ = top_reg) and
  11876. (
  11877. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11878. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11879. ) and
  11880. (taicpu(hp1).oper[0]^.typ = top_const) and
  11881. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11882. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11883. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11884. (taicpu(hp1).oper[0]^.val <
  11885. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11886. 8 * (
  11887. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11888. )
  11889. ) then
  11890. begin
  11891. { For:
  11892. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11893. sar ##, %reg1 shr ##, %reg1
  11894. Move the shift to before the movx instruction if the shift value
  11895. is not too large.
  11896. }
  11897. asml.Remove(hp1);
  11898. asml.InsertBefore(hp1, p);
  11899. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11900. case taicpu(p).opsize of
  11901. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11902. taicpu(hp1).opsize := S_B;
  11903. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11904. taicpu(hp1).opsize := S_W;
  11905. {$ifdef x86_64}
  11906. S_LQ:
  11907. taicpu(hp1).opsize := S_L;
  11908. {$endif}
  11909. else
  11910. InternalError(2020112401);
  11911. end;
  11912. if (taicpu(hp1).opcode = A_SHR) then
  11913. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11914. else
  11915. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11916. Result := True;
  11917. end;
  11918. if reg_and_hp1_is_instr and
  11919. (taicpu(p).oper[0]^.typ = top_reg) and
  11920. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11921. (
  11922. (taicpu(hp1).opcode = taicpu(p).opcode)
  11923. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11924. {$ifdef x86_64}
  11925. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11926. {$endif x86_64}
  11927. ) then
  11928. begin
  11929. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11930. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11931. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11932. begin
  11933. {
  11934. For example:
  11935. movzbw %al,%ax
  11936. movzwl %ax,%eax
  11937. Compress into:
  11938. movzbl %al,%eax
  11939. }
  11940. RegUsed := False;
  11941. case taicpu(p).opsize of
  11942. S_BW:
  11943. case taicpu(hp1).opsize of
  11944. S_WL:
  11945. begin
  11946. taicpu(p).opsize := S_BL;
  11947. RegUsed := True;
  11948. end;
  11949. {$ifdef x86_64}
  11950. S_WQ:
  11951. begin
  11952. if taicpu(p).opcode = A_MOVZX then
  11953. begin
  11954. taicpu(p).opsize := S_BL;
  11955. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11956. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11957. end
  11958. else
  11959. taicpu(p).opsize := S_BQ;
  11960. RegUsed := True;
  11961. end;
  11962. {$endif x86_64}
  11963. else
  11964. ;
  11965. end;
  11966. {$ifdef x86_64}
  11967. S_BL:
  11968. case taicpu(hp1).opsize of
  11969. S_LQ:
  11970. begin
  11971. if taicpu(p).opcode = A_MOVZX then
  11972. begin
  11973. taicpu(p).opsize := S_BL;
  11974. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11975. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11976. end
  11977. else
  11978. taicpu(p).opsize := S_BQ;
  11979. RegUsed := True;
  11980. end;
  11981. else
  11982. ;
  11983. end;
  11984. S_WL:
  11985. case taicpu(hp1).opsize of
  11986. S_LQ:
  11987. begin
  11988. if taicpu(p).opcode = A_MOVZX then
  11989. begin
  11990. taicpu(p).opsize := S_WL;
  11991. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11992. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11993. end
  11994. else
  11995. taicpu(p).opsize := S_WQ;
  11996. RegUsed := True;
  11997. end;
  11998. else
  11999. ;
  12000. end;
  12001. {$endif x86_64}
  12002. else
  12003. ;
  12004. end;
  12005. if RegUsed then
  12006. begin
  12007. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12008. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12009. RemoveInstruction(hp1);
  12010. Result := True;
  12011. Exit;
  12012. end;
  12013. end;
  12014. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12015. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12016. GetNextInstruction(hp1, hp2) and
  12017. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12018. (
  12019. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12020. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12021. {$ifdef x86_64}
  12022. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12023. {$endif x86_64}
  12024. ) and
  12025. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12026. (
  12027. (
  12028. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12029. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12030. ) or
  12031. (
  12032. { Only allow the operands in reverse order for TEST instructions }
  12033. (taicpu(hp2).opcode = A_TEST) and
  12034. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12035. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12036. )
  12037. ) then
  12038. begin
  12039. {
  12040. For example:
  12041. movzbl %al,%eax
  12042. movzbl (ref),%edx
  12043. andl %edx,%eax
  12044. (%edx deallocated)
  12045. Change to:
  12046. andb (ref),%al
  12047. movzbl %al,%eax
  12048. Rules are:
  12049. - First two instructions have the same opcode and opsize
  12050. - First instruction's operands are the same super-register
  12051. - Second instruction operates on a different register
  12052. - Third instruction is AND, OR, XOR or TEST
  12053. - Third instruction's operands are the destination registers of the first two instructions
  12054. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12055. - Second instruction's destination register is deallocated afterwards
  12056. }
  12057. TransferUsedRegs(TmpUsedRegs);
  12058. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12059. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12060. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12061. begin
  12062. case taicpu(p).opsize of
  12063. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12064. NewSize := S_B;
  12065. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12066. NewSize := S_W;
  12067. {$ifdef x86_64}
  12068. S_LQ:
  12069. NewSize := S_L;
  12070. {$endif x86_64}
  12071. else
  12072. InternalError(2021120301);
  12073. end;
  12074. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12075. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12076. taicpu(hp2).opsize := NewSize;
  12077. RemoveInstruction(hp1);
  12078. { With TEST, it's best to keep the MOVX instruction at the top }
  12079. if (taicpu(hp2).opcode <> A_TEST) then
  12080. begin
  12081. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12082. asml.Remove(p);
  12083. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12084. asml.InsertAfter(p, hp2);
  12085. p := hp2;
  12086. end
  12087. else
  12088. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12089. Result := True;
  12090. Exit;
  12091. end;
  12092. end;
  12093. end;
  12094. if taicpu(p).opcode=A_MOVZX then
  12095. begin
  12096. { removes superfluous And's after movzx's }
  12097. if reg_and_hp1_is_instr and
  12098. (taicpu(hp1).opcode = A_AND) and
  12099. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12100. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12101. {$ifdef x86_64}
  12102. { check for implicit extension to 64 bit }
  12103. or
  12104. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12105. (taicpu(hp1).opsize=S_Q) and
  12106. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12107. )
  12108. {$endif x86_64}
  12109. )
  12110. then
  12111. begin
  12112. case taicpu(p).opsize Of
  12113. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12114. if (taicpu(hp1).oper[0]^.val = $ff) then
  12115. begin
  12116. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12117. RemoveInstruction(hp1);
  12118. Result:=true;
  12119. exit;
  12120. end;
  12121. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12122. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12123. begin
  12124. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12125. RemoveInstruction(hp1);
  12126. Result:=true;
  12127. exit;
  12128. end;
  12129. {$ifdef x86_64}
  12130. S_LQ:
  12131. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12132. begin
  12133. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12134. RemoveInstruction(hp1);
  12135. Result:=true;
  12136. exit;
  12137. end;
  12138. {$endif x86_64}
  12139. else
  12140. ;
  12141. end;
  12142. { we cannot get rid of the and, but can we get rid of the movz ?}
  12143. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12144. begin
  12145. case taicpu(p).opsize Of
  12146. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12147. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12148. begin
  12149. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12150. RemoveCurrentP(p,hp1);
  12151. Result:=true;
  12152. exit;
  12153. end;
  12154. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12155. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12156. begin
  12157. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12158. RemoveCurrentP(p,hp1);
  12159. Result:=true;
  12160. exit;
  12161. end;
  12162. {$ifdef x86_64}
  12163. S_LQ:
  12164. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12165. begin
  12166. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12167. RemoveCurrentP(p,hp1);
  12168. Result:=true;
  12169. exit;
  12170. end;
  12171. {$endif x86_64}
  12172. else
  12173. ;
  12174. end;
  12175. end;
  12176. end;
  12177. { changes some movzx constructs to faster synonyms (all examples
  12178. are given with eax/ax, but are also valid for other registers)}
  12179. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12180. begin
  12181. case taicpu(p).opsize of
  12182. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12183. (the machine code is equivalent to movzbl %al,%eax), but the
  12184. code generator still generates that assembler instruction and
  12185. it is silently converted. This should probably be checked.
  12186. [Kit] }
  12187. S_BW:
  12188. begin
  12189. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12190. (
  12191. not IsMOVZXAcceptable
  12192. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12193. or (
  12194. (cs_opt_size in current_settings.optimizerswitches) and
  12195. (taicpu(p).oper[1]^.reg = NR_AX)
  12196. )
  12197. ) then
  12198. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12199. begin
  12200. DebugMsg(SPeepholeOptimization + 'var7',p);
  12201. taicpu(p).opcode := A_AND;
  12202. taicpu(p).changeopsize(S_W);
  12203. taicpu(p).loadConst(0,$ff);
  12204. Result := True;
  12205. end
  12206. else if not IsMOVZXAcceptable and
  12207. GetNextInstruction(p, hp1) and
  12208. (tai(hp1).typ = ait_instruction) and
  12209. (taicpu(hp1).opcode = A_AND) and
  12210. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12211. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12212. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12213. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12214. begin
  12215. DebugMsg(SPeepholeOptimization + 'var8',p);
  12216. taicpu(p).opcode := A_MOV;
  12217. taicpu(p).changeopsize(S_W);
  12218. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12219. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12220. Result := True;
  12221. end;
  12222. end;
  12223. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12224. S_BL:
  12225. if not IsMOVZXAcceptable then
  12226. begin
  12227. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12228. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12229. begin
  12230. DebugMsg(SPeepholeOptimization + 'var9',p);
  12231. taicpu(p).opcode := A_AND;
  12232. taicpu(p).changeopsize(S_L);
  12233. taicpu(p).loadConst(0,$ff);
  12234. Result := True;
  12235. end
  12236. else if GetNextInstruction(p, hp1) and
  12237. (tai(hp1).typ = ait_instruction) and
  12238. (taicpu(hp1).opcode = A_AND) and
  12239. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12240. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12241. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12242. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12243. begin
  12244. DebugMsg(SPeepholeOptimization + 'var10',p);
  12245. taicpu(p).opcode := A_MOV;
  12246. taicpu(p).changeopsize(S_L);
  12247. { do not use R_SUBWHOLE
  12248. as movl %rdx,%eax
  12249. is invalid in assembler PM }
  12250. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12251. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12252. Result := True;
  12253. end;
  12254. end;
  12255. {$endif i8086}
  12256. S_WL:
  12257. if not IsMOVZXAcceptable then
  12258. begin
  12259. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12260. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12261. begin
  12262. DebugMsg(SPeepholeOptimization + 'var11',p);
  12263. taicpu(p).opcode := A_AND;
  12264. taicpu(p).changeopsize(S_L);
  12265. taicpu(p).loadConst(0,$ffff);
  12266. Result := True;
  12267. end
  12268. else if GetNextInstruction(p, hp1) and
  12269. (tai(hp1).typ = ait_instruction) and
  12270. (taicpu(hp1).opcode = A_AND) and
  12271. (taicpu(hp1).oper[0]^.typ = top_const) and
  12272. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12273. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12274. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12275. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12276. begin
  12277. DebugMsg(SPeepholeOptimization + 'var12',p);
  12278. taicpu(p).opcode := A_MOV;
  12279. taicpu(p).changeopsize(S_L);
  12280. { do not use R_SUBWHOLE
  12281. as movl %rdx,%eax
  12282. is invalid in assembler PM }
  12283. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12284. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12285. Result := True;
  12286. end;
  12287. end;
  12288. else
  12289. InternalError(2017050705);
  12290. end;
  12291. end
  12292. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12293. begin
  12294. if GetNextInstruction(p, hp1) and
  12295. (tai(hp1).typ = ait_instruction) and
  12296. (taicpu(hp1).opcode = A_AND) and
  12297. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12298. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12299. begin
  12300. //taicpu(p).opcode := A_MOV;
  12301. case taicpu(p).opsize Of
  12302. S_BL:
  12303. begin
  12304. DebugMsg(SPeepholeOptimization + 'var13',p);
  12305. taicpu(hp1).changeopsize(S_L);
  12306. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12307. end;
  12308. S_WL:
  12309. begin
  12310. DebugMsg(SPeepholeOptimization + 'var14',p);
  12311. taicpu(hp1).changeopsize(S_L);
  12312. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12313. end;
  12314. S_BW:
  12315. begin
  12316. DebugMsg(SPeepholeOptimization + 'var15',p);
  12317. taicpu(hp1).changeopsize(S_W);
  12318. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12319. end;
  12320. else
  12321. Internalerror(2017050704)
  12322. end;
  12323. Result := True;
  12324. end;
  12325. end;
  12326. end;
  12327. end;
  12328. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12329. var
  12330. hp1, hp2 : tai;
  12331. MaskLength : Cardinal;
  12332. MaskedBits : TCgInt;
  12333. ActiveReg : TRegister;
  12334. begin
  12335. Result:=false;
  12336. { There are no optimisations for reference targets }
  12337. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12338. Exit;
  12339. while GetNextInstruction(p, hp1) and
  12340. (hp1.typ = ait_instruction) do
  12341. begin
  12342. if (taicpu(p).oper[0]^.typ = top_const) then
  12343. begin
  12344. case taicpu(hp1).opcode of
  12345. A_AND:
  12346. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12347. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12348. { the second register must contain the first one, so compare their subreg types }
  12349. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12350. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12351. { change
  12352. and const1, reg
  12353. and const2, reg
  12354. to
  12355. and (const1 and const2), reg
  12356. }
  12357. begin
  12358. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12359. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12360. RemoveCurrentP(p, hp1);
  12361. Result:=true;
  12362. exit;
  12363. end;
  12364. A_CMP:
  12365. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12366. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12367. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12368. { Just check that the condition on the next instruction is compatible }
  12369. GetNextInstruction(hp1, hp2) and
  12370. (hp2.typ = ait_instruction) and
  12371. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12372. then
  12373. { change
  12374. and 2^n, reg
  12375. cmp 2^n, reg
  12376. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12377. to
  12378. and 2^n, reg
  12379. test reg, reg
  12380. j(~c) / set(~c) / cmov(~c)
  12381. }
  12382. begin
  12383. { Keep TEST instruction in, rather than remove it, because
  12384. it may trigger other optimisations such as MovAndTest2Test }
  12385. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12386. taicpu(hp1).opcode := A_TEST;
  12387. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12388. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12389. Result := True;
  12390. Exit;
  12391. end
  12392. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12393. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12394. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12395. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12396. { change
  12397. and $ff/$ff/$ffff, reg
  12398. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12399. dealloc reg
  12400. to
  12401. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12402. }
  12403. begin
  12404. TransferUsedRegs(TmpUsedRegs);
  12405. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12406. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12407. begin
  12408. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12409. case taicpu(p).oper[0]^.val of
  12410. $ff:
  12411. begin
  12412. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12413. taicpu(hp1).opsize:=S_B;
  12414. end;
  12415. $ffff:
  12416. begin
  12417. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12418. taicpu(hp1).opsize:=S_W;
  12419. end;
  12420. $ffffffff:
  12421. begin
  12422. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12423. taicpu(hp1).opsize:=S_L;
  12424. end;
  12425. else
  12426. Internalerror(2023030401);
  12427. end;
  12428. RemoveCurrentP(p);
  12429. Result := True;
  12430. Exit;
  12431. end;
  12432. end;
  12433. A_MOVZX:
  12434. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12435. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12436. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12437. (
  12438. (
  12439. (taicpu(p).opsize=S_W) and
  12440. (taicpu(hp1).opsize=S_BW)
  12441. ) or
  12442. (
  12443. (taicpu(p).opsize=S_L) and
  12444. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12445. )
  12446. {$ifdef x86_64}
  12447. or
  12448. (
  12449. (taicpu(p).opsize=S_Q) and
  12450. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12451. )
  12452. {$endif x86_64}
  12453. ) then
  12454. begin
  12455. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12456. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12457. ) or
  12458. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12459. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12460. then
  12461. begin
  12462. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12463. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12464. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12465. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12466. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12467. }
  12468. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12469. RemoveInstruction(hp1);
  12470. { See if there are other optimisations possible }
  12471. Continue;
  12472. end;
  12473. end;
  12474. A_SHL:
  12475. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12476. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12477. begin
  12478. {$ifopt R+}
  12479. {$define RANGE_WAS_ON}
  12480. {$R-}
  12481. {$endif}
  12482. { get length of potential and mask }
  12483. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12484. { really a mask? }
  12485. {$ifdef RANGE_WAS_ON}
  12486. {$R+}
  12487. {$endif}
  12488. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12489. { unmasked part shifted out? }
  12490. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12491. begin
  12492. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12493. RemoveCurrentP(p, hp1);
  12494. Result:=true;
  12495. exit;
  12496. end;
  12497. end;
  12498. A_SHR:
  12499. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12500. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12501. (taicpu(hp1).oper[0]^.val <= 63) then
  12502. begin
  12503. { Does SHR combined with the AND cover all the bits?
  12504. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12505. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12506. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12507. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12508. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12509. begin
  12510. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12511. RemoveCurrentP(p, hp1);
  12512. Result := True;
  12513. Exit;
  12514. end;
  12515. end;
  12516. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12517. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12518. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12519. begin
  12520. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12521. (
  12522. (
  12523. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12524. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12525. ) or (
  12526. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12527. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12528. {$ifdef x86_64}
  12529. ) or (
  12530. (taicpu(hp1).opsize = S_LQ) and
  12531. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12532. {$endif x86_64}
  12533. )
  12534. ) then
  12535. begin
  12536. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12537. begin
  12538. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12539. RemoveInstruction(hp1);
  12540. { See if there are other optimisations possible }
  12541. Continue;
  12542. end;
  12543. { The super-registers are the same though.
  12544. Note that this change by itself doesn't improve
  12545. code speed, but it opens up other optimisations. }
  12546. {$ifdef x86_64}
  12547. { Convert 64-bit register to 32-bit }
  12548. case taicpu(hp1).opsize of
  12549. S_BQ:
  12550. begin
  12551. taicpu(hp1).opsize := S_BL;
  12552. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12553. end;
  12554. S_WQ:
  12555. begin
  12556. taicpu(hp1).opsize := S_WL;
  12557. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12558. end
  12559. else
  12560. ;
  12561. end;
  12562. {$endif x86_64}
  12563. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12564. taicpu(hp1).opcode := A_MOVZX;
  12565. { See if there are other optimisations possible }
  12566. Continue;
  12567. end;
  12568. end;
  12569. else
  12570. ;
  12571. end;
  12572. end
  12573. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12574. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12575. begin
  12576. {$ifdef x86_64}
  12577. if (taicpu(p).opsize = S_Q) then
  12578. begin
  12579. { Never necessary }
  12580. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12581. RemoveCurrentP(p, hp1);
  12582. Result := True;
  12583. Exit;
  12584. end;
  12585. {$endif x86_64}
  12586. { Forward check to determine necessity of and %reg,%reg }
  12587. TransferUsedRegs(TmpUsedRegs);
  12588. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12589. { Saves on a bunch of dereferences }
  12590. ActiveReg := taicpu(p).oper[1]^.reg;
  12591. case taicpu(hp1).opcode of
  12592. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12593. if (
  12594. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12595. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12596. ) and
  12597. (
  12598. (taicpu(hp1).opcode <> A_MOV) or
  12599. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12600. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12601. ) and
  12602. not (
  12603. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12604. (taicpu(hp1).opcode = A_MOV) and
  12605. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12606. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12607. ) and
  12608. (
  12609. (
  12610. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12611. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12612. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12613. ) or
  12614. (
  12615. {$ifdef x86_64}
  12616. (
  12617. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12618. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12619. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12620. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12621. ) and
  12622. {$endif x86_64}
  12623. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12624. )
  12625. ) then
  12626. begin
  12627. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12628. RemoveCurrentP(p, hp1);
  12629. Result := True;
  12630. Exit;
  12631. end;
  12632. A_ADD,
  12633. A_AND,
  12634. A_BSF,
  12635. A_BSR,
  12636. A_BTC,
  12637. A_BTR,
  12638. A_BTS,
  12639. A_OR,
  12640. A_SUB,
  12641. A_XOR:
  12642. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12643. if (
  12644. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12645. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12646. ) and
  12647. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12648. begin
  12649. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12650. RemoveCurrentP(p, hp1);
  12651. Result := True;
  12652. Exit;
  12653. end;
  12654. A_CMP,
  12655. A_TEST:
  12656. if (
  12657. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12658. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12659. ) and
  12660. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12661. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12662. begin
  12663. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12664. RemoveCurrentP(p, hp1);
  12665. Result := True;
  12666. Exit;
  12667. end;
  12668. A_BSWAP,
  12669. A_NEG,
  12670. A_NOT:
  12671. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12672. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12673. begin
  12674. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12675. RemoveCurrentP(p, hp1);
  12676. Result := True;
  12677. Exit;
  12678. end;
  12679. else
  12680. ;
  12681. end;
  12682. end;
  12683. if (taicpu(hp1).is_jmp) and
  12684. (taicpu(hp1).opcode<>A_JMP) and
  12685. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12686. begin
  12687. { change
  12688. and x, reg
  12689. jxx
  12690. to
  12691. test x, reg
  12692. jxx
  12693. if reg is deallocated before the
  12694. jump, but only if it's a conditional jump (PFV)
  12695. }
  12696. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12697. taicpu(p).opcode := A_TEST;
  12698. Exit;
  12699. end;
  12700. Break;
  12701. end;
  12702. { Lone AND tests }
  12703. if (taicpu(p).oper[0]^.typ = top_const) then
  12704. begin
  12705. {
  12706. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12707. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12708. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12709. }
  12710. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12711. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12712. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12713. begin
  12714. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12715. if taicpu(p).opsize = S_L then
  12716. begin
  12717. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12718. Result := True;
  12719. end;
  12720. end;
  12721. end;
  12722. { Backward check to determine necessity of and %reg,%reg }
  12723. if (taicpu(p).oper[0]^.typ = top_reg) and
  12724. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12725. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12726. GetLastInstruction(p, hp2) and
  12727. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12728. { Check size of adjacent instruction to determine if the AND is
  12729. effectively a null operation }
  12730. (
  12731. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12732. { Note: Don't include S_Q }
  12733. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12734. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12735. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12736. ) then
  12737. begin
  12738. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12739. { If GetNextInstruction returned False, hp1 will be nil }
  12740. RemoveCurrentP(p, hp1);
  12741. Result := True;
  12742. Exit;
  12743. end;
  12744. end;
  12745. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12746. var
  12747. hp1, hp2: tai;
  12748. NewRef: TReference;
  12749. Distance: Cardinal;
  12750. TempTracking: TAllUsedRegs;
  12751. { This entire nested function is used in an if-statement below, but we
  12752. want to avoid all the used reg transfers and GetNextInstruction calls
  12753. until we really have to check }
  12754. function MemRegisterNotUsedLater: Boolean; inline;
  12755. var
  12756. hp2: tai;
  12757. begin
  12758. TransferUsedRegs(TmpUsedRegs);
  12759. hp2 := p;
  12760. repeat
  12761. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12762. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12763. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12764. end;
  12765. begin
  12766. Result := False;
  12767. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12768. (taicpu(p).oper[1]^.typ = top_reg) then
  12769. begin
  12770. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12771. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12772. (hp1.typ <> ait_instruction) or
  12773. not
  12774. (
  12775. (cs_opt_level3 in current_settings.optimizerswitches) or
  12776. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12777. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12778. ) then
  12779. Exit;
  12780. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12781. addq $x, %rax
  12782. movq %rax, %rdx
  12783. sarq $63, %rdx
  12784. (%rax still in use)
  12785. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12786. leaq $x(%rax),%rdx
  12787. addq $x, %rax
  12788. sarq $63, %rdx
  12789. ...which is okay since it breaks the dependency chain between
  12790. addq and movq, but if OptPass2MOV is called first:
  12791. addq $x, %rax
  12792. cqto
  12793. ...which is better in all ways, taking only 2 cycles to execute
  12794. and much smaller in code size.
  12795. }
  12796. { The extra register tracking is quite strenuous }
  12797. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12798. MatchInstruction(hp1, A_MOV, []) then
  12799. begin
  12800. { Update the register tracking to the MOV instruction }
  12801. CopyUsedRegs(TempTracking);
  12802. hp2 := p;
  12803. repeat
  12804. UpdateUsedRegs(tai(hp2.Next));
  12805. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12806. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12807. OptPass2ADD get called again }
  12808. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12809. begin
  12810. { Reset the tracking to the current instruction }
  12811. RestoreUsedRegs(TempTracking);
  12812. ReleaseUsedRegs(TempTracking);
  12813. Result := True;
  12814. Exit;
  12815. end;
  12816. { Reset the tracking to the current instruction }
  12817. RestoreUsedRegs(TempTracking);
  12818. ReleaseUsedRegs(TempTracking);
  12819. { If OptPass2MOV returned True, we don't need to set Result to
  12820. True if hp1 didn't change because the ADD instruction didn't
  12821. get modified and we'll be evaluating hp1 again when the
  12822. peephole optimizer reaches it }
  12823. end;
  12824. { Change:
  12825. add %reg2,%reg1
  12826. (%reg2 not modified in between)
  12827. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12828. To:
  12829. mov/s/z #(%reg1,%reg2),%reg1
  12830. }
  12831. if (taicpu(p).oper[0]^.typ = top_reg) and
  12832. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12833. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12834. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12835. (
  12836. (
  12837. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12838. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12839. { r/esp cannot be an index }
  12840. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12841. ) or (
  12842. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12843. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12844. )
  12845. ) and (
  12846. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12847. (
  12848. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12849. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12850. MemRegisterNotUsedLater
  12851. )
  12852. ) then
  12853. begin
  12854. if (
  12855. { Instructions are guaranteed to be adjacent on -O2 and under }
  12856. (cs_opt_level3 in current_settings.optimizerswitches) and
  12857. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12858. ) then
  12859. begin
  12860. { If the other register is used in between, move the MOV
  12861. instruction to right after the ADD instruction so a
  12862. saving can still be made }
  12863. Asml.Remove(hp1);
  12864. Asml.InsertAfter(hp1, p);
  12865. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12866. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12867. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12868. RemoveCurrentp(p, hp1);
  12869. end
  12870. else
  12871. begin
  12872. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12873. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12874. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12875. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12876. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12877. { hp1 may not be the immediate next instruction under -O3 }
  12878. RemoveCurrentp(p)
  12879. else
  12880. RemoveCurrentp(p, hp1);
  12881. end;
  12882. Result := True;
  12883. Exit;
  12884. end;
  12885. { Change:
  12886. addl/q $x,%reg1
  12887. movl/q %reg1,%reg2
  12888. To:
  12889. leal/q $x(%reg1),%reg2
  12890. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12891. Breaks the dependency chain.
  12892. }
  12893. if (taicpu(p).oper[0]^.typ = top_const) and
  12894. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12895. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12896. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12897. (
  12898. { Instructions are guaranteed to be adjacent on -O2 and under }
  12899. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12900. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12901. ) then
  12902. begin
  12903. TransferUsedRegs(TmpUsedRegs);
  12904. hp2 := p;
  12905. repeat
  12906. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12907. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12908. if (
  12909. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12910. not (cs_opt_size in current_settings.optimizerswitches) or
  12911. (
  12912. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12913. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12914. )
  12915. ) then
  12916. begin
  12917. { Change the MOV instruction to a LEA instruction, and update the
  12918. first operand }
  12919. reference_reset(NewRef, 1, []);
  12920. NewRef.base := taicpu(p).oper[1]^.reg;
  12921. NewRef.scalefactor := 1;
  12922. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12923. taicpu(hp1).opcode := A_LEA;
  12924. taicpu(hp1).loadref(0, NewRef);
  12925. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12926. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12927. begin
  12928. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12929. { Move what is now the LEA instruction to before the ADD instruction }
  12930. Asml.Remove(hp1);
  12931. Asml.InsertBefore(hp1, p);
  12932. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12933. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12934. p := hp1;
  12935. end
  12936. else
  12937. begin
  12938. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12939. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12940. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12941. { hp1 may not be the immediate next instruction under -O3 }
  12942. RemoveCurrentp(p)
  12943. else
  12944. RemoveCurrentp(p, hp1);
  12945. end;
  12946. Result := True;
  12947. end;
  12948. end;
  12949. end;
  12950. end;
  12951. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12952. var
  12953. SubReg: TSubRegister;
  12954. begin
  12955. Result:=false;
  12956. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12957. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12958. with taicpu(p).oper[0]^.ref^ do
  12959. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12960. begin
  12961. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12962. begin
  12963. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12964. taicpu(p).opcode := A_ADD;
  12965. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12966. Result := True;
  12967. end
  12968. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12969. begin
  12970. if (base <> NR_NO) then
  12971. begin
  12972. if (scalefactor <= 1) then
  12973. begin
  12974. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12975. taicpu(p).opcode := A_ADD;
  12976. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12977. Result := True;
  12978. end;
  12979. end
  12980. else
  12981. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12982. if (scalefactor in [2, 4, 8]) then
  12983. begin
  12984. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12985. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12986. taicpu(p).opcode := A_SHL;
  12987. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12988. Result := True;
  12989. end;
  12990. end;
  12991. end;
  12992. end;
  12993. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12994. var
  12995. hp1, hp2: tai;
  12996. NewRef: TReference;
  12997. Distance: Cardinal;
  12998. TempTracking: TAllUsedRegs;
  12999. begin
  13000. Result := False;
  13001. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13002. MatchOpType(taicpu(p),top_const,top_reg) then
  13003. begin
  13004. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13005. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13006. (hp1.typ <> ait_instruction) or
  13007. not
  13008. (
  13009. (cs_opt_level3 in current_settings.optimizerswitches) or
  13010. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13011. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13012. ) then
  13013. Exit;
  13014. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13015. subq $x, %rax
  13016. movq %rax, %rdx
  13017. sarq $63, %rdx
  13018. (%rax still in use)
  13019. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13020. leaq $-x(%rax),%rdx
  13021. movq $x, %rax
  13022. sarq $63, %rdx
  13023. ...which is okay since it breaks the dependency chain between
  13024. subq and movq, but if OptPass2MOV is called first:
  13025. subq $x, %rax
  13026. cqto
  13027. ...which is better in all ways, taking only 2 cycles to execute
  13028. and much smaller in code size.
  13029. }
  13030. { The extra register tracking is quite strenuous }
  13031. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13032. MatchInstruction(hp1, A_MOV, []) then
  13033. begin
  13034. { Update the register tracking to the MOV instruction }
  13035. CopyUsedRegs(TempTracking);
  13036. hp2 := p;
  13037. repeat
  13038. UpdateUsedRegs(tai(hp2.Next));
  13039. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13040. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13041. OptPass2SUB get called again }
  13042. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13043. begin
  13044. { Reset the tracking to the current instruction }
  13045. RestoreUsedRegs(TempTracking);
  13046. ReleaseUsedRegs(TempTracking);
  13047. Result := True;
  13048. Exit;
  13049. end;
  13050. { Reset the tracking to the current instruction }
  13051. RestoreUsedRegs(TempTracking);
  13052. ReleaseUsedRegs(TempTracking);
  13053. { If OptPass2MOV returned True, we don't need to set Result to
  13054. True if hp1 didn't change because the SUB instruction didn't
  13055. get modified and we'll be evaluating hp1 again when the
  13056. peephole optimizer reaches it }
  13057. end;
  13058. { Change:
  13059. subl/q $x,%reg1
  13060. movl/q %reg1,%reg2
  13061. To:
  13062. leal/q $-x(%reg1),%reg2
  13063. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13064. Breaks the dependency chain and potentially permits the removal of
  13065. a CMP instruction if one follows.
  13066. }
  13067. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13068. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13069. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13070. (
  13071. { Instructions are guaranteed to be adjacent on -O2 and under }
  13072. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13073. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13074. ) then
  13075. begin
  13076. TransferUsedRegs(TmpUsedRegs);
  13077. hp2 := p;
  13078. repeat
  13079. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13080. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13081. if (
  13082. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13083. not (cs_opt_size in current_settings.optimizerswitches) or
  13084. (
  13085. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13086. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13087. )
  13088. ) then
  13089. begin
  13090. { Change the MOV instruction to a LEA instruction, and update the
  13091. first operand }
  13092. reference_reset(NewRef, 1, []);
  13093. NewRef.base := taicpu(p).oper[1]^.reg;
  13094. NewRef.scalefactor := 1;
  13095. NewRef.offset := -taicpu(p).oper[0]^.val;
  13096. taicpu(hp1).opcode := A_LEA;
  13097. taicpu(hp1).loadref(0, NewRef);
  13098. TransferUsedRegs(TmpUsedRegs);
  13099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13100. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13101. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13102. begin
  13103. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13104. { Move what is now the LEA instruction to before the SUB instruction }
  13105. Asml.Remove(hp1);
  13106. Asml.InsertBefore(hp1, p);
  13107. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13108. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13109. p := hp1;
  13110. end
  13111. else
  13112. begin
  13113. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13114. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13115. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13116. { hp1 may not be the immediate next instruction under -O3 }
  13117. RemoveCurrentp(p)
  13118. else
  13119. RemoveCurrentp(p, hp1);
  13120. end;
  13121. Result := True;
  13122. end;
  13123. end;
  13124. end;
  13125. end;
  13126. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13127. begin
  13128. { we can skip all instructions not messing with the stack pointer }
  13129. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13130. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13131. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13132. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13133. ({(taicpu(hp1).ops=0) or }
  13134. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13135. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13136. ) and }
  13137. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13138. )
  13139. ) do
  13140. GetNextInstruction(hp1,hp1);
  13141. Result:=assigned(hp1);
  13142. end;
  13143. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13144. var
  13145. hp1, hp2, hp3, hp4, hp5: tai;
  13146. begin
  13147. Result:=false;
  13148. hp5:=nil;
  13149. { replace
  13150. leal(q) x(<stackpointer>),<stackpointer>
  13151. call procname
  13152. leal(q) -x(<stackpointer>),<stackpointer>
  13153. ret
  13154. by
  13155. jmp procname
  13156. but do it only on level 4 because it destroys stack back traces
  13157. }
  13158. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13159. MatchOpType(taicpu(p),top_ref,top_reg) and
  13160. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13161. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13162. { the -8 or -24 are not required, but bail out early if possible,
  13163. higher values are unlikely }
  13164. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13165. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13166. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13167. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13168. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13169. GetNextInstruction(p, hp1) and
  13170. { Take a copy of hp1 }
  13171. SetAndTest(hp1, hp4) and
  13172. { trick to skip label }
  13173. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13174. SkipSimpleInstructions(hp1) and
  13175. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13176. GetNextInstruction(hp1, hp2) and
  13177. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13178. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13179. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13180. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13181. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13182. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13183. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13184. { Segment register will be NR_NO }
  13185. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13186. GetNextInstruction(hp2, hp3) and
  13187. { trick to skip label }
  13188. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13189. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13190. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13191. SetAndTest(hp3,hp5) and
  13192. GetNextInstruction(hp3,hp3) and
  13193. MatchInstruction(hp3,A_RET,[S_NO])
  13194. )
  13195. ) and
  13196. (taicpu(hp3).ops=0) then
  13197. begin
  13198. taicpu(hp1).opcode := A_JMP;
  13199. taicpu(hp1).is_jmp := true;
  13200. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13201. RemoveCurrentP(p, hp4);
  13202. RemoveInstruction(hp2);
  13203. RemoveInstruction(hp3);
  13204. if Assigned(hp5) then
  13205. begin
  13206. AsmL.Remove(hp5);
  13207. ASmL.InsertBefore(hp5,hp1)
  13208. end;
  13209. Result:=true;
  13210. end;
  13211. end;
  13212. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13213. {$ifdef x86_64}
  13214. var
  13215. hp1, hp2, hp3, hp4, hp5: tai;
  13216. {$endif x86_64}
  13217. begin
  13218. Result:=false;
  13219. {$ifdef x86_64}
  13220. hp5:=nil;
  13221. { replace
  13222. push %rax
  13223. call procname
  13224. pop %rcx
  13225. ret
  13226. by
  13227. jmp procname
  13228. but do it only on level 4 because it destroys stack back traces
  13229. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13230. for all supported calling conventions
  13231. }
  13232. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13233. MatchOpType(taicpu(p),top_reg) and
  13234. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13235. GetNextInstruction(p, hp1) and
  13236. { Take a copy of hp1 }
  13237. SetAndTest(hp1, hp4) and
  13238. { trick to skip label }
  13239. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13240. SkipSimpleInstructions(hp1) and
  13241. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13242. GetNextInstruction(hp1, hp2) and
  13243. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13244. MatchOpType(taicpu(hp2),top_reg) and
  13245. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13246. GetNextInstruction(hp2, hp3) and
  13247. { trick to skip label }
  13248. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13249. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13250. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13251. SetAndTest(hp3,hp5) and
  13252. GetNextInstruction(hp3,hp3) and
  13253. MatchInstruction(hp3,A_RET,[S_NO])
  13254. )
  13255. ) and
  13256. (taicpu(hp3).ops=0) then
  13257. begin
  13258. taicpu(hp1).opcode := A_JMP;
  13259. taicpu(hp1).is_jmp := true;
  13260. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13261. RemoveCurrentP(p, hp4);
  13262. RemoveInstruction(hp2);
  13263. RemoveInstruction(hp3);
  13264. if Assigned(hp5) then
  13265. begin
  13266. AsmL.Remove(hp5);
  13267. ASmL.InsertBefore(hp5,hp1)
  13268. end;
  13269. Result:=true;
  13270. end;
  13271. {$endif x86_64}
  13272. end;
  13273. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13274. var
  13275. Value, RegName: string;
  13276. begin
  13277. Result:=false;
  13278. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13279. begin
  13280. case taicpu(p).oper[0]^.val of
  13281. 0:
  13282. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13283. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13284. begin
  13285. { change "mov $0,%reg" into "xor %reg,%reg" }
  13286. taicpu(p).opcode := A_XOR;
  13287. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13288. Result := True;
  13289. {$ifdef x86_64}
  13290. end
  13291. else if (taicpu(p).opsize = S_Q) then
  13292. begin
  13293. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13294. { The actual optimization }
  13295. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13296. taicpu(p).changeopsize(S_L);
  13297. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13298. Result := True;
  13299. end;
  13300. $1..$FFFFFFFF:
  13301. begin
  13302. { Code size reduction by J. Gareth "Kit" Moreton }
  13303. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13304. case taicpu(p).opsize of
  13305. S_Q:
  13306. begin
  13307. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13308. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13309. { The actual optimization }
  13310. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13311. taicpu(p).changeopsize(S_L);
  13312. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13313. Result := True;
  13314. end;
  13315. else
  13316. { Do nothing };
  13317. end;
  13318. {$endif x86_64}
  13319. end;
  13320. -1:
  13321. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13322. if (cs_opt_size in current_settings.optimizerswitches) and
  13323. (taicpu(p).opsize <> S_B) and
  13324. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13325. begin
  13326. { change "mov $-1,%reg" into "or $-1,%reg" }
  13327. { NOTES:
  13328. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13329. - This operation creates a false dependency on the register, so only do it when optimising for size
  13330. - 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
  13331. }
  13332. taicpu(p).opcode := A_OR;
  13333. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13334. Result := True;
  13335. end;
  13336. else
  13337. { Do nothing };
  13338. end;
  13339. end;
  13340. end;
  13341. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13342. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13343. begin
  13344. Result := False;
  13345. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13346. Exit;
  13347. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13348. so don't bother optimising }
  13349. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13350. Exit;
  13351. if (taicpu(p).oper[0]^.typ <> top_const) or
  13352. { If the value can fit into an 8-bit signed integer, a smaller
  13353. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13354. falls within this range }
  13355. (
  13356. (taicpu(p).oper[0]^.val > -128) and
  13357. (taicpu(p).oper[0]^.val <= 127)
  13358. ) then
  13359. Exit;
  13360. { If we're optimising for size, this is acceptable }
  13361. if (cs_opt_size in current_settings.optimizerswitches) then
  13362. Exit(True);
  13363. if (taicpu(p).oper[1]^.typ = top_reg) and
  13364. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13365. Exit(True);
  13366. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13367. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13368. Exit(True);
  13369. end;
  13370. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13371. var
  13372. hp1: tai;
  13373. Value: TCGInt;
  13374. begin
  13375. Result := False;
  13376. if MatchOpType(taicpu(p), top_const, top_reg) then
  13377. begin
  13378. { Detect:
  13379. andw x, %ax (0 <= x < $8000)
  13380. ...
  13381. movzwl %ax,%eax
  13382. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13383. }
  13384. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13385. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13386. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13387. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13388. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13389. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13390. begin
  13391. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13392. taicpu(hp1).opcode := A_CWDE;
  13393. taicpu(hp1).clearop(0);
  13394. taicpu(hp1).clearop(1);
  13395. taicpu(hp1).ops := 0;
  13396. { A change was made, but not with p, so don't set Result, but
  13397. notify the compiler that a change was made }
  13398. Include(OptsToCheck, aoc_ForceNewIteration);
  13399. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13400. end;
  13401. end;
  13402. { If "not x" is a power of 2 (popcnt = 1), change:
  13403. and $x, %reg/ref
  13404. To:
  13405. btr lb(x), %reg/ref
  13406. }
  13407. if IsBTXAcceptable(p) and
  13408. (
  13409. { Make sure a TEST doesn't follow that plays with the register }
  13410. not GetNextInstruction(p, hp1) or
  13411. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13412. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13413. ) then
  13414. begin
  13415. {$push}{$R-}{$Q-}
  13416. { Value is a sign-extended 32-bit integer - just correct it
  13417. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13418. checks to see if this operand is an immediate. }
  13419. Value := not taicpu(p).oper[0]^.val;
  13420. {$pop}
  13421. {$ifdef x86_64}
  13422. if taicpu(p).opsize = S_L then
  13423. {$endif x86_64}
  13424. Value := Value and $FFFFFFFF;
  13425. if (PopCnt(QWord(Value)) = 1) then
  13426. begin
  13427. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13428. taicpu(p).opcode := A_BTR;
  13429. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13430. Result := True;
  13431. Exit;
  13432. end;
  13433. end;
  13434. end;
  13435. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13436. begin
  13437. Result := False;
  13438. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13439. Exit;
  13440. { Convert:
  13441. movswl %ax,%eax -> cwtl
  13442. movslq %eax,%rax -> cdqe
  13443. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13444. refer to the same opcode and depends only on the assembler's
  13445. current operand-size attribute. [Kit]
  13446. }
  13447. with taicpu(p) do
  13448. case opsize of
  13449. S_WL:
  13450. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13451. begin
  13452. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13453. opcode := A_CWDE;
  13454. clearop(0);
  13455. clearop(1);
  13456. ops := 0;
  13457. Result := True;
  13458. end;
  13459. {$ifdef x86_64}
  13460. S_LQ:
  13461. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13462. begin
  13463. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13464. opcode := A_CDQE;
  13465. clearop(0);
  13466. clearop(1);
  13467. ops := 0;
  13468. Result := True;
  13469. end;
  13470. {$endif x86_64}
  13471. else
  13472. ;
  13473. end;
  13474. end;
  13475. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13476. var
  13477. hp1, hp2: tai;
  13478. IdentityMask, Shift: TCGInt;
  13479. LimitSize: Topsize;
  13480. DoNotMerge: Boolean;
  13481. begin
  13482. Result := False;
  13483. { All these optimisations work on "shr const,%reg" }
  13484. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13485. Exit;
  13486. DoNotMerge := False;
  13487. Shift := taicpu(p).oper[0]^.val;
  13488. LimitSize := taicpu(p).opsize;
  13489. hp1 := p;
  13490. repeat
  13491. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13492. Break;
  13493. { Detect:
  13494. shr x, %reg
  13495. and y, %reg
  13496. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13497. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13498. }
  13499. case taicpu(hp1).opcode of
  13500. A_AND:
  13501. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13502. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13503. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13504. begin
  13505. { Make sure the FLAGS register isn't in use }
  13506. TransferUsedRegs(TmpUsedRegs);
  13507. hp2 := p;
  13508. repeat
  13509. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13510. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13511. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13512. begin
  13513. { Generate the identity mask }
  13514. case taicpu(p).opsize of
  13515. S_B:
  13516. IdentityMask := $FF shr Shift;
  13517. S_W:
  13518. IdentityMask := $FFFF shr Shift;
  13519. S_L:
  13520. IdentityMask := $FFFFFFFF shr Shift;
  13521. {$ifdef x86_64}
  13522. S_Q:
  13523. { We need to force the operands to be unsigned 64-bit
  13524. integers otherwise the wrong value is generated }
  13525. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13526. {$endif x86_64}
  13527. else
  13528. InternalError(2022081501);
  13529. end;
  13530. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13531. begin
  13532. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13533. { All the possible 1 bits are covered, so we can remove the AND }
  13534. hp2 := tai(hp1.Previous);
  13535. RemoveInstruction(hp1);
  13536. { p wasn't actually changed, so don't set Result to True,
  13537. but a change was nonetheless made elsewhere }
  13538. Include(OptsToCheck, aoc_ForceNewIteration);
  13539. { Do another pass in case other AND or MOVZX instructions
  13540. follow }
  13541. hp1 := hp2;
  13542. Continue;
  13543. end;
  13544. end;
  13545. end;
  13546. A_TEST, A_CMP, A_Jcc:
  13547. { Skip over conditional jumps and relevant comparisons }
  13548. Continue;
  13549. A_MOVZX:
  13550. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13551. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13552. begin
  13553. { Since the original register is being read as is, subsequent
  13554. SHRs must not be merged at this point }
  13555. DoNotMerge := True;
  13556. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13557. begin
  13558. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13559. begin
  13560. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13561. { All the possible 1 bits are covered, so we can remove the AND }
  13562. hp2 := tai(hp1.Previous);
  13563. RemoveInstruction(hp1);
  13564. hp1 := hp2;
  13565. end
  13566. else { Different register target }
  13567. begin
  13568. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13569. taicpu(hp1).opcode := A_MOV;
  13570. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13571. case taicpu(hp1).opsize of
  13572. S_BW:
  13573. taicpu(hp1).opsize := S_W;
  13574. S_BL, S_WL:
  13575. taicpu(hp1).opsize := S_L;
  13576. else
  13577. InternalError(2022081503);
  13578. end;
  13579. end;
  13580. end
  13581. else if (Shift > 0) and
  13582. (taicpu(p).opsize = S_W) and
  13583. (taicpu(hp1).opsize = S_WL) and
  13584. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13585. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13586. begin
  13587. { Detect:
  13588. shr x, %ax (x > 0)
  13589. ...
  13590. movzwl %ax,%eax
  13591. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13592. }
  13593. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13594. taicpu(hp1).opcode := A_CWDE;
  13595. taicpu(hp1).clearop(0);
  13596. taicpu(hp1).clearop(1);
  13597. taicpu(hp1).ops := 0;
  13598. end;
  13599. { Move onto the next instruction }
  13600. Continue;
  13601. end;
  13602. A_SHL, A_SAL, A_SHR:
  13603. if (taicpu(hp1).opsize <= LimitSize) and
  13604. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13605. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13606. begin
  13607. { Make sure the sizes don't exceed the register size limit
  13608. (measured by the shift value falling below the limit) }
  13609. if taicpu(hp1).opsize < LimitSize then
  13610. LimitSize := taicpu(hp1).opsize;
  13611. if taicpu(hp1).opcode = A_SHR then
  13612. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13613. else
  13614. begin
  13615. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13616. DoNotMerge := True;
  13617. end;
  13618. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13619. Break;
  13620. { Since we've established that the combined shift is within
  13621. limits, we can actually combine the adjacent SHR
  13622. instructions even if they're different sizes }
  13623. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13624. begin
  13625. hp2 := tai(hp1.Previous);
  13626. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13627. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13628. RemoveInstruction(hp1);
  13629. hp1 := hp2;
  13630. end;
  13631. { Move onto the next instruction }
  13632. Continue;
  13633. end;
  13634. else
  13635. ;
  13636. end;
  13637. Break;
  13638. until False;
  13639. { Detect the following (looking backwards):
  13640. shr %cl,%reg
  13641. shr x, %reg
  13642. Swap the two SHR instructions to minimise a pipeline stall.
  13643. }
  13644. if GetLastInstruction(p, hp1) and
  13645. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13646. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13647. { First operand will be %cl }
  13648. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13649. { Just to be sure }
  13650. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13651. begin
  13652. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13653. { Moving the entries this way ensures the register tracking remains correct }
  13654. Asml.Remove(p);
  13655. Asml.InsertBefore(p, hp1);
  13656. p := hp1;
  13657. { Don't set Result to True because the current instruction is now
  13658. "shr %cl,%reg" and there's nothing more we can do with it }
  13659. end;
  13660. end;
  13661. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13662. var
  13663. hp1, hp2: tai;
  13664. Opposite, SecondOpposite: TAsmOp;
  13665. NewCond: TAsmCond;
  13666. begin
  13667. Result := False;
  13668. { Change:
  13669. add/sub 128,(dest)
  13670. To:
  13671. sub/add -128,(dest)
  13672. This generaally takes fewer bytes to encode because -128 can be stored
  13673. in a signed byte, whereas +128 cannot.
  13674. }
  13675. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13676. begin
  13677. if taicpu(p).opcode = A_ADD then
  13678. Opposite := A_SUB
  13679. else
  13680. Opposite := A_ADD;
  13681. { Be careful if the flags are in use, because the CF flag inverts
  13682. when changing from ADD to SUB and vice versa }
  13683. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13684. GetNextInstruction(p, hp1) then
  13685. begin
  13686. TransferUsedRegs(TmpUsedRegs);
  13687. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13688. hp2 := hp1;
  13689. { Scan ahead to check if everything's safe }
  13690. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13691. begin
  13692. if (hp1.typ <> ait_instruction) then
  13693. { Probably unsafe since the flags are still in use }
  13694. Exit;
  13695. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13696. { Stop searching at an unconditional jump }
  13697. Break;
  13698. if not
  13699. (
  13700. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13701. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13702. ) and
  13703. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13704. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13705. Exit;
  13706. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13707. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13708. { Move to the next instruction }
  13709. GetNextInstruction(hp1, hp1);
  13710. end;
  13711. while Assigned(hp2) and (hp2 <> hp1) do
  13712. begin
  13713. NewCond := C_None;
  13714. case taicpu(hp2).condition of
  13715. C_A, C_NBE:
  13716. NewCond := C_BE;
  13717. C_B, C_C, C_NAE:
  13718. NewCond := C_AE;
  13719. C_AE, C_NB, C_NC:
  13720. NewCond := C_B;
  13721. C_BE, C_NA:
  13722. NewCond := C_A;
  13723. else
  13724. { No change needed };
  13725. end;
  13726. if NewCond <> C_None then
  13727. begin
  13728. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13729. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13730. taicpu(hp2).condition := NewCond;
  13731. end
  13732. else
  13733. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13734. begin
  13735. { Because of the flipping of the carry bit, to ensure
  13736. the operation remains equivalent, ADC becomes SBB
  13737. and vice versa, and the constant is not-inverted.
  13738. If multiple ADCs or SBBs appear in a row, each one
  13739. changed causes the carry bit to invert, so they all
  13740. need to be flipped }
  13741. if taicpu(hp2).opcode = A_ADC then
  13742. SecondOpposite := A_SBB
  13743. else
  13744. SecondOpposite := A_ADC;
  13745. if taicpu(hp2).oper[0]^.typ <> top_const then
  13746. { Should have broken out of this optimisation already }
  13747. InternalError(2021112901);
  13748. 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]^) + ' -> ' +
  13749. 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);
  13750. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13751. taicpu(hp2).opcode := SecondOpposite;
  13752. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13753. end;
  13754. { Move to the next instruction }
  13755. GetNextInstruction(hp2, hp2);
  13756. end;
  13757. if (hp2 <> hp1) then
  13758. InternalError(2021111501);
  13759. end;
  13760. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13761. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13762. taicpu(p).opcode := Opposite;
  13763. taicpu(p).oper[0]^.val := -128;
  13764. { No further optimisations can be made on this instruction, so move
  13765. onto the next one to save time }
  13766. p := tai(p.Next);
  13767. UpdateUsedRegs(p);
  13768. Result := True;
  13769. Exit;
  13770. end;
  13771. { Detect:
  13772. add/sub %reg2,(dest)
  13773. add/sub x, (dest)
  13774. (dest can be a register or a reference)
  13775. Swap the instructions to minimise a pipeline stall. This reverses the
  13776. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13777. optimisations could be made.
  13778. }
  13779. if (taicpu(p).oper[0]^.typ = top_reg) and
  13780. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13781. (
  13782. (
  13783. (taicpu(p).oper[1]^.typ = top_reg) and
  13784. { We can try searching further ahead if we're writing to a register }
  13785. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13786. ) or
  13787. (
  13788. (taicpu(p).oper[1]^.typ = top_ref) and
  13789. GetNextInstruction(p, hp1)
  13790. )
  13791. ) and
  13792. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13793. (taicpu(hp1).oper[0]^.typ = top_const) and
  13794. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13795. begin
  13796. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13797. TransferUsedRegs(TmpUsedRegs);
  13798. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13799. hp2 := p;
  13800. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13801. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13802. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13803. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13804. begin
  13805. asml.remove(hp1);
  13806. asml.InsertBefore(hp1, p);
  13807. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13808. Result := True;
  13809. end;
  13810. end;
  13811. end;
  13812. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13813. var
  13814. hp1: tai;
  13815. begin
  13816. Result:=false;
  13817. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13818. while GetNextInstruction(p, hp1) and
  13819. TrySwapMovCmp(p, hp1) do
  13820. begin
  13821. if MatchInstruction(hp1, A_MOV, []) then
  13822. begin
  13823. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13824. begin
  13825. { A little hacky, but since CMP doesn't read the flags, only
  13826. modify them, it's safe if they get scrambled by MOV -> XOR }
  13827. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13828. Result := PostPeepholeOptMov(hp1);
  13829. {$ifdef x86_64}
  13830. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13831. { Used to shrink instruction size }
  13832. PostPeepholeOptXor(hp1);
  13833. {$endif x86_64}
  13834. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13835. end
  13836. else
  13837. begin
  13838. Result := PostPeepholeOptMov(hp1);
  13839. {$ifdef x86_64}
  13840. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13841. { Used to shrink instruction size }
  13842. PostPeepholeOptXor(hp1);
  13843. {$endif x86_64}
  13844. end;
  13845. end;
  13846. { Enabling this flag is actually a null operation, but it marks
  13847. the code as 'modified' during this pass }
  13848. Include(OptsToCheck, aoc_ForceNewIteration);
  13849. end;
  13850. { change "cmp $0, %reg" to "test %reg, %reg" }
  13851. if MatchOpType(taicpu(p),top_const,top_reg) and
  13852. (taicpu(p).oper[0]^.val = 0) then
  13853. begin
  13854. taicpu(p).opcode := A_TEST;
  13855. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13856. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13857. Result:=true;
  13858. end;
  13859. end;
  13860. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13861. var
  13862. IsTestConstX, IsValid : Boolean;
  13863. hp1,hp2 : tai;
  13864. begin
  13865. Result:=false;
  13866. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13867. if (taicpu(p).opcode = A_TEST) then
  13868. while GetNextInstruction(p, hp1) and
  13869. TrySwapMovCmp(p, hp1) do
  13870. begin
  13871. if MatchInstruction(hp1, A_MOV, []) then
  13872. begin
  13873. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13874. begin
  13875. { A little hacky, but since TEST doesn't read the flags, only
  13876. modify them, it's safe if they get scrambled by MOV -> XOR }
  13877. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13878. Result := PostPeepholeOptMov(hp1);
  13879. {$ifdef x86_64}
  13880. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13881. { Used to shrink instruction size }
  13882. PostPeepholeOptXor(hp1);
  13883. {$endif x86_64}
  13884. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13885. end
  13886. else
  13887. begin
  13888. Result := PostPeepholeOptMov(hp1);
  13889. {$ifdef x86_64}
  13890. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13891. { Used to shrink instruction size }
  13892. PostPeepholeOptXor(hp1);
  13893. {$endif x86_64}
  13894. end;
  13895. end;
  13896. { Enabling this flag is actually a null operation, but it marks
  13897. the code as 'modified' during this pass }
  13898. Include(OptsToCheck, aoc_ForceNewIteration);
  13899. end;
  13900. { If x is a power of 2 (popcnt = 1), change:
  13901. or $x, %reg/ref
  13902. To:
  13903. bts lb(x), %reg/ref
  13904. }
  13905. if (taicpu(p).opcode = A_OR) and
  13906. IsBTXAcceptable(p) and
  13907. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13908. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13909. (
  13910. { Don't optimise if a test instruction follows }
  13911. not GetNextInstruction(p, hp1) or
  13912. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13913. ) then
  13914. begin
  13915. 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);
  13916. taicpu(p).opcode := A_BTS;
  13917. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13918. Result := True;
  13919. Exit;
  13920. end;
  13921. { If x is a power of 2 (popcnt = 1), change:
  13922. test $x, %reg/ref
  13923. je / sete / cmove (or jne / setne)
  13924. To:
  13925. bt lb(x), %reg/ref
  13926. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13927. }
  13928. if (taicpu(p).opcode = A_TEST) and
  13929. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13930. (taicpu(p).oper[0]^.typ = top_const) and
  13931. (
  13932. (cs_opt_size in current_settings.optimizerswitches) or
  13933. (
  13934. (taicpu(p).oper[1]^.typ = top_reg) and
  13935. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13936. ) or
  13937. (
  13938. (taicpu(p).oper[1]^.typ <> top_reg) and
  13939. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13940. )
  13941. ) and
  13942. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13943. { For sizes less than S_L, the byte size is equal or larger with BT,
  13944. so don't bother optimising }
  13945. (taicpu(p).opsize >= S_L) then
  13946. begin
  13947. IsValid := True;
  13948. { Check the next set of instructions, watching the FLAGS register
  13949. and the conditions used }
  13950. TransferUsedRegs(TmpUsedRegs);
  13951. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13952. hp1 := p;
  13953. hp2 := nil;
  13954. while GetNextInstruction(hp1, hp1) do
  13955. begin
  13956. if not Assigned(hp2) then
  13957. { The first instruction after TEST }
  13958. hp2 := hp1;
  13959. if (hp1.typ <> ait_instruction) then
  13960. begin
  13961. { If the flags are no longer in use, everything is fine }
  13962. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13963. IsValid := False;
  13964. Break;
  13965. end;
  13966. case taicpu(hp1).condition of
  13967. C_None:
  13968. begin
  13969. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13970. { Something is not quite normal, so play safe and don't change }
  13971. IsValid := False;
  13972. Break;
  13973. end;
  13974. C_E, C_Z, C_NE, C_NZ:
  13975. { This is fine };
  13976. else
  13977. begin
  13978. { Unsupported condition }
  13979. IsValid := False;
  13980. Break;
  13981. end;
  13982. end;
  13983. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13984. end;
  13985. if IsValid then
  13986. begin
  13987. while hp2 <> hp1 do
  13988. begin
  13989. case taicpu(hp2).condition of
  13990. C_Z, C_E:
  13991. taicpu(hp2).condition := C_NC;
  13992. C_NZ, C_NE:
  13993. taicpu(hp2).condition := C_C;
  13994. else
  13995. { Should not get this by this point }
  13996. InternalError(2022110701);
  13997. end;
  13998. GetNextInstruction(hp2, hp2);
  13999. end;
  14000. 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);
  14001. taicpu(p).opcode := A_BT;
  14002. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14003. Result := True;
  14004. Exit;
  14005. end;
  14006. end;
  14007. { removes the line marked with (x) from the sequence
  14008. and/or/xor/add/sub/... $x, %y
  14009. test/or %y, %y | test $-1, %y (x)
  14010. j(n)z _Label
  14011. as the first instruction already adjusts the ZF
  14012. %y operand may also be a reference }
  14013. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14014. MatchOperand(taicpu(p).oper[0]^,-1);
  14015. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14016. GetLastInstruction(p, hp1) and
  14017. (tai(hp1).typ = ait_instruction) and
  14018. GetNextInstruction(p,hp2) and
  14019. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14020. case taicpu(hp1).opcode Of
  14021. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14022. { These two instructions set the zero flag if the result is zero }
  14023. A_POPCNT, A_LZCNT:
  14024. begin
  14025. if (
  14026. { With POPCNT, an input of zero will set the zero flag
  14027. because the population count of zero is zero }
  14028. (taicpu(hp1).opcode = A_POPCNT) and
  14029. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14030. (
  14031. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14032. { Faster than going through the second half of the 'or'
  14033. condition below }
  14034. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14035. )
  14036. ) or (
  14037. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14038. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14039. { and in case of carry for A(E)/B(E)/C/NC }
  14040. (
  14041. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14042. (
  14043. (taicpu(hp1).opcode <> A_ADD) and
  14044. (taicpu(hp1).opcode <> A_SUB) and
  14045. (taicpu(hp1).opcode <> A_LZCNT)
  14046. )
  14047. )
  14048. ) then
  14049. begin
  14050. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14051. RemoveCurrentP(p, hp2);
  14052. Result:=true;
  14053. Exit;
  14054. end;
  14055. end;
  14056. A_SHL, A_SAL, A_SHR, A_SAR:
  14057. begin
  14058. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14059. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14060. { therefore, it's only safe to do this optimization for }
  14061. { shifts by a (nonzero) constant }
  14062. (taicpu(hp1).oper[0]^.typ = top_const) and
  14063. (taicpu(hp1).oper[0]^.val <> 0) and
  14064. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14065. { and in case of carry for A(E)/B(E)/C/NC }
  14066. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14067. begin
  14068. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14069. RemoveCurrentP(p, hp2);
  14070. Result:=true;
  14071. Exit;
  14072. end;
  14073. end;
  14074. A_DEC, A_INC, A_NEG:
  14075. begin
  14076. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14077. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14078. { and in case of carry for A(E)/B(E)/C/NC }
  14079. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14080. begin
  14081. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14082. RemoveCurrentP(p, hp2);
  14083. Result:=true;
  14084. Exit;
  14085. end;
  14086. end;
  14087. A_ANDN, A_BZHI:
  14088. begin
  14089. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14090. { Only the zero and sign flags are consistent with what the result is }
  14091. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14092. begin
  14093. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14094. RemoveCurrentP(p, hp2);
  14095. Result:=true;
  14096. Exit;
  14097. end;
  14098. end;
  14099. A_BEXTR:
  14100. begin
  14101. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14102. { Only the zero flag is set }
  14103. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14104. begin
  14105. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14106. RemoveCurrentP(p, hp2);
  14107. Result:=true;
  14108. Exit;
  14109. end;
  14110. end;
  14111. else
  14112. ;
  14113. end; { case }
  14114. { change "test $-1,%reg" into "test %reg,%reg" }
  14115. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14116. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14117. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14118. if MatchInstruction(p, A_OR, []) and
  14119. { Can only match if they're both registers }
  14120. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14121. begin
  14122. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14123. taicpu(p).opcode := A_TEST;
  14124. { No need to set Result to True, as we've done all the optimisations we can }
  14125. end;
  14126. end;
  14127. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14128. var
  14129. hp1,hp3 : tai;
  14130. {$ifndef x86_64}
  14131. hp2 : taicpu;
  14132. {$endif x86_64}
  14133. begin
  14134. Result:=false;
  14135. hp3:=nil;
  14136. {$ifndef x86_64}
  14137. { don't do this on modern CPUs, this really hurts them due to
  14138. broken call/ret pairing }
  14139. if (current_settings.optimizecputype < cpu_Pentium2) and
  14140. not(cs_create_pic in current_settings.moduleswitches) and
  14141. GetNextInstruction(p, hp1) and
  14142. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14143. MatchOpType(taicpu(hp1),top_ref) and
  14144. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14145. begin
  14146. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14147. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14148. InsertLLItem(p.previous, p, hp2);
  14149. taicpu(p).opcode := A_JMP;
  14150. taicpu(p).is_jmp := true;
  14151. RemoveInstruction(hp1);
  14152. Result:=true;
  14153. end
  14154. else
  14155. {$endif x86_64}
  14156. { replace
  14157. call procname
  14158. ret
  14159. by
  14160. jmp procname
  14161. but do it only on level 4 because it destroys stack back traces
  14162. else if the subroutine is marked as no return, remove the ret
  14163. }
  14164. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14165. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14166. GetNextInstruction(p, hp1) and
  14167. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14168. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14169. SetAndTest(hp1,hp3) and
  14170. GetNextInstruction(hp1,hp1) and
  14171. MatchInstruction(hp1,A_RET,[S_NO])
  14172. )
  14173. ) and
  14174. (taicpu(hp1).ops=0) then
  14175. begin
  14176. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14177. { we might destroy stack alignment here if we do not do a call }
  14178. (target_info.stackalign<=sizeof(SizeUInt)) then
  14179. begin
  14180. taicpu(p).opcode := A_JMP;
  14181. taicpu(p).is_jmp := true;
  14182. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14183. end
  14184. else
  14185. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14186. RemoveInstruction(hp1);
  14187. if Assigned(hp3) then
  14188. begin
  14189. AsmL.Remove(hp3);
  14190. AsmL.InsertBefore(hp3,p)
  14191. end;
  14192. Result:=true;
  14193. end;
  14194. end;
  14195. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14196. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14197. begin
  14198. case OpSize of
  14199. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14200. Result := (Val <= $FF) and (Val >= -128);
  14201. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14202. Result := (Val <= $FFFF) and (Val >= -32768);
  14203. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14204. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14205. else
  14206. Result := True;
  14207. end;
  14208. end;
  14209. var
  14210. hp1, hp2 : tai;
  14211. SizeChange: Boolean;
  14212. PreMessage: string;
  14213. begin
  14214. Result := False;
  14215. if (taicpu(p).oper[0]^.typ = top_reg) and
  14216. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14217. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14218. begin
  14219. { Change (using movzbl %al,%eax as an example):
  14220. movzbl %al, %eax movzbl %al, %eax
  14221. cmpl x, %eax testl %eax,%eax
  14222. To:
  14223. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14224. movzbl %al, %eax movzbl %al, %eax
  14225. Smaller instruction and minimises pipeline stall as the CPU
  14226. doesn't have to wait for the register to get zero-extended. [Kit]
  14227. Also allow if the smaller of the two registers is being checked,
  14228. as this still removes the false dependency.
  14229. }
  14230. if
  14231. (
  14232. (
  14233. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14234. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14235. ) or (
  14236. { If MatchOperand returns True, they must both be registers }
  14237. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14238. )
  14239. ) and
  14240. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14241. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14242. begin
  14243. 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);
  14244. asml.Remove(hp1);
  14245. asml.InsertBefore(hp1, p);
  14246. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14247. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14248. begin
  14249. taicpu(hp1).opcode := A_TEST;
  14250. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14251. end;
  14252. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14253. case taicpu(p).opsize of
  14254. S_BW, S_BL:
  14255. begin
  14256. SizeChange := taicpu(hp1).opsize <> S_B;
  14257. taicpu(hp1).changeopsize(S_B);
  14258. end;
  14259. S_WL:
  14260. begin
  14261. SizeChange := taicpu(hp1).opsize <> S_W;
  14262. taicpu(hp1).changeopsize(S_W);
  14263. end
  14264. else
  14265. InternalError(2020112701);
  14266. end;
  14267. UpdateUsedRegs(tai(p.Next));
  14268. { Check if the register is used aferwards - if not, we can
  14269. remove the movzx instruction completely }
  14270. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14271. begin
  14272. { Hp1 is a better position than p for debugging purposes }
  14273. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14274. RemoveCurrentp(p, hp1);
  14275. Result := True;
  14276. end;
  14277. if SizeChange then
  14278. DebugMsg(SPeepholeOptimization + PreMessage +
  14279. 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)
  14280. else
  14281. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14282. Exit;
  14283. end;
  14284. { Change (using movzwl %ax,%eax as an example):
  14285. movzwl %ax, %eax
  14286. movb %al, (dest) (Register is smaller than read register in movz)
  14287. To:
  14288. movb %al, (dest) (Move one back to avoid a false dependency)
  14289. movzwl %ax, %eax
  14290. }
  14291. if (taicpu(hp1).opcode = A_MOV) and
  14292. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14293. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14294. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14295. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14296. begin
  14297. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14298. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14299. asml.Remove(hp1);
  14300. asml.InsertBefore(hp1, p);
  14301. if taicpu(hp1).oper[1]^.typ = top_reg then
  14302. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14303. { Check if the register is used aferwards - if not, we can
  14304. remove the movzx instruction completely }
  14305. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14306. begin
  14307. { Hp1 is a better position than p for debugging purposes }
  14308. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14309. RemoveCurrentp(p, hp1);
  14310. Result := True;
  14311. end;
  14312. Exit;
  14313. end;
  14314. end;
  14315. end;
  14316. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14317. var
  14318. hp1: tai;
  14319. {$ifdef x86_64}
  14320. PreMessage, RegName: string;
  14321. {$endif x86_64}
  14322. begin
  14323. Result := False;
  14324. { If x is a power of 2 (popcnt = 1), change:
  14325. xor $x, %reg/ref
  14326. To:
  14327. btc lb(x), %reg/ref
  14328. }
  14329. if IsBTXAcceptable(p) and
  14330. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14331. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14332. (
  14333. { Don't optimise if a test instruction follows }
  14334. not GetNextInstruction(p, hp1) or
  14335. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14336. ) then
  14337. begin
  14338. 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);
  14339. taicpu(p).opcode := A_BTC;
  14340. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14341. Result := True;
  14342. Exit;
  14343. end;
  14344. {$ifdef x86_64}
  14345. { Code size reduction by J. Gareth "Kit" Moreton }
  14346. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14347. as this removes the REX prefix }
  14348. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14349. Exit;
  14350. if taicpu(p).oper[0]^.typ <> top_reg then
  14351. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14352. InternalError(2018011500);
  14353. case taicpu(p).opsize of
  14354. S_Q:
  14355. begin
  14356. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14357. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14358. { The actual optimization }
  14359. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14360. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14361. taicpu(p).changeopsize(S_L);
  14362. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14363. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14364. end;
  14365. else
  14366. ;
  14367. end;
  14368. {$endif x86_64}
  14369. end;
  14370. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14371. var
  14372. XReg: TRegister;
  14373. begin
  14374. Result := False;
  14375. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14376. Smaller encoding and slightly faster on some platforms (also works for
  14377. ZMM-sized registers) }
  14378. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14379. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14380. begin
  14381. XReg := taicpu(p).oper[0]^.reg;
  14382. if (taicpu(p).oper[1]^.reg = XReg) then
  14383. begin
  14384. taicpu(p).changeopsize(S_XMM);
  14385. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14386. if (cs_opt_size in current_settings.optimizerswitches) then
  14387. begin
  14388. { Change input registers to %xmm0 to reduce size. Note that
  14389. there's a risk of a false dependency doing this, so only
  14390. optimise for size here }
  14391. XReg := NR_XMM0;
  14392. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14393. end
  14394. else
  14395. begin
  14396. setsubreg(XReg, R_SUBMMX);
  14397. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14398. end;
  14399. taicpu(p).oper[0]^.reg := XReg;
  14400. taicpu(p).oper[1]^.reg := XReg;
  14401. Result := True;
  14402. end;
  14403. end;
  14404. end;
  14405. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14406. var
  14407. OperIdx: Integer;
  14408. begin
  14409. for OperIdx := 0 to p.ops - 1 do
  14410. if p.oper[OperIdx]^.typ = top_ref then
  14411. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14412. end;
  14413. end.