aoptx86.pas 677 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771
  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; UpdateTmpUsedRegs: Boolean) : 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. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  957. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGCARRY:
  959. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGPARITY:
  961. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGAUXILIARY:
  963. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGZERO:
  965. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGSIGN:
  967. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. R_SUBFLAGOVERFLOW:
  969. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  970. R_SUBFLAGINTERRUPT:
  971. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  972. R_SUBFLAGDIRECTION:
  973. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  974. else
  975. internalerror(2017042602);
  976. end;
  977. exit;
  978. end;
  979. case taicpu(p1).opcode of
  980. A_CALL:
  981. { We could potentially set Result to False if the register in
  982. question is non-volatile for the subroutine's calling convention,
  983. but this would require detecting the calling convention in use and
  984. also assuming that the routine doesn't contain malformed assembly
  985. language, for example... so it could only be done under -O4 as it
  986. would be considered a side-effect. [Kit] }
  987. Result := True;
  988. A_MOVSD:
  989. { special handling for SSE MOVSD }
  990. if (taicpu(p1).ops>0) then
  991. begin
  992. if taicpu(p1).ops<>2 then
  993. internalerror(2017042703);
  994. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  995. end;
  996. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  997. so fix it here (FK)
  998. }
  999. A_VMOVSS,
  1000. A_VMOVSD:
  1001. begin
  1002. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1003. exit;
  1004. end;
  1005. A_IMUL:
  1006. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1007. else
  1008. ;
  1009. end;
  1010. if Result then
  1011. exit;
  1012. with insprop[taicpu(p1).opcode] do
  1013. begin
  1014. if getregtype(reg)=R_INTREGISTER then
  1015. begin
  1016. case getsupreg(reg) of
  1017. RS_EAX:
  1018. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_ECX:
  1024. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EDX:
  1030. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_EBX:
  1036. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_ESP:
  1042. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_EBP:
  1048. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_ESI:
  1054. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_EDI:
  1060. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. end;
  1066. end;
  1067. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1068. if (WriteOps[OperIdx]*Ch<>[]) and
  1069. { The register doesn't get modified inside a reference }
  1070. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1071. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1072. begin
  1073. Result := true;
  1074. exit
  1075. end;
  1076. end;
  1077. end;
  1078. {$ifdef DEBUG_AOPTCPU}
  1079. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1080. begin
  1081. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1082. end;
  1083. function debug_tostr(i: tcgint): string; inline;
  1084. begin
  1085. Result := tostr(i);
  1086. end;
  1087. function debug_hexstr(i: tcgint): string;
  1088. begin
  1089. Result := '0x';
  1090. case i of
  1091. 0..$FF:
  1092. Result := Result + hexstr(i, 2);
  1093. $100..$FFFF:
  1094. Result := Result + hexstr(i, 4);
  1095. $10000..$FFFFFF:
  1096. Result := Result + hexstr(i, 6);
  1097. $1000000..$FFFFFFFF:
  1098. Result := Result + hexstr(i, 8);
  1099. else
  1100. Result := Result + hexstr(i, 16);
  1101. end;
  1102. end;
  1103. function debug_regname(r: TRegister): string; inline;
  1104. begin
  1105. Result := '%' + std_regname(r);
  1106. end;
  1107. { Debug output function - creates a string representation of an operator }
  1108. function debug_operstr(oper: TOper): string;
  1109. begin
  1110. case oper.typ of
  1111. top_const:
  1112. Result := '$' + debug_tostr(oper.val);
  1113. top_reg:
  1114. Result := debug_regname(oper.reg);
  1115. top_ref:
  1116. begin
  1117. if oper.ref^.offset <> 0 then
  1118. Result := debug_tostr(oper.ref^.offset) + '('
  1119. else
  1120. Result := '(';
  1121. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1122. begin
  1123. Result := Result + debug_regname(oper.ref^.base);
  1124. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1125. Result := Result + ',' + debug_regname(oper.ref^.index);
  1126. end
  1127. else
  1128. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1129. Result := Result + debug_regname(oper.ref^.index);
  1130. if (oper.ref^.scalefactor > 1) then
  1131. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1132. else
  1133. Result := Result + ')';
  1134. end;
  1135. else
  1136. Result := '[UNKNOWN]';
  1137. end;
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := std_op2str[opcode];
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := gas_opsize2str[opsize];
  1146. end;
  1147. {$else DEBUG_AOPTCPU}
  1148. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1149. begin
  1150. end;
  1151. function debug_tostr(i: tcgint): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. function debug_hexstr(i: tcgint): string; inline;
  1156. begin
  1157. Result := '';
  1158. end;
  1159. function debug_regname(r: TRegister): string; inline;
  1160. begin
  1161. Result := '';
  1162. end;
  1163. function debug_operstr(oper: TOper): string; inline;
  1164. begin
  1165. Result := '';
  1166. end;
  1167. function debug_op2str(opcode: tasmop): string; inline;
  1168. begin
  1169. Result := '';
  1170. end;
  1171. function debug_opsize2str(opsize: topsize): string; inline;
  1172. begin
  1173. Result := '';
  1174. end;
  1175. {$endif DEBUG_AOPTCPU}
  1176. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1177. begin
  1178. {$ifdef x86_64}
  1179. { Always fine on x86-64 }
  1180. Result := True;
  1181. {$else x86_64}
  1182. Result :=
  1183. {$ifdef i8086}
  1184. (current_settings.cputype >= cpu_386) and
  1185. {$endif i8086}
  1186. (
  1187. { Always accept if optimising for size }
  1188. (cs_opt_size in current_settings.optimizerswitches) or
  1189. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1190. (current_settings.optimizecputype >= cpu_Pentium2)
  1191. );
  1192. {$endif x86_64}
  1193. end;
  1194. { Attempts to allocate a volatile integer register for use between p and hp,
  1195. using AUsedRegs for the current register usage information. Returns NR_NO
  1196. if no free register could be found }
  1197. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1198. var
  1199. RegSet: TCPURegisterSet;
  1200. CurrentSuperReg: Integer;
  1201. CurrentReg: TRegister;
  1202. Currentp: tai;
  1203. Breakout: Boolean;
  1204. begin
  1205. Result := NR_NO;
  1206. RegSet :=
  1207. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1208. current_procinfo.saved_regs_int;
  1209. (*
  1210. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1211. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1212. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1213. *)
  1214. for CurrentSuperReg in RegSet do
  1215. begin
  1216. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1217. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1218. {$if defined(i386) or defined(i8086)}
  1219. { If the target size is 8-bit, make sure we can actually encode it }
  1220. and (
  1221. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1222. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1223. )
  1224. {$endif i386 or i8086}
  1225. then
  1226. begin
  1227. Currentp := p;
  1228. Breakout := False;
  1229. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1230. begin
  1231. case Currentp.typ of
  1232. ait_instruction:
  1233. begin
  1234. if RegInInstruction(CurrentReg, Currentp) then
  1235. begin
  1236. Breakout := True;
  1237. Break;
  1238. end;
  1239. { Cannot allocate across an unconditional jump }
  1240. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1241. Exit;
  1242. end;
  1243. ait_marker:
  1244. { Don't try anything more if a marker is hit }
  1245. Exit;
  1246. ait_regalloc:
  1247. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1248. begin
  1249. Breakout := True;
  1250. Break;
  1251. end;
  1252. else
  1253. ;
  1254. end;
  1255. end;
  1256. if Breakout then
  1257. { Try the next register }
  1258. Continue;
  1259. { We have a free register available }
  1260. Result := CurrentReg;
  1261. if not DontAlloc then
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. { Attempts to allocate a volatile MM register for use between p and hp,
  1268. using AUsedRegs for the current register usage information. Returns NR_NO
  1269. if no free register could be found }
  1270. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1271. var
  1272. RegSet: TCPURegisterSet;
  1273. CurrentSuperReg: Integer;
  1274. CurrentReg: TRegister;
  1275. Currentp: tai;
  1276. Breakout: Boolean;
  1277. begin
  1278. Result := NR_NO;
  1279. RegSet :=
  1280. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1281. current_procinfo.saved_regs_mm;
  1282. for CurrentSuperReg in RegSet do
  1283. begin
  1284. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1285. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1286. begin
  1287. Currentp := p;
  1288. Breakout := False;
  1289. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1290. begin
  1291. case Currentp.typ of
  1292. ait_instruction:
  1293. begin
  1294. if RegInInstruction(CurrentReg, Currentp) then
  1295. begin
  1296. Breakout := True;
  1297. Break;
  1298. end;
  1299. { Cannot allocate across an unconditional jump }
  1300. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1301. Exit;
  1302. end;
  1303. ait_marker:
  1304. { Don't try anything more if a marker is hit }
  1305. Exit;
  1306. ait_regalloc:
  1307. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1308. begin
  1309. Breakout := True;
  1310. Break;
  1311. end;
  1312. else
  1313. ;
  1314. end;
  1315. end;
  1316. if Breakout then
  1317. { Try the next register }
  1318. Continue;
  1319. { We have a free register available }
  1320. Result := CurrentReg;
  1321. if not DontAlloc then
  1322. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1323. Exit;
  1324. end;
  1325. end;
  1326. end;
  1327. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1328. begin
  1329. if not SuperRegistersEqual(reg1,reg2) then
  1330. exit(false);
  1331. if getregtype(reg1)<>R_INTREGISTER then
  1332. exit(true); {because SuperRegisterEqual is true}
  1333. case getsubreg(reg1) of
  1334. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1335. higher, it preserves the high bits, so the new value depends on
  1336. reg2's previous value. In other words, it is equivalent to doing:
  1337. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1338. R_SUBL:
  1339. exit(getsubreg(reg2)=R_SUBL);
  1340. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1341. higher, it actually does a:
  1342. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1343. R_SUBH:
  1344. exit(getsubreg(reg2)=R_SUBH);
  1345. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1346. bits of reg2:
  1347. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1348. R_SUBW:
  1349. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1350. { a write to R_SUBD always overwrites every other subregister,
  1351. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1352. R_SUBD,
  1353. R_SUBQ:
  1354. exit(true);
  1355. else
  1356. internalerror(2017042801);
  1357. end;
  1358. end;
  1359. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1360. begin
  1361. if not SuperRegistersEqual(reg1,reg2) then
  1362. exit(false);
  1363. if getregtype(reg1)<>R_INTREGISTER then
  1364. exit(true); {because SuperRegisterEqual is true}
  1365. case getsubreg(reg1) of
  1366. R_SUBL:
  1367. exit(getsubreg(reg2)<>R_SUBH);
  1368. R_SUBH:
  1369. exit(getsubreg(reg2)<>R_SUBL);
  1370. R_SUBW,
  1371. R_SUBD,
  1372. R_SUBQ:
  1373. exit(true);
  1374. else
  1375. internalerror(2017042802);
  1376. end;
  1377. end;
  1378. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1379. var
  1380. hp1 : tai;
  1381. l : TCGInt;
  1382. begin
  1383. result:=false;
  1384. { changes the code sequence
  1385. shr/sar const1, x
  1386. shl const2, x
  1387. to
  1388. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1389. if GetNextInstruction(p, hp1) and
  1390. MatchInstruction(hp1,A_SHL,[]) and
  1391. (taicpu(p).oper[0]^.typ = top_const) and
  1392. (taicpu(hp1).oper[0]^.typ = top_const) and
  1393. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1394. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1395. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1396. begin
  1397. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1398. not(cs_opt_size in current_settings.optimizerswitches) then
  1399. begin
  1400. { shr/sar const1, %reg
  1401. shl const2, %reg
  1402. with const1 > const2 }
  1403. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1404. taicpu(hp1).opcode := A_AND;
  1405. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1406. case taicpu(p).opsize Of
  1407. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1408. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1409. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1410. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1411. else
  1412. Internalerror(2017050703)
  1413. end;
  1414. end
  1415. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1416. not(cs_opt_size in current_settings.optimizerswitches) then
  1417. begin
  1418. { shr/sar const1, %reg
  1419. shl const2, %reg
  1420. with const1 < const2 }
  1421. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1422. taicpu(p).opcode := A_AND;
  1423. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1424. case taicpu(p).opsize Of
  1425. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1426. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1427. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1428. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1429. else
  1430. Internalerror(2017050702)
  1431. end;
  1432. end
  1433. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1434. begin
  1435. { shr/sar const1, %reg
  1436. shl const2, %reg
  1437. with const1 = const2 }
  1438. taicpu(p).opcode := A_AND;
  1439. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1440. case taicpu(p).opsize Of
  1441. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1442. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1443. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1444. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1445. else
  1446. Internalerror(2017050701)
  1447. end;
  1448. RemoveInstruction(hp1);
  1449. end;
  1450. end;
  1451. end;
  1452. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1453. var
  1454. opsize : topsize;
  1455. hp1, hp2 : tai;
  1456. tmpref : treference;
  1457. ShiftValue : Cardinal;
  1458. BaseValue : TCGInt;
  1459. begin
  1460. result:=false;
  1461. opsize:=taicpu(p).opsize;
  1462. { changes certain "imul const, %reg"'s to lea sequences }
  1463. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1464. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1465. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1466. if (taicpu(p).oper[0]^.val = 1) then
  1467. if (taicpu(p).ops = 2) then
  1468. { remove "imul $1, reg" }
  1469. begin
  1470. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1471. Result := RemoveCurrentP(p);
  1472. end
  1473. else
  1474. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1475. begin
  1476. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1477. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1478. asml.InsertAfter(hp1, p);
  1479. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1480. RemoveCurrentP(p, hp1);
  1481. Result := True;
  1482. end
  1483. else if ((taicpu(p).ops <= 2) or
  1484. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1485. not(cs_opt_size in current_settings.optimizerswitches) and
  1486. (not(GetNextInstruction(p, hp1)) or
  1487. not((tai(hp1).typ = ait_instruction) and
  1488. ((taicpu(hp1).opcode=A_Jcc) and
  1489. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1490. begin
  1491. {
  1492. imul X, reg1, reg2 to
  1493. lea (reg1,reg1,Y), reg2
  1494. shl ZZ,reg2
  1495. imul XX, reg1 to
  1496. lea (reg1,reg1,YY), reg1
  1497. shl ZZ,reg2
  1498. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1499. it does not exist as a separate optimization target in FPC though.
  1500. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1501. at most two zeros
  1502. }
  1503. reference_reset(tmpref,1,[]);
  1504. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1505. begin
  1506. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1507. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1508. TmpRef.base := taicpu(p).oper[1]^.reg;
  1509. TmpRef.index := taicpu(p).oper[1]^.reg;
  1510. if not(BaseValue in [3,5,9]) then
  1511. Internalerror(2018110101);
  1512. TmpRef.ScaleFactor := BaseValue-1;
  1513. if (taicpu(p).ops = 2) then
  1514. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1515. else
  1516. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1517. AsmL.InsertAfter(hp1,p);
  1518. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1519. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1520. RemoveCurrentP(p, hp1);
  1521. if ShiftValue>0 then
  1522. begin
  1523. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1524. AsmL.InsertAfter(hp2,hp1);
  1525. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1526. end;
  1527. Result := True;
  1528. end;
  1529. end;
  1530. end;
  1531. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1532. begin
  1533. Result := False;
  1534. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1535. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1536. begin
  1537. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1538. taicpu(p).opcode := A_MOV;
  1539. Result := True;
  1540. end;
  1541. end;
  1542. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1543. var
  1544. p: taicpu absolute hp; { Implicit typecast }
  1545. i: Integer;
  1546. begin
  1547. Result := False;
  1548. if not assigned(hp) or
  1549. (hp.typ <> ait_instruction) then
  1550. Exit;
  1551. Prefetch(insprop[p.opcode]);
  1552. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1553. with insprop[p.opcode] do
  1554. begin
  1555. case getsubreg(reg) of
  1556. R_SUBW,R_SUBD,R_SUBQ:
  1557. Result:=
  1558. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1559. uncommon flags are checked first }
  1560. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1561. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1562. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1563. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1564. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1565. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1566. R_SUBFLAGCARRY:
  1567. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1568. R_SUBFLAGPARITY:
  1569. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1570. R_SUBFLAGAUXILIARY:
  1571. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1572. R_SUBFLAGZERO:
  1573. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1574. R_SUBFLAGSIGN:
  1575. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1576. R_SUBFLAGOVERFLOW:
  1577. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1578. R_SUBFLAGINTERRUPT:
  1579. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1580. R_SUBFLAGDIRECTION:
  1581. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1582. else
  1583. internalerror(2017050501);
  1584. end;
  1585. exit;
  1586. end;
  1587. { Handle special cases first }
  1588. case p.opcode of
  1589. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1590. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1591. begin
  1592. Result :=
  1593. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1594. (p.oper[1]^.typ = top_reg) and
  1595. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1596. (
  1597. (p.oper[0]^.typ = top_const) or
  1598. (
  1599. (p.oper[0]^.typ = top_reg) and
  1600. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1601. ) or (
  1602. (p.oper[0]^.typ = top_ref) and
  1603. not RegInRef(reg,p.oper[0]^.ref^)
  1604. )
  1605. );
  1606. end;
  1607. A_MUL, A_IMUL:
  1608. Result :=
  1609. (
  1610. (p.ops=3) and { IMUL only }
  1611. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1612. (
  1613. (
  1614. (p.oper[1]^.typ=top_reg) and
  1615. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1616. ) or (
  1617. (p.oper[1]^.typ=top_ref) and
  1618. not RegInRef(reg,p.oper[1]^.ref^)
  1619. )
  1620. )
  1621. ) or (
  1622. (
  1623. (p.ops=1) and
  1624. (
  1625. (
  1626. (
  1627. (p.oper[0]^.typ=top_reg) and
  1628. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1629. )
  1630. ) or (
  1631. (p.oper[0]^.typ=top_ref) and
  1632. not RegInRef(reg,p.oper[0]^.ref^)
  1633. )
  1634. ) and (
  1635. (
  1636. (p.opsize=S_B) and
  1637. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1638. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1639. ) or (
  1640. (p.opsize=S_W) and
  1641. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1642. ) or (
  1643. (p.opsize=S_L) and
  1644. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1645. {$ifdef x86_64}
  1646. ) or (
  1647. (p.opsize=S_Q) and
  1648. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1649. {$endif x86_64}
  1650. )
  1651. )
  1652. )
  1653. );
  1654. A_CBW:
  1655. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1656. {$ifndef x86_64}
  1657. A_LDS:
  1658. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1659. A_LES:
  1660. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1661. {$endif not x86_64}
  1662. A_LFS:
  1663. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1664. A_LGS:
  1665. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1666. A_LSS:
  1667. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1668. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1669. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1670. A_LODSB:
  1671. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1672. A_LODSW:
  1673. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1674. {$ifdef x86_64}
  1675. A_LODSQ:
  1676. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1677. {$endif x86_64}
  1678. A_LODSD:
  1679. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1680. A_FSTSW, A_FNSTSW:
  1681. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1682. else
  1683. begin
  1684. with insprop[p.opcode] do
  1685. begin
  1686. if (
  1687. { xor %reg,%reg etc. is classed as a new value }
  1688. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1689. MatchOpType(p, top_reg, top_reg) and
  1690. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1691. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1692. ) then
  1693. begin
  1694. Result := True;
  1695. Exit;
  1696. end;
  1697. { Make sure the entire register is overwritten }
  1698. if (getregtype(reg) = R_INTREGISTER) then
  1699. begin
  1700. if (p.ops > 0) then
  1701. begin
  1702. if RegInOp(reg, p.oper[0]^) then
  1703. begin
  1704. if (p.oper[0]^.typ = top_ref) then
  1705. begin
  1706. if RegInRef(reg, p.oper[0]^.ref^) then
  1707. begin
  1708. Result := False;
  1709. Exit;
  1710. end;
  1711. end
  1712. else if (p.oper[0]^.typ = top_reg) then
  1713. begin
  1714. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1715. begin
  1716. Result := False;
  1717. Exit;
  1718. end
  1719. else if ([Ch_WOp1]*Ch<>[]) then
  1720. begin
  1721. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1722. Result := True
  1723. else
  1724. begin
  1725. Result := False;
  1726. Exit;
  1727. end;
  1728. end;
  1729. end;
  1730. end;
  1731. if (p.ops > 1) then
  1732. begin
  1733. if RegInOp(reg, p.oper[1]^) then
  1734. begin
  1735. if (p.oper[1]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[1]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[1]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp2]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. if (p.ops > 2) then
  1763. begin
  1764. if RegInOp(reg, p.oper[2]^) then
  1765. begin
  1766. if (p.oper[2]^.typ = top_ref) then
  1767. begin
  1768. if RegInRef(reg, p.oper[2]^.ref^) then
  1769. begin
  1770. Result := False;
  1771. Exit;
  1772. end;
  1773. end
  1774. else if (p.oper[2]^.typ = top_reg) then
  1775. begin
  1776. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1777. begin
  1778. Result := False;
  1779. Exit;
  1780. end
  1781. else if ([Ch_WOp3]*Ch<>[]) then
  1782. begin
  1783. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1784. Result := True
  1785. else
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end;
  1790. end;
  1791. end;
  1792. end;
  1793. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1794. begin
  1795. if (p.oper[3]^.typ = top_ref) then
  1796. begin
  1797. if RegInRef(reg, p.oper[3]^.ref^) then
  1798. begin
  1799. Result := False;
  1800. Exit;
  1801. end;
  1802. end
  1803. else if (p.oper[3]^.typ = top_reg) then
  1804. begin
  1805. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1806. begin
  1807. Result := False;
  1808. Exit;
  1809. end
  1810. else if ([Ch_WOp4]*Ch<>[]) then
  1811. begin
  1812. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1813. Result := True
  1814. else
  1815. begin
  1816. Result := False;
  1817. Exit;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. end;
  1824. end;
  1825. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1826. case getsupreg(reg) of
  1827. RS_EAX:
  1828. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1829. begin
  1830. Result := True;
  1831. Exit;
  1832. end;
  1833. RS_ECX:
  1834. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1835. begin
  1836. Result := True;
  1837. Exit;
  1838. end;
  1839. RS_EDX:
  1840. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1841. begin
  1842. Result := True;
  1843. Exit;
  1844. end;
  1845. RS_EBX:
  1846. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1847. begin
  1848. Result := True;
  1849. Exit;
  1850. end;
  1851. RS_ESP:
  1852. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1853. begin
  1854. Result := True;
  1855. Exit;
  1856. end;
  1857. RS_EBP:
  1858. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1859. begin
  1860. Result := True;
  1861. Exit;
  1862. end;
  1863. RS_ESI:
  1864. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1865. begin
  1866. Result := True;
  1867. Exit;
  1868. end;
  1869. RS_EDI:
  1870. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1871. begin
  1872. Result := True;
  1873. Exit;
  1874. end;
  1875. else
  1876. ;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. end;
  1882. end;
  1883. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1884. var
  1885. hp2,hp3 : tai;
  1886. begin
  1887. { some x86-64 issue a NOP before the real exit code }
  1888. if MatchInstruction(p,A_NOP,[]) then
  1889. GetNextInstruction(p,p);
  1890. result:=assigned(p) and (p.typ=ait_instruction) and
  1891. ((taicpu(p).opcode = A_RET) or
  1892. ((taicpu(p).opcode=A_LEAVE) and
  1893. GetNextInstruction(p,hp2) and
  1894. MatchInstruction(hp2,A_RET,[S_NO])
  1895. ) or
  1896. (((taicpu(p).opcode=A_LEA) and
  1897. MatchOpType(taicpu(p),top_ref,top_reg) and
  1898. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1899. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1900. ) and
  1901. GetNextInstruction(p,hp2) and
  1902. MatchInstruction(hp2,A_RET,[S_NO])
  1903. ) or
  1904. ((((taicpu(p).opcode=A_MOV) and
  1905. MatchOpType(taicpu(p),top_reg,top_reg) and
  1906. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1907. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1908. ((taicpu(p).opcode=A_LEA) and
  1909. MatchOpType(taicpu(p),top_ref,top_reg) and
  1910. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1911. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1912. )
  1913. ) and
  1914. GetNextInstruction(p,hp2) and
  1915. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1916. MatchOpType(taicpu(hp2),top_reg) and
  1917. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1918. GetNextInstruction(hp2,hp3) and
  1919. MatchInstruction(hp3,A_RET,[S_NO])
  1920. )
  1921. );
  1922. end;
  1923. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1924. begin
  1925. isFoldableArithOp := False;
  1926. case hp1.opcode of
  1927. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1928. isFoldableArithOp :=
  1929. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1930. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1931. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1932. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1933. (taicpu(hp1).oper[1]^.reg = reg);
  1934. A_INC,A_DEC,A_NEG,A_NOT:
  1935. isFoldableArithOp :=
  1936. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1937. (taicpu(hp1).oper[0]^.reg = reg);
  1938. else
  1939. ;
  1940. end;
  1941. end;
  1942. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1943. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1944. var
  1945. hp2: tai;
  1946. begin
  1947. hp2 := p;
  1948. repeat
  1949. hp2 := tai(hp2.previous);
  1950. if assigned(hp2) and
  1951. (hp2.typ = ait_regalloc) and
  1952. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1953. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1954. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1955. begin
  1956. RemoveInstruction(hp2);
  1957. break;
  1958. end;
  1959. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1960. end;
  1961. begin
  1962. case current_procinfo.procdef.returndef.typ of
  1963. arraydef,recorddef,pointerdef,
  1964. stringdef,enumdef,procdef,objectdef,errordef,
  1965. filedef,setdef,procvardef,
  1966. classrefdef,forwarddef:
  1967. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1968. orddef:
  1969. if current_procinfo.procdef.returndef.size <> 0 then
  1970. begin
  1971. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1972. { for int64/qword }
  1973. if current_procinfo.procdef.returndef.size = 8 then
  1974. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1975. end;
  1976. else
  1977. ;
  1978. end;
  1979. end;
  1980. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1981. var
  1982. hp1,hp2 : tai;
  1983. begin
  1984. result:=false;
  1985. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1986. begin
  1987. { vmova* reg1,reg1
  1988. =>
  1989. <nop> }
  1990. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  1991. begin
  1992. RemoveCurrentP(p);
  1993. result:=true;
  1994. exit;
  1995. end;
  1996. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1997. begin
  1998. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1999. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2000. begin
  2001. { vmova* reg1,reg2
  2002. vmova* reg2,reg3
  2003. dealloc reg2
  2004. =>
  2005. vmova* reg1,reg3 }
  2006. TransferUsedRegs(TmpUsedRegs);
  2007. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2008. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2009. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2010. begin
  2011. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2012. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2013. RemoveInstruction(hp1);
  2014. result:=true;
  2015. exit;
  2016. end;
  2017. { special case:
  2018. vmova* reg1,<op>
  2019. vmova* <op>,reg1
  2020. =>
  2021. vmova* reg1,<op> }
  2022. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2023. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2024. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2025. ) then
  2026. begin
  2027. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2028. RemoveInstruction(hp1);
  2029. result:=true;
  2030. exit;
  2031. end
  2032. end
  2033. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2034. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2035. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2036. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2037. ) and
  2038. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2039. begin
  2040. { vmova* reg1,reg2
  2041. vmovs* reg2,<op>
  2042. dealloc reg2
  2043. =>
  2044. vmovs* reg1,reg3 }
  2045. TransferUsedRegs(TmpUsedRegs);
  2046. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2047. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2048. begin
  2049. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2050. taicpu(p).opcode:=taicpu(hp1).opcode;
  2051. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2052. RemoveInstruction(hp1);
  2053. result:=true;
  2054. exit;
  2055. end
  2056. end;
  2057. end;
  2058. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2059. begin
  2060. if MatchInstruction(hp1,[A_VFMADDPD,
  2061. A_VFMADD132PD,
  2062. A_VFMADD132PS,
  2063. A_VFMADD132SD,
  2064. A_VFMADD132SS,
  2065. A_VFMADD213PD,
  2066. A_VFMADD213PS,
  2067. A_VFMADD213SD,
  2068. A_VFMADD213SS,
  2069. A_VFMADD231PD,
  2070. A_VFMADD231PS,
  2071. A_VFMADD231SD,
  2072. A_VFMADD231SS,
  2073. A_VFMADDSUB132PD,
  2074. A_VFMADDSUB132PS,
  2075. A_VFMADDSUB213PD,
  2076. A_VFMADDSUB213PS,
  2077. A_VFMADDSUB231PD,
  2078. A_VFMADDSUB231PS,
  2079. A_VFMSUB132PD,
  2080. A_VFMSUB132PS,
  2081. A_VFMSUB132SD,
  2082. A_VFMSUB132SS,
  2083. A_VFMSUB213PD,
  2084. A_VFMSUB213PS,
  2085. A_VFMSUB213SD,
  2086. A_VFMSUB213SS,
  2087. A_VFMSUB231PD,
  2088. A_VFMSUB231PS,
  2089. A_VFMSUB231SD,
  2090. A_VFMSUB231SS,
  2091. A_VFMSUBADD132PD,
  2092. A_VFMSUBADD132PS,
  2093. A_VFMSUBADD213PD,
  2094. A_VFMSUBADD213PS,
  2095. A_VFMSUBADD231PD,
  2096. A_VFMSUBADD231PS,
  2097. A_VFNMADD132PD,
  2098. A_VFNMADD132PS,
  2099. A_VFNMADD132SD,
  2100. A_VFNMADD132SS,
  2101. A_VFNMADD213PD,
  2102. A_VFNMADD213PS,
  2103. A_VFNMADD213SD,
  2104. A_VFNMADD213SS,
  2105. A_VFNMADD231PD,
  2106. A_VFNMADD231PS,
  2107. A_VFNMADD231SD,
  2108. A_VFNMADD231SS,
  2109. A_VFNMSUB132PD,
  2110. A_VFNMSUB132PS,
  2111. A_VFNMSUB132SD,
  2112. A_VFNMSUB132SS,
  2113. A_VFNMSUB213PD,
  2114. A_VFNMSUB213PS,
  2115. A_VFNMSUB213SD,
  2116. A_VFNMSUB213SS,
  2117. A_VFNMSUB231PD,
  2118. A_VFNMSUB231PS,
  2119. A_VFNMSUB231SD,
  2120. A_VFNMSUB231SS],[S_NO]) and
  2121. { we mix single and double opperations here because we assume that the compiler
  2122. generates vmovapd only after double operations and vmovaps only after single operations }
  2123. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2124. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2125. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2126. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2127. begin
  2128. TransferUsedRegs(TmpUsedRegs);
  2129. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2130. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2131. begin
  2132. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2133. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2134. RemoveCurrentP(p)
  2135. else
  2136. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2137. RemoveInstruction(hp2);
  2138. end;
  2139. end
  2140. else if (hp1.typ = ait_instruction) and
  2141. (((taicpu(p).opcode=A_MOVAPS) and
  2142. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2143. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2144. ((taicpu(p).opcode=A_MOVAPD) and
  2145. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2146. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2147. ) and
  2148. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2149. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2150. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2151. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2152. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2153. { change
  2154. movapX reg,reg2
  2155. addsX/subsX/... reg3, reg2
  2156. movapX reg2,reg
  2157. to
  2158. addsX/subsX/... reg3,reg
  2159. }
  2160. begin
  2161. TransferUsedRegs(TmpUsedRegs);
  2162. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2163. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2164. begin
  2165. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2166. debug_op2str(taicpu(p).opcode)+' '+
  2167. debug_op2str(taicpu(hp1).opcode)+' '+
  2168. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2169. { we cannot eliminate the first move if
  2170. the operations uses the same register for source and dest }
  2171. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2172. { Remember that hp1 is not necessarily the immediate
  2173. next instruction }
  2174. RemoveCurrentP(p);
  2175. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2176. RemoveInstruction(hp2);
  2177. result:=true;
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_VMOVAPD) and
  2182. (taicpu(hp1).opcode=A_VCOMISD)) or
  2183. ((taicpu(p).opcode=A_VMOVAPS) and
  2184. ((taicpu(hp1).opcode=A_VCOMISS))
  2185. )
  2186. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2187. { change
  2188. movapX reg,reg1
  2189. vcomisX reg1,reg1
  2190. to
  2191. vcomisX reg,reg
  2192. }
  2193. begin
  2194. TransferUsedRegs(TmpUsedRegs);
  2195. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2196. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2197. begin
  2198. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2199. debug_op2str(taicpu(p).opcode)+' '+
  2200. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2201. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2202. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2203. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2204. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2205. RemoveCurrentP(p);
  2206. result:=true;
  2207. exit;
  2208. end;
  2209. end
  2210. end;
  2211. end;
  2212. end;
  2213. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2214. var
  2215. hp1 : tai;
  2216. begin
  2217. result:=false;
  2218. { replace
  2219. V<Op>X %mreg1,%mreg2,%mreg3
  2220. VMovX %mreg3,%mreg4
  2221. dealloc %mreg3
  2222. by
  2223. V<Op>X %mreg1,%mreg2,%mreg4
  2224. ?
  2225. }
  2226. if GetNextInstruction(p,hp1) and
  2227. { we mix single and double operations here because we assume that the compiler
  2228. generates vmovapd only after double operations and vmovaps only after single operations }
  2229. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2230. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2231. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2232. begin
  2233. TransferUsedRegs(TmpUsedRegs);
  2234. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2235. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2236. begin
  2237. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2238. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2239. RemoveInstruction(hp1);
  2240. result:=true;
  2241. end;
  2242. end;
  2243. end;
  2244. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2245. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2246. begin
  2247. Result := False;
  2248. { For safety reasons, only check for exact register matches }
  2249. { Check base register }
  2250. if (ref.base = AOldReg) then
  2251. begin
  2252. ref.base := ANewReg;
  2253. Result := True;
  2254. end;
  2255. { Check index register }
  2256. if (ref.index = AOldReg) then
  2257. begin
  2258. ref.index := ANewReg;
  2259. Result := True;
  2260. end;
  2261. end;
  2262. { Replaces all references to AOldReg in an operand to ANewReg }
  2263. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2264. var
  2265. OldSupReg, NewSupReg: TSuperRegister;
  2266. OldSubReg, NewSubReg: TSubRegister;
  2267. OldRegType: TRegisterType;
  2268. ThisOper: POper;
  2269. begin
  2270. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2271. Result := False;
  2272. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2273. InternalError(2020011801);
  2274. OldSupReg := getsupreg(AOldReg);
  2275. OldSubReg := getsubreg(AOldReg);
  2276. OldRegType := getregtype(AOldReg);
  2277. NewSupReg := getsupreg(ANewReg);
  2278. NewSubReg := getsubreg(ANewReg);
  2279. if OldRegType <> getregtype(ANewReg) then
  2280. InternalError(2020011802);
  2281. if OldSubReg <> NewSubReg then
  2282. InternalError(2020011803);
  2283. case ThisOper^.typ of
  2284. top_reg:
  2285. if (
  2286. (ThisOper^.reg = AOldReg) or
  2287. (
  2288. (OldRegType = R_INTREGISTER) and
  2289. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2290. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2291. (
  2292. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2293. {$ifndef x86_64}
  2294. and (
  2295. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2296. don't have an 8-bit representation }
  2297. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2298. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2299. )
  2300. {$endif x86_64}
  2301. )
  2302. )
  2303. ) then
  2304. begin
  2305. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2306. Result := True;
  2307. end;
  2308. top_ref:
  2309. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2310. Result := True;
  2311. else
  2312. ;
  2313. end;
  2314. end;
  2315. { Replaces all references to AOldReg in an instruction to ANewReg }
  2316. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2317. const
  2318. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2319. var
  2320. OperIdx: Integer;
  2321. begin
  2322. Result := False;
  2323. for OperIdx := 0 to p.ops - 1 do
  2324. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2325. begin
  2326. { The shift and rotate instructions can only use CL }
  2327. if not (
  2328. (OperIdx = 0) and
  2329. { This second condition just helps to avoid unnecessarily
  2330. calling MatchInstruction for 10 different opcodes }
  2331. (p.oper[0]^.reg = NR_CL) and
  2332. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2333. ) then
  2334. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2335. end
  2336. else if p.oper[OperIdx]^.typ = top_ref then
  2337. { It's okay to replace registers in references that get written to }
  2338. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2339. end;
  2340. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2341. begin
  2342. Result :=
  2343. (ref^.index = NR_NO) and
  2344. (
  2345. {$ifdef x86_64}
  2346. (
  2347. (ref^.base = NR_RIP) and
  2348. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2349. ) or
  2350. {$endif x86_64}
  2351. (ref^.refaddr = addr_full) or
  2352. (ref^.base = NR_STACK_POINTER_REG) or
  2353. (ref^.base = current_procinfo.framepointer)
  2354. );
  2355. end;
  2356. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2357. var
  2358. l: asizeint;
  2359. begin
  2360. Result := False;
  2361. { Should have been checked previously }
  2362. if p.opcode <> A_LEA then
  2363. InternalError(2020072501);
  2364. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2365. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2366. not(cs_opt_size in current_settings.optimizerswitches) then
  2367. exit;
  2368. with p.oper[0]^.ref^ do
  2369. begin
  2370. if (base <> p.oper[1]^.reg) or
  2371. (index <> NR_NO) or
  2372. assigned(symbol) then
  2373. exit;
  2374. l:=offset;
  2375. if (l=1) and UseIncDec then
  2376. begin
  2377. p.opcode:=A_INC;
  2378. p.loadreg(0,p.oper[1]^.reg);
  2379. p.ops:=1;
  2380. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2381. end
  2382. else if (l=-1) and UseIncDec then
  2383. begin
  2384. p.opcode:=A_DEC;
  2385. p.loadreg(0,p.oper[1]^.reg);
  2386. p.ops:=1;
  2387. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2388. end
  2389. else
  2390. begin
  2391. if (l<0) and (l<>-2147483648) then
  2392. begin
  2393. p.opcode:=A_SUB;
  2394. p.loadConst(0,-l);
  2395. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2396. end
  2397. else
  2398. begin
  2399. p.opcode:=A_ADD;
  2400. p.loadConst(0,l);
  2401. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2402. end;
  2403. end;
  2404. end;
  2405. Result := True;
  2406. end;
  2407. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2408. var
  2409. CurrentReg, ReplaceReg: TRegister;
  2410. begin
  2411. Result := False;
  2412. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2413. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2414. case hp.opcode of
  2415. A_FSTSW, A_FNSTSW,
  2416. A_IN, A_INS, A_OUT, A_OUTS,
  2417. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2418. { These routines have explicit operands, but they are restricted in
  2419. what they can be (e.g. IN and OUT can only read from AL, AX or
  2420. EAX. }
  2421. Exit;
  2422. A_IMUL:
  2423. begin
  2424. { The 1-operand version writes to implicit registers
  2425. The 2-operand version reads from the first operator, and reads
  2426. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2427. the 3-operand version reads from a register that it doesn't write to
  2428. }
  2429. case hp.ops of
  2430. 1:
  2431. if (
  2432. (
  2433. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2434. ) or
  2435. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2436. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2437. begin
  2438. Result := True;
  2439. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2440. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2441. end;
  2442. 2:
  2443. { Only modify the first parameter }
  2444. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2445. begin
  2446. Result := True;
  2447. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2448. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2449. end;
  2450. 3:
  2451. { Only modify the second parameter }
  2452. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2453. begin
  2454. Result := True;
  2455. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2456. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2457. end;
  2458. else
  2459. InternalError(2020012901);
  2460. end;
  2461. end;
  2462. else
  2463. if (hp.ops > 0) and
  2464. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2465. begin
  2466. Result := True;
  2467. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2468. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2469. end;
  2470. end;
  2471. end;
  2472. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2473. var
  2474. hp2: tai;
  2475. p_SourceReg, p_TargetReg: TRegister;
  2476. begin
  2477. Result := False;
  2478. { Backward optimisation. If we have:
  2479. func. %reg1,%reg2
  2480. mov %reg2,%reg3
  2481. (dealloc %reg2)
  2482. Change to:
  2483. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2484. Perform similar optimisations with 1, 3 and 4-operand instructions
  2485. that only have one output.
  2486. }
  2487. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2488. begin
  2489. p_SourceReg := taicpu(p).oper[0]^.reg;
  2490. p_TargetReg := taicpu(p).oper[1]^.reg;
  2491. TransferUsedRegs(TmpUsedRegs);
  2492. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2493. GetLastInstruction(p, hp2) and
  2494. (hp2.typ = ait_instruction) and
  2495. { Have to make sure it's an instruction that only reads from
  2496. the first operands and only writes (not reads or modifies) to
  2497. the last one; in essence, a pure function such as BSR, POPCNT
  2498. or ANDN }
  2499. (
  2500. (
  2501. (taicpu(hp2).ops = 1) and
  2502. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2503. ) or
  2504. (
  2505. (taicpu(hp2).ops = 2) and
  2506. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2507. ) or
  2508. (
  2509. (taicpu(hp2).ops = 3) and
  2510. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2511. ) or
  2512. (
  2513. (taicpu(hp2).ops = 4) and
  2514. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2515. )
  2516. ) and
  2517. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2518. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2519. begin
  2520. case taicpu(hp2).opcode of
  2521. A_FSTSW, A_FNSTSW,
  2522. A_IN, A_INS, A_OUT, A_OUTS,
  2523. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2524. { These routines have explicit operands, but they are restricted in
  2525. what they can be (e.g. IN and OUT can only read from AL, AX or
  2526. EAX. }
  2527. ;
  2528. else
  2529. begin
  2530. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2531. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2532. if not RegInInstruction(p_TargetReg, hp2) then
  2533. begin
  2534. { Since we're allocating from an earlier point, we
  2535. need to remove the register from the tracking }
  2536. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2537. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2538. end;
  2539. RemoveCurrentp(p, hp1);
  2540. { If the Func was another MOV instruction, we might get
  2541. "mov %reg,%reg" that doesn't get removed in Pass 2
  2542. otherwise, so deal with it here (also do something
  2543. similar with lea (%reg),%reg}
  2544. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2545. begin
  2546. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2547. if p = hp2 then
  2548. RemoveCurrentp(p)
  2549. else
  2550. RemoveInstruction(hp2);
  2551. end;
  2552. Result := True;
  2553. Exit;
  2554. end;
  2555. end;
  2556. end;
  2557. end;
  2558. end;
  2559. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2560. var
  2561. hp1, hp2, hp3: tai;
  2562. DoOptimisation, TempBool: Boolean;
  2563. {$ifdef x86_64}
  2564. NewConst: TCGInt;
  2565. {$endif x86_64}
  2566. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2567. begin
  2568. if taicpu(hp1).opcode = signed_movop then
  2569. begin
  2570. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2571. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2572. end
  2573. else
  2574. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2575. end;
  2576. function TryConstMerge(var p1, p2: tai): Boolean;
  2577. var
  2578. ThisRef: TReference;
  2579. begin
  2580. Result := False;
  2581. ThisRef := taicpu(p2).oper[1]^.ref^;
  2582. { Only permit writes to the stack, since we can guarantee alignment with that }
  2583. if (ThisRef.index = NR_NO) and
  2584. (
  2585. (ThisRef.base = NR_STACK_POINTER_REG) or
  2586. (ThisRef.base = current_procinfo.framepointer)
  2587. ) then
  2588. begin
  2589. case taicpu(p).opsize of
  2590. S_B:
  2591. begin
  2592. { Word writes must be on a 2-byte boundary }
  2593. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2594. begin
  2595. { Reduce offset of second reference to see if it is sequential with the first }
  2596. Dec(ThisRef.offset, 1);
  2597. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2598. begin
  2599. { Make sure the constants aren't represented as a
  2600. negative number, as these won't merge properly }
  2601. taicpu(p1).opsize := S_W;
  2602. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2603. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2604. RemoveInstruction(p2);
  2605. Result := True;
  2606. end;
  2607. end;
  2608. end;
  2609. S_W:
  2610. begin
  2611. { Longword writes must be on a 4-byte boundary }
  2612. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2613. begin
  2614. { Reduce offset of second reference to see if it is sequential with the first }
  2615. Dec(ThisRef.offset, 2);
  2616. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2617. begin
  2618. { Make sure the constants aren't represented as a
  2619. negative number, as these won't merge properly }
  2620. taicpu(p1).opsize := S_L;
  2621. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2622. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2623. RemoveInstruction(p2);
  2624. Result := True;
  2625. end;
  2626. end;
  2627. end;
  2628. {$ifdef x86_64}
  2629. S_L:
  2630. begin
  2631. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2632. see if the constants can be encoded this way. }
  2633. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2634. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2635. { Quadword writes must be on an 8-byte boundary }
  2636. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2637. begin
  2638. { Reduce offset of second reference to see if it is sequential with the first }
  2639. Dec(ThisRef.offset, 4);
  2640. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2641. begin
  2642. { Make sure the constants aren't represented as a
  2643. negative number, as these won't merge properly }
  2644. taicpu(p1).opsize := S_Q;
  2645. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2646. taicpu(p1).oper[0]^.val := NewConst;
  2647. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2648. RemoveInstruction(p2);
  2649. Result := True;
  2650. end;
  2651. end;
  2652. end;
  2653. {$endif x86_64}
  2654. else
  2655. ;
  2656. end;
  2657. end;
  2658. end;
  2659. var
  2660. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2661. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2662. NewSize: topsize; NewOffset: asizeint;
  2663. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2664. SourceRef, TargetRef: TReference;
  2665. MovAligned, MovUnaligned: TAsmOp;
  2666. ThisRef: TReference;
  2667. JumpTracking: TLinkedList;
  2668. begin
  2669. Result:=false;
  2670. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2671. { remove mov reg1,reg1? }
  2672. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2673. then
  2674. begin
  2675. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2676. { take care of the register (de)allocs following p }
  2677. RemoveCurrentP(p, hp1);
  2678. Result:=true;
  2679. exit;
  2680. end;
  2681. { All the next optimisations require a next instruction }
  2682. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2683. Exit;
  2684. { Prevent compiler warnings }
  2685. p_TargetReg := NR_NO;
  2686. if taicpu(p).oper[1]^.typ = top_reg then
  2687. begin
  2688. { Saves on a large number of dereferences }
  2689. p_TargetReg := taicpu(p).oper[1]^.reg;
  2690. { Look for:
  2691. mov %reg1,%reg2
  2692. ??? %reg2,r/m
  2693. Change to:
  2694. mov %reg1,%reg2
  2695. ??? %reg1,r/m
  2696. }
  2697. if taicpu(p).oper[0]^.typ = top_reg then
  2698. begin
  2699. if RegReadByInstruction(p_TargetReg, hp1) and
  2700. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2701. begin
  2702. { A change has occurred, just not in p }
  2703. Result := True;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2706. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2707. { Just in case something didn't get modified (e.g. an
  2708. implicit register) }
  2709. not RegReadByInstruction(p_TargetReg, hp1) then
  2710. begin
  2711. { We can remove the original MOV }
  2712. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2713. RemoveCurrentp(p, hp1);
  2714. { UsedRegs got updated by RemoveCurrentp }
  2715. Result := True;
  2716. Exit;
  2717. end;
  2718. { If we know a MOV instruction has become a null operation, we might as well
  2719. get rid of it now to save time. }
  2720. if (taicpu(hp1).opcode = A_MOV) and
  2721. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2722. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2723. { Just being a register is enough to confirm it's a null operation }
  2724. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2725. begin
  2726. Result := True;
  2727. { Speed-up to reduce a pipeline stall... if we had something like...
  2728. movl %eax,%edx
  2729. movw %dx,%ax
  2730. ... the second instruction would change to movw %ax,%ax, but
  2731. given that it is now %ax that's active rather than %eax,
  2732. penalties might occur due to a partial register write, so instead,
  2733. change it to a MOVZX instruction when optimising for speed.
  2734. }
  2735. if not (cs_opt_size in current_settings.optimizerswitches) and
  2736. IsMOVZXAcceptable and
  2737. (taicpu(hp1).opsize < taicpu(p).opsize)
  2738. {$ifdef x86_64}
  2739. { operations already implicitly set the upper 64 bits to zero }
  2740. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2741. {$endif x86_64}
  2742. then
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2745. case taicpu(p).opsize of
  2746. S_W:
  2747. if taicpu(hp1).opsize = S_B then
  2748. taicpu(hp1).opsize := S_BL
  2749. else
  2750. InternalError(2020012911);
  2751. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2752. case taicpu(hp1).opsize of
  2753. S_B:
  2754. taicpu(hp1).opsize := S_BL;
  2755. S_W:
  2756. taicpu(hp1).opsize := S_WL;
  2757. else
  2758. InternalError(2020012912);
  2759. end;
  2760. else
  2761. InternalError(2020012910);
  2762. end;
  2763. taicpu(hp1).opcode := A_MOVZX;
  2764. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2765. end
  2766. else
  2767. begin
  2768. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2769. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2770. RemoveInstruction(hp1);
  2771. { The instruction after what was hp1 is now the immediate next instruction,
  2772. so we can continue to make optimisations if it's present }
  2773. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2774. Exit;
  2775. hp1 := hp2;
  2776. end;
  2777. end;
  2778. end;
  2779. end;
  2780. end;
  2781. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2782. overwrites the original destination register. e.g.
  2783. movl ###,%reg2d
  2784. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2785. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2786. }
  2787. if (taicpu(p).oper[1]^.typ = top_reg) and
  2788. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2789. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2790. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2791. begin
  2792. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2793. begin
  2794. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2795. case taicpu(p).oper[0]^.typ of
  2796. top_const:
  2797. { We have something like:
  2798. movb $x, %regb
  2799. movzbl %regb,%regd
  2800. Change to:
  2801. movl $x, %regd
  2802. }
  2803. begin
  2804. case taicpu(hp1).opsize of
  2805. S_BW:
  2806. begin
  2807. convert_mov_value(A_MOVSX, $FF);
  2808. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2809. taicpu(p).opsize := S_W;
  2810. end;
  2811. S_BL:
  2812. begin
  2813. convert_mov_value(A_MOVSX, $FF);
  2814. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2815. taicpu(p).opsize := S_L;
  2816. end;
  2817. S_WL:
  2818. begin
  2819. convert_mov_value(A_MOVSX, $FFFF);
  2820. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2821. taicpu(p).opsize := S_L;
  2822. end;
  2823. {$ifdef x86_64}
  2824. S_BQ:
  2825. begin
  2826. convert_mov_value(A_MOVSX, $FF);
  2827. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2828. taicpu(p).opsize := S_Q;
  2829. end;
  2830. S_WQ:
  2831. begin
  2832. convert_mov_value(A_MOVSX, $FFFF);
  2833. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2834. taicpu(p).opsize := S_Q;
  2835. end;
  2836. S_LQ:
  2837. begin
  2838. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2839. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2840. taicpu(p).opsize := S_Q;
  2841. end;
  2842. {$endif x86_64}
  2843. else
  2844. { If hp1 was a MOV instruction, it should have been
  2845. optimised already }
  2846. InternalError(2020021001);
  2847. end;
  2848. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2849. RemoveInstruction(hp1);
  2850. Result := True;
  2851. Exit;
  2852. end;
  2853. top_ref:
  2854. begin
  2855. { We have something like:
  2856. movb mem, %regb
  2857. movzbl %regb,%regd
  2858. Change to:
  2859. movzbl mem, %regd
  2860. }
  2861. ThisRef := taicpu(p).oper[0]^.ref^;
  2862. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2863. begin
  2864. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2865. taicpu(hp1).loadref(0, ThisRef);
  2866. { Make sure any registers in the references are properly tracked }
  2867. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2868. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2869. if (ThisRef.index <> NR_NO) then
  2870. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2871. RemoveCurrentP(p, hp1);
  2872. Result := True;
  2873. Exit;
  2874. end;
  2875. end;
  2876. else
  2877. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2878. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2879. Exit;
  2880. end;
  2881. end
  2882. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2883. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2884. optimised }
  2885. else
  2886. begin
  2887. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2888. RemoveCurrentP(p, hp1);
  2889. Result := True;
  2890. Exit;
  2891. end;
  2892. end;
  2893. if (taicpu(hp1).opcode = A_AND) and
  2894. (taicpu(p).oper[1]^.typ = top_reg) and
  2895. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2896. begin
  2897. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2898. begin
  2899. case taicpu(p).opsize of
  2900. S_L:
  2901. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2902. begin
  2903. { Optimize out:
  2904. mov x, %reg
  2905. and ffffffffh, %reg
  2906. }
  2907. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2908. RemoveInstruction(hp1);
  2909. Result:=true;
  2910. exit;
  2911. end;
  2912. S_Q: { TODO: Confirm if this is even possible }
  2913. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2914. begin
  2915. { Optimize out:
  2916. mov x, %reg
  2917. and ffffffffffffffffh, %reg
  2918. }
  2919. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2920. RemoveInstruction(hp1);
  2921. Result:=true;
  2922. exit;
  2923. end;
  2924. else
  2925. ;
  2926. end;
  2927. if (
  2928. (taicpu(p).oper[0]^.typ=top_reg) or
  2929. (
  2930. (taicpu(p).oper[0]^.typ=top_ref) and
  2931. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2932. )
  2933. ) and
  2934. GetNextInstruction(hp1,hp2) and
  2935. MatchInstruction(hp2,A_TEST,[]) and
  2936. (
  2937. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2938. (
  2939. { If the register being tested is smaller than the one
  2940. that received a bitwise AND, permit it if the constant
  2941. fits into the smaller size }
  2942. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2943. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2944. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2945. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2946. (
  2947. (
  2948. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2949. (taicpu(hp1).oper[0]^.val <= $FF)
  2950. ) or
  2951. (
  2952. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2953. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2954. {$ifdef x86_64}
  2955. ) or
  2956. (
  2957. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2958. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2959. {$endif x86_64}
  2960. )
  2961. )
  2962. )
  2963. ) and
  2964. (
  2965. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2966. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2967. ) and
  2968. GetNextInstruction(hp2,hp3) and
  2969. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2970. (taicpu(hp3).condition in [C_E,C_NE]) then
  2971. begin
  2972. TransferUsedRegs(TmpUsedRegs);
  2973. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2974. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2975. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2978. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2979. taicpu(hp1).opcode:=A_TEST;
  2980. { Shrink the TEST instruction down to the smallest possible size }
  2981. case taicpu(hp1).oper[0]^.val of
  2982. 0..255:
  2983. if (taicpu(hp1).opsize <> S_B)
  2984. {$ifndef x86_64}
  2985. and (
  2986. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2987. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2988. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2989. )
  2990. {$endif x86_64}
  2991. then
  2992. begin
  2993. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2994. { Only print debug message if the TEST instruction
  2995. is a different size before and after }
  2996. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2997. taicpu(hp1).opsize := S_B;
  2998. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2999. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3000. end;
  3001. 256..65535:
  3002. if (taicpu(hp1).opsize <> S_W) then
  3003. begin
  3004. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3005. { Only print debug message if the TEST instruction
  3006. is a different size before and after }
  3007. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3008. taicpu(hp1).opsize := S_W;
  3009. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3010. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3011. end;
  3012. {$ifdef x86_64}
  3013. 65536..$7FFFFFFF:
  3014. if (taicpu(hp1).opsize <> S_L) then
  3015. begin
  3016. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3017. { Only print debug message if the TEST instruction
  3018. is a different size before and after }
  3019. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3020. taicpu(hp1).opsize := S_L;
  3021. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3022. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3023. end;
  3024. {$endif x86_64}
  3025. else
  3026. ;
  3027. end;
  3028. RemoveInstruction(hp2);
  3029. RemoveCurrentP(p, hp1);
  3030. Result:=true;
  3031. exit;
  3032. end;
  3033. end;
  3034. end
  3035. else if IsMOVZXAcceptable and
  3036. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3037. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3038. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3039. then
  3040. begin
  3041. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3042. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3043. case taicpu(p).opsize of
  3044. S_B:
  3045. if (taicpu(hp1).oper[0]^.val = $ff) then
  3046. begin
  3047. { Convert:
  3048. movb x, %regl movb x, %regl
  3049. andw ffh, %regw andl ffh, %regd
  3050. To:
  3051. movzbw x, %regd movzbl x, %regd
  3052. (Identical registers, just different sizes)
  3053. }
  3054. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3055. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3056. case taicpu(hp1).opsize of
  3057. S_W: NewSize := S_BW;
  3058. S_L: NewSize := S_BL;
  3059. {$ifdef x86_64}
  3060. S_Q: NewSize := S_BQ;
  3061. {$endif x86_64}
  3062. else
  3063. InternalError(2018011510);
  3064. end;
  3065. end
  3066. else
  3067. NewSize := S_NO;
  3068. S_W:
  3069. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3070. begin
  3071. { Convert:
  3072. movw x, %regw
  3073. andl ffffh, %regd
  3074. To:
  3075. movzwl x, %regd
  3076. (Identical registers, just different sizes)
  3077. }
  3078. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3079. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3080. case taicpu(hp1).opsize of
  3081. S_L: NewSize := S_WL;
  3082. {$ifdef x86_64}
  3083. S_Q: NewSize := S_WQ;
  3084. {$endif x86_64}
  3085. else
  3086. InternalError(2018011511);
  3087. end;
  3088. end
  3089. else
  3090. NewSize := S_NO;
  3091. else
  3092. NewSize := S_NO;
  3093. end;
  3094. if NewSize <> S_NO then
  3095. begin
  3096. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3097. { The actual optimization }
  3098. taicpu(p).opcode := A_MOVZX;
  3099. taicpu(p).changeopsize(NewSize);
  3100. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3101. { Safeguard if "and" is followed by a conditional command }
  3102. TransferUsedRegs(TmpUsedRegs);
  3103. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3104. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3105. begin
  3106. { At this point, the "and" command is effectively equivalent to
  3107. "test %reg,%reg". This will be handled separately by the
  3108. Peephole Optimizer. [Kit] }
  3109. DebugMsg(SPeepholeOptimization + PreMessage +
  3110. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3111. end
  3112. else
  3113. begin
  3114. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3115. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3116. RemoveInstruction(hp1);
  3117. end;
  3118. Result := True;
  3119. Exit;
  3120. end;
  3121. end;
  3122. end;
  3123. if (taicpu(hp1).opcode = A_OR) and
  3124. (taicpu(p).oper[1]^.typ = top_reg) and
  3125. MatchOperand(taicpu(p).oper[0]^, 0) and
  3126. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3127. begin
  3128. { mov 0, %reg
  3129. or ###,%reg
  3130. Change to (only if the flags are not used):
  3131. mov ###,%reg
  3132. }
  3133. TransferUsedRegs(TmpUsedRegs);
  3134. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3135. DoOptimisation := True;
  3136. { Even if the flags are used, we might be able to do the optimisation
  3137. if the conditions are predictable }
  3138. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3139. begin
  3140. { Only perform if ### = %reg (the same register) or equal to 0,
  3141. so %reg is guaranteed to still have a value of zero }
  3142. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3143. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3144. begin
  3145. hp2 := hp1;
  3146. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3147. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3148. GetNextInstruction(hp2, hp3) do
  3149. begin
  3150. { Don't continue modifying if the flags state is getting changed }
  3151. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3152. Break;
  3153. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3154. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3155. begin
  3156. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3157. begin
  3158. { Condition is always true }
  3159. case taicpu(hp3).opcode of
  3160. A_Jcc:
  3161. begin
  3162. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3163. { Check for jump shortcuts before we destroy the condition }
  3164. DoJumpOptimizations(hp3, TempBool);
  3165. MakeUnconditional(taicpu(hp3));
  3166. Result := True;
  3167. end;
  3168. A_CMOVcc:
  3169. begin
  3170. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3171. taicpu(hp3).opcode := A_MOV;
  3172. taicpu(hp3).condition := C_None;
  3173. Result := True;
  3174. end;
  3175. A_SETcc:
  3176. begin
  3177. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3178. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3179. taicpu(hp3).opcode := A_MOV;
  3180. taicpu(hp3).ops := 2;
  3181. taicpu(hp3).condition := C_None;
  3182. taicpu(hp3).opsize := S_B;
  3183. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3184. taicpu(hp3).loadconst(0, 1);
  3185. Result := True;
  3186. end;
  3187. else
  3188. InternalError(2021090701);
  3189. end;
  3190. end
  3191. 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
  3192. begin
  3193. { Condition is always false }
  3194. case taicpu(hp3).opcode of
  3195. A_Jcc:
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3198. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3199. RemoveInstruction(hp3);
  3200. Result := True;
  3201. { Since hp3 was deleted, hp2 must not be updated }
  3202. Continue;
  3203. end;
  3204. A_CMOVcc:
  3205. begin
  3206. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3207. RemoveInstruction(hp3);
  3208. Result := True;
  3209. { Since hp3 was deleted, hp2 must not be updated }
  3210. Continue;
  3211. end;
  3212. A_SETcc:
  3213. begin
  3214. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3215. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3216. taicpu(hp3).opcode := A_MOV;
  3217. taicpu(hp3).ops := 2;
  3218. taicpu(hp3).condition := C_None;
  3219. taicpu(hp3).opsize := S_B;
  3220. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3221. taicpu(hp3).loadconst(0, 0);
  3222. Result := True;
  3223. end;
  3224. else
  3225. InternalError(2021090702);
  3226. end;
  3227. end
  3228. else
  3229. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3230. DoOptimisation := False;
  3231. end;
  3232. hp2 := hp3;
  3233. end;
  3234. { Flags are still in use - don't optimise }
  3235. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3236. DoOptimisation := False;
  3237. end
  3238. else
  3239. DoOptimisation := False;
  3240. end;
  3241. if DoOptimisation then
  3242. begin
  3243. {$ifdef x86_64}
  3244. { OR only supports 32-bit sign-extended constants for 64-bit
  3245. instructions, so compensate for this if the constant is
  3246. encoded as a value greater than or equal to 2^31 }
  3247. if (taicpu(hp1).opsize = S_Q) and
  3248. (taicpu(hp1).oper[0]^.typ = top_const) and
  3249. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3250. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3251. {$endif x86_64}
  3252. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3253. taicpu(hp1).opcode := A_MOV;
  3254. RemoveCurrentP(p, hp1);
  3255. Result := True;
  3256. Exit;
  3257. end;
  3258. end;
  3259. { Next instruction is also a MOV ? }
  3260. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3261. begin
  3262. if MatchOpType(taicpu(p), top_const, top_ref) and
  3263. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3264. TryConstMerge(p, hp1) then
  3265. begin
  3266. Result := True;
  3267. { In case we have four byte writes in a row, check for 2 more
  3268. right now so we don't have to wait for another iteration of
  3269. pass 1
  3270. }
  3271. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3272. case taicpu(p).opsize of
  3273. S_W:
  3274. begin
  3275. if GetNextInstruction(p, hp1) and
  3276. MatchInstruction(hp1, A_MOV, [S_B]) and
  3277. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3278. GetNextInstruction(hp1, hp2) and
  3279. MatchInstruction(hp2, A_MOV, [S_B]) and
  3280. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3281. { Try to merge the two bytes }
  3282. TryConstMerge(hp1, hp2) then
  3283. { Now try to merge the two words (hp2 will get deleted) }
  3284. TryConstMerge(p, hp1);
  3285. end;
  3286. S_L:
  3287. begin
  3288. { Though this only really benefits x86_64 and not i386, it
  3289. gets a potential optimisation done faster and hence
  3290. reduces the number of times OptPass1MOV is entered }
  3291. if GetNextInstruction(p, hp1) and
  3292. MatchInstruction(hp1, A_MOV, [S_W]) and
  3293. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3294. GetNextInstruction(hp1, hp2) and
  3295. MatchInstruction(hp2, A_MOV, [S_W]) and
  3296. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3297. { Try to merge the two words }
  3298. TryConstMerge(hp1, hp2) then
  3299. { This will always fail on i386, so don't bother
  3300. calling it unless we're doing x86_64 }
  3301. {$ifdef x86_64}
  3302. { Now try to merge the two longwords (hp2 will get deleted) }
  3303. TryConstMerge(p, hp1)
  3304. {$endif x86_64}
  3305. ;
  3306. end;
  3307. else
  3308. ;
  3309. end;
  3310. Exit;
  3311. end;
  3312. if (taicpu(p).oper[1]^.typ = top_reg) and
  3313. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3314. begin
  3315. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3316. TransferUsedRegs(TmpUsedRegs);
  3317. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3318. { we have
  3319. mov x, %treg
  3320. mov %treg, y
  3321. }
  3322. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3323. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3324. { we've got
  3325. mov x, %treg
  3326. mov %treg, y
  3327. with %treg is not used after }
  3328. case taicpu(p).oper[0]^.typ Of
  3329. { top_reg is covered by DeepMOVOpt }
  3330. top_const:
  3331. begin
  3332. { change
  3333. mov const, %treg
  3334. mov %treg, y
  3335. to
  3336. mov const, y
  3337. }
  3338. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3339. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3340. begin
  3341. if taicpu(hp1).oper[1]^.typ=top_reg then
  3342. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3343. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3344. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3345. RemoveInstruction(hp1);
  3346. Result:=true;
  3347. Exit;
  3348. end;
  3349. end;
  3350. top_ref:
  3351. case taicpu(hp1).oper[1]^.typ of
  3352. top_reg:
  3353. begin
  3354. { change
  3355. mov mem, %treg
  3356. mov %treg, %reg
  3357. to
  3358. mov mem, %reg"
  3359. }
  3360. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3361. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3362. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3363. RemoveInstruction(hp1);
  3364. Result:=true;
  3365. Exit;
  3366. end;
  3367. top_ref:
  3368. begin
  3369. {$ifdef x86_64}
  3370. { Look for the following to simplify:
  3371. mov x(mem1), %reg
  3372. mov %reg, y(mem2)
  3373. mov x+8(mem1), %reg
  3374. mov %reg, y+8(mem2)
  3375. Change to:
  3376. movdqu x(mem1), %xmmreg
  3377. movdqu %xmmreg, y(mem2)
  3378. ...but only as long as the memory blocks don't overlap
  3379. }
  3380. SourceRef := taicpu(p).oper[0]^.ref^;
  3381. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3382. if (taicpu(p).opsize = S_Q) and
  3383. GetNextInstruction(hp1, hp2) and
  3384. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3385. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3386. begin
  3387. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3388. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3389. Inc(SourceRef.offset, 8);
  3390. if UseAVX then
  3391. begin
  3392. MovAligned := A_VMOVDQA;
  3393. MovUnaligned := A_VMOVDQU;
  3394. end
  3395. else
  3396. begin
  3397. MovAligned := A_MOVDQA;
  3398. MovUnaligned := A_MOVDQU;
  3399. end;
  3400. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3401. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3402. begin
  3403. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3404. Inc(TargetRef.offset, 8);
  3405. if GetNextInstruction(hp2, hp3) and
  3406. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3407. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3408. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3409. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3410. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3411. begin
  3412. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3413. if NewMMReg <> NR_NO then
  3414. begin
  3415. { Remember that the offsets are 8 ahead }
  3416. if ((SourceRef.offset mod 16) = 8) and
  3417. (
  3418. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3419. (SourceRef.base = current_procinfo.framepointer) or
  3420. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3421. ) then
  3422. taicpu(p).opcode := MovAligned
  3423. else
  3424. taicpu(p).opcode := MovUnaligned;
  3425. taicpu(p).opsize := S_XMM;
  3426. taicpu(p).oper[1]^.reg := NewMMReg;
  3427. if ((TargetRef.offset mod 16) = 8) and
  3428. (
  3429. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3430. (TargetRef.base = current_procinfo.framepointer) or
  3431. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3432. ) then
  3433. taicpu(hp1).opcode := MovAligned
  3434. else
  3435. taicpu(hp1).opcode := MovUnaligned;
  3436. taicpu(hp1).opsize := S_XMM;
  3437. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3438. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3439. RemoveInstruction(hp2);
  3440. RemoveInstruction(hp3);
  3441. Result := True;
  3442. Exit;
  3443. end;
  3444. end;
  3445. end
  3446. else
  3447. begin
  3448. { See if the next references are 8 less rather than 8 greater }
  3449. Dec(SourceRef.offset, 16); { -8 the other way }
  3450. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3451. begin
  3452. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3453. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3454. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3455. GetNextInstruction(hp2, hp3) and
  3456. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3457. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3458. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3459. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3460. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3461. begin
  3462. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3463. if NewMMReg <> NR_NO then
  3464. begin
  3465. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3466. if ((SourceRef.offset mod 16) = 0) and
  3467. (
  3468. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3469. (SourceRef.base = current_procinfo.framepointer) or
  3470. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3471. ) then
  3472. taicpu(hp2).opcode := MovAligned
  3473. else
  3474. taicpu(hp2).opcode := MovUnaligned;
  3475. taicpu(hp2).opsize := S_XMM;
  3476. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3477. if ((TargetRef.offset mod 16) = 0) and
  3478. (
  3479. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3480. (TargetRef.base = current_procinfo.framepointer) or
  3481. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3482. ) then
  3483. taicpu(hp3).opcode := MovAligned
  3484. else
  3485. taicpu(hp3).opcode := MovUnaligned;
  3486. taicpu(hp3).opsize := S_XMM;
  3487. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3488. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3489. RemoveInstruction(hp1);
  3490. RemoveCurrentP(p, hp2);
  3491. Result := True;
  3492. Exit;
  3493. end;
  3494. end;
  3495. end;
  3496. end;
  3497. end;
  3498. {$endif x86_64}
  3499. end;
  3500. else
  3501. { The write target should be a reg or a ref }
  3502. InternalError(2021091601);
  3503. end;
  3504. else
  3505. ;
  3506. end
  3507. else
  3508. { %treg is used afterwards, but all eventualities
  3509. other than the first MOV instruction being a constant
  3510. are covered by DeepMOVOpt, so only check for that }
  3511. if (taicpu(p).oper[0]^.typ = top_const) and
  3512. (
  3513. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3514. not (cs_opt_size in current_settings.optimizerswitches) or
  3515. (taicpu(hp1).opsize = S_B)
  3516. ) and
  3517. (
  3518. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3519. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3520. ) then
  3521. begin
  3522. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3523. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3524. end;
  3525. end;
  3526. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3527. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3528. { mov reg1, mem1 or mov mem1, reg1
  3529. mov mem2, reg2 mov reg2, mem2}
  3530. begin
  3531. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3532. { mov reg1, mem1 or mov mem1, reg1
  3533. mov mem2, reg1 mov reg2, mem1}
  3534. begin
  3535. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3536. { Removes the second statement from
  3537. mov reg1, mem1/reg2
  3538. mov mem1/reg2, reg1 }
  3539. begin
  3540. if taicpu(p).oper[0]^.typ=top_reg then
  3541. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3542. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3543. RemoveInstruction(hp1);
  3544. Result:=true;
  3545. exit;
  3546. end
  3547. else
  3548. begin
  3549. TransferUsedRegs(TmpUsedRegs);
  3550. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3551. if (taicpu(p).oper[1]^.typ = top_ref) and
  3552. { mov reg1, mem1
  3553. mov mem2, reg1 }
  3554. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3555. GetNextInstruction(hp1, hp2) and
  3556. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3557. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3558. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3559. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3560. { change to
  3561. mov reg1, mem1 mov reg1, mem1
  3562. mov mem2, reg1 cmp reg1, mem2
  3563. cmp mem1, reg1
  3564. }
  3565. begin
  3566. RemoveInstruction(hp2);
  3567. taicpu(hp1).opcode := A_CMP;
  3568. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3569. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3570. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3571. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3572. end;
  3573. end;
  3574. end
  3575. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3576. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3577. begin
  3578. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3579. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3580. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3581. end
  3582. else
  3583. begin
  3584. TransferUsedRegs(TmpUsedRegs);
  3585. if GetNextInstruction(hp1, hp2) and
  3586. MatchOpType(taicpu(p),top_ref,top_reg) and
  3587. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3588. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3589. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3590. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3591. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3592. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3593. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3594. { mov mem1, %reg1
  3595. mov %reg1, mem2
  3596. mov mem2, reg2
  3597. to:
  3598. mov mem1, reg2
  3599. mov reg2, mem2}
  3600. begin
  3601. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3602. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3603. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3604. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3605. RemoveInstruction(hp2);
  3606. Result := True;
  3607. end
  3608. {$ifdef i386}
  3609. { this is enabled for i386 only, as the rules to create the reg sets below
  3610. are too complicated for x86-64, so this makes this code too error prone
  3611. on x86-64
  3612. }
  3613. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3614. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3615. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3616. { mov mem1, reg1 mov mem1, reg1
  3617. mov reg1, mem2 mov reg1, mem2
  3618. mov mem2, reg2 mov mem2, reg1
  3619. to: to:
  3620. mov mem1, reg1 mov mem1, reg1
  3621. mov mem1, reg2 mov reg1, mem2
  3622. mov reg1, mem2
  3623. or (if mem1 depends on reg1
  3624. and/or if mem2 depends on reg2)
  3625. to:
  3626. mov mem1, reg1
  3627. mov reg1, mem2
  3628. mov reg1, reg2
  3629. }
  3630. begin
  3631. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3632. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3633. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3634. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3635. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3636. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3637. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3638. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3639. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3640. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3641. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3642. end
  3643. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3644. begin
  3645. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3646. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3647. end
  3648. else
  3649. begin
  3650. RemoveInstruction(hp2);
  3651. end
  3652. {$endif i386}
  3653. ;
  3654. end;
  3655. end
  3656. { movl [mem1],reg1
  3657. movl [mem1],reg2
  3658. to
  3659. movl [mem1],reg1
  3660. movl reg1,reg2
  3661. }
  3662. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3663. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3664. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3665. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3666. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3667. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3668. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3670. begin
  3671. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3672. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3673. end;
  3674. { movl const1,[mem1]
  3675. movl [mem1],reg1
  3676. to
  3677. movl const1,reg1
  3678. movl reg1,[mem1]
  3679. }
  3680. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3681. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3682. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3683. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3684. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3685. begin
  3686. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3687. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3688. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3689. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3690. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3691. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3692. Result:=true;
  3693. exit;
  3694. end;
  3695. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3696. { Change:
  3697. movl %reg1,%reg2
  3698. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3699. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3700. To:
  3701. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3702. movl x(%reg1),%reg1
  3703. movl %reg1,%regX
  3704. }
  3705. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3706. begin
  3707. p_SourceReg := taicpu(p).oper[0]^.reg;
  3708. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3709. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3710. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3711. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3712. GetNextInstruction(hp1, hp2) and
  3713. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3714. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3715. begin
  3716. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3717. if RegInRef(p_TargetReg, SourceRef) and
  3718. { If %reg1 also appears in the second reference, then it will
  3719. not refer to the same memory block as the first reference }
  3720. not RegInRef(p_SourceReg, SourceRef) then
  3721. begin
  3722. { Check to see if the references match if %reg2 is changed to %reg1 }
  3723. if SourceRef.base = p_TargetReg then
  3724. SourceRef.base := p_SourceReg;
  3725. if SourceRef.index = p_TargetReg then
  3726. SourceRef.index := p_SourceReg;
  3727. { RefsEqual also checks to ensure both references are non-volatile }
  3728. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3729. begin
  3730. taicpu(hp2).loadreg(0, p_SourceReg);
  3731. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3732. Result := True;
  3733. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3734. begin
  3735. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3736. RemoveCurrentP(p, hp1);
  3737. Exit;
  3738. end
  3739. else
  3740. begin
  3741. { Check to see if %reg2 is no longer in use }
  3742. TransferUsedRegs(TmpUsedRegs);
  3743. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3744. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3745. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3746. begin
  3747. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3748. RemoveCurrentP(p, hp1);
  3749. Exit;
  3750. end;
  3751. end;
  3752. { If we reach this point, p and hp1 weren't actually modified,
  3753. so we can do a bit more work on this pass }
  3754. end;
  3755. end;
  3756. end;
  3757. end;
  3758. end;
  3759. {$ifdef x86_64}
  3760. { Change:
  3761. movl %reg1l,%reg2l
  3762. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3763. To:
  3764. movl %reg1l,%reg2l
  3765. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3766. If %reg1 = %reg3, convert to:
  3767. movl %reg1l,%reg2l
  3768. andl %reg1l,%reg1l
  3769. }
  3770. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3771. MatchOpType(taicpu(p), top_reg, top_reg) and
  3772. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3773. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3774. begin
  3775. TransferUsedRegs(TmpUsedRegs);
  3776. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3777. taicpu(hp1).opsize := S_L;
  3778. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3779. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3780. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3781. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3782. begin
  3783. { %reg1 = %reg3 }
  3784. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3785. taicpu(hp1).opcode := A_AND;
  3786. end
  3787. else
  3788. begin
  3789. { %reg1 <> %reg3 }
  3790. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3791. end;
  3792. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3793. begin
  3794. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3795. RemoveCurrentP(p, hp1);
  3796. Result := True;
  3797. Exit;
  3798. end
  3799. else
  3800. begin
  3801. { Initial instruction wasn't actually changed }
  3802. Include(OptsToCheck, aoc_ForceNewIteration);
  3803. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3804. appears below since %reg1 has technically changed }
  3805. if taicpu(hp1).opcode = A_AND then
  3806. Exit;
  3807. end;
  3808. end;
  3809. {$endif x86_64}
  3810. { search further than the next instruction for a mov (as long as it's not a jump) }
  3811. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3812. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3813. (taicpu(p).oper[1]^.typ = top_reg) and
  3814. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3815. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3816. begin
  3817. { we work with hp2 here, so hp1 can be still used later on when
  3818. checking for GetNextInstruction_p }
  3819. hp3 := hp1;
  3820. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3821. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3822. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3823. TransferUsedRegs(TmpUsedRegs);
  3824. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3825. if NotFirstIteration then
  3826. JumpTracking := TLinkedList.Create
  3827. else
  3828. JumpTracking := nil;
  3829. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3830. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3831. (hp2.typ=ait_instruction) do
  3832. begin
  3833. case taicpu(hp2).opcode of
  3834. A_POP:
  3835. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3836. begin
  3837. if not CrossJump and
  3838. not RegUsedBetween(p_TargetReg, p, hp2) then
  3839. begin
  3840. { We can remove the original MOV since the register
  3841. wasn't used between it and its popping from the stack }
  3842. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3843. RemoveCurrentp(p, hp1);
  3844. Result := True;
  3845. JumpTracking.Free;
  3846. Exit;
  3847. end;
  3848. { Can't go any further }
  3849. Break;
  3850. end;
  3851. A_MOV:
  3852. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3853. ((taicpu(p).oper[0]^.typ=top_const) or
  3854. ((taicpu(p).oper[0]^.typ=top_reg) and
  3855. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3856. )
  3857. ) then
  3858. begin
  3859. { we have
  3860. mov x, %treg
  3861. mov %treg, y
  3862. }
  3863. { We don't need to call UpdateUsedRegs for every instruction between
  3864. p and hp2 because the register we're concerned about will not
  3865. become deallocated (otherwise GetNextInstructionUsingReg would
  3866. have stopped at an earlier instruction). [Kit] }
  3867. TempRegUsed :=
  3868. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3869. RegReadByInstruction(p_TargetReg, hp3) or
  3870. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3871. case taicpu(p).oper[0]^.typ Of
  3872. top_reg:
  3873. begin
  3874. { change
  3875. mov %reg, %treg
  3876. mov %treg, y
  3877. to
  3878. mov %reg, y
  3879. }
  3880. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3881. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3882. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3883. begin
  3884. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3885. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3886. if TempRegUsed then
  3887. begin
  3888. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3889. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3890. { Set the start of the next GetNextInstructionUsingRegCond search
  3891. to start at the entry right before hp2 (which is about to be removed) }
  3892. hp3 := tai(hp2.Previous);
  3893. RemoveInstruction(hp2);
  3894. Include(OptsToCheck, aoc_ForceNewIteration);
  3895. { See if there's more we can optimise }
  3896. Continue;
  3897. end
  3898. else
  3899. begin
  3900. RemoveInstruction(hp2);
  3901. { We can remove the original MOV too }
  3902. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3903. RemoveCurrentP(p, hp1);
  3904. Result:=true;
  3905. JumpTracking.Free;
  3906. Exit;
  3907. end;
  3908. end
  3909. else
  3910. begin
  3911. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3912. taicpu(hp2).loadReg(0, p_SourceReg);
  3913. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3914. { Check to see if the register also appears in the reference }
  3915. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3916. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3917. { Don't remove the first instruction if the temporary register is in use }
  3918. if not TempRegUsed and
  3919. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3920. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3921. begin
  3922. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3923. RemoveCurrentP(p, hp1);
  3924. Result:=true;
  3925. JumpTracking.Free;
  3926. Exit;
  3927. end;
  3928. { No need to set Result to True here. If there's another instruction later
  3929. on that can be optimised, it will be detected when the main Pass 1 loop
  3930. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3931. end;
  3932. end;
  3933. top_const:
  3934. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3935. begin
  3936. { change
  3937. mov const, %treg
  3938. mov %treg, y
  3939. to
  3940. mov const, y
  3941. }
  3942. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3943. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3944. begin
  3945. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3946. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3947. if TempRegUsed then
  3948. begin
  3949. { Don't remove the first instruction if the temporary register is in use }
  3950. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3951. { No need to set Result to True. If there's another instruction later on
  3952. that can be optimised, it will be detected when the main Pass 1 loop
  3953. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3954. end
  3955. else
  3956. begin
  3957. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3958. RemoveCurrentP(p, hp1);
  3959. Result:=true;
  3960. Exit;
  3961. end;
  3962. end;
  3963. end;
  3964. else
  3965. Internalerror(2019103001);
  3966. end;
  3967. end
  3968. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3969. begin
  3970. if not CrossJump and
  3971. not RegUsedBetween(p_TargetReg, p, hp2) and
  3972. not RegReadByInstruction(p_TargetReg, hp2) then
  3973. begin
  3974. { Register is not used before it is overwritten }
  3975. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3976. RemoveCurrentp(p, hp1);
  3977. Result := True;
  3978. Exit;
  3979. end;
  3980. if (taicpu(p).oper[0]^.typ = top_const) and
  3981. (taicpu(hp2).oper[0]^.typ = top_const) then
  3982. begin
  3983. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3984. begin
  3985. { Same value - register hasn't changed }
  3986. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3987. RemoveInstruction(hp2);
  3988. Include(OptsToCheck, aoc_ForceNewIteration);
  3989. { See if there's more we can optimise }
  3990. Continue;
  3991. end;
  3992. end;
  3993. {$ifdef x86_64}
  3994. end
  3995. { Change:
  3996. movl %reg1l,%reg2l
  3997. ...
  3998. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3999. To:
  4000. movl %reg1l,%reg2l
  4001. ...
  4002. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4003. If %reg1 = %reg3, convert to:
  4004. movl %reg1l,%reg2l
  4005. ...
  4006. andl %reg1l,%reg1l
  4007. }
  4008. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4009. (taicpu(p).oper[0]^.typ = top_reg) and
  4010. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4011. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4012. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4013. begin
  4014. TempRegUsed :=
  4015. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4016. RegReadByInstruction(p_TargetReg, hp3) or
  4017. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4018. taicpu(hp2).opsize := S_L;
  4019. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4020. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4021. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4022. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4023. begin
  4024. { %reg1 = %reg3 }
  4025. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4026. taicpu(hp2).opcode := A_AND;
  4027. end
  4028. else
  4029. begin
  4030. { %reg1 <> %reg3 }
  4031. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4032. end;
  4033. if not TempRegUsed then
  4034. begin
  4035. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4036. RemoveCurrentP(p, hp1);
  4037. Result := True;
  4038. Exit;
  4039. end
  4040. else
  4041. begin
  4042. { Initial instruction wasn't actually changed }
  4043. Include(OptsToCheck, aoc_ForceNewIteration);
  4044. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4045. appears below since %reg1 has technically changed }
  4046. if taicpu(hp2).opcode = A_AND then
  4047. Break;
  4048. end;
  4049. {$endif x86_64}
  4050. end;
  4051. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4052. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4053. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4054. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4055. begin
  4056. {
  4057. Change from:
  4058. mov ###, %reg
  4059. ...
  4060. movs/z %reg,%reg (Same register, just different sizes)
  4061. To:
  4062. movs/z ###, %reg (Longer version)
  4063. ...
  4064. (remove)
  4065. }
  4066. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4067. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4068. { Keep the first instruction as mov if ### is a constant }
  4069. if taicpu(p).oper[0]^.typ = top_const then
  4070. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4071. else
  4072. begin
  4073. taicpu(p).opcode := taicpu(hp2).opcode;
  4074. taicpu(p).opsize := taicpu(hp2).opsize;
  4075. end;
  4076. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4077. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4078. RemoveInstruction(hp2);
  4079. Result := True;
  4080. JumpTracking.Free;
  4081. Exit;
  4082. end;
  4083. else
  4084. { Move down to the if-block below };
  4085. end;
  4086. { Also catches MOV/S/Z instructions that aren't modified }
  4087. if taicpu(p).oper[0]^.typ = top_reg then
  4088. begin
  4089. p_SourceReg := taicpu(p).oper[0]^.reg;
  4090. if
  4091. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4092. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4093. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4094. begin
  4095. Result := True;
  4096. { Just in case something didn't get modified (e.g. an
  4097. implicit register). Also, if it does read from this
  4098. register, then there's no longer an advantage to
  4099. changing the register on subsequent instructions.}
  4100. if not RegReadByInstruction(p_TargetReg, hp2) then
  4101. begin
  4102. { If a conditional jump was crossed, do not delete
  4103. the original MOV no matter what }
  4104. if not CrossJump and
  4105. { RegEndOfLife returns True if the register is
  4106. deallocated before the next instruction or has
  4107. been loaded with a new value }
  4108. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4109. begin
  4110. { We can remove the original MOV }
  4111. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4112. RemoveCurrentp(p, hp1);
  4113. JumpTracking.Free;
  4114. Result := True;
  4115. Exit;
  4116. end;
  4117. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4118. begin
  4119. { See if there's more we can optimise }
  4120. hp3 := hp2;
  4121. Continue;
  4122. end;
  4123. end;
  4124. end;
  4125. end;
  4126. { Break out of the while loop under normal circumstances }
  4127. Break;
  4128. end;
  4129. JumpTracking.Free;
  4130. end;
  4131. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4132. (taicpu(p).oper[1]^.typ = top_reg) and
  4133. (taicpu(p).opsize = S_L) and
  4134. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4135. (hp2.typ = ait_instruction) and
  4136. (taicpu(hp2).opcode = A_AND) and
  4137. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4138. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4139. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4140. ) then
  4141. begin
  4142. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4143. begin
  4144. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4145. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4146. begin
  4147. { Optimize out:
  4148. mov x, %reg
  4149. and ffffffffh, %reg
  4150. }
  4151. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4152. RemoveInstruction(hp2);
  4153. Result:=true;
  4154. exit;
  4155. end;
  4156. end;
  4157. end;
  4158. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4159. x >= RetOffset) as it doesn't do anything (it writes either to a
  4160. parameter or to the temporary storage room for the function
  4161. result)
  4162. }
  4163. if IsExitCode(hp1) and
  4164. (taicpu(p).oper[1]^.typ = top_ref) and
  4165. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4166. (
  4167. (
  4168. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4169. not (
  4170. assigned(current_procinfo.procdef.funcretsym) and
  4171. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4172. )
  4173. ) or
  4174. { Also discard writes to the stack that are below the base pointer,
  4175. as this is temporary storage rather than a function result on the
  4176. stack, say. }
  4177. (
  4178. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4179. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4180. )
  4181. ) then
  4182. begin
  4183. RemoveCurrentp(p, hp1);
  4184. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4185. RemoveLastDeallocForFuncRes(p);
  4186. Result:=true;
  4187. exit;
  4188. end;
  4189. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4190. begin
  4191. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4192. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4193. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4194. begin
  4195. { change
  4196. mov reg1, mem1
  4197. test/cmp x, mem1
  4198. to
  4199. mov reg1, mem1
  4200. test/cmp x, reg1
  4201. }
  4202. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4203. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4204. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4205. Result := True;
  4206. Exit;
  4207. end;
  4208. if DoMovCmpMemOpt(p, hp1, True) then
  4209. begin
  4210. Result := True;
  4211. Exit;
  4212. end;
  4213. end;
  4214. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4215. { If the flags register is in use, don't change the instruction to an
  4216. ADD otherwise this will scramble the flags. [Kit] }
  4217. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4218. begin
  4219. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4220. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4221. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4222. ) or
  4223. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4224. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4225. )
  4226. ) then
  4227. { mov reg1,ref
  4228. lea reg2,[reg1,reg2]
  4229. to
  4230. add reg2,ref}
  4231. begin
  4232. TransferUsedRegs(TmpUsedRegs);
  4233. { reg1 may not be used afterwards }
  4234. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4235. begin
  4236. Taicpu(hp1).opcode:=A_ADD;
  4237. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4238. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4239. RemoveCurrentp(p, hp1);
  4240. result:=true;
  4241. exit;
  4242. end;
  4243. end;
  4244. { If the LEA instruction can be converted into an arithmetic instruction,
  4245. it may be possible to then fold it in the next optimisation, otherwise
  4246. there's nothing more that can be optimised here. }
  4247. if not ConvertLEA(taicpu(hp1)) then
  4248. Exit;
  4249. end;
  4250. if (taicpu(p).oper[1]^.typ = top_reg) and
  4251. (hp1.typ = ait_instruction) and
  4252. GetNextInstruction(hp1, hp2) and
  4253. MatchInstruction(hp2,A_MOV,[]) and
  4254. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4255. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4256. (
  4257. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4258. {$ifdef x86_64}
  4259. or
  4260. (
  4261. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4262. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4263. )
  4264. {$endif x86_64}
  4265. ) then
  4266. begin
  4267. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4268. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4269. { change movsX/movzX reg/ref, reg2
  4270. add/sub/or/... reg3/$const, reg2
  4271. mov reg2 reg/ref
  4272. dealloc reg2
  4273. to
  4274. add/sub/or/... reg3/$const, reg/ref }
  4275. begin
  4276. TransferUsedRegs(TmpUsedRegs);
  4277. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4278. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4279. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4280. begin
  4281. { by example:
  4282. movswl %si,%eax movswl %si,%eax p
  4283. decl %eax addl %edx,%eax hp1
  4284. movw %ax,%si movw %ax,%si hp2
  4285. ->
  4286. movswl %si,%eax movswl %si,%eax p
  4287. decw %eax addw %edx,%eax hp1
  4288. movw %ax,%si movw %ax,%si hp2
  4289. }
  4290. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4291. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4292. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4293. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4294. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4295. {
  4296. ->
  4297. movswl %si,%eax movswl %si,%eax p
  4298. decw %si addw %dx,%si hp1
  4299. movw %ax,%si movw %ax,%si hp2
  4300. }
  4301. case taicpu(hp1).ops of
  4302. 1:
  4303. begin
  4304. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4305. if taicpu(hp1).oper[0]^.typ=top_reg then
  4306. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4307. end;
  4308. 2:
  4309. begin
  4310. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4311. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4312. (taicpu(hp1).opcode<>A_SHL) and
  4313. (taicpu(hp1).opcode<>A_SHR) and
  4314. (taicpu(hp1).opcode<>A_SAR) then
  4315. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4316. end;
  4317. else
  4318. internalerror(2008042701);
  4319. end;
  4320. {
  4321. ->
  4322. decw %si addw %dx,%si p
  4323. }
  4324. RemoveInstruction(hp2);
  4325. RemoveCurrentP(p, hp1);
  4326. Result:=True;
  4327. Exit;
  4328. end;
  4329. end;
  4330. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4331. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4332. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4333. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4334. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4335. )
  4336. {$ifdef i386}
  4337. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4338. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4339. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4340. {$endif i386}
  4341. then
  4342. { change movsX/movzX reg/ref, reg2
  4343. add/sub/or/... regX/$const, reg2
  4344. mov reg2, reg3
  4345. dealloc reg2
  4346. to
  4347. movsX/movzX reg/ref, reg3
  4348. add/sub/or/... reg3/$const, reg3
  4349. }
  4350. begin
  4351. TransferUsedRegs(TmpUsedRegs);
  4352. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4353. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4354. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4355. begin
  4356. { by example:
  4357. movswl %si,%eax movswl %si,%eax p
  4358. decl %eax addl %edx,%eax hp1
  4359. movw %ax,%si movw %ax,%si hp2
  4360. ->
  4361. movswl %si,%eax movswl %si,%eax p
  4362. decw %eax addw %edx,%eax hp1
  4363. movw %ax,%si movw %ax,%si hp2
  4364. }
  4365. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4366. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4367. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4368. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4369. { limit size of constants as well to avoid assembler errors, but
  4370. check opsize to avoid overflow when left shifting the 1 }
  4371. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4372. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4373. {$ifdef x86_64}
  4374. { Be careful of, for example:
  4375. movl %reg1,%reg2
  4376. addl %reg3,%reg2
  4377. movq %reg2,%reg4
  4378. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4379. }
  4380. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4381. begin
  4382. taicpu(hp2).changeopsize(S_L);
  4383. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4384. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4385. end;
  4386. {$endif x86_64}
  4387. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4388. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4389. if taicpu(p).oper[0]^.typ=top_reg then
  4390. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4391. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4392. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4393. {
  4394. ->
  4395. movswl %si,%eax movswl %si,%eax p
  4396. decw %si addw %dx,%si hp1
  4397. movw %ax,%si movw %ax,%si hp2
  4398. }
  4399. case taicpu(hp1).ops of
  4400. 1:
  4401. begin
  4402. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4403. if taicpu(hp1).oper[0]^.typ=top_reg then
  4404. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4405. end;
  4406. 2:
  4407. begin
  4408. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4409. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4410. (taicpu(hp1).opcode<>A_SHL) and
  4411. (taicpu(hp1).opcode<>A_SHR) and
  4412. (taicpu(hp1).opcode<>A_SAR) then
  4413. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4414. end;
  4415. else
  4416. internalerror(2018111801);
  4417. end;
  4418. {
  4419. ->
  4420. decw %si addw %dx,%si p
  4421. }
  4422. RemoveInstruction(hp2);
  4423. end;
  4424. end;
  4425. end;
  4426. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4427. GetNextInstruction(hp1, hp2) and
  4428. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4429. MatchOperand(Taicpu(p).oper[0]^,0) and
  4430. (Taicpu(p).oper[1]^.typ = top_reg) and
  4431. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4432. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4433. { mov reg1,0
  4434. bts reg1,operand1 --> mov reg1,operand2
  4435. or reg1,operand2 bts reg1,operand1}
  4436. begin
  4437. Taicpu(hp2).opcode:=A_MOV;
  4438. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4439. asml.remove(hp1);
  4440. insertllitem(hp2,hp2.next,hp1);
  4441. RemoveCurrentp(p, hp1);
  4442. Result:=true;
  4443. exit;
  4444. end;
  4445. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4446. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4447. GetNextInstruction(hp1, hp2) and
  4448. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4449. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4450. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4451. { change
  4452. mov reg1,reg2
  4453. sub reg3,reg2
  4454. cmp reg3,reg1
  4455. into
  4456. mov reg1,reg2
  4457. sub reg3,reg2
  4458. }
  4459. begin
  4460. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4461. RemoveInstruction(hp2);
  4462. Result:=true;
  4463. exit;
  4464. end;
  4465. {
  4466. mov ref,reg0
  4467. <op> reg0,reg1
  4468. dealloc reg0
  4469. to
  4470. <op> ref,reg1
  4471. }
  4472. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4473. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4474. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4475. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4476. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4477. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4478. begin
  4479. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4480. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4486. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4487. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4488. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4489. begin
  4490. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4491. {$ifdef x86_64}
  4492. { Convert:
  4493. movq x(ref),%reg64
  4494. shrq y,%reg64
  4495. To:
  4496. movl x+4(ref),%reg32
  4497. shrl y-32,%reg32 (Remove if y = 32)
  4498. }
  4499. if (taicpu(p).opsize = S_Q) and
  4500. (taicpu(hp1).opcode = A_SHR) and
  4501. (taicpu(hp1).oper[0]^.val >= 32) then
  4502. begin
  4503. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4504. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4505. { Convert to 32-bit }
  4506. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4507. taicpu(p).opsize := S_L;
  4508. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4509. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4510. if (taicpu(hp1).oper[0]^.val = 32) then
  4511. begin
  4512. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4513. RemoveInstruction(hp1);
  4514. end
  4515. else
  4516. begin
  4517. { This will potentially open up more arithmetic operations since
  4518. the peephole optimizer now has a big hint that only the lower
  4519. 32 bits are currently in use (and opcodes are smaller in size) }
  4520. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4521. taicpu(hp1).opsize := S_L;
  4522. Dec(taicpu(hp1).oper[0]^.val, 32);
  4523. DebugMsg(SPeepholeOptimization + PreMessage +
  4524. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4525. end;
  4526. Result := True;
  4527. Exit;
  4528. end;
  4529. {$endif x86_64}
  4530. { Convert:
  4531. movl x(ref),%reg
  4532. shrl $24,%reg
  4533. To:
  4534. movzbl x+3(ref),%reg
  4535. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4536. Also accept sar instead of shr, but convert to movsx instead of movzx
  4537. }
  4538. if taicpu(hp1).opcode = A_SHR then
  4539. MovUnaligned := A_MOVZX
  4540. else
  4541. MovUnaligned := A_MOVSX;
  4542. NewSize := S_NO;
  4543. NewOffset := 0;
  4544. case taicpu(p).opsize of
  4545. S_B:
  4546. { No valid combinations };
  4547. S_W:
  4548. if (taicpu(hp1).oper[0]^.val = 8) then
  4549. begin
  4550. NewSize := S_BW;
  4551. NewOffset := 1;
  4552. end;
  4553. S_L:
  4554. case taicpu(hp1).oper[0]^.val of
  4555. 16:
  4556. begin
  4557. NewSize := S_WL;
  4558. NewOffset := 2;
  4559. end;
  4560. 24:
  4561. begin
  4562. NewSize := S_BL;
  4563. NewOffset := 3;
  4564. end;
  4565. else
  4566. ;
  4567. end;
  4568. {$ifdef x86_64}
  4569. S_Q:
  4570. case taicpu(hp1).oper[0]^.val of
  4571. 32:
  4572. begin
  4573. if taicpu(hp1).opcode = A_SAR then
  4574. begin
  4575. { 32-bit to 64-bit is a distinct instruction }
  4576. MovUnaligned := A_MOVSXD;
  4577. NewSize := S_LQ;
  4578. NewOffset := 4;
  4579. end
  4580. else
  4581. { Should have been handled by MovShr2Mov above }
  4582. InternalError(2022081811);
  4583. end;
  4584. 48:
  4585. begin
  4586. NewSize := S_WQ;
  4587. NewOffset := 6;
  4588. end;
  4589. 56:
  4590. begin
  4591. NewSize := S_BQ;
  4592. NewOffset := 7;
  4593. end;
  4594. else
  4595. ;
  4596. end;
  4597. {$endif x86_64}
  4598. else
  4599. InternalError(2022081810);
  4600. end;
  4601. if (NewSize <> S_NO) and
  4602. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4603. begin
  4604. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4605. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4606. debug_op2str(MovUnaligned);
  4607. {$ifdef x86_64}
  4608. if MovUnaligned <> A_MOVSXD then
  4609. { Don't add size suffix for MOVSXD }
  4610. {$endif x86_64}
  4611. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4612. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4613. taicpu(p).opcode := MovUnaligned;
  4614. taicpu(p).opsize := NewSize;
  4615. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4616. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4617. RemoveInstruction(hp1);
  4618. Result := True;
  4619. Exit;
  4620. end;
  4621. end;
  4622. { Backward optimisation shared with OptPass2MOV }
  4623. if FuncMov2Func(p, hp1) then
  4624. begin
  4625. Result := True;
  4626. Exit;
  4627. end;
  4628. end;
  4629. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4630. var
  4631. hp1 : tai;
  4632. begin
  4633. Result:=false;
  4634. if taicpu(p).ops <> 2 then
  4635. exit;
  4636. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4637. GetNextInstruction(p,hp1) then
  4638. begin
  4639. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4640. (taicpu(hp1).ops = 2) then
  4641. begin
  4642. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4643. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4644. { movXX reg1, mem1 or movXX mem1, reg1
  4645. movXX mem2, reg2 movXX reg2, mem2}
  4646. begin
  4647. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4648. { movXX reg1, mem1 or movXX mem1, reg1
  4649. movXX mem2, reg1 movXX reg2, mem1}
  4650. begin
  4651. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4652. begin
  4653. { Removes the second statement from
  4654. movXX reg1, mem1/reg2
  4655. movXX mem1/reg2, reg1
  4656. }
  4657. if taicpu(p).oper[0]^.typ=top_reg then
  4658. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4659. { Removes the second statement from
  4660. movXX mem1/reg1, reg2
  4661. movXX reg2, mem1/reg1
  4662. }
  4663. if (taicpu(p).oper[1]^.typ=top_reg) and
  4664. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4665. begin
  4666. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4667. RemoveInstruction(hp1);
  4668. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4669. Result:=true;
  4670. exit;
  4671. end
  4672. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4673. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4674. begin
  4675. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4676. RemoveInstruction(hp1);
  4677. Result:=true;
  4678. exit;
  4679. end;
  4680. end
  4681. end;
  4682. end;
  4683. end;
  4684. end;
  4685. end;
  4686. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4687. var
  4688. hp1 : tai;
  4689. begin
  4690. result:=false;
  4691. { replace
  4692. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4693. MovX %mreg2,%mreg1
  4694. dealloc %mreg2
  4695. by
  4696. <Op>X %mreg2,%mreg1
  4697. ?
  4698. }
  4699. if GetNextInstruction(p,hp1) and
  4700. { we mix single and double opperations here because we assume that the compiler
  4701. generates vmovapd only after double operations and vmovaps only after single operations }
  4702. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4703. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4704. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4705. (taicpu(p).oper[0]^.typ=top_reg) then
  4706. begin
  4707. TransferUsedRegs(TmpUsedRegs);
  4708. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4709. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4710. begin
  4711. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4712. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4713. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4714. RemoveInstruction(hp1);
  4715. result:=true;
  4716. end;
  4717. end;
  4718. end;
  4719. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4720. var
  4721. hp1, p_label, p_dist, hp1_dist: tai;
  4722. JumpLabel, JumpLabel_dist: TAsmLabel;
  4723. FirstValue, SecondValue: TCGInt;
  4724. TempBool: Boolean;
  4725. begin
  4726. Result := False;
  4727. if (taicpu(p).oper[0]^.typ = top_const) and
  4728. (taicpu(p).oper[0]^.val <> -1) then
  4729. begin
  4730. { Convert unsigned maximum constants to -1 to aid optimisation }
  4731. case taicpu(p).opsize of
  4732. S_B:
  4733. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4734. begin
  4735. taicpu(p).oper[0]^.val := -1;
  4736. Result := True;
  4737. Exit;
  4738. end;
  4739. S_W:
  4740. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4741. begin
  4742. taicpu(p).oper[0]^.val := -1;
  4743. Result := True;
  4744. Exit;
  4745. end;
  4746. S_L:
  4747. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4748. begin
  4749. taicpu(p).oper[0]^.val := -1;
  4750. Result := True;
  4751. Exit;
  4752. end;
  4753. {$ifdef x86_64}
  4754. S_Q:
  4755. { Storing anything greater than $7FFFFFFF is not possible so do
  4756. nothing };
  4757. {$endif x86_64}
  4758. else
  4759. InternalError(2021121001);
  4760. end;
  4761. end;
  4762. if GetNextInstruction(p, hp1) and
  4763. TrySwapMovCmp(p, hp1) then
  4764. begin
  4765. Result := True;
  4766. Exit;
  4767. end;
  4768. if MatchInstruction(hp1, A_Jcc, []) then
  4769. begin
  4770. TempBool := True;
  4771. if DoJumpOptimizations(hp1, TempBool) or
  4772. not TempBool then
  4773. begin
  4774. Result := True;
  4775. if Assigned(hp1) then
  4776. begin
  4777. if (hp1.typ in [ait_align]) then
  4778. SkipAligns(hp1, hp1);
  4779. { CollapseZeroDistJump will be set to the label after the
  4780. jump if it optimises, whether or not it's live or dead }
  4781. if (hp1.typ in [ait_label]) and
  4782. not (tai_label(hp1).labsym.is_used) then
  4783. GetNextInstruction(hp1, hp1);
  4784. end;
  4785. TransferUsedRegs(TmpUsedRegs);
  4786. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4787. if not Assigned(hp1) or
  4788. (
  4789. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4790. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4791. ) then
  4792. begin
  4793. { No more conditional jumps; conditional statement is no longer required }
  4794. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4795. RemoveCurrentP(p);
  4796. end;
  4797. Exit;
  4798. end;
  4799. end;
  4800. { Search for:
  4801. test $x,(reg/ref)
  4802. jne @lbl1
  4803. test $y,(reg/ref) (same register or reference)
  4804. jne @lbl1
  4805. Change to:
  4806. test $(x or y),(reg/ref)
  4807. jne @lbl1
  4808. (Note, this doesn't work with je instead of jne)
  4809. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4810. Also search for:
  4811. test $x,(reg/ref)
  4812. je @lbl1
  4813. test $y,(reg/ref)
  4814. je/jne @lbl2
  4815. If (x or y) = x, then the second jump is deterministic
  4816. }
  4817. if (
  4818. (
  4819. (taicpu(p).oper[0]^.typ = top_const) or
  4820. (
  4821. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4822. (taicpu(p).oper[0]^.typ = top_reg) and
  4823. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4824. )
  4825. ) and
  4826. MatchInstruction(hp1, A_JCC, [])
  4827. ) then
  4828. begin
  4829. if (taicpu(p).oper[0]^.typ = top_reg) and
  4830. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4831. FirstValue := -1
  4832. else
  4833. FirstValue := taicpu(p).oper[0]^.val;
  4834. { If we have several test/jne's in a row, it might be the case that
  4835. the second label doesn't go to the same location, but the one
  4836. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4837. so accommodate for this with a while loop.
  4838. }
  4839. hp1_dist := hp1;
  4840. if GetNextInstruction(hp1, p_dist) and
  4841. (p_dist.typ = ait_instruction) and
  4842. (
  4843. (
  4844. (taicpu(p_dist).opcode = A_TEST) and
  4845. (
  4846. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4847. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4848. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4849. )
  4850. ) or
  4851. (
  4852. { cmp 0,%reg = test %reg,%reg }
  4853. (taicpu(p_dist).opcode = A_CMP) and
  4854. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4855. )
  4856. ) and
  4857. { Make sure the destination operands are actually the same }
  4858. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4859. GetNextInstruction(p_dist, hp1_dist) and
  4860. MatchInstruction(hp1_dist, A_JCC, []) then
  4861. begin
  4862. if
  4863. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4864. (
  4865. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4866. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4867. ) then
  4868. SecondValue := -1
  4869. else
  4870. SecondValue := taicpu(p_dist).oper[0]^.val;
  4871. { If both of the TEST constants are identical, delete the second
  4872. TEST that is unnecessary. }
  4873. if (FirstValue = SecondValue) then
  4874. begin
  4875. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4876. RemoveInstruction(p_dist);
  4877. { Don't let the flags register become deallocated and reallocated between the jumps }
  4878. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4879. Result := True;
  4880. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4881. begin
  4882. { Since the second jump's condition is a subset of the first, we
  4883. know it will never branch because the first jump dominates it.
  4884. Get it out of the way now rather than wait for the jump
  4885. optimisations for a speed boost. }
  4886. if IsJumpToLabel(taicpu(hp1_dist)) then
  4887. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4888. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4889. RemoveInstruction(hp1_dist);
  4890. end
  4891. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4892. begin
  4893. { If the inverse of the first condition is a subset of the second,
  4894. the second one will definitely branch if the first one doesn't }
  4895. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4896. MakeUnconditional(taicpu(hp1_dist));
  4897. RemoveDeadCodeAfterJump(hp1_dist);
  4898. end;
  4899. Exit;
  4900. end;
  4901. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4902. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4903. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4904. then the second jump will never branch, so it can also be
  4905. removed regardless of where it goes }
  4906. (
  4907. (FirstValue = -1) or
  4908. (SecondValue = -1) or
  4909. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4910. ) then
  4911. begin
  4912. { Same jump location... can be a register since nothing's changed }
  4913. { If any of the entries are equivalent to test %reg,%reg, then the
  4914. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4915. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4916. if IsJumpToLabel(taicpu(hp1_dist)) then
  4917. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4918. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4919. RemoveInstruction(hp1_dist);
  4920. { Only remove the second test if no jumps or other conditional instructions follow }
  4921. TransferUsedRegs(TmpUsedRegs);
  4922. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4923. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4924. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4925. RemoveInstruction(p_dist);
  4926. Result := True;
  4927. Exit;
  4928. end;
  4929. end;
  4930. end;
  4931. { Search for:
  4932. test %reg,%reg
  4933. j(c1) @lbl1
  4934. ...
  4935. @lbl:
  4936. test %reg,%reg (same register)
  4937. j(c2) @lbl2
  4938. If c2 is a subset of c1, change to:
  4939. test %reg,%reg
  4940. j(c1) @lbl2
  4941. (@lbl1 may become a dead label as a result)
  4942. }
  4943. if (taicpu(p).oper[1]^.typ = top_reg) and
  4944. (taicpu(p).oper[0]^.typ = top_reg) and
  4945. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4946. MatchInstruction(hp1, A_JCC, []) and
  4947. IsJumpToLabel(taicpu(hp1)) then
  4948. begin
  4949. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4950. p_label := nil;
  4951. if Assigned(JumpLabel) then
  4952. p_label := getlabelwithsym(JumpLabel);
  4953. if Assigned(p_label) and
  4954. GetNextInstruction(p_label, p_dist) and
  4955. MatchInstruction(p_dist, A_TEST, []) and
  4956. { It's fine if the second test uses smaller sub-registers }
  4957. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4958. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4959. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4960. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4961. GetNextInstruction(p_dist, hp1_dist) and
  4962. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4963. begin
  4964. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4965. if JumpLabel = JumpLabel_dist then
  4966. { This is an infinite loop }
  4967. Exit;
  4968. { Best optimisation when the first condition is a subset (or equal) of the second }
  4969. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4970. begin
  4971. { Any registers used here will already be allocated }
  4972. if Assigned(JumpLabel) then
  4973. JumpLabel.DecRefs;
  4974. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4975. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4976. Result := True;
  4977. Exit;
  4978. end;
  4979. end;
  4980. end;
  4981. end;
  4982. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4983. var
  4984. hp1, hp2: tai;
  4985. ActiveReg: TRegister;
  4986. OldOffset: asizeint;
  4987. ThisConst: TCGInt;
  4988. function RegDeallocated: Boolean;
  4989. begin
  4990. TransferUsedRegs(TmpUsedRegs);
  4991. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4992. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4993. end;
  4994. begin
  4995. result:=false;
  4996. hp1 := nil;
  4997. { replace
  4998. addX const,%reg1
  4999. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5000. dealloc %reg1
  5001. by
  5002. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5003. }
  5004. if MatchOpType(taicpu(p),top_const,top_reg) then
  5005. begin
  5006. ActiveReg := taicpu(p).oper[1]^.reg;
  5007. { Ensures the entire register was updated }
  5008. if (taicpu(p).opsize >= S_L) and
  5009. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5010. MatchInstruction(hp1,A_LEA,[]) and
  5011. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5012. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5013. (
  5014. { Cover the case where the register in the reference is also the destination register }
  5015. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5016. (
  5017. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5018. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5019. RegDeallocated
  5020. )
  5021. ) then
  5022. begin
  5023. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5024. {$push}
  5025. {$R-}{$Q-}
  5026. { Explicitly disable overflow checking for these offset calculation
  5027. as those do not matter for the final result }
  5028. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5029. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5030. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5031. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5032. {$pop}
  5033. {$ifdef x86_64}
  5034. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5035. begin
  5036. { Overflow; abort }
  5037. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5038. end
  5039. else
  5040. {$endif x86_64}
  5041. begin
  5042. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5043. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5044. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5045. RemoveCurrentP(p, hp1)
  5046. else
  5047. RemoveCurrentP(p);
  5048. result:=true;
  5049. Exit;
  5050. end;
  5051. end;
  5052. if (
  5053. { Save calling GetNextInstructionUsingReg again }
  5054. Assigned(hp1) or
  5055. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5056. ) and
  5057. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5058. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5059. begin
  5060. if taicpu(hp1).oper[0]^.typ = top_const then
  5061. begin
  5062. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5063. if taicpu(hp1).opcode = A_ADD then
  5064. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5065. else
  5066. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5067. Result := True;
  5068. { Handle any overflows }
  5069. case taicpu(p).opsize of
  5070. S_B:
  5071. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5072. S_W:
  5073. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5074. S_L:
  5075. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5076. {$ifdef x86_64}
  5077. S_Q:
  5078. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5079. { Overflow; abort }
  5080. Result := False
  5081. else
  5082. taicpu(p).oper[0]^.val := ThisConst;
  5083. {$endif x86_64}
  5084. else
  5085. InternalError(2021102610);
  5086. end;
  5087. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5088. if Result then
  5089. begin
  5090. if (taicpu(p).oper[0]^.val < 0) and
  5091. (
  5092. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5093. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5094. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5095. ) then
  5096. begin
  5097. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5098. taicpu(p).opcode := A_SUB;
  5099. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5100. end
  5101. else
  5102. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5103. RemoveInstruction(hp1);
  5104. end;
  5105. end
  5106. else
  5107. begin
  5108. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5109. TransferUsedRegs(TmpUsedRegs);
  5110. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5111. hp2 := p;
  5112. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5113. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5114. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5115. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5116. begin
  5117. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5118. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5119. Asml.Remove(p);
  5120. Asml.InsertAfter(p, hp1);
  5121. p := hp1;
  5122. Result := True;
  5123. Exit;
  5124. end;
  5125. end;
  5126. end;
  5127. if DoArithCombineOpt(p) then
  5128. Result:=true;
  5129. end;
  5130. end;
  5131. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5132. var
  5133. hp1: tai;
  5134. ref: Integer;
  5135. saveref: treference;
  5136. Multiple: TCGInt;
  5137. Adjacent: Boolean;
  5138. begin
  5139. Result:=false;
  5140. { play save and throw an error if LEA uses a seg register prefix,
  5141. this is most likely an error somewhere else }
  5142. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5143. internalerror(2022022001);
  5144. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5145. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5146. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5147. (
  5148. { do not mess with leas accessing the stack pointer
  5149. unless it's a null operation }
  5150. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5151. (
  5152. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5153. (taicpu(p).oper[0]^.ref^.offset = 0)
  5154. )
  5155. ) and
  5156. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5157. begin
  5158. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5159. begin
  5160. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5161. begin
  5162. taicpu(p).opcode := A_MOV;
  5163. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5164. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5165. end
  5166. else
  5167. begin
  5168. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5169. RemoveCurrentP(p);
  5170. end;
  5171. Result:=true;
  5172. exit;
  5173. end
  5174. else if (
  5175. { continue to use lea to adjust the stack pointer,
  5176. it is the recommended way, but only if not optimizing for size }
  5177. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5178. (cs_opt_size in current_settings.optimizerswitches)
  5179. ) and
  5180. { If the flags register is in use, don't change the instruction
  5181. to an ADD otherwise this will scramble the flags. [Kit] }
  5182. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5183. ConvertLEA(taicpu(p)) then
  5184. begin
  5185. Result:=true;
  5186. exit;
  5187. end;
  5188. end;
  5189. { Don't optimise if the stack or frame pointer is the destination register }
  5190. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5191. Exit;
  5192. if GetNextInstruction(p,hp1) and
  5193. (hp1.typ=ait_instruction) then
  5194. begin
  5195. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5196. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5197. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5198. begin
  5199. TransferUsedRegs(TmpUsedRegs);
  5200. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5201. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5202. begin
  5203. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5204. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5205. RemoveInstruction(hp1);
  5206. result:=true;
  5207. exit;
  5208. end;
  5209. end;
  5210. { changes
  5211. lea <ref1>, reg1
  5212. <op> ...,<ref. with reg1>,...
  5213. to
  5214. <op> ...,<ref1>,... }
  5215. { find a reference which uses reg1 }
  5216. 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
  5217. ref:=0
  5218. 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
  5219. ref:=1
  5220. else
  5221. ref:=-1;
  5222. if (ref<>-1) and
  5223. { reg1 must be either the base or the index }
  5224. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5225. begin
  5226. { reg1 can be removed from the reference }
  5227. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5228. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5229. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5230. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5231. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5232. else
  5233. Internalerror(2019111201);
  5234. { check if the can insert all data of the lea into the second instruction }
  5235. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5236. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5237. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5238. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5239. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5240. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5241. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5242. {$ifdef x86_64}
  5243. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5244. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5245. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5246. )
  5247. {$endif x86_64}
  5248. then
  5249. begin
  5250. { reg1 might not used by the second instruction after it is remove from the reference }
  5251. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5252. begin
  5253. TransferUsedRegs(TmpUsedRegs);
  5254. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5255. { reg1 is not updated so it might not be used afterwards }
  5256. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5257. begin
  5258. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5259. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5260. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5261. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5262. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5263. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5264. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5265. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5266. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5267. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5268. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5269. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5270. RemoveCurrentP(p, hp1);
  5271. result:=true;
  5272. exit;
  5273. end
  5274. end;
  5275. end;
  5276. { recover }
  5277. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5278. end;
  5279. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5280. if Adjacent or
  5281. { Check further ahead (up to 2 instructions ahead for -O2) }
  5282. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5283. begin
  5284. { Check common LEA/LEA conditions }
  5285. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5286. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5287. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5288. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5289. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5290. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5291. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5292. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5293. (
  5294. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5295. calling it (since it calls GetNextInstruction) }
  5296. Adjacent or
  5297. (
  5298. (
  5299. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5300. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5301. ) and (
  5302. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5303. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5304. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5305. )
  5306. )
  5307. ) then
  5308. begin
  5309. { changes
  5310. lea (regX,scale), reg1
  5311. lea offset(reg1,reg1), reg1
  5312. to
  5313. lea offset(regX,scale*2), reg1
  5314. and
  5315. lea (regX,scale1), reg1
  5316. lea offset(reg1,scale2), reg1
  5317. to
  5318. lea offset(regX,scale1*scale2), reg1
  5319. ... so long as the final scale does not exceed 8
  5320. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5321. }
  5322. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5323. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5324. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5325. (
  5326. (
  5327. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5328. ) or (
  5329. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5330. (
  5331. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5332. (
  5333. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5334. Adjacent or
  5335. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5336. )
  5337. )
  5338. )
  5339. ) and (
  5340. (
  5341. { lea (reg1,scale2), reg1 variant }
  5342. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5343. (
  5344. (
  5345. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5346. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5347. ) or (
  5348. { lea (regX,regX), reg1 variant }
  5349. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5350. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5351. )
  5352. )
  5353. ) or (
  5354. { lea (reg1,reg1), reg1 variant }
  5355. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5356. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5357. )
  5358. ) then
  5359. begin
  5360. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5361. { Make everything homogeneous to make calculations easier }
  5362. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5363. begin
  5364. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5365. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5366. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5367. else
  5368. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5369. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5370. end;
  5371. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5372. begin
  5373. { Just to prevent miscalculations }
  5374. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5375. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5376. else
  5377. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5378. end
  5379. else
  5380. begin
  5381. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5382. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5383. end;
  5384. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5385. RemoveCurrentP(p);
  5386. result:=true;
  5387. exit;
  5388. end
  5389. { changes
  5390. lea offset1(regX), reg1
  5391. lea offset2(reg1), reg1
  5392. to
  5393. lea offset1+offset2(regX), reg1 }
  5394. else if
  5395. (
  5396. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5397. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5398. ) or (
  5399. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5400. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5401. (
  5402. (
  5403. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5404. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5405. ) or (
  5406. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5407. (
  5408. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5409. (
  5410. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5411. (
  5412. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5413. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5414. )
  5415. )
  5416. )
  5417. )
  5418. )
  5419. ) then
  5420. begin
  5421. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5422. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5423. begin
  5424. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5425. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5426. { if the register is used as index and base, we have to increase for base as well
  5427. and adapt base }
  5428. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5429. begin
  5430. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5431. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5432. end;
  5433. end
  5434. else
  5435. begin
  5436. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5437. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5438. end;
  5439. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5440. begin
  5441. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5442. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5443. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5444. end;
  5445. RemoveCurrentP(p);
  5446. result:=true;
  5447. exit;
  5448. end;
  5449. end;
  5450. { Change:
  5451. leal/q $x(%reg1),%reg2
  5452. ...
  5453. shll/q $y,%reg2
  5454. To:
  5455. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5456. }
  5457. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5458. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5459. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5460. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5461. (taicpu(hp1).oper[0]^.val <= 3) then
  5462. begin
  5463. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5464. TransferUsedRegs(TmpUsedRegs);
  5465. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5466. if
  5467. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5468. (this works even if scalefactor is zero) }
  5469. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5470. { Ensure offset doesn't go out of bounds }
  5471. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5472. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5473. (
  5474. (
  5475. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5476. (
  5477. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5478. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5479. (
  5480. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5481. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5482. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5483. )
  5484. )
  5485. ) or (
  5486. (
  5487. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5488. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5489. ) and
  5490. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5491. )
  5492. ) then
  5493. begin
  5494. repeat
  5495. with taicpu(p).oper[0]^.ref^ do
  5496. begin
  5497. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5498. if index = base then
  5499. begin
  5500. if Multiple > 4 then
  5501. { Optimisation will no longer work because resultant
  5502. scale factor will exceed 8 }
  5503. Break;
  5504. base := NR_NO;
  5505. scalefactor := 2;
  5506. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5507. end
  5508. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5509. begin
  5510. { Scale factor only works on the index register }
  5511. index := base;
  5512. base := NR_NO;
  5513. end;
  5514. { For safety }
  5515. if scalefactor <= 1 then
  5516. begin
  5517. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5518. scalefactor := Multiple;
  5519. end
  5520. else
  5521. begin
  5522. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5523. scalefactor := scalefactor * Multiple;
  5524. end;
  5525. offset := offset * Multiple;
  5526. end;
  5527. RemoveInstruction(hp1);
  5528. Result := True;
  5529. Exit;
  5530. { This repeat..until loop exists for the benefit of Break }
  5531. until True;
  5532. end;
  5533. end;
  5534. end;
  5535. end;
  5536. end;
  5537. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5538. var
  5539. hp1 : tai;
  5540. SubInstr: Boolean;
  5541. ThisConst: TCGInt;
  5542. const
  5543. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5544. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5545. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5546. begin
  5547. Result := False;
  5548. if taicpu(p).oper[0]^.typ <> top_const then
  5549. { Should have been confirmed before calling }
  5550. InternalError(2021102601);
  5551. SubInstr := (taicpu(p).opcode = A_SUB);
  5552. if GetLastInstruction(p, hp1) and
  5553. (hp1.typ = ait_instruction) and
  5554. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5555. begin
  5556. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5557. { Bad size }
  5558. InternalError(2022042001);
  5559. case taicpu(hp1).opcode Of
  5560. A_INC:
  5561. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5562. begin
  5563. if SubInstr then
  5564. ThisConst := taicpu(p).oper[0]^.val - 1
  5565. else
  5566. ThisConst := taicpu(p).oper[0]^.val + 1;
  5567. end
  5568. else
  5569. Exit;
  5570. A_DEC:
  5571. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5572. begin
  5573. if SubInstr then
  5574. ThisConst := taicpu(p).oper[0]^.val + 1
  5575. else
  5576. ThisConst := taicpu(p).oper[0]^.val - 1;
  5577. end
  5578. else
  5579. Exit;
  5580. A_SUB:
  5581. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5582. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5583. begin
  5584. if SubInstr then
  5585. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5586. else
  5587. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5588. end
  5589. else
  5590. Exit;
  5591. A_ADD:
  5592. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5593. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5594. begin
  5595. if SubInstr then
  5596. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5597. else
  5598. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5599. end
  5600. else
  5601. Exit;
  5602. else
  5603. Exit;
  5604. end;
  5605. { Check that the values are in range }
  5606. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5607. { Overflow; abort }
  5608. Exit;
  5609. if (ThisConst = 0) then
  5610. begin
  5611. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5612. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5613. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5614. RemoveInstruction(hp1);
  5615. hp1 := tai(p.next);
  5616. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5617. if not GetLastInstruction(hp1, p) then
  5618. p := hp1;
  5619. end
  5620. else
  5621. begin
  5622. if taicpu(hp1).opercnt=1 then
  5623. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5624. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5625. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5626. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5627. else
  5628. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5629. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5630. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5631. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5632. RemoveInstruction(hp1);
  5633. taicpu(p).loadconst(0, ThisConst);
  5634. end;
  5635. Result := True;
  5636. end;
  5637. end;
  5638. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5639. begin
  5640. Result := False;
  5641. if UpdateTmpUsedRegs then
  5642. TransferUsedRegs(TmpUsedRegs);
  5643. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5644. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5645. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5646. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5647. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5648. (
  5649. (
  5650. (taicpu(hp1).opcode = A_TEST)
  5651. ) or (
  5652. (taicpu(hp1).opcode = A_CMP) and
  5653. { A sanity check more than anything }
  5654. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5655. )
  5656. ) then
  5657. begin
  5658. { change
  5659. mov mem, %reg
  5660. cmp/test x, %reg / test %reg,%reg
  5661. (reg deallocated)
  5662. to
  5663. cmp/test x, mem / cmp 0, mem
  5664. }
  5665. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5666. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5667. begin
  5668. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5669. if (taicpu(hp1).opcode = A_TEST) and
  5670. (
  5671. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5672. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5673. ) then
  5674. begin
  5675. taicpu(hp1).opcode := A_CMP;
  5676. taicpu(hp1).loadconst(0, 0);
  5677. end;
  5678. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5679. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5680. RemoveCurrentP(p, hp1);
  5681. Result := True;
  5682. Exit;
  5683. end;
  5684. end;
  5685. end;
  5686. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5687. var
  5688. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5689. ThisReg, SecondReg: TRegister;
  5690. JumpLoc: TAsmLabel;
  5691. NewSize: TOpSize;
  5692. begin
  5693. Result := False;
  5694. {
  5695. Convert:
  5696. j<c> .L1
  5697. .L2:
  5698. mov 1,reg
  5699. jmp .L3 (or ret, although it might not be a RET yet)
  5700. .L1:
  5701. mov 0,reg
  5702. jmp .L3 (or ret)
  5703. ( As long as .L3 <> .L1 or .L2)
  5704. To:
  5705. mov 0,reg
  5706. set<not(c)> reg
  5707. jmp .L3 (or ret)
  5708. .L2:
  5709. mov 1,reg
  5710. jmp .L3 (or ret)
  5711. .L1:
  5712. mov 0,reg
  5713. jmp .L3 (or ret)
  5714. }
  5715. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5716. Exit;
  5717. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5718. if GetNextInstruction(hp_label, hp2) and
  5719. MatchInstruction(hp2,A_MOV,[]) and
  5720. (taicpu(hp2).oper[0]^.typ = top_const) and
  5721. (
  5722. (
  5723. (taicpu(hp2).oper[1]^.typ = top_reg)
  5724. {$ifdef i386}
  5725. { Under i386, ESI, EDI, EBP and ESP
  5726. don't have an 8-bit representation }
  5727. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5728. {$endif i386}
  5729. ) or (
  5730. {$ifdef i386}
  5731. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5732. {$endif i386}
  5733. (taicpu(hp2).opsize = S_B)
  5734. )
  5735. ) and
  5736. GetNextInstruction(hp2, hp3) and
  5737. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5738. (
  5739. (taicpu(hp3).opcode=A_RET) or
  5740. (
  5741. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5742. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5743. )
  5744. ) and
  5745. GetNextInstruction(hp3, hp4) and
  5746. SkipAligns(hp4, hp4) and
  5747. (hp4.typ=ait_label) and
  5748. (tai_label(hp4).labsym=JumpLoc) and
  5749. (
  5750. not (cs_opt_size in current_settings.optimizerswitches) or
  5751. { If the initial jump is the label's only reference, then it will
  5752. become a dead label if the other conditions are met and hence
  5753. remove at least 2 instructions, including a jump }
  5754. (JumpLoc.getrefs = 1)
  5755. ) and
  5756. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5757. that will be optimised out }
  5758. GetNextInstruction(hp4, hp5) and
  5759. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5760. (taicpu(hp5).oper[0]^.typ = top_const) and
  5761. (
  5762. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5763. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5764. ) and
  5765. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5766. GetNextInstruction(hp5,hp6) and
  5767. (
  5768. (hp6.typ<>ait_label) or
  5769. SkipLabels(hp6, hp6)
  5770. ) and
  5771. (hp6.typ=ait_instruction) then
  5772. begin
  5773. { First, let's look at the two jumps that are hp3 and hp6 }
  5774. if not
  5775. (
  5776. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5777. (
  5778. (taicpu(hp6).opcode=A_RET) or
  5779. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5780. )
  5781. ) then
  5782. { If condition is False, then the JMP/RET instructions matched conventionally }
  5783. begin
  5784. { See if one of the jumps can be instantly converted into a RET }
  5785. if (taicpu(hp3).opcode=A_JMP) then
  5786. begin
  5787. { Reuse hp5 }
  5788. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5789. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5790. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5791. Exit;
  5792. if MatchInstruction(hp5, A_RET, []) then
  5793. begin
  5794. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5795. ConvertJumpToRET(hp3, hp5);
  5796. Result := True;
  5797. end
  5798. else
  5799. Exit;
  5800. end;
  5801. if (taicpu(hp6).opcode=A_JMP) then
  5802. begin
  5803. { Reuse hp5 }
  5804. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5805. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5806. Exit;
  5807. if MatchInstruction(hp5, A_RET, []) then
  5808. begin
  5809. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5810. ConvertJumpToRET(hp6, hp5);
  5811. Result := True;
  5812. end
  5813. else
  5814. Exit;
  5815. end;
  5816. if not
  5817. (
  5818. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5819. (
  5820. (taicpu(hp6).opcode=A_RET) or
  5821. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5822. )
  5823. ) then
  5824. { Still doesn't match }
  5825. Exit;
  5826. end;
  5827. if (taicpu(hp2).oper[0]^.val = 1) then
  5828. begin
  5829. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5830. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5831. end
  5832. else
  5833. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5834. if taicpu(hp2).opsize=S_B then
  5835. begin
  5836. if taicpu(hp2).oper[1]^.typ = top_reg then
  5837. begin
  5838. SecondReg := taicpu(hp2).oper[1]^.reg;
  5839. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5840. end
  5841. else
  5842. begin
  5843. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5844. SecondReg := NR_NO;
  5845. end;
  5846. hp_pos := p;
  5847. hp_allocstart := hp4;
  5848. end
  5849. else
  5850. begin
  5851. { Will be a register because the size can't be S_B otherwise }
  5852. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5853. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5854. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5855. if (cs_opt_size in current_settings.optimizerswitches) then
  5856. begin
  5857. { Favour using MOVZX when optimising for size }
  5858. case taicpu(hp2).opsize of
  5859. S_W:
  5860. NewSize := S_BW;
  5861. S_L:
  5862. NewSize := S_BL;
  5863. {$ifdef x86_64}
  5864. S_Q:
  5865. begin
  5866. NewSize := S_BL;
  5867. { Will implicitly zero-extend to 64-bit }
  5868. setsubreg(SecondReg, R_SUBD);
  5869. end;
  5870. {$endif x86_64}
  5871. else
  5872. InternalError(2022101301);
  5873. end;
  5874. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5875. { Inserting it right before p will guarantee that the flags are also tracked }
  5876. Asml.InsertBefore(hp5, p);
  5877. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5878. hp_pos := hp5;
  5879. hp_allocstart := hp4;
  5880. end
  5881. else
  5882. begin
  5883. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5884. { Inserting it right before p will guarantee that the flags are also tracked }
  5885. Asml.InsertBefore(hp5, p);
  5886. hp_pos := p;
  5887. hp_allocstart := hp5;
  5888. end;
  5889. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5890. end;
  5891. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5892. taicpu(hp4).condition := taicpu(p).condition;
  5893. asml.InsertBefore(hp4, hp_pos);
  5894. if taicpu(hp3).is_jmp then
  5895. begin
  5896. JumpLoc.decrefs;
  5897. MakeUnconditional(taicpu(p));
  5898. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5899. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5900. end
  5901. else
  5902. ConvertJumpToRET(p, hp3);
  5903. if SecondReg <> NR_NO then
  5904. { Ensure the destination register is allocated over this region }
  5905. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5906. if (JumpLoc.getrefs = 0) then
  5907. RemoveDeadCodeAfterJump(hp3);
  5908. Result:=true;
  5909. exit;
  5910. end;
  5911. end;
  5912. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5913. var
  5914. hp1, hp2: tai;
  5915. ActiveReg: TRegister;
  5916. OldOffset: asizeint;
  5917. ThisConst: TCGInt;
  5918. function RegDeallocated: Boolean;
  5919. begin
  5920. TransferUsedRegs(TmpUsedRegs);
  5921. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5922. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5923. end;
  5924. begin
  5925. Result:=false;
  5926. hp1 := nil;
  5927. { replace
  5928. subX const,%reg1
  5929. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5930. dealloc %reg1
  5931. by
  5932. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5933. }
  5934. if MatchOpType(taicpu(p),top_const,top_reg) then
  5935. begin
  5936. ActiveReg := taicpu(p).oper[1]^.reg;
  5937. { Ensures the entire register was updated }
  5938. if (taicpu(p).opsize >= S_L) and
  5939. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5940. MatchInstruction(hp1,A_LEA,[]) and
  5941. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5942. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5943. (
  5944. { Cover the case where the register in the reference is also the destination register }
  5945. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5946. (
  5947. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5948. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5949. RegDeallocated
  5950. )
  5951. ) then
  5952. begin
  5953. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5954. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5955. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5956. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5957. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5958. {$ifdef x86_64}
  5959. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5960. begin
  5961. { Overflow; abort }
  5962. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5963. end
  5964. else
  5965. {$endif x86_64}
  5966. begin
  5967. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5968. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5969. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5970. RemoveCurrentP(p, hp1)
  5971. else
  5972. RemoveCurrentP(p);
  5973. result:=true;
  5974. Exit;
  5975. end;
  5976. end;
  5977. if (
  5978. { Save calling GetNextInstructionUsingReg again }
  5979. Assigned(hp1) or
  5980. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5981. ) and
  5982. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5983. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5984. begin
  5985. if taicpu(hp1).oper[0]^.typ = top_const then
  5986. begin
  5987. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5988. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5989. Result := True;
  5990. { Handle any overflows }
  5991. case taicpu(p).opsize of
  5992. S_B:
  5993. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5994. S_W:
  5995. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5996. S_L:
  5997. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5998. {$ifdef x86_64}
  5999. S_Q:
  6000. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6001. { Overflow; abort }
  6002. Result := False
  6003. else
  6004. taicpu(p).oper[0]^.val := ThisConst;
  6005. {$endif x86_64}
  6006. else
  6007. InternalError(2021102611);
  6008. end;
  6009. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6010. if Result then
  6011. begin
  6012. if (taicpu(p).oper[0]^.val < 0) and
  6013. (
  6014. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6015. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6016. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6017. ) then
  6018. begin
  6019. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6020. taicpu(p).opcode := A_SUB;
  6021. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6022. end
  6023. else
  6024. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6025. RemoveInstruction(hp1);
  6026. end;
  6027. end
  6028. else
  6029. begin
  6030. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6031. TransferUsedRegs(TmpUsedRegs);
  6032. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6033. hp2 := p;
  6034. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6035. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6036. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6037. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6038. begin
  6039. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6040. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6041. Asml.Remove(p);
  6042. Asml.InsertAfter(p, hp1);
  6043. p := hp1;
  6044. Result := True;
  6045. Exit;
  6046. end;
  6047. end;
  6048. end;
  6049. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6050. { * change "sub/add const1, reg" or "dec reg" followed by
  6051. "sub const2, reg" to one "sub ..., reg" }
  6052. {$ifdef i386}
  6053. if (taicpu(p).oper[0]^.val = 2) and
  6054. (ActiveReg = NR_ESP) and
  6055. { Don't do the sub/push optimization if the sub }
  6056. { comes from setting up the stack frame (JM) }
  6057. (not(GetLastInstruction(p,hp1)) or
  6058. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6059. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6060. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6061. begin
  6062. hp1 := tai(p.next);
  6063. while Assigned(hp1) and
  6064. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6065. not RegReadByInstruction(NR_ESP,hp1) and
  6066. not RegModifiedByInstruction(NR_ESP,hp1) do
  6067. hp1 := tai(hp1.next);
  6068. if Assigned(hp1) and
  6069. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6070. begin
  6071. taicpu(hp1).changeopsize(S_L);
  6072. if taicpu(hp1).oper[0]^.typ=top_reg then
  6073. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6074. hp1 := tai(p.next);
  6075. RemoveCurrentp(p, hp1);
  6076. Result:=true;
  6077. exit;
  6078. end;
  6079. end;
  6080. {$endif i386}
  6081. if DoArithCombineOpt(p) then
  6082. Result:=true;
  6083. end;
  6084. end;
  6085. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6086. var
  6087. TmpBool1,TmpBool2 : Boolean;
  6088. tmpref : treference;
  6089. hp1,hp2: tai;
  6090. mask, shiftval: tcgint;
  6091. begin
  6092. Result:=false;
  6093. { All these optimisations work on "shl/sal const,%reg" }
  6094. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6095. Exit;
  6096. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6097. (taicpu(p).oper[0]^.val <= 3) then
  6098. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6099. begin
  6100. { should we check the next instruction? }
  6101. TmpBool1 := True;
  6102. { have we found an add/sub which could be
  6103. integrated in the lea? }
  6104. TmpBool2 := False;
  6105. reference_reset(tmpref,2,[]);
  6106. TmpRef.index := taicpu(p).oper[1]^.reg;
  6107. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6108. while TmpBool1 and
  6109. GetNextInstruction(p, hp1) and
  6110. (tai(hp1).typ = ait_instruction) and
  6111. ((((taicpu(hp1).opcode = A_ADD) or
  6112. (taicpu(hp1).opcode = A_SUB)) and
  6113. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6114. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6115. (((taicpu(hp1).opcode = A_INC) or
  6116. (taicpu(hp1).opcode = A_DEC)) and
  6117. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6118. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6119. ((taicpu(hp1).opcode = A_LEA) and
  6120. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6121. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6122. (not GetNextInstruction(hp1,hp2) or
  6123. not instrReadsFlags(hp2)) Do
  6124. begin
  6125. TmpBool1 := False;
  6126. if taicpu(hp1).opcode=A_LEA then
  6127. begin
  6128. if (TmpRef.base = NR_NO) and
  6129. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6130. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6131. { Segment register isn't a concern here }
  6132. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6133. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6134. begin
  6135. TmpBool1 := True;
  6136. TmpBool2 := True;
  6137. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6138. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6139. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6140. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6141. RemoveInstruction(hp1);
  6142. end
  6143. end
  6144. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6145. begin
  6146. TmpBool1 := True;
  6147. TmpBool2 := True;
  6148. case taicpu(hp1).opcode of
  6149. A_ADD:
  6150. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6151. A_SUB:
  6152. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6153. else
  6154. internalerror(2019050536);
  6155. end;
  6156. RemoveInstruction(hp1);
  6157. end
  6158. else
  6159. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6160. (((taicpu(hp1).opcode = A_ADD) and
  6161. (TmpRef.base = NR_NO)) or
  6162. (taicpu(hp1).opcode = A_INC) or
  6163. (taicpu(hp1).opcode = A_DEC)) then
  6164. begin
  6165. TmpBool1 := True;
  6166. TmpBool2 := True;
  6167. case taicpu(hp1).opcode of
  6168. A_ADD:
  6169. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6170. A_INC:
  6171. inc(TmpRef.offset);
  6172. A_DEC:
  6173. dec(TmpRef.offset);
  6174. else
  6175. internalerror(2019050535);
  6176. end;
  6177. RemoveInstruction(hp1);
  6178. end;
  6179. end;
  6180. if TmpBool2
  6181. {$ifndef x86_64}
  6182. or
  6183. ((current_settings.optimizecputype < cpu_Pentium2) and
  6184. (taicpu(p).oper[0]^.val <= 3) and
  6185. not(cs_opt_size in current_settings.optimizerswitches))
  6186. {$endif x86_64}
  6187. then
  6188. begin
  6189. if not(TmpBool2) and
  6190. (taicpu(p).oper[0]^.val=1) then
  6191. begin
  6192. taicpu(p).opcode := A_ADD;
  6193. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6194. end
  6195. else
  6196. begin
  6197. taicpu(p).opcode := A_LEA;
  6198. taicpu(p).loadref(0, TmpRef);
  6199. end;
  6200. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6201. Result := True;
  6202. end;
  6203. end
  6204. {$ifndef x86_64}
  6205. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6206. begin
  6207. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6208. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6209. (unlike shl, which is only Tairable in the U pipe) }
  6210. if taicpu(p).oper[0]^.val=1 then
  6211. begin
  6212. taicpu(p).opcode := A_ADD;
  6213. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6214. Result := True;
  6215. end
  6216. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6217. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6218. else if (taicpu(p).opsize = S_L) and
  6219. (taicpu(p).oper[0]^.val<= 3) then
  6220. begin
  6221. reference_reset(tmpref,2,[]);
  6222. TmpRef.index := taicpu(p).oper[1]^.reg;
  6223. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6224. taicpu(p).opcode := A_LEA;
  6225. taicpu(p).loadref(0, TmpRef);
  6226. Result := True;
  6227. end;
  6228. end
  6229. {$endif x86_64}
  6230. else if
  6231. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6232. (
  6233. (
  6234. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6235. SetAndTest(hp1, hp2)
  6236. {$ifdef x86_64}
  6237. ) or
  6238. (
  6239. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6240. GetNextInstruction(hp1, hp2) and
  6241. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6242. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6243. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6244. {$endif x86_64}
  6245. )
  6246. ) and
  6247. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6248. begin
  6249. { Change:
  6250. shl x, %reg1
  6251. mov -(1<<x), %reg2
  6252. and %reg2, %reg1
  6253. Or:
  6254. shl x, %reg1
  6255. and -(1<<x), %reg1
  6256. To just:
  6257. shl x, %reg1
  6258. Since the and operation only zeroes bits that are already zero from the shl operation
  6259. }
  6260. case taicpu(p).oper[0]^.val of
  6261. 8:
  6262. mask:=$FFFFFFFFFFFFFF00;
  6263. 16:
  6264. mask:=$FFFFFFFFFFFF0000;
  6265. 32:
  6266. mask:=$FFFFFFFF00000000;
  6267. 63:
  6268. { Constant pre-calculated to prevent overflow errors with Int64 }
  6269. mask:=$8000000000000000;
  6270. else
  6271. begin
  6272. if taicpu(p).oper[0]^.val >= 64 then
  6273. { Shouldn't happen realistically, since the register
  6274. is guaranteed to be set to zero at this point }
  6275. mask := 0
  6276. else
  6277. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6278. end;
  6279. end;
  6280. if taicpu(hp1).oper[0]^.val = mask then
  6281. begin
  6282. { Everything checks out, perform the optimisation, as long as
  6283. the FLAGS register isn't being used}
  6284. TransferUsedRegs(TmpUsedRegs);
  6285. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6286. {$ifdef x86_64}
  6287. if (hp1 <> hp2) then
  6288. begin
  6289. { "shl/mov/and" version }
  6290. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6291. { Don't do the optimisation if the FLAGS register is in use }
  6292. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6293. begin
  6294. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6295. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6296. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6297. begin
  6298. RemoveInstruction(hp1);
  6299. Result := True;
  6300. end;
  6301. { Only set Result to True if the 'mov' instruction was removed }
  6302. RemoveInstruction(hp2);
  6303. end;
  6304. end
  6305. else
  6306. {$endif x86_64}
  6307. begin
  6308. { "shl/and" version }
  6309. { Don't do the optimisation if the FLAGS register is in use }
  6310. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6311. begin
  6312. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6313. RemoveInstruction(hp1);
  6314. Result := True;
  6315. end;
  6316. end;
  6317. Exit;
  6318. end
  6319. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6320. begin
  6321. { Even if the mask doesn't allow for its removal, we might be
  6322. able to optimise the mask for the "shl/and" version, which
  6323. may permit other peephole optimisations }
  6324. {$ifdef DEBUG_AOPTCPU}
  6325. mask := taicpu(hp1).oper[0]^.val and mask;
  6326. if taicpu(hp1).oper[0]^.val <> mask then
  6327. begin
  6328. DebugMsg(
  6329. SPeepholeOptimization +
  6330. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6331. ' to $' + debug_tostr(mask) +
  6332. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6333. taicpu(hp1).oper[0]^.val := mask;
  6334. end;
  6335. {$else DEBUG_AOPTCPU}
  6336. { If debugging is off, just set the operand even if it's the same }
  6337. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6338. {$endif DEBUG_AOPTCPU}
  6339. end;
  6340. end;
  6341. {
  6342. change
  6343. shl/sal const,reg
  6344. <op> ...(...,reg,1),...
  6345. into
  6346. <op> ...(...,reg,1 shl const),...
  6347. if const in 1..3
  6348. }
  6349. if MatchOpType(taicpu(p), top_const, top_reg) and
  6350. (taicpu(p).oper[0]^.val in [1..3]) and
  6351. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6352. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6353. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6354. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6355. MatchOpType(taicpu(hp1),top_ref))
  6356. ) and
  6357. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6358. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6359. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6360. begin
  6361. TransferUsedRegs(TmpUsedRegs);
  6362. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6363. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6364. begin
  6365. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6366. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6367. RemoveCurrentP(p);
  6368. Result:=true;
  6369. exit;
  6370. end;
  6371. end;
  6372. if MatchOpType(taicpu(p), top_const, top_reg) and
  6373. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6374. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6375. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6376. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6377. begin
  6378. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6379. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6380. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6381. {$ifdef x86_64}
  6382. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6383. {$endif x86_64}
  6384. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6385. begin
  6386. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6387. taicpu(hp1).opcode:=A_MOV;
  6388. taicpu(hp1).oper[0]^.val:=0;
  6389. end
  6390. else
  6391. begin
  6392. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6393. taicpu(hp1).oper[0]^.val:=shiftval;
  6394. end;
  6395. RemoveCurrentP(p);
  6396. Result:=true;
  6397. exit;
  6398. end;
  6399. end;
  6400. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6401. begin
  6402. case shr_size of
  6403. S_B:
  6404. { No valid combinations }
  6405. Result := False;
  6406. S_W:
  6407. Result := (Shift >= 8) and (movz_size = S_BW);
  6408. S_L:
  6409. Result :=
  6410. (Shift >= 24) { Any opsize is valid for this shift } or
  6411. ((Shift >= 16) and (movz_size = S_WL));
  6412. {$ifdef x86_64}
  6413. S_Q:
  6414. Result :=
  6415. (Shift >= 56) { Any opsize is valid for this shift } or
  6416. ((Shift >= 48) and (movz_size = S_WL));
  6417. {$endif x86_64}
  6418. else
  6419. InternalError(2022081510);
  6420. end;
  6421. end;
  6422. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6423. var
  6424. hp1, hp2: tai;
  6425. Shift: TCGInt;
  6426. LimitSize: Topsize;
  6427. DoNotMerge: Boolean;
  6428. begin
  6429. Result := False;
  6430. { All these optimisations work on "shr const,%reg" }
  6431. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6432. Exit;
  6433. DoNotMerge := False;
  6434. Shift := taicpu(p).oper[0]^.val;
  6435. LimitSize := taicpu(p).opsize;
  6436. hp1 := p;
  6437. repeat
  6438. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6439. Exit;
  6440. case taicpu(hp1).opcode of
  6441. A_TEST, A_CMP, A_Jcc:
  6442. { Skip over conditional jumps and relevant comparisons }
  6443. Continue;
  6444. A_MOVZX:
  6445. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6446. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6447. begin
  6448. { Since the original register is being read as is, subsequent
  6449. SHRs must not be merged at this point }
  6450. DoNotMerge := True;
  6451. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6452. begin
  6453. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6454. begin
  6455. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6456. taicpu(hp1).opcode := A_MOV;
  6457. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6458. case taicpu(hp1).opsize of
  6459. S_BW:
  6460. taicpu(hp1).opsize := S_W;
  6461. S_BL, S_WL:
  6462. taicpu(hp1).opsize := S_L;
  6463. else
  6464. InternalError(2022081503);
  6465. end;
  6466. { p itself hasn't changed, so no need to set Result to True }
  6467. Include(OptsToCheck, aoc_ForceNewIteration);
  6468. { See if there's anything afterwards that can be
  6469. optimised, since the input register hasn't changed }
  6470. Continue;
  6471. end;
  6472. { NOTE: If the MOVZX instruction reads and writes the same
  6473. register, defer this to the post-peephole optimisation stage }
  6474. Exit;
  6475. end;
  6476. end;
  6477. A_SHL, A_SAL, A_SHR:
  6478. if (taicpu(hp1).opsize <= LimitSize) and
  6479. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6480. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6481. begin
  6482. { Make sure the sizes don't exceed the register size limit
  6483. (measured by the shift value falling below the limit) }
  6484. if taicpu(hp1).opsize < LimitSize then
  6485. LimitSize := taicpu(hp1).opsize;
  6486. if taicpu(hp1).opcode = A_SHR then
  6487. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6488. else
  6489. begin
  6490. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6491. DoNotMerge := True;
  6492. end;
  6493. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6494. Exit;
  6495. { Since we've established that the combined shift is within
  6496. limits, we can actually combine the adjacent SHR
  6497. instructions even if they're different sizes }
  6498. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6499. begin
  6500. hp2 := tai(hp1.Previous);
  6501. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6502. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6503. RemoveInstruction(hp1);
  6504. hp1 := hp2;
  6505. { Though p has changed, only the constant has, and its
  6506. effects can still be detected on the next iteration of
  6507. the repeat..until loop }
  6508. Include(OptsToCheck, aoc_ForceNewIteration);
  6509. end;
  6510. { Move onto the next instruction }
  6511. Continue;
  6512. end;
  6513. else
  6514. ;
  6515. end;
  6516. Break;
  6517. until False;
  6518. end;
  6519. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6520. var
  6521. CurrentRef: TReference;
  6522. FullReg: TRegister;
  6523. hp1, hp2: tai;
  6524. begin
  6525. Result := False;
  6526. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6527. Exit;
  6528. { We assume you've checked if the operand is actually a reference by
  6529. this point. If it isn't, you'll most likely get an access violation }
  6530. CurrentRef := first_mov.oper[1]^.ref^;
  6531. { Memory must be aligned }
  6532. if (CurrentRef.offset mod 4) <> 0 then
  6533. Exit;
  6534. Inc(CurrentRef.offset);
  6535. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6536. if MatchOperand(second_mov.oper[0]^, 0) and
  6537. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6538. GetNextInstruction(second_mov, hp1) and
  6539. (hp1.typ = ait_instruction) and
  6540. (taicpu(hp1).opcode = A_MOV) and
  6541. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6542. (taicpu(hp1).oper[0]^.val = 0) then
  6543. begin
  6544. Inc(CurrentRef.offset);
  6545. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6546. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6547. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6548. begin
  6549. case taicpu(hp1).opsize of
  6550. S_B:
  6551. if GetNextInstruction(hp1, hp2) and
  6552. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6553. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6554. (taicpu(hp2).oper[0]^.val = 0) then
  6555. begin
  6556. Inc(CurrentRef.offset);
  6557. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6558. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6559. (taicpu(hp2).opsize = S_B) then
  6560. begin
  6561. RemoveInstruction(hp1);
  6562. RemoveInstruction(hp2);
  6563. first_mov.opsize := S_L;
  6564. if first_mov.oper[0]^.typ = top_reg then
  6565. begin
  6566. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6567. { Reuse second_mov as a MOVZX instruction }
  6568. second_mov.opcode := A_MOVZX;
  6569. second_mov.opsize := S_BL;
  6570. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6571. second_mov.loadreg(1, FullReg);
  6572. first_mov.oper[0]^.reg := FullReg;
  6573. asml.Remove(second_mov);
  6574. asml.InsertBefore(second_mov, first_mov);
  6575. end
  6576. else
  6577. { It's a value }
  6578. begin
  6579. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6580. RemoveInstruction(second_mov);
  6581. end;
  6582. Result := True;
  6583. Exit;
  6584. end;
  6585. end;
  6586. S_W:
  6587. begin
  6588. RemoveInstruction(hp1);
  6589. first_mov.opsize := S_L;
  6590. if first_mov.oper[0]^.typ = top_reg then
  6591. begin
  6592. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6593. { Reuse second_mov as a MOVZX instruction }
  6594. second_mov.opcode := A_MOVZX;
  6595. second_mov.opsize := S_BL;
  6596. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6597. second_mov.loadreg(1, FullReg);
  6598. first_mov.oper[0]^.reg := FullReg;
  6599. asml.Remove(second_mov);
  6600. asml.InsertBefore(second_mov, first_mov);
  6601. end
  6602. else
  6603. { It's a value }
  6604. begin
  6605. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6606. RemoveInstruction(second_mov);
  6607. end;
  6608. Result := True;
  6609. Exit;
  6610. end;
  6611. else
  6612. ;
  6613. end;
  6614. end;
  6615. end;
  6616. end;
  6617. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6618. { returns true if a "continue" should be done after this optimization }
  6619. var
  6620. hp1, hp2, hp3: tai;
  6621. begin
  6622. Result := false;
  6623. hp3 := nil;
  6624. if MatchOpType(taicpu(p),top_ref) and
  6625. GetNextInstruction(p, hp1) and
  6626. (hp1.typ = ait_instruction) and
  6627. (((taicpu(hp1).opcode = A_FLD) and
  6628. (taicpu(p).opcode = A_FSTP)) or
  6629. ((taicpu(p).opcode = A_FISTP) and
  6630. (taicpu(hp1).opcode = A_FILD))) and
  6631. MatchOpType(taicpu(hp1),top_ref) and
  6632. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6633. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6634. begin
  6635. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6636. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6637. GetNextInstruction(hp1, hp2) and
  6638. (((hp2.typ = ait_instruction) and
  6639. IsExitCode(hp2) and
  6640. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6641. not(assigned(current_procinfo.procdef.funcretsym) and
  6642. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6643. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6644. { fstp <temp>
  6645. fld <temp>
  6646. <dealloc> <temp>
  6647. }
  6648. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6649. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6650. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6651. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6652. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6653. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6654. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6655. )
  6656. )
  6657. ) then
  6658. begin
  6659. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6660. RemoveInstruction(hp1);
  6661. RemoveCurrentP(p, hp2);
  6662. { first case: exit code }
  6663. if hp2.typ = ait_instruction then
  6664. RemoveLastDeallocForFuncRes(p);
  6665. Result := true;
  6666. end
  6667. else
  6668. { we can do this only in fast math mode as fstp is rounding ...
  6669. ... still disabled as it breaks the compiler and/or rtl }
  6670. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6671. { ... or if another fstp equal to the first one follows }
  6672. GetNextInstruction(hp1,hp2) and
  6673. (hp2.typ = ait_instruction) and
  6674. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6675. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6676. begin
  6677. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6678. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6679. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6680. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6681. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6682. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6683. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6684. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6685. ) then
  6686. begin
  6687. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6688. RemoveCurrentP(p,hp2);
  6689. RemoveInstruction(hp1);
  6690. Result := true;
  6691. end
  6692. else if { fst can't store an extended/comp value }
  6693. (taicpu(p).opsize <> S_FX) and
  6694. (taicpu(p).opsize <> S_IQ) then
  6695. begin
  6696. if (taicpu(p).opcode = A_FSTP) then
  6697. taicpu(p).opcode := A_FST
  6698. else
  6699. taicpu(p).opcode := A_FIST;
  6700. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6701. RemoveInstruction(hp1);
  6702. Result := true;
  6703. end;
  6704. end;
  6705. end;
  6706. end;
  6707. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6708. var
  6709. hp1, hp2, hp3: tai;
  6710. begin
  6711. result:=false;
  6712. if MatchOpType(taicpu(p),top_reg) and
  6713. GetNextInstruction(p, hp1) and
  6714. (hp1.typ = Ait_Instruction) and
  6715. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6716. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6717. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6718. { change to
  6719. fld reg fxxx reg,st
  6720. fxxxp st, st1 (hp1)
  6721. Remark: non commutative operations must be reversed!
  6722. }
  6723. begin
  6724. case taicpu(hp1).opcode Of
  6725. A_FMULP,A_FADDP,
  6726. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6727. begin
  6728. case taicpu(hp1).opcode Of
  6729. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6730. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6731. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6732. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6733. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6734. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6735. else
  6736. internalerror(2019050534);
  6737. end;
  6738. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6739. taicpu(hp1).oper[1]^.reg := NR_ST;
  6740. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6741. RemoveCurrentP(p, hp1);
  6742. Result:=true;
  6743. exit;
  6744. end;
  6745. else
  6746. ;
  6747. end;
  6748. end
  6749. else
  6750. if MatchOpType(taicpu(p),top_ref) and
  6751. GetNextInstruction(p, hp2) and
  6752. (hp2.typ = Ait_Instruction) and
  6753. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6754. (taicpu(p).opsize in [S_FS, S_FL]) and
  6755. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6756. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6757. if GetLastInstruction(p, hp1) and
  6758. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6759. MatchOpType(taicpu(hp1),top_ref) and
  6760. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6761. if ((taicpu(hp2).opcode = A_FMULP) or
  6762. (taicpu(hp2).opcode = A_FADDP)) then
  6763. { change to
  6764. fld/fst mem1 (hp1) fld/fst mem1
  6765. fld mem1 (p) fadd/
  6766. faddp/ fmul st, st
  6767. fmulp st, st1 (hp2) }
  6768. begin
  6769. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6770. RemoveCurrentP(p, hp1);
  6771. if (taicpu(hp2).opcode = A_FADDP) then
  6772. taicpu(hp2).opcode := A_FADD
  6773. else
  6774. taicpu(hp2).opcode := A_FMUL;
  6775. taicpu(hp2).oper[1]^.reg := NR_ST;
  6776. end
  6777. else
  6778. { change to
  6779. fld/fst mem1 (hp1) fld/fst mem1
  6780. fld mem1 (p) fld st
  6781. }
  6782. begin
  6783. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6784. taicpu(p).changeopsize(S_FL);
  6785. taicpu(p).loadreg(0,NR_ST);
  6786. end
  6787. else
  6788. begin
  6789. case taicpu(hp2).opcode Of
  6790. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6791. { change to
  6792. fld/fst mem1 (hp1) fld/fst mem1
  6793. fld mem2 (p) fxxx mem2
  6794. fxxxp st, st1 (hp2) }
  6795. begin
  6796. case taicpu(hp2).opcode Of
  6797. A_FADDP: taicpu(p).opcode := A_FADD;
  6798. A_FMULP: taicpu(p).opcode := A_FMUL;
  6799. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6800. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6801. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6802. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6803. else
  6804. internalerror(2019050533);
  6805. end;
  6806. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6807. RemoveInstruction(hp2);
  6808. end
  6809. else
  6810. ;
  6811. end
  6812. end
  6813. end;
  6814. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6815. begin
  6816. Result := condition_in(cond1, cond2) or
  6817. { Not strictly subsets due to the actual flags checked, but because we're
  6818. comparing integers, E is a subset of AE and GE and their aliases }
  6819. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6820. end;
  6821. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6822. var
  6823. v: TCGInt;
  6824. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6825. FirstMatch, TempBool: Boolean;
  6826. NewReg: TRegister;
  6827. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6828. begin
  6829. Result:=false;
  6830. { All these optimisations need a next instruction }
  6831. if not GetNextInstruction(p, hp1) then
  6832. Exit;
  6833. { Search for:
  6834. cmp ###,###
  6835. j(c1) @lbl1
  6836. ...
  6837. @lbl:
  6838. cmp ###,### (same comparison as above)
  6839. j(c2) @lbl2
  6840. If c1 is a subset of c2, change to:
  6841. cmp ###,###
  6842. j(c1) @lbl2
  6843. (@lbl1 may become a dead label as a result)
  6844. }
  6845. { Also handle cases where there are multiple jumps in a row }
  6846. p_jump := hp1;
  6847. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6848. begin
  6849. if IsJumpToLabel(taicpu(p_jump)) then
  6850. begin
  6851. { Do jump optimisations first in case the condition becomes
  6852. unnecessary }
  6853. TempBool := True;
  6854. if DoJumpOptimizations(p_jump, TempBool) or
  6855. not TempBool then
  6856. begin
  6857. if Assigned(p_jump) then
  6858. begin
  6859. hp1 := p_jump;
  6860. if (p_jump.typ in [ait_align]) then
  6861. SkipAligns(p_jump, p_jump);
  6862. { CollapseZeroDistJump will be set to the label after the
  6863. jump if it optimises, whether or not it's live or dead }
  6864. if (p_jump.typ in [ait_label]) and
  6865. not (tai_label(p_jump).labsym.is_used) then
  6866. GetNextInstruction(p_jump, p_jump);
  6867. end;
  6868. TransferUsedRegs(TmpUsedRegs);
  6869. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6870. if not Assigned(p_jump) or
  6871. (
  6872. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6873. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6874. ) then
  6875. begin
  6876. { No more conditional jumps; conditional statement is no longer required }
  6877. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6878. RemoveCurrentP(p);
  6879. Result := True;
  6880. Exit;
  6881. end;
  6882. hp1 := p_jump;
  6883. Include(OptsToCheck, aoc_ForceNewIteration);
  6884. Continue;
  6885. end;
  6886. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6887. if GetNextInstruction(p_jump, hp2) and
  6888. (
  6889. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6890. not TempBool
  6891. ) then
  6892. begin
  6893. hp1 := p_jump;
  6894. Include(OptsToCheck, aoc_ForceNewIteration);
  6895. Continue;
  6896. end;
  6897. p_label := nil;
  6898. if Assigned(JumpLabel) then
  6899. p_label := getlabelwithsym(JumpLabel);
  6900. if Assigned(p_label) and
  6901. GetNextInstruction(p_label, p_dist) and
  6902. MatchInstruction(p_dist, A_CMP, []) and
  6903. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6904. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6905. GetNextInstruction(p_dist, hp1_dist) and
  6906. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6907. begin
  6908. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6909. if JumpLabel = JumpLabel_dist then
  6910. { This is an infinite loop }
  6911. Exit;
  6912. { Best optimisation when the first condition is a subset (or equal) of the second }
  6913. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6914. begin
  6915. { Any registers used here will already be allocated }
  6916. if Assigned(JumpLabel) then
  6917. JumpLabel.DecRefs;
  6918. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6919. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6920. Result := True;
  6921. { Don't exit yet. Since p and p_jump haven't actually been
  6922. removed, we can check for more on this iteration }
  6923. end
  6924. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6925. GetNextInstruction(hp1_dist, hp1_label) and
  6926. SkipAligns(hp1_label, hp1_label) and
  6927. (hp1_label.typ = ait_label) then
  6928. begin
  6929. JumpLabel_far := tai_label(hp1_label).labsym;
  6930. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6931. { This is an infinite loop }
  6932. Exit;
  6933. if Assigned(JumpLabel_far) then
  6934. begin
  6935. { In this situation, if the first jump branches, the second one will never,
  6936. branch so change the destination label to after the second jump }
  6937. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6938. if Assigned(JumpLabel) then
  6939. JumpLabel.DecRefs;
  6940. JumpLabel_far.IncRefs;
  6941. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6942. Result := True;
  6943. { Don't exit yet. Since p and p_jump haven't actually been
  6944. removed, we can check for more on this iteration }
  6945. Continue;
  6946. end;
  6947. end;
  6948. end;
  6949. end;
  6950. { Search for:
  6951. cmp ###,###
  6952. j(c1) @lbl1
  6953. cmp ###,### (same as first)
  6954. Remove second cmp
  6955. }
  6956. if GetNextInstruction(p_jump, hp2) and
  6957. (
  6958. (
  6959. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6960. (
  6961. (
  6962. MatchOpType(taicpu(p), top_const, top_reg) and
  6963. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6964. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6965. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6966. ) or (
  6967. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6968. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6969. )
  6970. )
  6971. ) or (
  6972. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6973. MatchOperand(taicpu(p).oper[0]^, 0) and
  6974. (taicpu(p).oper[1]^.typ = top_reg) and
  6975. MatchInstruction(hp2, A_TEST, []) and
  6976. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6977. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6978. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6979. )
  6980. ) then
  6981. begin
  6982. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6983. RemoveInstruction(hp2);
  6984. Result := True;
  6985. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6986. end;
  6987. GetNextInstruction(p_jump, p_jump);
  6988. end;
  6989. if (
  6990. { Don't call GetNextInstruction again if we already have it }
  6991. (hp1 = p_jump) or
  6992. GetNextInstruction(p, hp1)
  6993. ) and
  6994. MatchInstruction(hp1, A_Jcc, []) and
  6995. IsJumpToLabel(taicpu(hp1)) and
  6996. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  6997. GetNextInstruction(hp1, hp2) then
  6998. begin
  6999. {
  7000. cmp x, y (or "cmp y, x")
  7001. je @lbl
  7002. mov x, y
  7003. @lbl:
  7004. (x and y can be constants, registers or references)
  7005. Change to:
  7006. mov x, y (x and y will always be equal in the end)
  7007. @lbl: (may beceome a dead label)
  7008. Also:
  7009. cmp x, y (or "cmp y, x")
  7010. jne @lbl
  7011. mov x, y
  7012. @lbl:
  7013. (x and y can be constants, registers or references)
  7014. Change to:
  7015. Absolutely nothing! (Except @lbl if it's still live)
  7016. }
  7017. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7018. (
  7019. (
  7020. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7021. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7022. ) or (
  7023. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7024. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7025. )
  7026. ) and
  7027. GetNextInstruction(hp2, hp1_label) and
  7028. SkipAligns(hp1_label, hp1_label) and
  7029. (hp1_label.typ = ait_label) and
  7030. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7031. begin
  7032. tai_label(hp1_label).labsym.DecRefs;
  7033. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7034. begin
  7035. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7036. RemoveInstruction(hp2);
  7037. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7038. end
  7039. else
  7040. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7041. RemoveInstruction(hp1);
  7042. RemoveCurrentp(p, hp2);
  7043. Result := True;
  7044. Exit;
  7045. end;
  7046. {
  7047. Try to optimise the following:
  7048. cmp $x,### ($x and $y can be registers or constants)
  7049. je @lbl1 (only reference)
  7050. cmp $y,### (### are identical)
  7051. @Lbl:
  7052. sete %reg1
  7053. Change to:
  7054. cmp $x,###
  7055. sete %reg2 (allocate new %reg2)
  7056. cmp $y,###
  7057. sete %reg1
  7058. orb %reg2,%reg1
  7059. (dealloc %reg2)
  7060. This adds an instruction (so don't perform under -Os), but it removes
  7061. a conditional branch.
  7062. }
  7063. if not (cs_opt_size in current_settings.optimizerswitches) and
  7064. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7065. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7066. { The first operand of CMP instructions can only be a register or
  7067. immediate anyway, so no need to check }
  7068. GetNextInstruction(hp2, p_label) and
  7069. (p_label.typ = ait_label) and
  7070. (tai_label(p_label).labsym.getrefs = 1) and
  7071. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7072. GetNextInstruction(p_label, p_dist) and
  7073. MatchInstruction(p_dist, A_SETcc, []) and
  7074. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7075. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7076. begin
  7077. TransferUsedRegs(TmpUsedRegs);
  7078. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7079. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7080. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7081. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7082. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7083. { Get the instruction after the SETcc instruction so we can
  7084. allocate a new register over the entire range }
  7085. GetNextInstruction(p_dist, hp1_dist) then
  7086. begin
  7087. { Register can appear in p if it's not used afterwards, so only
  7088. allocate between hp1 and hp1_dist }
  7089. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7090. if NewReg <> NR_NO then
  7091. begin
  7092. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7093. { Change the jump instruction into a SETcc instruction }
  7094. taicpu(hp1).opcode := A_SETcc;
  7095. taicpu(hp1).opsize := S_B;
  7096. taicpu(hp1).loadreg(0, NewReg);
  7097. { This is now a dead label }
  7098. tai_label(p_label).labsym.decrefs;
  7099. { Prefer adding before the next instruction so the FLAGS
  7100. register is deallicated first }
  7101. AsmL.InsertBefore(
  7102. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7103. hp1_dist
  7104. );
  7105. Result := True;
  7106. { Don't exit yet, as p wasn't changed and hp1, while
  7107. modified, is still intact and might be optimised by the
  7108. SETcc optimisation below }
  7109. end;
  7110. end;
  7111. end;
  7112. end;
  7113. if taicpu(p).oper[0]^.typ = top_const then
  7114. begin
  7115. if (taicpu(p).oper[0]^.val = 0) and
  7116. (taicpu(p).oper[1]^.typ = top_reg) and
  7117. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7118. begin
  7119. hp2 := p;
  7120. FirstMatch := True;
  7121. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7122. anything meaningful once it's converted to "test %reg,%reg";
  7123. additionally, some jumps will always (or never) branch, so
  7124. evaluate every jump immediately following the
  7125. comparison, optimising the conditions if possible.
  7126. Similarly with SETcc... those that are always set to 0 or 1
  7127. are changed to MOV instructions }
  7128. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7129. (
  7130. GetNextInstruction(hp2, hp1) and
  7131. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7132. ) do
  7133. begin
  7134. FirstMatch := False;
  7135. case taicpu(hp1).condition of
  7136. C_B, C_C, C_NAE, C_O:
  7137. { For B/NAE:
  7138. Will never branch since an unsigned integer can never be below zero
  7139. For C/O:
  7140. Result cannot overflow because 0 is being subtracted
  7141. }
  7142. begin
  7143. if taicpu(hp1).opcode = A_Jcc then
  7144. begin
  7145. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7146. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7147. RemoveInstruction(hp1);
  7148. { Since hp1 was deleted, hp2 must not be updated }
  7149. Continue;
  7150. end
  7151. else
  7152. begin
  7153. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7154. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7155. taicpu(hp1).opcode := A_MOV;
  7156. taicpu(hp1).ops := 2;
  7157. taicpu(hp1).condition := C_None;
  7158. taicpu(hp1).opsize := S_B;
  7159. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7160. taicpu(hp1).loadconst(0, 0);
  7161. end;
  7162. end;
  7163. C_BE, C_NA:
  7164. begin
  7165. { Will only branch if equal to zero }
  7166. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7167. taicpu(hp1).condition := C_E;
  7168. end;
  7169. C_A, C_NBE:
  7170. begin
  7171. { Will only branch if not equal to zero }
  7172. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7173. taicpu(hp1).condition := C_NE;
  7174. end;
  7175. C_AE, C_NB, C_NC, C_NO:
  7176. begin
  7177. { Will always branch }
  7178. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7179. if taicpu(hp1).opcode = A_Jcc then
  7180. begin
  7181. MakeUnconditional(taicpu(hp1));
  7182. { Any jumps/set that follow will now be dead code }
  7183. RemoveDeadCodeAfterJump(taicpu(hp1));
  7184. Break;
  7185. end
  7186. else
  7187. begin
  7188. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7189. taicpu(hp1).opcode := A_MOV;
  7190. taicpu(hp1).ops := 2;
  7191. taicpu(hp1).condition := C_None;
  7192. taicpu(hp1).opsize := S_B;
  7193. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7194. taicpu(hp1).loadconst(0, 1);
  7195. end;
  7196. end;
  7197. C_None:
  7198. InternalError(2020012201);
  7199. C_P, C_PE, C_NP, C_PO:
  7200. { We can't handle parity checks and they should never be generated
  7201. after a general-purpose CMP (it's used in some floating-point
  7202. comparisons that don't use CMP) }
  7203. InternalError(2020012202);
  7204. else
  7205. { Zero/Equality, Sign, their complements and all of the
  7206. signed comparisons do not need to be converted };
  7207. end;
  7208. hp2 := hp1;
  7209. end;
  7210. { Convert the instruction to a TEST }
  7211. taicpu(p).opcode := A_TEST;
  7212. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7213. Result := True;
  7214. Exit;
  7215. end
  7216. else if (taicpu(p).oper[0]^.val = 1) and
  7217. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7218. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7219. begin
  7220. { Convert; To:
  7221. cmp $1,r/m cmp $0,r/m
  7222. jl @lbl jle @lbl
  7223. (Also do inverted conditions)
  7224. }
  7225. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7226. taicpu(p).oper[0]^.val := 0;
  7227. if taicpu(hp1).condition in [C_L, C_NGE] then
  7228. taicpu(hp1).condition := C_LE
  7229. else
  7230. taicpu(hp1).condition := C_NLE;
  7231. { If the instruction is now "cmp $0,%reg", convert it to a
  7232. TEST (and effectively do the work of the "cmp $0,%reg" in
  7233. the block above)
  7234. }
  7235. if (taicpu(p).oper[1]^.typ = top_reg) then
  7236. begin
  7237. taicpu(p).opcode := A_TEST;
  7238. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7239. end;
  7240. Result := True;
  7241. Exit;
  7242. end
  7243. else if (taicpu(p).oper[1]^.typ = top_reg)
  7244. {$ifdef x86_64}
  7245. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7246. {$endif x86_64}
  7247. then
  7248. begin
  7249. { cmp register,$8000 neg register
  7250. je target --> jo target
  7251. .... only if register is deallocated before jump.}
  7252. case Taicpu(p).opsize of
  7253. S_B: v:=$80;
  7254. S_W: v:=$8000;
  7255. S_L: v:=qword($80000000);
  7256. else
  7257. internalerror(2013112905);
  7258. end;
  7259. if (taicpu(p).oper[0]^.val=v) and
  7260. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7261. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7262. begin
  7263. TransferUsedRegs(TmpUsedRegs);
  7264. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7265. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7266. begin
  7267. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7268. Taicpu(p).opcode:=A_NEG;
  7269. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7270. Taicpu(p).clearop(1);
  7271. Taicpu(p).ops:=1;
  7272. if Taicpu(hp1).condition=C_E then
  7273. Taicpu(hp1).condition:=C_O
  7274. else
  7275. Taicpu(hp1).condition:=C_NO;
  7276. Result:=true;
  7277. exit;
  7278. end;
  7279. end;
  7280. end;
  7281. end;
  7282. if TrySwapMovCmp(p, hp1) then
  7283. begin
  7284. Result := True;
  7285. Exit;
  7286. end;
  7287. end;
  7288. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7289. var
  7290. hp1: tai;
  7291. begin
  7292. {
  7293. remove the second (v)pxor from
  7294. pxor reg,reg
  7295. ...
  7296. pxor reg,reg
  7297. }
  7298. Result:=false;
  7299. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7300. MatchOpType(taicpu(p),top_reg,top_reg) and
  7301. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7302. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7303. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7304. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7305. begin
  7306. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7307. RemoveInstruction(hp1);
  7308. Result:=true;
  7309. Exit;
  7310. end
  7311. {
  7312. replace
  7313. pxor reg1,reg1
  7314. movapd/s reg1,reg2
  7315. dealloc reg1
  7316. by
  7317. pxor reg2,reg2
  7318. }
  7319. else if GetNextInstruction(p,hp1) and
  7320. { we mix single and double opperations here because we assume that the compiler
  7321. generates vmovapd only after double operations and vmovaps only after single operations }
  7322. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7323. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7324. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7325. (taicpu(p).oper[0]^.typ=top_reg) then
  7326. begin
  7327. TransferUsedRegs(TmpUsedRegs);
  7328. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7329. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7330. begin
  7331. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7332. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7333. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7334. RemoveInstruction(hp1);
  7335. result:=true;
  7336. end;
  7337. end;
  7338. end;
  7339. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7340. var
  7341. hp1: tai;
  7342. begin
  7343. {
  7344. remove the second (v)pxor from
  7345. (v)pxor reg,reg
  7346. ...
  7347. (v)pxor reg,reg
  7348. }
  7349. Result:=false;
  7350. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7351. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7352. begin
  7353. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7354. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7355. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7356. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7357. begin
  7358. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7359. RemoveInstruction(hp1);
  7360. Result:=true;
  7361. Exit;
  7362. end;
  7363. {$ifdef x86_64}
  7364. {
  7365. replace
  7366. vpxor reg1,reg1,reg1
  7367. vmov reg,mem
  7368. by
  7369. movq $0,mem
  7370. }
  7371. if GetNextInstruction(p,hp1) and
  7372. MatchInstruction(hp1,A_VMOVSD,[]) and
  7373. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7374. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7375. begin
  7376. TransferUsedRegs(TmpUsedRegs);
  7377. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7378. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7379. begin
  7380. taicpu(hp1).loadconst(0,0);
  7381. taicpu(hp1).opcode:=A_MOV;
  7382. taicpu(hp1).opsize:=S_Q;
  7383. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7384. RemoveCurrentP(p);
  7385. result:=true;
  7386. Exit;
  7387. end;
  7388. end;
  7389. {$endif x86_64}
  7390. end
  7391. {
  7392. replace
  7393. vpxor reg1,reg1,reg2
  7394. by
  7395. vpxor reg2,reg2,reg2
  7396. to avoid unncessary data dependencies
  7397. }
  7398. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7399. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7400. begin
  7401. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7402. { avoid unncessary data dependency }
  7403. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7404. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7405. result:=true;
  7406. exit;
  7407. end;
  7408. Result:=OptPass1VOP(p);
  7409. end;
  7410. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7411. var
  7412. hp1 : tai;
  7413. begin
  7414. result:=false;
  7415. { replace
  7416. IMul const,%mreg1,%mreg2
  7417. Mov %reg2,%mreg3
  7418. dealloc %mreg3
  7419. by
  7420. Imul const,%mreg1,%mreg23
  7421. }
  7422. if (taicpu(p).ops=3) and
  7423. GetNextInstruction(p,hp1) and
  7424. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7425. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7426. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7427. begin
  7428. TransferUsedRegs(TmpUsedRegs);
  7429. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7430. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7431. begin
  7432. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7433. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7434. RemoveInstruction(hp1);
  7435. result:=true;
  7436. end;
  7437. end;
  7438. end;
  7439. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7440. var
  7441. hp1 : tai;
  7442. begin
  7443. result:=false;
  7444. { replace
  7445. IMul %reg0,%reg1,%reg2
  7446. Mov %reg2,%reg3
  7447. dealloc %reg2
  7448. by
  7449. Imul %reg0,%reg1,%reg3
  7450. }
  7451. if GetNextInstruction(p,hp1) and
  7452. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7453. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7454. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7455. begin
  7456. TransferUsedRegs(TmpUsedRegs);
  7457. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7458. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7459. begin
  7460. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7461. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7462. RemoveInstruction(hp1);
  7463. result:=true;
  7464. end;
  7465. end;
  7466. end;
  7467. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7468. var
  7469. hp1: tai;
  7470. begin
  7471. Result:=false;
  7472. { get rid of
  7473. (v)cvtss2sd reg0,<reg1,>reg2
  7474. (v)cvtss2sd reg2,<reg2,>reg0
  7475. }
  7476. if GetNextInstruction(p,hp1) and
  7477. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7478. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7479. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7480. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7481. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7482. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7483. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7484. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7485. )
  7486. ) then
  7487. begin
  7488. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7489. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7490. begin
  7491. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7492. RemoveCurrentP(p);
  7493. RemoveInstruction(hp1);
  7494. end
  7495. else
  7496. begin
  7497. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7498. if taicpu(hp1).opcode=A_CVTSD2SS then
  7499. begin
  7500. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7501. taicpu(p).opcode:=A_MOVAPS;
  7502. end
  7503. else
  7504. begin
  7505. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7506. taicpu(p).opcode:=A_VMOVAPS;
  7507. end;
  7508. taicpu(p).ops:=2;
  7509. RemoveInstruction(hp1);
  7510. end;
  7511. Result:=true;
  7512. Exit;
  7513. end;
  7514. end;
  7515. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7516. var
  7517. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7518. ThisReg: TRegister;
  7519. begin
  7520. Result := False;
  7521. if not GetNextInstruction(p,hp1) then
  7522. Exit;
  7523. {
  7524. convert
  7525. j<c> .L1
  7526. mov 1,reg
  7527. jmp .L2
  7528. .L1
  7529. mov 0,reg
  7530. .L2
  7531. into
  7532. mov 0,reg
  7533. set<not(c)> reg
  7534. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7535. would destroy the flag contents
  7536. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7537. executed at the same time as a previous comparison.
  7538. set<not(c)> reg
  7539. movzx reg, reg
  7540. }
  7541. if MatchInstruction(hp1,A_MOV,[]) and
  7542. (taicpu(hp1).oper[0]^.typ = top_const) and
  7543. (
  7544. (
  7545. (taicpu(hp1).oper[1]^.typ = top_reg)
  7546. {$ifdef i386}
  7547. { Under i386, ESI, EDI, EBP and ESP
  7548. don't have an 8-bit representation }
  7549. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7550. {$endif i386}
  7551. ) or (
  7552. {$ifdef i386}
  7553. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7554. {$endif i386}
  7555. (taicpu(hp1).opsize = S_B)
  7556. )
  7557. ) and
  7558. GetNextInstruction(hp1,hp2) and
  7559. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7560. GetNextInstruction(hp2,hp3) and
  7561. SkipAligns(hp3, hp3) and
  7562. (hp3.typ=ait_label) and
  7563. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7564. GetNextInstruction(hp3,hp4) and
  7565. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7566. (taicpu(hp4).oper[0]^.typ = top_const) and
  7567. (
  7568. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7569. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7570. ) and
  7571. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7572. GetNextInstruction(hp4,hp5) and
  7573. SkipAligns(hp5, hp5) and
  7574. (hp5.typ=ait_label) and
  7575. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7576. begin
  7577. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7578. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7579. tai_label(hp3).labsym.DecRefs;
  7580. { If this isn't the only reference to the middle label, we can
  7581. still make a saving - only that the first jump and everything
  7582. that follows will remain. }
  7583. if (tai_label(hp3).labsym.getrefs = 0) then
  7584. begin
  7585. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7586. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7587. else
  7588. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7589. { remove jump, first label and second MOV (also catching any aligns) }
  7590. repeat
  7591. if not GetNextInstruction(hp2, hp3) then
  7592. InternalError(2021040810);
  7593. RemoveInstruction(hp2);
  7594. hp2 := hp3;
  7595. until hp2 = hp5;
  7596. { Don't decrement reference count before the removal loop
  7597. above, otherwise GetNextInstruction won't stop on the
  7598. the label }
  7599. tai_label(hp5).labsym.DecRefs;
  7600. end
  7601. else
  7602. begin
  7603. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7604. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7605. else
  7606. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7607. end;
  7608. taicpu(p).opcode:=A_SETcc;
  7609. taicpu(p).opsize:=S_B;
  7610. taicpu(p).is_jmp:=False;
  7611. if taicpu(hp1).opsize=S_B then
  7612. begin
  7613. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7614. if taicpu(hp1).oper[1]^.typ = top_reg then
  7615. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7616. RemoveInstruction(hp1);
  7617. end
  7618. else
  7619. begin
  7620. { Will be a register because the size can't be S_B otherwise }
  7621. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7622. taicpu(p).loadreg(0, ThisReg);
  7623. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7624. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7625. begin
  7626. case taicpu(hp1).opsize of
  7627. S_W:
  7628. taicpu(hp1).opsize := S_BW;
  7629. S_L:
  7630. taicpu(hp1).opsize := S_BL;
  7631. {$ifdef x86_64}
  7632. S_Q:
  7633. begin
  7634. taicpu(hp1).opsize := S_BL;
  7635. { Change the destination register to 32-bit }
  7636. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7637. end;
  7638. {$endif x86_64}
  7639. else
  7640. InternalError(2021040820);
  7641. end;
  7642. taicpu(hp1).opcode := A_MOVZX;
  7643. taicpu(hp1).loadreg(0, ThisReg);
  7644. end
  7645. else
  7646. begin
  7647. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7648. { hp1 is already a MOV instruction with the correct register }
  7649. taicpu(hp1).loadconst(0, 0);
  7650. { Inserting it right before p will guarantee that the flags are also tracked }
  7651. asml.Remove(hp1);
  7652. asml.InsertBefore(hp1, p);
  7653. end;
  7654. end;
  7655. Result:=true;
  7656. exit;
  7657. end
  7658. else if (hp1.typ = ait_label) then
  7659. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7660. end;
  7661. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7662. var
  7663. hp1, hp2, hp3: tai;
  7664. SourceRef, TargetRef: TReference;
  7665. CurrentReg: TRegister;
  7666. begin
  7667. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7668. if not UseAVX then
  7669. InternalError(2021100501);
  7670. Result := False;
  7671. { Look for the following to simplify:
  7672. vmovdqa/u x(mem1), %xmmreg
  7673. vmovdqa/u %xmmreg, y(mem2)
  7674. vmovdqa/u x+16(mem1), %xmmreg
  7675. vmovdqa/u %xmmreg, y+16(mem2)
  7676. Change to:
  7677. vmovdqa/u x(mem1), %ymmreg
  7678. vmovdqa/u %ymmreg, y(mem2)
  7679. vpxor %ymmreg, %ymmreg, %ymmreg
  7680. ( The VPXOR instruction is to zero the upper half, thus removing the
  7681. need to call the potentially expensive VZEROUPPER instruction. Other
  7682. peephole optimisations can remove VPXOR if it's unnecessary )
  7683. }
  7684. TransferUsedRegs(TmpUsedRegs);
  7685. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7686. { NOTE: In the optimisations below, if the references dictate that an
  7687. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7688. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7689. if (taicpu(p).opsize = S_XMM) and
  7690. MatchOpType(taicpu(p), top_ref, top_reg) and
  7691. GetNextInstruction(p, hp1) and
  7692. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7693. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7694. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7695. begin
  7696. SourceRef := taicpu(p).oper[0]^.ref^;
  7697. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7698. if GetNextInstruction(hp1, hp2) and
  7699. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7700. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7701. begin
  7702. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7703. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7704. Inc(SourceRef.offset, 16);
  7705. { Reuse the register in the first block move }
  7706. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7707. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7708. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7709. begin
  7710. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7711. Inc(TargetRef.offset, 16);
  7712. if GetNextInstruction(hp2, hp3) and
  7713. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7714. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7715. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7716. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7717. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7718. begin
  7719. { Update the register tracking to the new size }
  7720. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7721. { Remember that the offsets are 16 ahead }
  7722. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7723. if not (
  7724. ((SourceRef.offset mod 32) = 16) and
  7725. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7726. ) then
  7727. taicpu(p).opcode := A_VMOVDQU;
  7728. taicpu(p).opsize := S_YMM;
  7729. taicpu(p).oper[1]^.reg := CurrentReg;
  7730. if not (
  7731. ((TargetRef.offset mod 32) = 16) and
  7732. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7733. ) then
  7734. taicpu(hp1).opcode := A_VMOVDQU;
  7735. taicpu(hp1).opsize := S_YMM;
  7736. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7737. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7738. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7739. if (pi_uses_ymm in current_procinfo.flags) then
  7740. RemoveInstruction(hp2)
  7741. else
  7742. begin
  7743. taicpu(hp2).opcode := A_VPXOR;
  7744. taicpu(hp2).opsize := S_YMM;
  7745. taicpu(hp2).loadreg(0, CurrentReg);
  7746. taicpu(hp2).loadreg(1, CurrentReg);
  7747. taicpu(hp2).loadreg(2, CurrentReg);
  7748. taicpu(hp2).ops := 3;
  7749. end;
  7750. RemoveInstruction(hp3);
  7751. Result := True;
  7752. Exit;
  7753. end;
  7754. end
  7755. else
  7756. begin
  7757. { See if the next references are 16 less rather than 16 greater }
  7758. Dec(SourceRef.offset, 32); { -16 the other way }
  7759. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7760. begin
  7761. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7762. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7763. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7764. GetNextInstruction(hp2, hp3) and
  7765. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7766. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7767. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7768. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7769. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7770. begin
  7771. { Update the register tracking to the new size }
  7772. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7773. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7774. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7775. if not(
  7776. ((SourceRef.offset mod 32) = 0) and
  7777. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7778. ) then
  7779. taicpu(hp2).opcode := A_VMOVDQU;
  7780. taicpu(hp2).opsize := S_YMM;
  7781. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7782. if not (
  7783. ((TargetRef.offset mod 32) = 0) and
  7784. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7785. ) then
  7786. taicpu(hp3).opcode := A_VMOVDQU;
  7787. taicpu(hp3).opsize := S_YMM;
  7788. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7789. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7790. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7791. if (pi_uses_ymm in current_procinfo.flags) then
  7792. RemoveInstruction(hp1)
  7793. else
  7794. begin
  7795. taicpu(hp1).opcode := A_VPXOR;
  7796. taicpu(hp1).opsize := S_YMM;
  7797. taicpu(hp1).loadreg(0, CurrentReg);
  7798. taicpu(hp1).loadreg(1, CurrentReg);
  7799. taicpu(hp1).loadreg(2, CurrentReg);
  7800. taicpu(hp1).ops := 3;
  7801. Asml.Remove(hp1);
  7802. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7803. end;
  7804. RemoveCurrentP(p, hp2);
  7805. Result := True;
  7806. Exit;
  7807. end;
  7808. end;
  7809. end;
  7810. end;
  7811. end;
  7812. end;
  7813. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7814. var
  7815. hp2, hp3, first_assignment: tai;
  7816. IncCount, OperIdx: Integer;
  7817. OrigLabel: TAsmLabel;
  7818. begin
  7819. Count := 0;
  7820. Result := False;
  7821. first_assignment := nil;
  7822. if (LoopCount >= 20) then
  7823. begin
  7824. { Guard against infinite loops }
  7825. Exit;
  7826. end;
  7827. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7828. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7829. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7830. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7831. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7832. Exit;
  7833. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7834. {
  7835. change
  7836. jmp .L1
  7837. ...
  7838. .L1:
  7839. mov ##, ## ( multiple movs possible )
  7840. jmp/ret
  7841. into
  7842. mov ##, ##
  7843. jmp/ret
  7844. }
  7845. if not Assigned(hp1) then
  7846. begin
  7847. hp1 := GetLabelWithSym(OrigLabel);
  7848. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7849. Exit;
  7850. end;
  7851. hp2 := hp1;
  7852. while Assigned(hp2) do
  7853. begin
  7854. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7855. SkipLabels(hp2,hp2);
  7856. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7857. Break;
  7858. case taicpu(hp2).opcode of
  7859. A_MOVSD:
  7860. begin
  7861. if taicpu(hp2).ops = 0 then
  7862. { Wrong MOVSD }
  7863. Break;
  7864. Inc(Count);
  7865. if Count >= 5 then
  7866. { Too many to be worthwhile }
  7867. Break;
  7868. GetNextInstruction(hp2, hp2);
  7869. Continue;
  7870. end;
  7871. A_MOV,
  7872. A_MOVD,
  7873. A_MOVQ,
  7874. A_MOVSX,
  7875. {$ifdef x86_64}
  7876. A_MOVSXD,
  7877. {$endif x86_64}
  7878. A_MOVZX,
  7879. A_MOVAPS,
  7880. A_MOVUPS,
  7881. A_MOVSS,
  7882. A_MOVAPD,
  7883. A_MOVUPD,
  7884. A_MOVDQA,
  7885. A_MOVDQU,
  7886. A_VMOVSS,
  7887. A_VMOVAPS,
  7888. A_VMOVUPS,
  7889. A_VMOVSD,
  7890. A_VMOVAPD,
  7891. A_VMOVUPD,
  7892. A_VMOVDQA,
  7893. A_VMOVDQU:
  7894. begin
  7895. Inc(Count);
  7896. if Count >= 5 then
  7897. { Too many to be worthwhile }
  7898. Break;
  7899. GetNextInstruction(hp2, hp2);
  7900. Continue;
  7901. end;
  7902. A_JMP:
  7903. begin
  7904. { Guard against infinite loops }
  7905. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7906. Exit;
  7907. { Analyse this jump first in case it also duplicates assignments }
  7908. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7909. begin
  7910. { Something did change! }
  7911. Result := True;
  7912. Inc(Count, IncCount);
  7913. if Count >= 5 then
  7914. begin
  7915. { Too many to be worthwhile }
  7916. Exit;
  7917. end;
  7918. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7919. Break;
  7920. end;
  7921. Result := True;
  7922. Break;
  7923. end;
  7924. A_RET:
  7925. begin
  7926. Result := True;
  7927. Break;
  7928. end;
  7929. else
  7930. Break;
  7931. end;
  7932. end;
  7933. if Result then
  7934. begin
  7935. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7936. if Count = 0 then
  7937. begin
  7938. Result := False;
  7939. Exit;
  7940. end;
  7941. hp3 := p;
  7942. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7943. while True do
  7944. begin
  7945. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7946. SkipLabels(hp1,hp1);
  7947. if (hp1.typ <> ait_instruction) then
  7948. InternalError(2021040720);
  7949. case taicpu(hp1).opcode of
  7950. A_JMP:
  7951. begin
  7952. { Change the original jump to the new destination }
  7953. OrigLabel.decrefs;
  7954. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7955. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7956. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7957. if not Assigned(first_assignment) then
  7958. InternalError(2021040810)
  7959. else
  7960. p := first_assignment;
  7961. Exit;
  7962. end;
  7963. A_RET:
  7964. begin
  7965. { Now change the jump into a RET instruction }
  7966. ConvertJumpToRET(p, hp1);
  7967. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7968. if not Assigned(first_assignment) then
  7969. InternalError(2021040811)
  7970. else
  7971. p := first_assignment;
  7972. Exit;
  7973. end;
  7974. else
  7975. begin
  7976. { Duplicate the MOV instruction }
  7977. hp3:=tai(hp1.getcopy);
  7978. if first_assignment = nil then
  7979. first_assignment := hp3;
  7980. asml.InsertBefore(hp3, p);
  7981. { Make sure the compiler knows about any final registers written here }
  7982. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7983. with taicpu(hp3).oper[OperIdx]^ do
  7984. begin
  7985. case typ of
  7986. top_ref:
  7987. begin
  7988. if (ref^.base <> NR_NO) and
  7989. (getsupreg(ref^.base) <> RS_ESP) and
  7990. (getsupreg(ref^.base) <> RS_EBP)
  7991. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7992. then
  7993. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7994. if (ref^.index <> NR_NO) and
  7995. (getsupreg(ref^.index) <> RS_ESP) and
  7996. (getsupreg(ref^.index) <> RS_EBP)
  7997. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7998. (ref^.index <> ref^.base) then
  7999. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8000. end;
  8001. top_reg:
  8002. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8003. else
  8004. ;
  8005. end;
  8006. end;
  8007. end;
  8008. end;
  8009. if not GetNextInstruction(hp1, hp1) then
  8010. { Should have dropped out earlier }
  8011. InternalError(2021040710);
  8012. end;
  8013. end;
  8014. end;
  8015. const
  8016. WriteOp: array[0..3] of set of TInsChange = (
  8017. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8018. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8019. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8020. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8021. RegWriteFlags: array[0..7] of set of TInsChange = (
  8022. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8023. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8024. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8025. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8026. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8027. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8028. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8029. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8030. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8031. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8032. var
  8033. hp2: tai;
  8034. X: Integer;
  8035. begin
  8036. { If we have something like:
  8037. op ###,###
  8038. mov ###,###
  8039. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8040. interfere in regards to what they write to.
  8041. NOTE: p must be a 2-operand instruction
  8042. }
  8043. Result := False;
  8044. if (hp1.typ <> ait_instruction) or
  8045. taicpu(hp1).is_jmp or
  8046. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8047. Exit;
  8048. { NOP is a pipeline fence, likely marking the beginning of the function
  8049. epilogue, so drop out. Similarly, drop out if POP or RET are
  8050. encountered }
  8051. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8052. Exit;
  8053. if (taicpu(hp1).opcode = A_MOVSD) and
  8054. (taicpu(hp1).ops = 0) then
  8055. { Wrong MOVSD }
  8056. Exit;
  8057. { Check for writes to specific registers first }
  8058. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8059. for X := 0 to 7 do
  8060. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8061. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8062. Exit;
  8063. for X := 0 to taicpu(hp1).ops - 1 do
  8064. begin
  8065. { Check to see if this operand writes to something }
  8066. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8067. { And matches something in the CMP/TEST instruction }
  8068. (
  8069. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8070. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8071. (
  8072. { If it's a register, make sure the register written to doesn't
  8073. appear in the cmp instruction as part of a reference }
  8074. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8075. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8076. )
  8077. ) then
  8078. Exit;
  8079. end;
  8080. { Check p to make sure it doesn't write to something that affects hp1 }
  8081. { Check for writes to specific registers first }
  8082. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8083. for X := 0 to 7 do
  8084. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8085. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8086. Exit;
  8087. for X := 0 to taicpu(p).ops - 1 do
  8088. begin
  8089. { Check to see if this operand writes to something }
  8090. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8091. { And matches something in hp1 }
  8092. (taicpu(p).oper[X]^.typ = top_reg) and
  8093. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8094. Exit;
  8095. end;
  8096. { The instruction can be safely moved }
  8097. asml.Remove(hp1);
  8098. { Try to insert after the last instructions where the FLAGS register is not
  8099. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8100. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8101. asml.InsertBefore(hp1, hp2)
  8102. { Failing that, try to insert after the last instructions where the
  8103. FLAGS register is not yet in use }
  8104. else if GetLastInstruction(p, hp2) and
  8105. (
  8106. (hp2.typ <> ait_instruction) or
  8107. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8108. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8109. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8110. ) then
  8111. asml.InsertAfter(hp1, hp2)
  8112. else
  8113. { Note, if p.Previous is nil (even if it should logically never be the
  8114. case), FindRegAllocBackward immediately exits with False and so we
  8115. safely land here (we can't just pass p because FindRegAllocBackward
  8116. immediately exits on an instruction). [Kit] }
  8117. asml.InsertBefore(hp1, p);
  8118. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8119. { We can't trust UsedRegs because we're looking backwards, although we
  8120. know the registers are allocated after p at the very least, so manually
  8121. create tai_regalloc objects if needed }
  8122. for X := 0 to taicpu(hp1).ops - 1 do
  8123. case taicpu(hp1).oper[X]^.typ of
  8124. top_reg:
  8125. begin
  8126. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8127. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8128. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8129. end;
  8130. top_ref:
  8131. begin
  8132. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8133. begin
  8134. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8135. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8136. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8137. end;
  8138. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8139. begin
  8140. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8141. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8142. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8143. end;
  8144. end;
  8145. else
  8146. ;
  8147. end;
  8148. Result := True;
  8149. end;
  8150. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8151. var
  8152. hp2: tai;
  8153. X: Integer;
  8154. begin
  8155. { If we have something like:
  8156. cmp ###,%reg1
  8157. mov 0,%reg2
  8158. And no modified registers are shared, move the instruction to before
  8159. the comparison as this means it can be optimised without worrying
  8160. about the FLAGS register. (CMP/MOV is generated by
  8161. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8162. As long as the second instruction doesn't use the flags or one of the
  8163. registers used by CMP or TEST (also check any references that use the
  8164. registers), then it can be moved prior to the comparison.
  8165. }
  8166. Result := False;
  8167. if not TrySwapMovOp(p, hp1) then
  8168. Exit;
  8169. if taicpu(hp1).opcode = A_LEA then
  8170. { The flags will be overwritten by the CMP/TEST instruction }
  8171. ConvertLEA(taicpu(hp1));
  8172. Result := True;
  8173. { Can we move it one further back? }
  8174. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8175. { Check to see if CMP/TEST is a comparison against zero }
  8176. (
  8177. (
  8178. (taicpu(p).opcode = A_CMP) and
  8179. MatchOperand(taicpu(p).oper[0]^, 0)
  8180. ) or
  8181. (
  8182. (taicpu(p).opcode = A_TEST) and
  8183. (
  8184. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8185. MatchOperand(taicpu(p).oper[0]^, -1)
  8186. )
  8187. )
  8188. ) and
  8189. { These instructions set the zero flag if the result is zero }
  8190. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8191. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8192. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8193. TrySwapMovOp(hp2, hp1);
  8194. end;
  8195. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8196. function IsXCHGAcceptable: Boolean; inline;
  8197. begin
  8198. { Always accept if optimising for size }
  8199. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8200. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8201. than 3, so it becomes a saving compared to three MOVs with two of
  8202. them able to execute simultaneously. [Kit] }
  8203. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8204. end;
  8205. var
  8206. NewRef: TReference;
  8207. hp1, hp2, hp3, hp4: Tai;
  8208. {$ifndef x86_64}
  8209. OperIdx: Integer;
  8210. {$endif x86_64}
  8211. NewInstr : Taicpu;
  8212. NewAligh : Tai_align;
  8213. DestLabel: TAsmLabel;
  8214. TempTracking: TAllUsedRegs;
  8215. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8216. var
  8217. NextInstr: tai;
  8218. begin
  8219. Result := False;
  8220. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8221. if not GetNextInstruction(InputInstr, NextInstr) or
  8222. (
  8223. { The FLAGS register isn't always tracked properly, so do not
  8224. perform this optimisation if a conditional statement follows }
  8225. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8226. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8227. ) then
  8228. begin
  8229. reference_reset(NewRef, 1, []);
  8230. NewRef.base := taicpu(p).oper[0]^.reg;
  8231. NewRef.scalefactor := 1;
  8232. if taicpu(InputInstr).opcode = A_ADD then
  8233. begin
  8234. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8235. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8236. end
  8237. else
  8238. begin
  8239. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8240. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8241. end;
  8242. taicpu(p).opcode := A_LEA;
  8243. taicpu(p).loadref(0, NewRef);
  8244. RemoveInstruction(InputInstr);
  8245. Result := True;
  8246. end;
  8247. end;
  8248. begin
  8249. Result:=false;
  8250. { This optimisation adds an instruction, so only do it for speed }
  8251. if not (cs_opt_size in current_settings.optimizerswitches) and
  8252. MatchOpType(taicpu(p), top_const, top_reg) and
  8253. (taicpu(p).oper[0]^.val = 0) then
  8254. begin
  8255. { To avoid compiler warning }
  8256. DestLabel := nil;
  8257. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8258. InternalError(2021040750);
  8259. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8260. Exit;
  8261. case hp1.typ of
  8262. ait_align,
  8263. ait_label:
  8264. begin
  8265. { Change:
  8266. mov $0,%reg mov $0,%reg
  8267. @Lbl1: @Lbl1:
  8268. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8269. je @Lbl2 jne @Lbl2
  8270. To: To:
  8271. mov $0,%reg mov $0,%reg
  8272. jmp @Lbl2 jmp @Lbl3
  8273. (align) (align)
  8274. @Lbl1: @Lbl1:
  8275. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8276. je @Lbl2 je @Lbl2
  8277. @Lbl3: <-- Only if label exists
  8278. (Not if it's optimised for size)
  8279. }
  8280. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8281. Exit;
  8282. if (hp2.typ = ait_instruction) and
  8283. (
  8284. { Register sizes must exactly match }
  8285. (
  8286. (taicpu(hp2).opcode = A_CMP) and
  8287. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8288. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8289. ) or (
  8290. (taicpu(hp2).opcode = A_TEST) and
  8291. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8292. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8293. )
  8294. ) and GetNextInstruction(hp2, hp3) and
  8295. (hp3.typ = ait_instruction) and
  8296. (taicpu(hp3).opcode = A_JCC) and
  8297. (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
  8298. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8299. begin
  8300. { Check condition of jump }
  8301. { Always true? }
  8302. if condition_in(C_E, taicpu(hp3).condition) then
  8303. begin
  8304. { Copy label symbol and obtain matching label entry for the
  8305. conditional jump, as this will be our destination}
  8306. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8307. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8308. Result := True;
  8309. end
  8310. { Always false? }
  8311. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8312. begin
  8313. { This is only worth it if there's a jump to take }
  8314. case hp2.typ of
  8315. ait_instruction:
  8316. begin
  8317. if taicpu(hp2).opcode = A_JMP then
  8318. begin
  8319. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8320. { An unconditional jump follows the conditional jump which will always be false,
  8321. so use this jump's destination for the new jump }
  8322. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8323. Result := True;
  8324. end
  8325. else if taicpu(hp2).opcode = A_JCC then
  8326. begin
  8327. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8328. if condition_in(C_E, taicpu(hp2).condition) then
  8329. begin
  8330. { A second conditional jump follows the conditional jump which will always be false,
  8331. while the second jump is always True, so use this jump's destination for the new jump }
  8332. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8333. Result := True;
  8334. end;
  8335. { Don't risk it if the jump isn't always true (Result remains False) }
  8336. end;
  8337. end;
  8338. else
  8339. { If anything else don't optimise };
  8340. end;
  8341. end;
  8342. if Result then
  8343. begin
  8344. { Just so we have something to insert as a paremeter}
  8345. reference_reset(NewRef, 1, []);
  8346. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8347. { Now actually load the correct parameter (this also
  8348. increases the reference count) }
  8349. NewInstr.loadsymbol(0, DestLabel, 0);
  8350. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8351. begin
  8352. { Get instruction before original label (may not be p under -O3) }
  8353. if not GetLastInstruction(hp1, hp2) then
  8354. { Shouldn't fail here }
  8355. InternalError(2021040701);
  8356. { Before the aligns too }
  8357. while (hp2.typ = ait_align) do
  8358. if not GetLastInstruction(hp2, hp2) then
  8359. { Shouldn't fail here }
  8360. InternalError(2021040702);
  8361. end
  8362. else
  8363. hp2 := p;
  8364. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8365. AsmL.InsertAfter(NewInstr, hp2);
  8366. { Add new alignment field }
  8367. (* AsmL.InsertAfter(
  8368. cai_align.create_max(
  8369. current_settings.alignment.jumpalign,
  8370. current_settings.alignment.jumpalignskipmax
  8371. ),
  8372. NewInstr
  8373. ); *)
  8374. end;
  8375. Exit;
  8376. end;
  8377. end;
  8378. else
  8379. ;
  8380. end;
  8381. end;
  8382. if not GetNextInstruction(p, hp1) then
  8383. Exit;
  8384. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8385. and DoMovCmpMemOpt(p, hp1, True) then
  8386. begin
  8387. Result := True;
  8388. Exit;
  8389. end
  8390. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8391. begin
  8392. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8393. further, but we can't just put this jump optimisation in pass 1
  8394. because it tends to perform worse when conditional jumps are
  8395. nearby (e.g. when converting CMOV instructions). [Kit] }
  8396. CopyUsedRegs(TempTracking);
  8397. UpdateUsedRegs(tai(p.Next));
  8398. if OptPass2JMP(hp1) then
  8399. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8400. Result := OptPass1MOV(p);
  8401. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8402. returned True and the instruction is still a MOV, thus checking
  8403. the optimisations below }
  8404. { If OptPass2JMP returned False, no optimisations were done to
  8405. the jump and there are no further optimisations that can be done
  8406. to the MOV instruction on this pass }
  8407. { Restore register state }
  8408. RestoreUsedRegs(TempTracking);
  8409. ReleaseUsedRegs(TempTracking);
  8410. end
  8411. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8412. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8413. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8414. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8415. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8416. begin
  8417. { Change:
  8418. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8419. addl/q $x,%reg2 subl/q $x,%reg2
  8420. To:
  8421. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8422. }
  8423. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8424. { be lazy, checking separately for sub would be slightly better }
  8425. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8426. begin
  8427. TransferUsedRegs(TmpUsedRegs);
  8428. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8429. if TryMovArith2Lea(hp1) then
  8430. begin
  8431. Result := True;
  8432. Exit;
  8433. end
  8434. end
  8435. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8436. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8437. { Same as above, but also adds or subtracts to %reg2 in between.
  8438. It's still valid as long as the flags aren't in use }
  8439. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8440. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8441. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8442. { be lazy, checking separately for sub would be slightly better }
  8443. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8444. begin
  8445. TransferUsedRegs(TmpUsedRegs);
  8446. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8447. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8448. if TryMovArith2Lea(hp2) then
  8449. begin
  8450. Result := True;
  8451. Exit;
  8452. end;
  8453. end;
  8454. end
  8455. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8456. {$ifdef x86_64}
  8457. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8458. {$else x86_64}
  8459. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8460. {$endif x86_64}
  8461. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8462. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8463. { mov reg1, reg2 mov reg1, reg2
  8464. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8465. begin
  8466. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8467. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8468. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8469. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8470. TransferUsedRegs(TmpUsedRegs);
  8471. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8472. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8473. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8474. then
  8475. begin
  8476. RemoveCurrentP(p, hp1);
  8477. Result:=true;
  8478. end;
  8479. exit;
  8480. end
  8481. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8482. IsXCHGAcceptable and
  8483. { XCHG doesn't support 8-byte registers }
  8484. (taicpu(p).opsize <> S_B) and
  8485. MatchInstruction(hp1, A_MOV, []) and
  8486. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8487. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8488. GetNextInstruction(hp1, hp2) and
  8489. MatchInstruction(hp2, A_MOV, []) and
  8490. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8491. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8492. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8493. begin
  8494. { mov %reg1,%reg2
  8495. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8496. mov %reg2,%reg3
  8497. (%reg2 not used afterwards)
  8498. Note that xchg takes 3 cycles to execute, and generally mov's take
  8499. only one cycle apiece, but the first two mov's can be executed in
  8500. parallel, only taking 2 cycles overall. Older processors should
  8501. therefore only optimise for size. [Kit]
  8502. }
  8503. TransferUsedRegs(TmpUsedRegs);
  8504. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8505. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8506. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8507. begin
  8508. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8509. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8510. taicpu(hp1).opcode := A_XCHG;
  8511. RemoveCurrentP(p, hp1);
  8512. RemoveInstruction(hp2);
  8513. Result := True;
  8514. Exit;
  8515. end;
  8516. end
  8517. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8518. MatchInstruction(hp1, A_SAR, []) then
  8519. begin
  8520. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8521. begin
  8522. { the use of %edx also covers the opsize being S_L }
  8523. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8524. begin
  8525. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8526. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8527. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8528. begin
  8529. { Change:
  8530. movl %eax,%edx
  8531. sarl $31,%edx
  8532. To:
  8533. cltd
  8534. }
  8535. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8536. RemoveInstruction(hp1);
  8537. taicpu(p).opcode := A_CDQ;
  8538. taicpu(p).opsize := S_NO;
  8539. taicpu(p).clearop(1);
  8540. taicpu(p).clearop(0);
  8541. taicpu(p).ops:=0;
  8542. Result := True;
  8543. end
  8544. else if (cs_opt_size in current_settings.optimizerswitches) and
  8545. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8546. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8547. begin
  8548. { Change:
  8549. movl %edx,%eax
  8550. sarl $31,%edx
  8551. To:
  8552. movl %edx,%eax
  8553. cltd
  8554. Note that this creates a dependency between the two instructions,
  8555. so only perform if optimising for size.
  8556. }
  8557. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8558. taicpu(hp1).opcode := A_CDQ;
  8559. taicpu(hp1).opsize := S_NO;
  8560. taicpu(hp1).clearop(1);
  8561. taicpu(hp1).clearop(0);
  8562. taicpu(hp1).ops:=0;
  8563. end;
  8564. {$ifndef x86_64}
  8565. end
  8566. { Don't bother if CMOV is supported, because a more optimal
  8567. sequence would have been generated for the Abs() intrinsic }
  8568. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8569. { the use of %eax also covers the opsize being S_L }
  8570. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8571. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8572. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8573. GetNextInstruction(hp1, hp2) and
  8574. MatchInstruction(hp2, A_XOR, [S_L]) and
  8575. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8576. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8577. GetNextInstruction(hp2, hp3) and
  8578. MatchInstruction(hp3, A_SUB, [S_L]) and
  8579. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8580. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8581. begin
  8582. { Change:
  8583. movl %eax,%edx
  8584. sarl $31,%eax
  8585. xorl %eax,%edx
  8586. subl %eax,%edx
  8587. (Instruction that uses %edx)
  8588. (%eax deallocated)
  8589. (%edx deallocated)
  8590. To:
  8591. cltd
  8592. xorl %edx,%eax <-- Note the registers have swapped
  8593. subl %edx,%eax
  8594. (Instruction that uses %eax) <-- %eax rather than %edx
  8595. }
  8596. TransferUsedRegs(TmpUsedRegs);
  8597. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8598. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8599. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8600. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8601. begin
  8602. if GetNextInstruction(hp3, hp4) and
  8603. not RegModifiedByInstruction(NR_EDX, hp4) and
  8604. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8605. begin
  8606. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8607. taicpu(p).opcode := A_CDQ;
  8608. taicpu(p).clearop(1);
  8609. taicpu(p).clearop(0);
  8610. taicpu(p).ops:=0;
  8611. RemoveInstruction(hp1);
  8612. taicpu(hp2).loadreg(0, NR_EDX);
  8613. taicpu(hp2).loadreg(1, NR_EAX);
  8614. taicpu(hp3).loadreg(0, NR_EDX);
  8615. taicpu(hp3).loadreg(1, NR_EAX);
  8616. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8617. { Convert references in the following instruction (hp4) from %edx to %eax }
  8618. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8619. with taicpu(hp4).oper[OperIdx]^ do
  8620. case typ of
  8621. top_reg:
  8622. if getsupreg(reg) = RS_EDX then
  8623. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8624. top_ref:
  8625. begin
  8626. if getsupreg(reg) = RS_EDX then
  8627. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8628. if getsupreg(reg) = RS_EDX then
  8629. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8630. end;
  8631. else
  8632. ;
  8633. end;
  8634. end;
  8635. end;
  8636. {$else x86_64}
  8637. end;
  8638. end
  8639. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8640. { the use of %rdx also covers the opsize being S_Q }
  8641. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8642. begin
  8643. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8644. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8645. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8646. begin
  8647. { Change:
  8648. movq %rax,%rdx
  8649. sarq $63,%rdx
  8650. To:
  8651. cqto
  8652. }
  8653. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8654. RemoveInstruction(hp1);
  8655. taicpu(p).opcode := A_CQO;
  8656. taicpu(p).opsize := S_NO;
  8657. taicpu(p).clearop(1);
  8658. taicpu(p).clearop(0);
  8659. taicpu(p).ops:=0;
  8660. Result := True;
  8661. end
  8662. else if (cs_opt_size in current_settings.optimizerswitches) and
  8663. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8664. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8665. begin
  8666. { Change:
  8667. movq %rdx,%rax
  8668. sarq $63,%rdx
  8669. To:
  8670. movq %rdx,%rax
  8671. cqto
  8672. Note that this creates a dependency between the two instructions,
  8673. so only perform if optimising for size.
  8674. }
  8675. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8676. taicpu(hp1).opcode := A_CQO;
  8677. taicpu(hp1).opsize := S_NO;
  8678. taicpu(hp1).clearop(1);
  8679. taicpu(hp1).clearop(0);
  8680. taicpu(hp1).ops:=0;
  8681. {$endif x86_64}
  8682. end;
  8683. end;
  8684. end
  8685. else if MatchInstruction(hp1, A_MOV, []) and
  8686. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8687. { Though "GetNextInstruction" could be factored out, along with
  8688. the instructions that depend on hp2, it is an expensive call that
  8689. should be delayed for as long as possible, hence we do cheaper
  8690. checks first that are likely to be False. [Kit] }
  8691. begin
  8692. if (
  8693. (
  8694. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8695. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8696. (
  8697. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8698. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8699. )
  8700. ) or
  8701. (
  8702. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8703. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8704. (
  8705. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8706. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8707. )
  8708. )
  8709. ) and
  8710. GetNextInstruction(hp1, hp2) and
  8711. MatchInstruction(hp2, A_SAR, []) and
  8712. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8713. begin
  8714. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8715. begin
  8716. { Change:
  8717. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8718. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8719. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8720. To:
  8721. movl r/m,%eax <- Note the change in register
  8722. cltd
  8723. }
  8724. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8725. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8726. taicpu(p).loadreg(1, NR_EAX);
  8727. taicpu(hp1).opcode := A_CDQ;
  8728. taicpu(hp1).clearop(1);
  8729. taicpu(hp1).clearop(0);
  8730. taicpu(hp1).ops:=0;
  8731. RemoveInstruction(hp2);
  8732. (*
  8733. {$ifdef x86_64}
  8734. end
  8735. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8736. { This code sequence does not get generated - however it might become useful
  8737. if and when 128-bit signed integer types make an appearance, so the code
  8738. is kept here for when it is eventually needed. [Kit] }
  8739. (
  8740. (
  8741. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8742. (
  8743. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8744. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8745. )
  8746. ) or
  8747. (
  8748. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8749. (
  8750. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8751. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8752. )
  8753. )
  8754. ) and
  8755. GetNextInstruction(hp1, hp2) and
  8756. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8757. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8758. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8759. begin
  8760. { Change:
  8761. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8762. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8763. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8764. To:
  8765. movq r/m,%rax <- Note the change in register
  8766. cqto
  8767. }
  8768. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8769. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8770. taicpu(p).loadreg(1, NR_RAX);
  8771. taicpu(hp1).opcode := A_CQO;
  8772. taicpu(hp1).clearop(1);
  8773. taicpu(hp1).clearop(0);
  8774. taicpu(hp1).ops:=0;
  8775. RemoveInstruction(hp2);
  8776. {$endif x86_64}
  8777. *)
  8778. end;
  8779. end;
  8780. {$ifdef x86_64}
  8781. end
  8782. else if (taicpu(p).opsize = S_L) and
  8783. (taicpu(p).oper[1]^.typ = top_reg) and
  8784. (
  8785. MatchInstruction(hp1, A_MOV,[]) and
  8786. (taicpu(hp1).opsize = S_L) and
  8787. (taicpu(hp1).oper[1]^.typ = top_reg)
  8788. ) and (
  8789. GetNextInstruction(hp1, hp2) and
  8790. (tai(hp2).typ=ait_instruction) and
  8791. (taicpu(hp2).opsize = S_Q) and
  8792. (
  8793. (
  8794. MatchInstruction(hp2, A_ADD,[]) and
  8795. (taicpu(hp2).opsize = S_Q) and
  8796. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8797. (
  8798. (
  8799. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8800. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8801. ) or (
  8802. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8803. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8804. )
  8805. )
  8806. ) or (
  8807. MatchInstruction(hp2, A_LEA,[]) and
  8808. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8809. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8810. (
  8811. (
  8812. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8813. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8814. ) or (
  8815. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8816. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8817. )
  8818. ) and (
  8819. (
  8820. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8821. ) or (
  8822. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8823. )
  8824. )
  8825. )
  8826. )
  8827. ) and (
  8828. GetNextInstruction(hp2, hp3) and
  8829. MatchInstruction(hp3, A_SHR,[]) and
  8830. (taicpu(hp3).opsize = S_Q) and
  8831. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8832. (taicpu(hp3).oper[0]^.val = 1) and
  8833. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8834. ) then
  8835. begin
  8836. { Change movl x, reg1d movl x, reg1d
  8837. movl y, reg2d movl y, reg2d
  8838. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8839. shrq $1, reg1q shrq $1, reg1q
  8840. ( reg1d and reg2d can be switched around in the first two instructions )
  8841. To movl x, reg1d
  8842. addl y, reg1d
  8843. rcrl $1, reg1d
  8844. This corresponds to the common expression (x + y) shr 1, where
  8845. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8846. smaller code, but won't account for x + y causing an overflow). [Kit]
  8847. }
  8848. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8849. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8850. { Change first MOV command to have the same register as the final output }
  8851. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8852. else
  8853. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8854. { Change second MOV command to an ADD command. This is easier than
  8855. converting the existing command because it means we don't have to
  8856. touch 'y', which might be a complicated reference, and also the
  8857. fact that the third command might either be ADD or LEA. [Kit] }
  8858. taicpu(hp1).opcode := A_ADD;
  8859. { Delete old ADD/LEA instruction }
  8860. RemoveInstruction(hp2);
  8861. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8862. taicpu(hp3).opcode := A_RCR;
  8863. taicpu(hp3).changeopsize(S_L);
  8864. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8865. {$endif x86_64}
  8866. end;
  8867. if FuncMov2Func(p, hp1) then
  8868. begin
  8869. Result := True;
  8870. Exit;
  8871. end;
  8872. end;
  8873. {$push}
  8874. {$q-}{$r-}
  8875. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8876. var
  8877. ThisReg: TRegister;
  8878. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8879. TargetSubReg: TSubRegister;
  8880. hp1, hp2: tai;
  8881. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8882. { Store list of found instructions so we don't have to call
  8883. GetNextInstructionUsingReg multiple times }
  8884. InstrList: array of taicpu;
  8885. InstrMax, Index: Integer;
  8886. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8887. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8888. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8889. WorkingValue: TCgInt;
  8890. PreMessage: string;
  8891. { Data flow analysis }
  8892. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8893. BitwiseOnly, OrXorUsed,
  8894. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8895. function CheckOverflowConditions: Boolean;
  8896. begin
  8897. Result := True;
  8898. if (TestValSignedMax > SignedUpperLimit) then
  8899. UpperSignedOverflow := True;
  8900. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8901. LowerSignedOverflow := True;
  8902. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8903. LowerUnsignedOverflow := True;
  8904. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8905. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8906. begin
  8907. { Absolute overflow }
  8908. Result := False;
  8909. Exit;
  8910. end;
  8911. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8912. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8913. ShiftDownOverflow := True;
  8914. if (TestValMin < 0) or (TestValMax < 0) then
  8915. begin
  8916. LowerUnsignedOverflow := True;
  8917. UpperUnsignedOverflow := True;
  8918. end;
  8919. end;
  8920. function AdjustInitialLoadAndSize: Boolean;
  8921. begin
  8922. Result := False;
  8923. if not p_removed then
  8924. begin
  8925. if TargetSize = MinSize then
  8926. begin
  8927. { Convert the input MOVZX to a MOV }
  8928. if (taicpu(p).oper[0]^.typ = top_reg) and
  8929. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8930. begin
  8931. { Or remove it completely! }
  8932. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8933. RemoveCurrentP(p);
  8934. p_removed := True;
  8935. end
  8936. else
  8937. begin
  8938. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8939. taicpu(p).opcode := A_MOV;
  8940. taicpu(p).oper[1]^.reg := ThisReg;
  8941. taicpu(p).opsize := TargetSize;
  8942. end;
  8943. Result := True;
  8944. end
  8945. else if TargetSize <> MaxSize then
  8946. begin
  8947. case MaxSize of
  8948. S_L:
  8949. if TargetSize = S_W then
  8950. begin
  8951. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8952. taicpu(p).opsize := S_BW;
  8953. taicpu(p).oper[1]^.reg := ThisReg;
  8954. Result := True;
  8955. end
  8956. else
  8957. InternalError(2020112341);
  8958. S_W:
  8959. if TargetSize = S_L then
  8960. begin
  8961. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8962. taicpu(p).opsize := S_BL;
  8963. taicpu(p).oper[1]^.reg := ThisReg;
  8964. Result := True;
  8965. end
  8966. else
  8967. InternalError(2020112342);
  8968. else
  8969. ;
  8970. end;
  8971. end
  8972. else if not hp1_removed and not RegInUse then
  8973. begin
  8974. { If we have something like:
  8975. movzbl (oper),%regd
  8976. add x, %regd
  8977. movzbl %regb, %regd
  8978. We can reduce the register size to the input of the final
  8979. movzbl instruction. Overflows won't have any effect.
  8980. }
  8981. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8982. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8983. begin
  8984. TargetSize := S_B;
  8985. setsubreg(ThisReg, R_SUBL);
  8986. Result := True;
  8987. end
  8988. else if (taicpu(p).opsize = S_WL) and
  8989. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8990. begin
  8991. TargetSize := S_W;
  8992. setsubreg(ThisReg, R_SUBW);
  8993. Result := True;
  8994. end;
  8995. if Result then
  8996. begin
  8997. { Convert the input MOVZX to a MOV }
  8998. if (taicpu(p).oper[0]^.typ = top_reg) and
  8999. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9000. begin
  9001. { Or remove it completely! }
  9002. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9003. RemoveCurrentP(p);
  9004. p_removed := True;
  9005. end
  9006. else
  9007. begin
  9008. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9009. taicpu(p).opcode := A_MOV;
  9010. taicpu(p).oper[1]^.reg := ThisReg;
  9011. taicpu(p).opsize := TargetSize;
  9012. end;
  9013. end;
  9014. end;
  9015. end;
  9016. end;
  9017. procedure AdjustFinalLoad;
  9018. begin
  9019. if not LowerUnsignedOverflow then
  9020. begin
  9021. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9022. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9023. begin
  9024. { Convert the output MOVZX to a MOV }
  9025. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9026. begin
  9027. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9028. if (MinSize = S_B) or
  9029. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9030. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9031. begin
  9032. { Remove it completely! }
  9033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9034. { Be careful; if p = hp1 and p was also removed, p
  9035. will become a dangling pointer }
  9036. if p = hp1 then
  9037. begin
  9038. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9039. p_removed := True;
  9040. end
  9041. else
  9042. RemoveInstruction(hp1);
  9043. hp1_removed := True;
  9044. end;
  9045. end
  9046. else
  9047. begin
  9048. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9049. taicpu(hp1).opcode := A_MOV;
  9050. taicpu(hp1).oper[0]^.reg := ThisReg;
  9051. taicpu(hp1).opsize := TargetSize;
  9052. end;
  9053. end
  9054. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9055. begin
  9056. { Need to change the size of the output }
  9057. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9058. taicpu(hp1).oper[0]^.reg := ThisReg;
  9059. taicpu(hp1).opsize := S_BL;
  9060. end;
  9061. end;
  9062. end;
  9063. function CompressInstructions: Boolean;
  9064. var
  9065. LocalIndex: Integer;
  9066. begin
  9067. Result := False;
  9068. { The objective here is to try to find a combination that
  9069. removes one of the MOV/Z instructions. }
  9070. if (
  9071. (taicpu(p).oper[0]^.typ <> top_reg) or
  9072. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9073. ) and
  9074. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9075. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9076. begin
  9077. { Make a preference to remove the second MOVZX instruction }
  9078. case taicpu(hp1).opsize of
  9079. S_BL, S_WL:
  9080. begin
  9081. TargetSize := S_L;
  9082. TargetSubReg := R_SUBD;
  9083. end;
  9084. S_BW:
  9085. begin
  9086. TargetSize := S_W;
  9087. TargetSubReg := R_SUBW;
  9088. end;
  9089. else
  9090. InternalError(2020112302);
  9091. end;
  9092. end
  9093. else
  9094. begin
  9095. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9096. begin
  9097. { Exceeded lower bound but not upper bound }
  9098. TargetSize := MaxSize;
  9099. end
  9100. else if not LowerUnsignedOverflow then
  9101. begin
  9102. { Size didn't exceed lower bound }
  9103. TargetSize := MinSize;
  9104. end
  9105. else
  9106. Exit;
  9107. end;
  9108. case TargetSize of
  9109. S_B:
  9110. TargetSubReg := R_SUBL;
  9111. S_W:
  9112. TargetSubReg := R_SUBW;
  9113. S_L:
  9114. TargetSubReg := R_SUBD;
  9115. else
  9116. InternalError(2020112350);
  9117. end;
  9118. { Update the register to its new size }
  9119. setsubreg(ThisReg, TargetSubReg);
  9120. RegInUse := False;
  9121. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9122. begin
  9123. { Check to see if the active register is used afterwards;
  9124. if not, we can change it and make a saving. }
  9125. TransferUsedRegs(TmpUsedRegs);
  9126. { The target register may be marked as in use to cross
  9127. a jump to a distant label, so exclude it }
  9128. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9129. hp2 := p;
  9130. repeat
  9131. { Explicitly check for the excluded register (don't include the first
  9132. instruction as it may be reading from here }
  9133. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9134. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9135. begin
  9136. RegInUse := True;
  9137. Break;
  9138. end;
  9139. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9140. if not GetNextInstruction(hp2, hp2) then
  9141. InternalError(2020112340);
  9142. until (hp2 = hp1);
  9143. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9144. { We might still be able to get away with this }
  9145. RegInUse := not
  9146. (
  9147. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9148. (hp2.typ = ait_instruction) and
  9149. (
  9150. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9151. instruction that doesn't actually contain ThisReg }
  9152. (cs_opt_level3 in current_settings.optimizerswitches) or
  9153. RegInInstruction(ThisReg, hp2)
  9154. ) and
  9155. RegLoadedWithNewValue(ThisReg, hp2)
  9156. );
  9157. if not RegInUse then
  9158. begin
  9159. { Force the register size to the same as this instruction so it can be removed}
  9160. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9161. begin
  9162. TargetSize := S_L;
  9163. TargetSubReg := R_SUBD;
  9164. end
  9165. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9166. begin
  9167. TargetSize := S_W;
  9168. TargetSubReg := R_SUBW;
  9169. end;
  9170. ThisReg := taicpu(hp1).oper[1]^.reg;
  9171. setsubreg(ThisReg, TargetSubReg);
  9172. RegChanged := True;
  9173. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9174. TransferUsedRegs(TmpUsedRegs);
  9175. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9176. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9177. if p = hp1 then
  9178. begin
  9179. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9180. p_removed := True;
  9181. end
  9182. else
  9183. RemoveInstruction(hp1);
  9184. hp1_removed := True;
  9185. { Instruction will become "mov %reg,%reg" }
  9186. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9187. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9188. begin
  9189. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9190. RemoveCurrentP(p);
  9191. p_removed := True;
  9192. end
  9193. else
  9194. taicpu(p).oper[1]^.reg := ThisReg;
  9195. Result := True;
  9196. end
  9197. else
  9198. begin
  9199. if TargetSize <> MaxSize then
  9200. begin
  9201. { Since the register is in use, we have to force it to
  9202. MaxSize otherwise part of it may become undefined later on }
  9203. TargetSize := MaxSize;
  9204. case TargetSize of
  9205. S_B:
  9206. TargetSubReg := R_SUBL;
  9207. S_W:
  9208. TargetSubReg := R_SUBW;
  9209. S_L:
  9210. TargetSubReg := R_SUBD;
  9211. else
  9212. InternalError(2020112351);
  9213. end;
  9214. setsubreg(ThisReg, TargetSubReg);
  9215. end;
  9216. AdjustFinalLoad;
  9217. end;
  9218. end
  9219. else
  9220. AdjustFinalLoad;
  9221. Result := AdjustInitialLoadAndSize or Result;
  9222. { Now go through every instruction we found and change the
  9223. size. If TargetSize = MaxSize, then almost no changes are
  9224. needed and Result can remain False if it hasn't been set
  9225. yet.
  9226. If RegChanged is True, then the register requires changing
  9227. and so the point about TargetSize = MaxSize doesn't apply. }
  9228. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9229. begin
  9230. for LocalIndex := 0 to InstrMax do
  9231. begin
  9232. { If p_removed is true, then the original MOV/Z was removed
  9233. and removing the AND instruction may not be safe if it
  9234. appears first }
  9235. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9236. InternalError(2020112310);
  9237. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9238. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9239. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9240. InstrList[LocalIndex].opsize := TargetSize;
  9241. end;
  9242. Result := True;
  9243. end;
  9244. end;
  9245. begin
  9246. Result := False;
  9247. p_removed := False;
  9248. hp1_removed := False;
  9249. ThisReg := taicpu(p).oper[1]^.reg;
  9250. { Check for:
  9251. movs/z ###,%ecx (or %cx or %rcx)
  9252. ...
  9253. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9254. (dealloc %ecx)
  9255. Change to:
  9256. mov ###,%cl (if ### = %cl, then remove completely)
  9257. ...
  9258. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9259. }
  9260. if (getsupreg(ThisReg) = RS_ECX) and
  9261. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9262. (hp1.typ = ait_instruction) and
  9263. (
  9264. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9265. instruction that doesn't actually contain ECX }
  9266. (cs_opt_level3 in current_settings.optimizerswitches) or
  9267. RegInInstruction(NR_ECX, hp1) or
  9268. (
  9269. { It's common for the shift/rotate's read/write register to be
  9270. initialised in between, so under -O2 and under, search ahead
  9271. one more instruction
  9272. }
  9273. GetNextInstruction(hp1, hp1) and
  9274. (hp1.typ = ait_instruction) and
  9275. RegInInstruction(NR_ECX, hp1)
  9276. )
  9277. ) and
  9278. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9279. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9280. begin
  9281. TransferUsedRegs(TmpUsedRegs);
  9282. hp2 := p;
  9283. repeat
  9284. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9285. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9286. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9287. begin
  9288. case taicpu(p).opsize of
  9289. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9290. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9291. begin
  9292. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9293. RemoveCurrentP(p);
  9294. end
  9295. else
  9296. begin
  9297. taicpu(p).opcode := A_MOV;
  9298. taicpu(p).opsize := S_B;
  9299. taicpu(p).oper[1]^.reg := NR_CL;
  9300. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9301. end;
  9302. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9303. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9304. begin
  9305. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9306. RemoveCurrentP(p);
  9307. end
  9308. else
  9309. begin
  9310. taicpu(p).opcode := A_MOV;
  9311. taicpu(p).opsize := S_W;
  9312. taicpu(p).oper[1]^.reg := NR_CX;
  9313. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9314. end;
  9315. {$ifdef x86_64}
  9316. S_LQ:
  9317. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9318. begin
  9319. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9320. RemoveCurrentP(p);
  9321. end
  9322. else
  9323. begin
  9324. taicpu(p).opcode := A_MOV;
  9325. taicpu(p).opsize := S_L;
  9326. taicpu(p).oper[1]^.reg := NR_ECX;
  9327. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9328. end;
  9329. {$endif x86_64}
  9330. else
  9331. InternalError(2021120401);
  9332. end;
  9333. Result := True;
  9334. Exit;
  9335. end;
  9336. end;
  9337. { This is anything but quick! }
  9338. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9339. Exit;
  9340. SetLength(InstrList, 0);
  9341. InstrMax := -1;
  9342. case taicpu(p).opsize of
  9343. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9344. begin
  9345. {$if defined(i386) or defined(i8086)}
  9346. { If the target size is 8-bit, make sure we can actually encode it }
  9347. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9348. Exit;
  9349. {$endif i386 or i8086}
  9350. LowerLimit := $FF;
  9351. SignedLowerLimit := $7F;
  9352. SignedLowerLimitBottom := -128;
  9353. MinSize := S_B;
  9354. if taicpu(p).opsize = S_BW then
  9355. begin
  9356. MaxSize := S_W;
  9357. UpperLimit := $FFFF;
  9358. SignedUpperLimit := $7FFF;
  9359. SignedUpperLimitBottom := -32768;
  9360. end
  9361. else
  9362. begin
  9363. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9364. MaxSize := S_L;
  9365. UpperLimit := $FFFFFFFF;
  9366. SignedUpperLimit := $7FFFFFFF;
  9367. SignedUpperLimitBottom := -2147483648;
  9368. end;
  9369. end;
  9370. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9371. begin
  9372. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9373. LowerLimit := $FFFF;
  9374. SignedLowerLimit := $7FFF;
  9375. SignedLowerLimitBottom := -32768;
  9376. UpperLimit := $FFFFFFFF;
  9377. SignedUpperLimit := $7FFFFFFF;
  9378. SignedUpperLimitBottom := -2147483648;
  9379. MinSize := S_W;
  9380. MaxSize := S_L;
  9381. end;
  9382. {$ifdef x86_64}
  9383. S_LQ:
  9384. begin
  9385. { Both the lower and upper limits are set to 32-bit. If a limit
  9386. is breached, then optimisation is impossible }
  9387. LowerLimit := $FFFFFFFF;
  9388. SignedLowerLimit := $7FFFFFFF;
  9389. SignedLowerLimitBottom := -2147483648;
  9390. UpperLimit := $FFFFFFFF;
  9391. SignedUpperLimit := $7FFFFFFF;
  9392. SignedUpperLimitBottom := -2147483648;
  9393. MinSize := S_L;
  9394. MaxSize := S_L;
  9395. end;
  9396. {$endif x86_64}
  9397. else
  9398. InternalError(2020112301);
  9399. end;
  9400. TestValMin := 0;
  9401. TestValMax := LowerLimit;
  9402. TestValSignedMax := SignedLowerLimit;
  9403. TryShiftDownLimit := LowerLimit;
  9404. TryShiftDown := S_NO;
  9405. ShiftDownOverflow := False;
  9406. RegChanged := False;
  9407. BitwiseOnly := True;
  9408. OrXorUsed := False;
  9409. UpperSignedOverflow := False;
  9410. LowerSignedOverflow := False;
  9411. UpperUnsignedOverflow := False;
  9412. LowerUnsignedOverflow := False;
  9413. hp1 := p;
  9414. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9415. (hp1.typ = ait_instruction) and
  9416. (
  9417. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9418. instruction that doesn't actually contain ThisReg }
  9419. (cs_opt_level3 in current_settings.optimizerswitches) or
  9420. { This allows this Movx optimisation to work through the SETcc instructions
  9421. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9422. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9423. skip over these SETcc instructions). }
  9424. (taicpu(hp1).opcode = A_SETcc) or
  9425. RegInInstruction(ThisReg, hp1)
  9426. ) do
  9427. begin
  9428. case taicpu(hp1).opcode of
  9429. A_INC,A_DEC:
  9430. begin
  9431. { Has to be an exact match on the register }
  9432. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9433. Break;
  9434. if taicpu(hp1).opcode = A_INC then
  9435. begin
  9436. Inc(TestValMin);
  9437. Inc(TestValMax);
  9438. Inc(TestValSignedMax);
  9439. end
  9440. else
  9441. begin
  9442. Dec(TestValMin);
  9443. Dec(TestValMax);
  9444. Dec(TestValSignedMax);
  9445. end;
  9446. end;
  9447. A_TEST, A_CMP:
  9448. begin
  9449. if (
  9450. { Too high a risk of non-linear behaviour that breaks DFA
  9451. here, unless it's cmp $0,%reg, which is equivalent to
  9452. test %reg,%reg }
  9453. OrXorUsed and
  9454. (taicpu(hp1).opcode = A_CMP) and
  9455. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9456. ) or
  9457. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9458. { Has to be an exact match on the register }
  9459. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9460. (
  9461. { Permit "test %reg,%reg" }
  9462. (taicpu(hp1).opcode = A_TEST) and
  9463. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9464. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9465. ) or
  9466. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9467. { Make sure the comparison value is not smaller than the
  9468. smallest allowed signed value for the minimum size (e.g.
  9469. -128 for 8-bit) }
  9470. not (
  9471. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9472. { Is it in the negative range? }
  9473. (
  9474. (taicpu(hp1).oper[0]^.val < 0) and
  9475. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9476. )
  9477. ) then
  9478. Break;
  9479. { Check to see if the active register is used afterwards }
  9480. TransferUsedRegs(TmpUsedRegs);
  9481. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9482. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9483. begin
  9484. { Make sure the comparison or any previous instructions
  9485. hasn't pushed the test values outside of the range of
  9486. MinSize }
  9487. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9488. begin
  9489. { Exceeded lower bound but not upper bound }
  9490. Exit;
  9491. end
  9492. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9493. begin
  9494. { Size didn't exceed lower bound }
  9495. TargetSize := MinSize;
  9496. end
  9497. else
  9498. Break;
  9499. case TargetSize of
  9500. S_B:
  9501. TargetSubReg := R_SUBL;
  9502. S_W:
  9503. TargetSubReg := R_SUBW;
  9504. S_L:
  9505. TargetSubReg := R_SUBD;
  9506. else
  9507. InternalError(2021051002);
  9508. end;
  9509. if TargetSize <> MaxSize then
  9510. begin
  9511. { Update the register to its new size }
  9512. setsubreg(ThisReg, TargetSubReg);
  9513. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9514. taicpu(hp1).oper[1]^.reg := ThisReg;
  9515. taicpu(hp1).opsize := TargetSize;
  9516. { Convert the input MOVZX to a MOV if necessary }
  9517. AdjustInitialLoadAndSize;
  9518. if (InstrMax >= 0) then
  9519. begin
  9520. for Index := 0 to InstrMax do
  9521. begin
  9522. { If p_removed is true, then the original MOV/Z was removed
  9523. and removing the AND instruction may not be safe if it
  9524. appears first }
  9525. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9526. InternalError(2020112311);
  9527. if InstrList[Index].oper[0]^.typ = top_reg then
  9528. InstrList[Index].oper[0]^.reg := ThisReg;
  9529. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9530. InstrList[Index].opsize := MinSize;
  9531. end;
  9532. end;
  9533. Result := True;
  9534. end;
  9535. Exit;
  9536. end;
  9537. end;
  9538. A_SETcc:
  9539. begin
  9540. { This allows this Movx optimisation to work through the SETcc instructions
  9541. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9542. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9543. skip over these SETcc instructions). }
  9544. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9545. { Of course, break out if the current register is used }
  9546. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9547. Break
  9548. else
  9549. { We must use Continue so the instruction doesn't get added
  9550. to InstrList }
  9551. Continue;
  9552. end;
  9553. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9554. begin
  9555. if
  9556. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9557. { Has to be an exact match on the register }
  9558. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9559. (
  9560. (
  9561. (taicpu(hp1).oper[0]^.typ = top_const) and
  9562. (
  9563. (
  9564. (taicpu(hp1).opcode = A_SHL) and
  9565. (
  9566. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9567. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9568. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9569. )
  9570. ) or (
  9571. (taicpu(hp1).opcode <> A_SHL) and
  9572. (
  9573. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9574. { Is it in the negative range? }
  9575. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9576. )
  9577. )
  9578. )
  9579. ) or (
  9580. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9581. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9582. )
  9583. ) then
  9584. Break;
  9585. { Only process OR and XOR if there are only bitwise operations,
  9586. since otherwise they can too easily fool the data flow
  9587. analysis (they can cause non-linear behaviour) }
  9588. case taicpu(hp1).opcode of
  9589. A_ADD:
  9590. begin
  9591. if OrXorUsed then
  9592. { Too high a risk of non-linear behaviour that breaks DFA here }
  9593. Break
  9594. else
  9595. BitwiseOnly := False;
  9596. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9597. begin
  9598. TestValMin := TestValMin * 2;
  9599. TestValMax := TestValMax * 2;
  9600. TestValSignedMax := TestValSignedMax * 2;
  9601. end
  9602. else
  9603. begin
  9604. WorkingValue := taicpu(hp1).oper[0]^.val;
  9605. TestValMin := TestValMin + WorkingValue;
  9606. TestValMax := TestValMax + WorkingValue;
  9607. TestValSignedMax := TestValSignedMax + WorkingValue;
  9608. end;
  9609. end;
  9610. A_SUB:
  9611. begin
  9612. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9613. begin
  9614. TestValMin := 0;
  9615. TestValMax := 0;
  9616. TestValSignedMax := 0;
  9617. end
  9618. else
  9619. begin
  9620. if OrXorUsed then
  9621. { Too high a risk of non-linear behaviour that breaks DFA here }
  9622. Break
  9623. else
  9624. BitwiseOnly := False;
  9625. WorkingValue := taicpu(hp1).oper[0]^.val;
  9626. TestValMin := TestValMin - WorkingValue;
  9627. TestValMax := TestValMax - WorkingValue;
  9628. TestValSignedMax := TestValSignedMax - WorkingValue;
  9629. end;
  9630. end;
  9631. A_AND:
  9632. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9633. begin
  9634. { we might be able to go smaller if AND appears first }
  9635. if InstrMax = -1 then
  9636. case MinSize of
  9637. S_B:
  9638. ;
  9639. S_W:
  9640. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9641. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9642. begin
  9643. TryShiftDown := S_B;
  9644. TryShiftDownLimit := $FF;
  9645. end;
  9646. S_L:
  9647. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9648. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9649. begin
  9650. TryShiftDown := S_B;
  9651. TryShiftDownLimit := $FF;
  9652. end
  9653. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9654. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9655. begin
  9656. TryShiftDown := S_W;
  9657. TryShiftDownLimit := $FFFF;
  9658. end;
  9659. else
  9660. InternalError(2020112320);
  9661. end;
  9662. WorkingValue := taicpu(hp1).oper[0]^.val;
  9663. TestValMin := TestValMin and WorkingValue;
  9664. TestValMax := TestValMax and WorkingValue;
  9665. TestValSignedMax := TestValSignedMax and WorkingValue;
  9666. end;
  9667. A_OR:
  9668. begin
  9669. if not BitwiseOnly then
  9670. Break;
  9671. OrXorUsed := True;
  9672. WorkingValue := taicpu(hp1).oper[0]^.val;
  9673. TestValMin := TestValMin or WorkingValue;
  9674. TestValMax := TestValMax or WorkingValue;
  9675. TestValSignedMax := TestValSignedMax or WorkingValue;
  9676. end;
  9677. A_XOR:
  9678. begin
  9679. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9680. begin
  9681. TestValMin := 0;
  9682. TestValMax := 0;
  9683. TestValSignedMax := 0;
  9684. end
  9685. else
  9686. begin
  9687. if not BitwiseOnly then
  9688. Break;
  9689. OrXorUsed := True;
  9690. WorkingValue := taicpu(hp1).oper[0]^.val;
  9691. TestValMin := TestValMin xor WorkingValue;
  9692. TestValMax := TestValMax xor WorkingValue;
  9693. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9694. end;
  9695. end;
  9696. A_SHL:
  9697. begin
  9698. BitwiseOnly := False;
  9699. WorkingValue := taicpu(hp1).oper[0]^.val;
  9700. TestValMin := TestValMin shl WorkingValue;
  9701. TestValMax := TestValMax shl WorkingValue;
  9702. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9703. end;
  9704. A_SHR,
  9705. { The first instruction was MOVZX, so the value won't be negative }
  9706. A_SAR:
  9707. begin
  9708. if InstrMax <> -1 then
  9709. BitwiseOnly := False
  9710. else
  9711. { we might be able to go smaller if SHR appears first }
  9712. case MinSize of
  9713. S_B:
  9714. ;
  9715. S_W:
  9716. if (taicpu(hp1).oper[0]^.val >= 8) then
  9717. begin
  9718. TryShiftDown := S_B;
  9719. TryShiftDownLimit := $FF;
  9720. TryShiftDownSignedLimit := $7F;
  9721. TryShiftDownSignedLimitLower := -128;
  9722. end;
  9723. S_L:
  9724. if (taicpu(hp1).oper[0]^.val >= 24) then
  9725. begin
  9726. TryShiftDown := S_B;
  9727. TryShiftDownLimit := $FF;
  9728. TryShiftDownSignedLimit := $7F;
  9729. TryShiftDownSignedLimitLower := -128;
  9730. end
  9731. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9732. begin
  9733. TryShiftDown := S_W;
  9734. TryShiftDownLimit := $FFFF;
  9735. TryShiftDownSignedLimit := $7FFF;
  9736. TryShiftDownSignedLimitLower := -32768;
  9737. end;
  9738. else
  9739. InternalError(2020112321);
  9740. end;
  9741. WorkingValue := taicpu(hp1).oper[0]^.val;
  9742. if taicpu(hp1).opcode = A_SAR then
  9743. begin
  9744. TestValMin := SarInt64(TestValMin, WorkingValue);
  9745. TestValMax := SarInt64(TestValMax, WorkingValue);
  9746. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9747. end
  9748. else
  9749. begin
  9750. TestValMin := TestValMin shr WorkingValue;
  9751. TestValMax := TestValMax shr WorkingValue;
  9752. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9753. end;
  9754. end;
  9755. else
  9756. InternalError(2020112303);
  9757. end;
  9758. end;
  9759. (*
  9760. A_IMUL:
  9761. case taicpu(hp1).ops of
  9762. 2:
  9763. begin
  9764. if not MatchOpType(hp1, top_reg, top_reg) or
  9765. { Has to be an exact match on the register }
  9766. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9767. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9768. Break;
  9769. TestValMin := TestValMin * TestValMin;
  9770. TestValMax := TestValMax * TestValMax;
  9771. TestValSignedMax := TestValSignedMax * TestValMax;
  9772. end;
  9773. 3:
  9774. begin
  9775. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9776. { Has to be an exact match on the register }
  9777. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9778. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9779. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9780. { Is it in the negative range? }
  9781. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9782. Break;
  9783. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9784. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9785. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9786. end;
  9787. else
  9788. Break;
  9789. end;
  9790. A_IDIV:
  9791. case taicpu(hp1).ops of
  9792. 3:
  9793. begin
  9794. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9795. { Has to be an exact match on the register }
  9796. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9797. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9798. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9799. { Is it in the negative range? }
  9800. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9801. Break;
  9802. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9803. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9804. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9805. end;
  9806. else
  9807. Break;
  9808. end;
  9809. *)
  9810. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9811. begin
  9812. { If there are no instructions in between, then we might be able to make a saving }
  9813. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9814. Break;
  9815. { We have something like:
  9816. movzbw %dl,%dx
  9817. ...
  9818. movswl %dx,%edx
  9819. Change the latter to a zero-extension then enter the
  9820. A_MOVZX case branch.
  9821. }
  9822. {$ifdef x86_64}
  9823. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9824. begin
  9825. { this becomes a zero extension from 32-bit to 64-bit, but
  9826. the upper 32 bits are already zero, so just delete the
  9827. instruction }
  9828. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9829. RemoveInstruction(hp1);
  9830. Result := True;
  9831. Exit;
  9832. end
  9833. else
  9834. {$endif x86_64}
  9835. begin
  9836. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9837. taicpu(hp1).opcode := A_MOVZX;
  9838. {$ifdef x86_64}
  9839. case taicpu(hp1).opsize of
  9840. S_BQ:
  9841. begin
  9842. taicpu(hp1).opsize := S_BL;
  9843. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9844. end;
  9845. S_WQ:
  9846. begin
  9847. taicpu(hp1).opsize := S_WL;
  9848. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9849. end;
  9850. S_LQ:
  9851. begin
  9852. taicpu(hp1).opcode := A_MOV;
  9853. taicpu(hp1).opsize := S_L;
  9854. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9855. { In this instance, we need to break out because the
  9856. instruction is no longer MOVZX or MOVSXD }
  9857. Result := True;
  9858. Exit;
  9859. end;
  9860. else
  9861. ;
  9862. end;
  9863. {$endif x86_64}
  9864. Result := CompressInstructions;
  9865. Exit;
  9866. end;
  9867. end;
  9868. A_MOVZX:
  9869. begin
  9870. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9871. Break;
  9872. if (InstrMax = -1) then
  9873. begin
  9874. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9875. begin
  9876. { Optimise around i40003 }
  9877. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9878. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9879. {$ifndef x86_64}
  9880. and (
  9881. (taicpu(p).oper[0]^.typ <> top_reg) or
  9882. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9883. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9884. )
  9885. {$endif not x86_64}
  9886. then
  9887. begin
  9888. if (taicpu(p).oper[0]^.typ = top_reg) then
  9889. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9890. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9891. taicpu(p).opsize := S_BL;
  9892. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9893. RemoveInstruction(hp1);
  9894. Result := True;
  9895. Exit;
  9896. end;
  9897. end
  9898. else
  9899. begin
  9900. { Will return false if the second parameter isn't ThisReg
  9901. (can happen on -O2 and under) }
  9902. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9903. begin
  9904. { The two MOVZX instructions are adjacent, so remove the first one }
  9905. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9906. RemoveCurrentP(p);
  9907. Result := True;
  9908. Exit;
  9909. end;
  9910. Break;
  9911. end;
  9912. end;
  9913. Result := CompressInstructions;
  9914. Exit;
  9915. end;
  9916. else
  9917. { This includes ADC, SBB and IDIV }
  9918. Break;
  9919. end;
  9920. if not CheckOverflowConditions then
  9921. Break;
  9922. { Contains highest index (so instruction count - 1) }
  9923. Inc(InstrMax);
  9924. if InstrMax > High(InstrList) then
  9925. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9926. InstrList[InstrMax] := taicpu(hp1);
  9927. end;
  9928. end;
  9929. {$pop}
  9930. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9931. var
  9932. hp1 : tai;
  9933. begin
  9934. Result:=false;
  9935. if (taicpu(p).ops >= 2) and
  9936. ((taicpu(p).oper[0]^.typ = top_const) or
  9937. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9938. (taicpu(p).oper[1]^.typ = top_reg) and
  9939. ((taicpu(p).ops = 2) or
  9940. ((taicpu(p).oper[2]^.typ = top_reg) and
  9941. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9942. GetLastInstruction(p,hp1) and
  9943. MatchInstruction(hp1,A_MOV,[]) and
  9944. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9945. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9946. begin
  9947. TransferUsedRegs(TmpUsedRegs);
  9948. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9949. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9950. { change
  9951. mov reg1,reg2
  9952. imul y,reg2 to imul y,reg1,reg2 }
  9953. begin
  9954. taicpu(p).ops := 3;
  9955. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9956. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9957. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9958. RemoveInstruction(hp1);
  9959. result:=true;
  9960. end;
  9961. end;
  9962. end;
  9963. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9964. var
  9965. ThisLabel: TAsmLabel;
  9966. begin
  9967. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9968. ThisLabel.decrefs;
  9969. taicpu(p).condition := C_None;
  9970. taicpu(p).opcode := A_RET;
  9971. taicpu(p).is_jmp := false;
  9972. taicpu(p).ops := taicpu(ret_p).ops;
  9973. case taicpu(ret_p).ops of
  9974. 0:
  9975. taicpu(p).clearop(0);
  9976. 1:
  9977. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9978. else
  9979. internalerror(2016041301);
  9980. end;
  9981. { If the original label is now dead, it might turn out that the label
  9982. immediately follows p. As a result, everything beyond it, which will
  9983. be just some final register configuration and a RET instruction, is
  9984. now dead code. [Kit] }
  9985. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9986. running RemoveDeadCodeAfterJump for each RET instruction, because
  9987. this optimisation rarely happens and most RETs appear at the end of
  9988. routines where there is nothing that can be stripped. [Kit] }
  9989. if not ThisLabel.is_used then
  9990. RemoveDeadCodeAfterJump(p);
  9991. end;
  9992. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9993. var
  9994. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9995. Unconditional, PotentialModified: Boolean;
  9996. OperPtr: POper;
  9997. NewRef: TReference;
  9998. InstrList: array of taicpu;
  9999. InstrMax, Index: Integer;
  10000. const
  10001. {$ifdef DEBUG_AOPTCPU}
  10002. SNoFlags: shortstring = ' so the flags aren''t modified';
  10003. {$else DEBUG_AOPTCPU}
  10004. SNoFlags = '';
  10005. {$endif DEBUG_AOPTCPU}
  10006. begin
  10007. Result:=false;
  10008. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10009. begin
  10010. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10011. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10012. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10013. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10014. GetNextInstruction(hp1, hp2) and
  10015. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10016. { Change from: To:
  10017. set(C) %reg j(~C) label
  10018. test %reg,%reg/cmp $0,%reg
  10019. je label
  10020. set(C) %reg j(C) label
  10021. test %reg,%reg/cmp $0,%reg
  10022. jne label
  10023. (Also do something similar with sete/setne instead of je/jne)
  10024. }
  10025. begin
  10026. { Before we do anything else, we need to check the instructions
  10027. in between SETcc and TEST to make sure they don't modify the
  10028. FLAGS register - if -O2 or under, there won't be any
  10029. instructions between SET and TEST }
  10030. TransferUsedRegs(TmpUsedRegs);
  10031. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10032. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10033. begin
  10034. next := p;
  10035. SetLength(InstrList, 0);
  10036. InstrMax := -1;
  10037. PotentialModified := False;
  10038. { Make a note of every instruction that modifies the FLAGS
  10039. register }
  10040. while GetNextInstruction(next, next) and (next <> hp1) do
  10041. begin
  10042. if next.typ <> ait_instruction then
  10043. { GetNextInstructionUsingReg should have returned False }
  10044. InternalError(2021051701);
  10045. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10046. begin
  10047. case taicpu(next).opcode of
  10048. A_SETcc,
  10049. A_CMOVcc,
  10050. A_Jcc:
  10051. begin
  10052. if PotentialModified then
  10053. { Not safe because the flags were modified earlier }
  10054. Exit
  10055. else
  10056. { Condition is the same as the initial SETcc, so this is safe
  10057. (don't add to instruction list though) }
  10058. Continue;
  10059. end;
  10060. A_ADD:
  10061. begin
  10062. if (taicpu(next).opsize = S_B) or
  10063. { LEA doesn't support 8-bit operands }
  10064. (taicpu(next).oper[1]^.typ <> top_reg) or
  10065. { Must write to a register }
  10066. (taicpu(next).oper[0]^.typ = top_ref) then
  10067. { Require a constant or a register }
  10068. Exit;
  10069. PotentialModified := True;
  10070. end;
  10071. A_SUB:
  10072. begin
  10073. if (taicpu(next).opsize = S_B) or
  10074. { LEA doesn't support 8-bit operands }
  10075. (taicpu(next).oper[1]^.typ <> top_reg) or
  10076. { Must write to a register }
  10077. (taicpu(next).oper[0]^.typ <> top_const) or
  10078. (taicpu(next).oper[0]^.val = $80000000) then
  10079. { Can't subtract a register with LEA - also
  10080. check that the value isn't -2^31, as this
  10081. can't be negated }
  10082. Exit;
  10083. PotentialModified := True;
  10084. end;
  10085. A_SAL,
  10086. A_SHL:
  10087. begin
  10088. if (taicpu(next).opsize = S_B) or
  10089. { LEA doesn't support 8-bit operands }
  10090. (taicpu(next).oper[1]^.typ <> top_reg) or
  10091. { Must write to a register }
  10092. (taicpu(next).oper[0]^.typ <> top_const) or
  10093. (taicpu(next).oper[0]^.val < 0) or
  10094. (taicpu(next).oper[0]^.val > 3) then
  10095. Exit;
  10096. PotentialModified := True;
  10097. end;
  10098. A_IMUL:
  10099. begin
  10100. if (taicpu(next).ops <> 3) or
  10101. (taicpu(next).oper[1]^.typ <> top_reg) or
  10102. { Must write to a register }
  10103. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10104. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10105. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10106. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10107. Exit
  10108. else
  10109. PotentialModified := True;
  10110. end;
  10111. else
  10112. { Don't know how to change this, so abort }
  10113. Exit;
  10114. end;
  10115. { Contains highest index (so instruction count - 1) }
  10116. Inc(InstrMax);
  10117. if InstrMax > High(InstrList) then
  10118. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10119. InstrList[InstrMax] := taicpu(next);
  10120. end;
  10121. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10122. end;
  10123. if not Assigned(next) or (next <> hp1) then
  10124. { It should be equal to hp1 }
  10125. InternalError(2021051702);
  10126. { Cycle through each instruction and check to see if we can
  10127. change them to versions that don't modify the flags }
  10128. if (InstrMax >= 0) then
  10129. begin
  10130. for Index := 0 to InstrMax do
  10131. case InstrList[Index].opcode of
  10132. A_ADD:
  10133. begin
  10134. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10135. InstrList[Index].opcode := A_LEA;
  10136. reference_reset(NewRef, 1, []);
  10137. NewRef.base := InstrList[Index].oper[1]^.reg;
  10138. if InstrList[Index].oper[0]^.typ = top_reg then
  10139. begin
  10140. NewRef.index := InstrList[Index].oper[0]^.reg;
  10141. NewRef.scalefactor := 1;
  10142. end
  10143. else
  10144. NewRef.offset := InstrList[Index].oper[0]^.val;
  10145. InstrList[Index].loadref(0, NewRef);
  10146. end;
  10147. A_SUB:
  10148. begin
  10149. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10150. InstrList[Index].opcode := A_LEA;
  10151. reference_reset(NewRef, 1, []);
  10152. NewRef.base := InstrList[Index].oper[1]^.reg;
  10153. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10154. InstrList[Index].loadref(0, NewRef);
  10155. end;
  10156. A_SHL,
  10157. A_SAL:
  10158. begin
  10159. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10160. InstrList[Index].opcode := A_LEA;
  10161. reference_reset(NewRef, 1, []);
  10162. NewRef.index := InstrList[Index].oper[1]^.reg;
  10163. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10164. InstrList[Index].loadref(0, NewRef);
  10165. end;
  10166. A_IMUL:
  10167. begin
  10168. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10169. InstrList[Index].opcode := A_LEA;
  10170. reference_reset(NewRef, 1, []);
  10171. NewRef.index := InstrList[Index].oper[1]^.reg;
  10172. case InstrList[Index].oper[0]^.val of
  10173. 2, 4, 8:
  10174. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10175. else {3, 5 and 9}
  10176. begin
  10177. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10178. NewRef.base := InstrList[Index].oper[1]^.reg;
  10179. end;
  10180. end;
  10181. InstrList[Index].loadref(0, NewRef);
  10182. end;
  10183. else
  10184. InternalError(2021051710);
  10185. end;
  10186. end;
  10187. { Mark the FLAGS register as used across this whole block }
  10188. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10189. end;
  10190. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10191. JumpC := taicpu(hp2).condition;
  10192. Unconditional := False;
  10193. if conditions_equal(JumpC, C_E) then
  10194. SetC := inverse_cond(taicpu(p).condition)
  10195. else if conditions_equal(JumpC, C_NE) then
  10196. SetC := taicpu(p).condition
  10197. else
  10198. { We've got something weird here (and inefficent) }
  10199. begin
  10200. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10201. SetC := C_NONE;
  10202. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10203. if condition_in(C_AE, JumpC) then
  10204. Unconditional := True
  10205. else
  10206. { Not sure what to do with this jump - drop out }
  10207. Exit;
  10208. end;
  10209. RemoveInstruction(hp1);
  10210. if Unconditional then
  10211. MakeUnconditional(taicpu(hp2))
  10212. else
  10213. begin
  10214. if SetC = C_NONE then
  10215. InternalError(2018061402);
  10216. taicpu(hp2).SetCondition(SetC);
  10217. end;
  10218. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10219. TmpUsedRegs }
  10220. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10221. begin
  10222. RemoveCurrentp(p, hp2);
  10223. if taicpu(hp2).opcode = A_SETcc then
  10224. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10225. else
  10226. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10227. end
  10228. else
  10229. if taicpu(hp2).opcode = A_SETcc then
  10230. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10231. else
  10232. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10233. Result := True;
  10234. end
  10235. else if
  10236. { Make sure the instructions are adjacent }
  10237. (
  10238. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10239. GetNextInstruction(p, hp1)
  10240. ) and
  10241. MatchInstruction(hp1, A_MOV, [S_B]) and
  10242. { Writing to memory is allowed }
  10243. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10244. begin
  10245. {
  10246. Watch out for sequences such as:
  10247. set(c)b %regb
  10248. movb %regb,(ref)
  10249. movb $0,1(ref)
  10250. movb $0,2(ref)
  10251. movb $0,3(ref)
  10252. Much more efficient to turn it into:
  10253. movl $0,%regl
  10254. set(c)b %regb
  10255. movl %regl,(ref)
  10256. Or:
  10257. set(c)b %regb
  10258. movzbl %regb,%regl
  10259. movl %regl,(ref)
  10260. }
  10261. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10262. GetNextInstruction(hp1, hp2) and
  10263. MatchInstruction(hp2, A_MOV, [S_B]) and
  10264. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10265. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10266. begin
  10267. { Don't do anything else except set Result to True }
  10268. end
  10269. else
  10270. begin
  10271. if taicpu(p).oper[0]^.typ = top_reg then
  10272. begin
  10273. TransferUsedRegs(TmpUsedRegs);
  10274. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10275. end;
  10276. { If it's not a register, it's a memory address }
  10277. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10278. begin
  10279. { Even if the register is still in use, we can minimise the
  10280. pipeline stall by changing the MOV into another SETcc. }
  10281. taicpu(hp1).opcode := A_SETcc;
  10282. taicpu(hp1).condition := taicpu(p).condition;
  10283. if taicpu(hp1).oper[1]^.typ = top_ref then
  10284. begin
  10285. { Swapping the operand pointers like this is probably a
  10286. bit naughty, but it is far faster than using loadoper
  10287. to transfer the reference from oper[1] to oper[0] if
  10288. you take into account the extra procedure calls and
  10289. the memory allocation and deallocation required }
  10290. OperPtr := taicpu(hp1).oper[1];
  10291. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10292. taicpu(hp1).oper[0] := OperPtr;
  10293. end
  10294. else
  10295. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10296. taicpu(hp1).clearop(1);
  10297. taicpu(hp1).ops := 1;
  10298. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10299. end
  10300. else
  10301. begin
  10302. if taicpu(hp1).oper[1]^.typ = top_reg then
  10303. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10304. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10305. RemoveInstruction(hp1);
  10306. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10307. end
  10308. end;
  10309. Result := True;
  10310. end;
  10311. end;
  10312. end;
  10313. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10314. var
  10315. hp1: tai;
  10316. Count: Integer;
  10317. OrigLabel: TAsmLabel;
  10318. begin
  10319. result := False;
  10320. { Sometimes, the optimisations below can permit this }
  10321. RemoveDeadCodeAfterJump(p);
  10322. 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
  10323. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10324. begin
  10325. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10326. { Also a side-effect of optimisations }
  10327. if CollapseZeroDistJump(p, OrigLabel) then
  10328. begin
  10329. Result := True;
  10330. Exit;
  10331. end;
  10332. hp1 := GetLabelWithSym(OrigLabel);
  10333. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10334. begin
  10335. if taicpu(hp1).opcode = A_RET then
  10336. begin
  10337. {
  10338. change
  10339. jmp .L1
  10340. ...
  10341. .L1:
  10342. ret
  10343. into
  10344. ret
  10345. }
  10346. begin
  10347. ConvertJumpToRET(p, hp1);
  10348. result:=true;
  10349. end;
  10350. end
  10351. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10352. not (cs_opt_size in current_settings.optimizerswitches) and
  10353. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10354. begin
  10355. Result := True;
  10356. Exit;
  10357. end;
  10358. end;
  10359. end;
  10360. end;
  10361. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10362. begin
  10363. Result := assigned(p) and
  10364. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10365. (taicpu(p).oper[1]^.typ = top_reg) and
  10366. (
  10367. (taicpu(p).oper[0]^.typ = top_reg) or
  10368. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10369. it is not expected that this can cause a seg. violation }
  10370. (
  10371. (taicpu(p).oper[0]^.typ = top_ref) and
  10372. { TODO: Can we detect which references become constants at this
  10373. stage so we don't have to do a blanket ban? }
  10374. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10375. (
  10376. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10377. (
  10378. { If the reference also appears in the condition, then we know it's safe, otherwise
  10379. any kind of access violation would have occurred already }
  10380. Assigned(cond_p) and
  10381. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10382. (cond_p.typ = ait_instruction) and
  10383. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10384. { Just consider 2-operand comparison instructions for now to be safe }
  10385. (taicpu(cond_p).ops = 2) and
  10386. (
  10387. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10388. (
  10389. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10390. { Don't risk identical registers but different offsets, as we may have constructs
  10391. such as buffer streams with things like length fields that indicate whether
  10392. any more data follows. And there are probably some contrived examples where
  10393. writing to offsets behind the one being read also lead to access violations }
  10394. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10395. (
  10396. { Check that we're not modifying a register that appears in the reference }
  10397. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10398. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10399. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10400. )
  10401. )
  10402. )
  10403. )
  10404. )
  10405. )
  10406. );
  10407. end;
  10408. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10409. begin
  10410. { Update integer registers, ignoring deallocations }
  10411. repeat
  10412. while assigned(p) and
  10413. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10414. (p.typ = ait_label) or
  10415. ((p.typ = ait_marker) and
  10416. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10417. p := tai(p.next);
  10418. while assigned(p) and
  10419. (p.typ=ait_RegAlloc) Do
  10420. begin
  10421. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10422. begin
  10423. case tai_regalloc(p).ratype of
  10424. ra_alloc :
  10425. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10426. else
  10427. ;
  10428. end;
  10429. end;
  10430. p := tai(p.next);
  10431. end;
  10432. until not(assigned(p)) or
  10433. (not(p.typ in SkipInstr) and
  10434. not((p.typ = ait_label) and
  10435. labelCanBeSkipped(tai_label(p))));
  10436. end;
  10437. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10438. var
  10439. hp1,hp2: tai;
  10440. carryadd_opcode : TAsmOp;
  10441. symbol: TAsmSymbol;
  10442. increg, tmpreg: TRegister;
  10443. {$ifndef i8086}
  10444. { Code and variables specific to CMOV optimisations }
  10445. hp3,hp4,hp5,
  10446. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10447. l, c, w, x : Longint;
  10448. condition, second_condition : TAsmCond;
  10449. FoundMatchingJump, RegMatch: Boolean;
  10450. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10451. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10452. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10453. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10454. new register to store the constant }
  10455. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10456. var
  10457. RegSize: TSubRegister;
  10458. CurrentVal: TCGInt;
  10459. NewReg: TRegister;
  10460. X: ShortInt;
  10461. begin
  10462. Result := False;
  10463. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10464. Exit;
  10465. if StoredCount >= MAX_CMOV_REGISTERS then
  10466. { Arrays are full }
  10467. Exit;
  10468. { Remember that CMOV can't encode 8-bit registers }
  10469. case taicpu(p).opsize of
  10470. S_W:
  10471. RegSize := R_SUBW;
  10472. S_L:
  10473. RegSize := R_SUBD;
  10474. S_Q:
  10475. RegSize := R_SUBQ;
  10476. else
  10477. InternalError(2021100401);
  10478. end;
  10479. { See if the value has already been reserved for another CMOV instruction }
  10480. CurrentVal := taicpu(p).oper[0]^.val;
  10481. for X := 0 to StoredCount - 1 do
  10482. if ConstVals[X] = CurrentVal then
  10483. begin
  10484. ConstRegs[StoredCount] := ConstRegs[X];
  10485. ConstVals[StoredCount] := CurrentVal;
  10486. Result := True;
  10487. Inc(StoredCount);
  10488. { Don't increase CMOVCount this time, since we're re-using a register }
  10489. Exit;
  10490. end;
  10491. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10492. if NewReg = NR_NO then
  10493. { No free registers }
  10494. Exit;
  10495. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10496. up vying for the same register }
  10497. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10498. ConstRegs[StoredCount] := NewReg;
  10499. ConstVals[StoredCount] := CurrentVal;
  10500. Inc(StoredCount);
  10501. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10502. MOV required adds complexity and will cause diminishing returns
  10503. sooner than normal. This is more of an approximate weighting than
  10504. anything else. }
  10505. Inc(CMOVCount);
  10506. Result := True;
  10507. end;
  10508. {$endif i8086}
  10509. begin
  10510. result:=false;
  10511. if GetNextInstruction(p,hp1) then
  10512. begin
  10513. if (hp1.typ=ait_label) then
  10514. begin
  10515. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10516. Exit;
  10517. end
  10518. else if (hp1.typ<>ait_instruction) then
  10519. Exit;
  10520. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10521. if (
  10522. (
  10523. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10524. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10525. (Taicpu(hp1).oper[0]^.val=1)
  10526. ) or
  10527. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10528. ) and
  10529. GetNextInstruction(hp1,hp2) and
  10530. SkipAligns(hp2, hp2) and
  10531. (hp2.typ = ait_label) and
  10532. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10533. { jb @@1 cmc
  10534. inc/dec operand --> adc/sbb operand,0
  10535. @@1:
  10536. ... and ...
  10537. jnb @@1
  10538. inc/dec operand --> adc/sbb operand,0
  10539. @@1: }
  10540. begin
  10541. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10542. begin
  10543. case taicpu(hp1).opcode of
  10544. A_INC,
  10545. A_ADD:
  10546. carryadd_opcode:=A_ADC;
  10547. A_DEC,
  10548. A_SUB:
  10549. carryadd_opcode:=A_SBB;
  10550. else
  10551. InternalError(2021011001);
  10552. end;
  10553. Taicpu(p).clearop(0);
  10554. Taicpu(p).ops:=0;
  10555. Taicpu(p).is_jmp:=false;
  10556. Taicpu(p).opcode:=A_CMC;
  10557. Taicpu(p).condition:=C_NONE;
  10558. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10559. Taicpu(hp1).ops:=2;
  10560. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10561. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10562. else
  10563. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10564. Taicpu(hp1).loadconst(0,0);
  10565. Taicpu(hp1).opcode:=carryadd_opcode;
  10566. result:=true;
  10567. exit;
  10568. end
  10569. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10570. begin
  10571. case taicpu(hp1).opcode of
  10572. A_INC,
  10573. A_ADD:
  10574. carryadd_opcode:=A_ADC;
  10575. A_DEC,
  10576. A_SUB:
  10577. carryadd_opcode:=A_SBB;
  10578. else
  10579. InternalError(2021011002);
  10580. end;
  10581. Taicpu(hp1).ops:=2;
  10582. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10583. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10584. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10585. else
  10586. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10587. Taicpu(hp1).loadconst(0,0);
  10588. Taicpu(hp1).opcode:=carryadd_opcode;
  10589. RemoveCurrentP(p, hp1);
  10590. result:=true;
  10591. exit;
  10592. end
  10593. {
  10594. jcc @@1 setcc tmpreg
  10595. inc/dec/add/sub operand -> (movzx tmpreg)
  10596. @@1: add/sub tmpreg,operand
  10597. While this increases code size slightly, it makes the code much faster if the
  10598. jump is unpredictable
  10599. }
  10600. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10601. begin
  10602. { search for an available register which is volatile }
  10603. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10604. if increg <> NR_NO then
  10605. begin
  10606. { We don't need to check if tmpreg is in hp1 or not, because
  10607. it will be marked as in use at p (if not, this is
  10608. indictive of a compiler bug). }
  10609. TAsmLabel(symbol).decrefs;
  10610. Taicpu(p).clearop(0);
  10611. Taicpu(p).ops:=1;
  10612. Taicpu(p).is_jmp:=false;
  10613. Taicpu(p).opcode:=A_SETcc;
  10614. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10615. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10616. Taicpu(p).loadreg(0,increg);
  10617. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10618. begin
  10619. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10620. R_SUBW:
  10621. begin
  10622. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10623. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10624. end;
  10625. R_SUBD:
  10626. begin
  10627. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10628. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10629. end;
  10630. {$ifdef x86_64}
  10631. R_SUBQ:
  10632. begin
  10633. { MOVZX doesn't have a 64-bit variant, because
  10634. the 32-bit version implicitly zeroes the
  10635. upper 32-bits of the destination register }
  10636. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10637. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10638. setsubreg(tmpreg, R_SUBQ);
  10639. end;
  10640. {$endif x86_64}
  10641. else
  10642. Internalerror(2020030601);
  10643. end;
  10644. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10645. asml.InsertAfter(hp2,p);
  10646. end
  10647. else
  10648. tmpreg := increg;
  10649. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10650. begin
  10651. Taicpu(hp1).ops:=2;
  10652. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10653. end;
  10654. Taicpu(hp1).loadreg(0,tmpreg);
  10655. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10656. Result := True;
  10657. { p is no longer a Jcc instruction, so exit }
  10658. Exit;
  10659. end;
  10660. end;
  10661. end;
  10662. { Detect the following:
  10663. jmp<cond> @Lbl1
  10664. jmp @Lbl2
  10665. ...
  10666. @Lbl1:
  10667. ret
  10668. Change to:
  10669. jmp<inv_cond> @Lbl2
  10670. ret
  10671. }
  10672. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10673. begin
  10674. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10675. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10676. MatchInstruction(hp2,A_RET,[S_NO]) then
  10677. begin
  10678. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10679. { Change label address to that of the unconditional jump }
  10680. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10681. TAsmLabel(symbol).DecRefs;
  10682. taicpu(hp1).opcode := A_RET;
  10683. taicpu(hp1).is_jmp := false;
  10684. taicpu(hp1).ops := taicpu(hp2).ops;
  10685. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10686. case taicpu(hp2).ops of
  10687. 0:
  10688. taicpu(hp1).clearop(0);
  10689. 1:
  10690. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10691. else
  10692. internalerror(2016041302);
  10693. end;
  10694. end;
  10695. {$ifndef i8086}
  10696. end
  10697. {
  10698. convert
  10699. j<c> .L1
  10700. mov 1,reg
  10701. jmp .L2
  10702. .L1
  10703. mov 0,reg
  10704. .L2
  10705. into
  10706. mov 0,reg
  10707. set<not(c)> reg
  10708. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10709. would destroy the flag contents
  10710. }
  10711. else if MatchInstruction(hp1,A_MOV,[]) and
  10712. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10713. {$ifdef i386}
  10714. (
  10715. { Under i386, ESI, EDI, EBP and ESP
  10716. don't have an 8-bit representation }
  10717. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10718. ) and
  10719. {$endif i386}
  10720. (taicpu(hp1).oper[0]^.val=1) and
  10721. GetNextInstruction(hp1,hp2) and
  10722. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10723. GetNextInstruction(hp2,hp3) and
  10724. { skip align }
  10725. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10726. (hp3.typ=ait_label) and
  10727. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10728. (tai_label(hp3).labsym.getrefs=1) and
  10729. GetNextInstruction(hp3,hp4) and
  10730. MatchInstruction(hp4,A_MOV,[]) and
  10731. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10732. (taicpu(hp4).oper[0]^.val=0) and
  10733. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10734. GetNextInstruction(hp4,hp5) and
  10735. (hp5.typ=ait_label) and
  10736. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10737. (tai_label(hp5).labsym.getrefs=1) then
  10738. begin
  10739. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10740. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10741. { remove last label }
  10742. RemoveInstruction(hp5);
  10743. { remove second label }
  10744. RemoveInstruction(hp3);
  10745. { if align is present remove it }
  10746. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10747. RemoveInstruction(hp3);
  10748. { remove jmp }
  10749. RemoveInstruction(hp2);
  10750. if taicpu(hp1).opsize=S_B then
  10751. RemoveInstruction(hp1)
  10752. else
  10753. taicpu(hp1).loadconst(0,0);
  10754. taicpu(hp4).opcode:=A_SETcc;
  10755. taicpu(hp4).opsize:=S_B;
  10756. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10757. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10758. taicpu(hp4).opercnt:=1;
  10759. taicpu(hp4).ops:=1;
  10760. taicpu(hp4).freeop(1);
  10761. RemoveCurrentP(p);
  10762. Result:=true;
  10763. exit;
  10764. end
  10765. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10766. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10767. begin
  10768. { check for
  10769. jCC xxx
  10770. <several movs>
  10771. xxx:
  10772. Also spot:
  10773. Jcc xxx
  10774. <several movs>
  10775. jmp xxx
  10776. Change to:
  10777. <several cmovs with inverted condition>
  10778. jmp xxx (only for the 2nd case)
  10779. }
  10780. hp2 := p;
  10781. hp_lblxxx := hp1;
  10782. hp_flagalloc := nil;
  10783. hp_stop := nil;
  10784. FoundMatchingJump := False;
  10785. { Remember the first instruction in the first block of MOVs }
  10786. hpmov1 := hp1;
  10787. TransferUsedRegs(TmpUsedRegs);
  10788. while assigned(hp_lblxxx) and
  10789. { stop on labels }
  10790. (hp_lblxxx.typ <> ait_label) do
  10791. begin
  10792. { Keep track of all integer registers that are used }
  10793. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10794. if hp_lblxxx.typ = ait_instruction then
  10795. begin
  10796. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10797. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10798. begin
  10799. hp_stop := hp_lblxxx;
  10800. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10801. begin
  10802. { We found Jcc xxx; <several movs>; Jmp xxx }
  10803. FoundMatchingJump := True;
  10804. Break;
  10805. end;
  10806. { If it's not the jump we're looking for, it's
  10807. possibly the "if..else" variant }
  10808. end
  10809. { Check to see if we have a valid MOV instruction instead }
  10810. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10811. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10812. Break
  10813. else
  10814. { This will be a valid MOV }
  10815. hp_stop := hp_lblxxx;
  10816. end;
  10817. hp2 := hp_lblxxx;
  10818. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10819. end;
  10820. { Just make sure the last MOV is included if there's no jump }
  10821. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10822. hp_stop := hp_lblxxx;
  10823. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10824. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10825. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10826. jmp yyy; xxx:; movs; yyy:" variation }
  10827. if assigned(hp_lblxxx) and
  10828. (
  10829. { If we found JMP xxx, we don't actually need a label
  10830. (hp_lblxxx is the JMP instruction instead) }
  10831. FoundMatchingJump or
  10832. { Make sure we actually have the right label }
  10833. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10834. ) then
  10835. begin
  10836. { Use TmpUsedRegs to track registers that we reserve }
  10837. { When allocating temporary registers, try to look one
  10838. instruction back, as defining them before a CMP or TEST
  10839. instruction will be faster, and also avoid picking a
  10840. register that was only just deallocated }
  10841. if GetLastInstruction(p, hp_prev) and
  10842. 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
  10843. begin
  10844. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10845. for l := 0 to 1 do
  10846. with taicpu(hp_prev).oper[l]^ do
  10847. case typ of
  10848. top_reg:
  10849. if getregtype(reg) = R_INTREGISTER then
  10850. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10851. top_ref:
  10852. begin
  10853. if
  10854. {$ifdef x86_64}
  10855. (ref^.base <> NR_RIP) and
  10856. {$endif x86_64}
  10857. (ref^.base <> NR_NO) then
  10858. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10859. if (ref^.index <> NR_NO) then
  10860. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10861. end
  10862. else
  10863. ;
  10864. end;
  10865. { When inserting instructions before hp_prev, try to insert
  10866. them before the allocation of the FLAGS register }
  10867. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10868. { If not found, set it equal to hp_prev so it's something sensible }
  10869. hp_flagalloc := hp_prev;
  10870. hp_prev2 := nil;
  10871. { When dealing with a comparison against zero, take
  10872. note of the instruction before it to see if we can
  10873. move instructions further back in order to benefit
  10874. PostPeepholeOptTestOr.
  10875. }
  10876. if (
  10877. (
  10878. (taicpu(hp_prev).opcode = A_CMP) and
  10879. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10880. ) or
  10881. (
  10882. (taicpu(hp_prev).opcode = A_TEST) and
  10883. (
  10884. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10885. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10886. )
  10887. )
  10888. ) and
  10889. GetLastInstruction(hp_prev, hp_prev2) then
  10890. begin
  10891. if (hp_prev2.typ = ait_instruction) and
  10892. { These instructions set the zero flag if the result is zero }
  10893. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10894. begin
  10895. { Also mark all the registers in this previous instruction
  10896. as 'in use', even if they've just been deallocated }
  10897. for l := 0 to 1 do
  10898. with taicpu(hp_prev2).oper[l]^ do
  10899. case typ of
  10900. top_reg:
  10901. if getregtype(reg) = R_INTREGISTER then
  10902. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10903. top_ref:
  10904. begin
  10905. if
  10906. {$ifdef x86_64}
  10907. (ref^.base <> NR_RIP) and
  10908. {$endif x86_64}
  10909. (ref^.base <> NR_NO) then
  10910. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10911. if (ref^.index <> NR_NO) then
  10912. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10913. end
  10914. else
  10915. ;
  10916. end;
  10917. end
  10918. else
  10919. { Unsuitable instruction }
  10920. hp_prev2 := nil;
  10921. end;
  10922. end
  10923. else
  10924. begin
  10925. hp_prev := p;
  10926. { When inserting instructions before hp_prev, try to insert
  10927. them before the allocation of the FLAGS register }
  10928. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10929. { If not found, set it equal to p so it's something sensible }
  10930. hp_flagalloc := p;
  10931. hp_prev2 := nil;
  10932. end;
  10933. l := 0;
  10934. c := 0;
  10935. { Initialise RegWrites, ConstRegs and ConstVals }
  10936. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  10937. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  10938. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  10939. while assigned(hp1) and
  10940. { Stop on the label we found }
  10941. (hp1 <> hp_lblxxx) do
  10942. begin
  10943. case hp1.typ of
  10944. ait_instruction:
  10945. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10946. begin
  10947. if CanBeCMOV(hp1, hp_prev) then
  10948. Inc(l)
  10949. else if not (cs_opt_size in current_settings.optimizerswitches) and
  10950. { CMOV with constants grows the code size }
  10951. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  10952. begin
  10953. { Register was reserved by TryCMOVConst and
  10954. stored on ConstRegs[c] }
  10955. end
  10956. else
  10957. Break;
  10958. end
  10959. else
  10960. Break;
  10961. else
  10962. ;
  10963. end;
  10964. GetNextInstruction(hp1,hp1);
  10965. end;
  10966. if (hp1 = hp_lblxxx) then
  10967. begin
  10968. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  10969. begin
  10970. { Repurpose TmpUsedRegs to mark registers that we've defined }
  10971. TmpUsedRegs[R_INTREGISTER].Clear;
  10972. x := 0;
  10973. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  10974. condition := inverse_cond(taicpu(p).condition);
  10975. UpdateUsedRegs(tai(p.next));
  10976. hp1 := hpmov1;
  10977. repeat
  10978. if not Assigned(hp1) then
  10979. InternalError(2018062900);
  10980. if (hp1.typ = ait_instruction) then
  10981. begin
  10982. { Extra safeguard }
  10983. if (taicpu(hp1).opcode <> A_MOV) then
  10984. InternalError(2018062901);
  10985. if taicpu(hp1).oper[0]^.typ = top_const then
  10986. begin
  10987. if x >= MAX_CMOV_REGISTERS then
  10988. InternalError(2021100410);
  10989. { If it's in TmpUsedRegs, then this register
  10990. is being used more than once and hence has
  10991. already had its value defined (it gets
  10992. added to UsedRegs through AllocRegBetween
  10993. below) }
  10994. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  10995. begin
  10996. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  10997. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  10998. asml.InsertBefore(hp_new, hp_flagalloc);
  10999. if Assigned(hp_prev2) then
  11000. TrySwapMovOp(hp_prev2, hp_new);
  11001. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11002. end
  11003. else
  11004. { We just need an instruction between hp_prev and hp1
  11005. where we know the register is marked as in use }
  11006. hp_new := hpmov1;
  11007. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11008. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11009. Inc(x);
  11010. end;
  11011. taicpu(hp1).opcode := A_CMOVcc;
  11012. taicpu(hp1).condition := condition;
  11013. end;
  11014. UpdateUsedRegs(tai(hp1.next));
  11015. GetNextInstruction(hp1, hp1);
  11016. until (hp1 = hp_lblxxx);
  11017. hp2 := hp_lblxxx;
  11018. repeat
  11019. if not Assigned(hp2) then
  11020. InternalError(2018062910);
  11021. case hp2.typ of
  11022. ait_label:
  11023. { What we expected - break out of the loop (it won't be a dead label at the top of
  11024. a cluster because that was optimised at an earlier stage) }
  11025. Break;
  11026. ait_align:
  11027. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11028. begin
  11029. hp2 := tai(hp2.Next);
  11030. Continue;
  11031. end;
  11032. ait_instruction:
  11033. begin
  11034. if taicpu(hp2).opcode<>A_JMP then
  11035. InternalError(2018062912);
  11036. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11037. Break;
  11038. end
  11039. else
  11040. begin
  11041. { Might be a comment or temporary allocation entry }
  11042. if not (hp2.typ in SkipInstr) then
  11043. InternalError(2018062911);
  11044. hp2 := tai(hp2.Next);
  11045. Continue;
  11046. end;
  11047. end;
  11048. until False;
  11049. { Now we can safely decrement the reference count }
  11050. tasmlabel(symbol).decrefs;
  11051. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11052. { Remove the original jump }
  11053. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11054. if hp2.typ=ait_instruction then
  11055. begin
  11056. p := hp2;
  11057. Result := True;
  11058. end
  11059. else
  11060. begin
  11061. UpdateUsedRegs(tai(hp2.next));
  11062. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11063. { Remove the label if this is its final reference }
  11064. if (tasmlabel(symbol).getrefs=0) then
  11065. begin
  11066. { Make sure the aligns get stripped too }
  11067. hp1 := tai(hp_lblxxx.Previous);
  11068. while Assigned(hp1) and (hp1.typ = ait_align) do
  11069. begin
  11070. hp_lblxxx := hp1;
  11071. hp1 := tai(hp_lblxxx.Previous);
  11072. end;
  11073. StripLabelFast(hp_lblxxx);
  11074. end;
  11075. end;
  11076. Exit;
  11077. end;
  11078. end
  11079. else if assigned(hp_lblxxx) and
  11080. { check further for
  11081. jCC xxx
  11082. <several movs 1>
  11083. jmp yyy
  11084. xxx:
  11085. <several movs 2>
  11086. yyy:
  11087. }
  11088. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11089. { hp1 should be pointing to jmp yyy }
  11090. MatchInstruction(hp1, A_JMP, []) and
  11091. { real label and jump, no further references to the
  11092. label are allowed }
  11093. (TAsmLabel(symbol).getrefs=1) and
  11094. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11095. begin
  11096. hp_jump := hp1;
  11097. { Don't set c to zero }
  11098. l := 0;
  11099. w := 0;
  11100. GetNextInstruction(hp_lblxxx, hpmov2);
  11101. hp2 := hp_lblxxx;
  11102. hp_lblyyy := hpmov2;
  11103. while assigned(hp_lblyyy) and
  11104. { stop on labels }
  11105. (hp_lblyyy.typ <> ait_label) do
  11106. begin
  11107. { Keep track of all integer registers that are used }
  11108. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11109. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11110. Break;
  11111. hp2 := hp_lblyyy;
  11112. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11113. end;
  11114. { Analyse the second batch of MOVs to see if the setup is valid }
  11115. hp1 := hpmov2;
  11116. while assigned(hp1) and
  11117. (hp1 <> hp_lblyyy) do
  11118. begin
  11119. case hp1.typ of
  11120. ait_instruction:
  11121. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11122. begin
  11123. if CanBeCMOV(hp1, hp_prev) then
  11124. Inc(l)
  11125. else if not (cs_opt_size in current_settings.optimizerswitches)
  11126. { CMOV with constants grows the code size }
  11127. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11128. begin
  11129. { Register was reserved by TryCMOVConst and
  11130. stored on ConstRegs[c] }
  11131. end
  11132. else
  11133. Break;
  11134. end
  11135. else
  11136. Break;
  11137. else
  11138. ;
  11139. end;
  11140. GetNextInstruction(hp1,hp1);
  11141. end;
  11142. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11143. TmpUsedRegs[R_INTREGISTER].Clear;
  11144. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11145. (hp1 = hp_lblyyy) and
  11146. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11147. begin
  11148. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11149. second_condition := taicpu(p).condition;
  11150. condition := inverse_cond(taicpu(p).condition);
  11151. UpdateUsedRegs(tai(p.next));
  11152. { Scan through the first set of MOVs to update UsedRegs,
  11153. but don't process them yet }
  11154. hp1 := hpmov1;
  11155. repeat
  11156. if not Assigned(hp1) then
  11157. InternalError(2018062901);
  11158. UpdateUsedRegs(tai(hp1.next));
  11159. GetNextInstruction(hp1, hp1);
  11160. until (hp1 = hp_lblxxx);
  11161. UpdateUsedRegs(tai(hp_lblxxx.next));
  11162. { Process the second set of MOVs first,
  11163. because if a destination register is
  11164. shared between the first and second MOV
  11165. sets, it is more efficient to turn the
  11166. first one into a MOV instruction and place
  11167. it before the CMP if possible, but we
  11168. won't know which registers are shared
  11169. until we've processed at least one list,
  11170. so we might as well make it the second
  11171. one since that won't be modified again. }
  11172. hp1 := hpmov2;
  11173. repeat
  11174. if not Assigned(hp1) then
  11175. InternalError(2018062902);
  11176. if (hp1.typ = ait_instruction) then
  11177. begin
  11178. { Extra safeguard }
  11179. if (taicpu(hp1).opcode <> A_MOV) then
  11180. InternalError(2018062903);
  11181. if taicpu(hp1).oper[0]^.typ = top_const then
  11182. begin
  11183. RegMatch := False;
  11184. for x := 0 to c - 1 do
  11185. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11186. begin
  11187. RegMatch := True;
  11188. { If it's in TmpUsedRegs, then this register
  11189. is being used more than once and hence has
  11190. already had its value defined (it gets
  11191. added to UsedRegs through AllocRegBetween
  11192. below) }
  11193. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11194. begin
  11195. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11196. asml.InsertBefore(hp_new, hp_flagalloc);
  11197. if Assigned(hp_prev2) then
  11198. TrySwapMovOp(hp_prev2, hp_new);
  11199. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11200. end
  11201. else
  11202. { We just need an instruction between hp_prev and hp1
  11203. where we know the register is marked as in use }
  11204. hp_new := hpmov2;
  11205. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11206. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11207. Break;
  11208. end;
  11209. if not RegMatch then
  11210. InternalError(2021100411);
  11211. end;
  11212. taicpu(hp1).opcode := A_CMOVcc;
  11213. taicpu(hp1).condition := second_condition;
  11214. { Store these writes to search for
  11215. duplicates later on }
  11216. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11217. Inc(w);
  11218. end;
  11219. UpdateUsedRegs(tai(hp1.next));
  11220. GetNextInstruction(hp1, hp1);
  11221. until (hp1 = hp_lblyyy);
  11222. { Now do the first set of MOVs }
  11223. hp1 := hpmov1;
  11224. repeat
  11225. if not Assigned(hp1) then
  11226. InternalError(2018062904);
  11227. if (hp1.typ = ait_instruction) then
  11228. begin
  11229. RegMatch := False;
  11230. { Extra safeguard }
  11231. if (taicpu(hp1).opcode <> A_MOV) then
  11232. InternalError(2018062905);
  11233. { Search through the RegWrites list to see
  11234. if there are any opposing CMOV pairs that
  11235. write to the same register }
  11236. for x := 0 to w - 1 do
  11237. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11238. begin
  11239. { We have a match. Keep this as a MOV }
  11240. { Move ahead in preparation }
  11241. GetNextInstruction(hp1, hp1);
  11242. RegMatch := True;
  11243. Break;
  11244. end;
  11245. if RegMatch then
  11246. Continue;
  11247. if taicpu(hp1).oper[0]^.typ = top_const then
  11248. begin
  11249. RegMatch := False;
  11250. for x := 0 to c - 1 do
  11251. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11252. begin
  11253. RegMatch := True;
  11254. { If it's in TmpUsedRegs, then this register
  11255. is being used more than once and hence has
  11256. already had its value defined (it gets
  11257. added to UsedRegs through AllocRegBetween
  11258. below) }
  11259. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11260. begin
  11261. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11262. asml.InsertBefore(hp_new, hp_flagalloc);
  11263. if Assigned(hp_prev2) then
  11264. TrySwapMovOp(hp_prev2, hp_new);
  11265. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11266. end
  11267. else
  11268. { We just need an instruction between hp_prev and hp1
  11269. where we know the register is marked as in use }
  11270. hp_new := hpmov1;
  11271. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11272. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11273. Break;
  11274. end;
  11275. if not RegMatch then
  11276. InternalError(2021100412);
  11277. end;
  11278. taicpu(hp1).opcode := A_CMOVcc;
  11279. taicpu(hp1).condition := condition;
  11280. end;
  11281. GetNextInstruction(hp1, hp1);
  11282. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11283. UpdateUsedRegs(tai(hp_jump.next));
  11284. UpdateUsedRegs(tai(hp_lblyyy.next));
  11285. { Get first instruction after label }
  11286. hp1 := p;
  11287. GetNextInstruction(hp_lblyyy, p);
  11288. { Don't dereference yet, as doing so will cause
  11289. GetNextInstruction to skip the label and
  11290. optional align marker. [Kit] }
  11291. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11292. { remove Jcc }
  11293. RemoveInstruction(hp1);
  11294. { Now we can safely decrement it }
  11295. tasmlabel(symbol).decrefs;
  11296. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11297. { Make sure the aligns get stripped too }
  11298. hp1 := tai(hp_lblxxx.Previous);
  11299. while Assigned(hp1) and (hp1.typ = ait_align) do
  11300. begin
  11301. hp_lblxxx := hp1;
  11302. hp1 := tai(hp_lblxxx.Previous);
  11303. end;
  11304. StripLabelFast(hp_lblxxx);
  11305. { remove jmp }
  11306. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11307. RemoveInstruction(hp_jump);
  11308. { As before, now we can safely decrement it }
  11309. TAsmLabel(symbol).decrefs;
  11310. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11311. if TAsmLabel(symbol).getrefs = 0 then
  11312. begin
  11313. { Make sure the aligns get stripped too }
  11314. hp1 := tai(hp_lblyyy.Previous);
  11315. while Assigned(hp1) and (hp1.typ = ait_align) do
  11316. begin
  11317. hp_lblyyy := hp1;
  11318. hp1 := tai(hp_lblyyy.Previous);
  11319. end;
  11320. StripLabelFast(hp_lblyyy);
  11321. end;
  11322. if Assigned(p) then
  11323. result := True;
  11324. exit;
  11325. end;
  11326. end;
  11327. end;
  11328. {$endif i8086}
  11329. end;
  11330. end;
  11331. end;
  11332. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11333. var
  11334. hp1,hp2,hp3: tai;
  11335. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11336. NewSize: TOpSize;
  11337. NewRegSize: TSubRegister;
  11338. Limit: TCgInt;
  11339. SwapOper: POper;
  11340. begin
  11341. result:=false;
  11342. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11343. GetNextInstruction(p,hp1) and
  11344. (hp1.typ = ait_instruction);
  11345. if reg_and_hp1_is_instr and
  11346. (
  11347. (taicpu(hp1).opcode <> A_LEA) or
  11348. { If the LEA instruction can be converted into an arithmetic instruction,
  11349. it may be possible to then fold it. }
  11350. (
  11351. { If the flags register is in use, don't change the instruction
  11352. to an ADD otherwise this will scramble the flags. [Kit] }
  11353. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11354. ConvertLEA(taicpu(hp1))
  11355. )
  11356. ) and
  11357. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11358. GetNextInstruction(hp1,hp2) and
  11359. MatchInstruction(hp2,A_MOV,[]) and
  11360. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11361. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11362. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11363. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11364. {$ifdef i386}
  11365. { not all registers have byte size sub registers on i386 }
  11366. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11367. {$endif i386}
  11368. (((taicpu(hp1).ops=2) and
  11369. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11370. ((taicpu(hp1).ops=1) and
  11371. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11372. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11373. begin
  11374. { change movsX/movzX reg/ref, reg2
  11375. add/sub/or/... reg3/$const, reg2
  11376. mov reg2 reg/ref
  11377. to add/sub/or/... reg3/$const, reg/ref }
  11378. { by example:
  11379. movswl %si,%eax movswl %si,%eax p
  11380. decl %eax addl %edx,%eax hp1
  11381. movw %ax,%si movw %ax,%si hp2
  11382. ->
  11383. movswl %si,%eax movswl %si,%eax p
  11384. decw %eax addw %edx,%eax hp1
  11385. movw %ax,%si movw %ax,%si hp2
  11386. }
  11387. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11388. {
  11389. ->
  11390. movswl %si,%eax movswl %si,%eax p
  11391. decw %si addw %dx,%si hp1
  11392. movw %ax,%si movw %ax,%si hp2
  11393. }
  11394. case taicpu(hp1).ops of
  11395. 1:
  11396. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11397. 2:
  11398. begin
  11399. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11400. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11401. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11402. end;
  11403. else
  11404. internalerror(2008042702);
  11405. end;
  11406. {
  11407. ->
  11408. decw %si addw %dx,%si p
  11409. }
  11410. DebugMsg(SPeepholeOptimization + 'var3',p);
  11411. RemoveCurrentP(p, hp1);
  11412. RemoveInstruction(hp2);
  11413. Result := True;
  11414. Exit;
  11415. end;
  11416. if reg_and_hp1_is_instr and
  11417. (taicpu(hp1).opcode = A_MOV) and
  11418. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11419. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11420. {$ifdef x86_64}
  11421. { check for implicit extension to 64 bit }
  11422. or
  11423. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11424. (taicpu(hp1).opsize=S_Q) and
  11425. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11426. )
  11427. {$endif x86_64}
  11428. )
  11429. then
  11430. begin
  11431. { change
  11432. movx %reg1,%reg2
  11433. mov %reg2,%reg3
  11434. dealloc %reg2
  11435. into
  11436. movx %reg,%reg3
  11437. }
  11438. TransferUsedRegs(TmpUsedRegs);
  11439. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11440. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11441. begin
  11442. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11443. {$ifdef x86_64}
  11444. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11445. (taicpu(hp1).opsize=S_Q) then
  11446. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11447. else
  11448. {$endif x86_64}
  11449. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11450. RemoveInstruction(hp1);
  11451. Result := True;
  11452. Exit;
  11453. end;
  11454. end;
  11455. if reg_and_hp1_is_instr and
  11456. ((taicpu(hp1).opcode=A_MOV) or
  11457. (taicpu(hp1).opcode=A_ADD) or
  11458. (taicpu(hp1).opcode=A_SUB) or
  11459. (taicpu(hp1).opcode=A_CMP) or
  11460. (taicpu(hp1).opcode=A_OR) or
  11461. (taicpu(hp1).opcode=A_XOR) or
  11462. (taicpu(hp1).opcode=A_AND)
  11463. ) and
  11464. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11465. begin
  11466. AndTest := (taicpu(hp1).opcode=A_AND) and
  11467. GetNextInstruction(hp1, hp2) and
  11468. (hp2.typ = ait_instruction) and
  11469. (
  11470. (
  11471. (taicpu(hp2).opcode=A_TEST) and
  11472. (
  11473. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11474. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11475. (
  11476. { If the AND and TEST instructions share a constant, this is also valid }
  11477. (taicpu(hp1).oper[0]^.typ = top_const) and
  11478. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11479. )
  11480. ) and
  11481. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11482. ) or
  11483. (
  11484. (taicpu(hp2).opcode=A_CMP) and
  11485. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11486. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11487. )
  11488. );
  11489. { change
  11490. movx (oper),%reg2
  11491. and $x,%reg2
  11492. test %reg2,%reg2
  11493. dealloc %reg2
  11494. into
  11495. op %reg1,%reg3
  11496. if the second op accesses only the bits stored in reg1
  11497. }
  11498. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11499. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11500. (taicpu(hp1).oper[0]^.typ = top_const) and
  11501. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11502. AndTest then
  11503. begin
  11504. { Check if the AND constant is in range }
  11505. case taicpu(p).opsize of
  11506. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11507. begin
  11508. NewSize := S_B;
  11509. Limit := $FF;
  11510. end;
  11511. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11512. begin
  11513. NewSize := S_W;
  11514. Limit := $FFFF;
  11515. end;
  11516. {$ifdef x86_64}
  11517. S_LQ:
  11518. begin
  11519. NewSize := S_L;
  11520. Limit := $FFFFFFFF;
  11521. end;
  11522. {$endif x86_64}
  11523. else
  11524. InternalError(2021120303);
  11525. end;
  11526. if (
  11527. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11528. { Check for negative operands }
  11529. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11530. ) and
  11531. GetNextInstruction(hp2,hp3) and
  11532. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11533. (taicpu(hp3).condition in [C_E,C_NE]) then
  11534. begin
  11535. TransferUsedRegs(TmpUsedRegs);
  11536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11537. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11538. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11539. begin
  11540. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11541. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11542. taicpu(hp1).opcode := A_TEST;
  11543. taicpu(hp1).opsize := NewSize;
  11544. RemoveInstruction(hp2);
  11545. RemoveCurrentP(p, hp1);
  11546. Result:=true;
  11547. exit;
  11548. end;
  11549. end;
  11550. end;
  11551. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11552. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11553. (taicpu(hp1).opsize=S_B)) or
  11554. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11555. (taicpu(hp1).opsize=S_W))
  11556. {$ifdef x86_64}
  11557. or ((taicpu(p).opsize=S_LQ) and
  11558. (taicpu(hp1).opsize=S_L))
  11559. {$endif x86_64}
  11560. ) and
  11561. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11562. begin
  11563. { change
  11564. movx %reg1,%reg2
  11565. op %reg2,%reg3
  11566. dealloc %reg2
  11567. into
  11568. op %reg1,%reg3
  11569. if the second op accesses only the bits stored in reg1
  11570. }
  11571. TransferUsedRegs(TmpUsedRegs);
  11572. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11573. if AndTest then
  11574. begin
  11575. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11576. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11577. end
  11578. else
  11579. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11580. if not RegUsed then
  11581. begin
  11582. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11583. if taicpu(p).oper[0]^.typ=top_reg then
  11584. begin
  11585. case taicpu(hp1).opsize of
  11586. S_B:
  11587. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11588. S_W:
  11589. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11590. S_L:
  11591. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11592. else
  11593. Internalerror(2020102301);
  11594. end;
  11595. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11596. end
  11597. else
  11598. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11599. RemoveCurrentP(p);
  11600. if AndTest then
  11601. RemoveInstruction(hp2);
  11602. result:=true;
  11603. exit;
  11604. end;
  11605. end
  11606. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11607. (
  11608. { Bitwise operations only }
  11609. (taicpu(hp1).opcode=A_AND) or
  11610. (taicpu(hp1).opcode=A_TEST) or
  11611. (
  11612. (taicpu(hp1).oper[0]^.typ = top_const) and
  11613. (
  11614. (taicpu(hp1).opcode=A_OR) or
  11615. (taicpu(hp1).opcode=A_XOR)
  11616. )
  11617. )
  11618. ) and
  11619. (
  11620. (taicpu(hp1).oper[0]^.typ = top_const) or
  11621. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11622. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11623. ) then
  11624. begin
  11625. { change
  11626. movx %reg2,%reg2
  11627. op const,%reg2
  11628. into
  11629. op const,%reg2 (smaller version)
  11630. movx %reg2,%reg2
  11631. also change
  11632. movx %reg1,%reg2
  11633. and/test (oper),%reg2
  11634. dealloc %reg2
  11635. into
  11636. and/test (oper),%reg1
  11637. }
  11638. case taicpu(p).opsize of
  11639. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11640. begin
  11641. NewSize := S_B;
  11642. NewRegSize := R_SUBL;
  11643. Limit := $FF;
  11644. end;
  11645. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11646. begin
  11647. NewSize := S_W;
  11648. NewRegSize := R_SUBW;
  11649. Limit := $FFFF;
  11650. end;
  11651. {$ifdef x86_64}
  11652. S_LQ:
  11653. begin
  11654. NewSize := S_L;
  11655. NewRegSize := R_SUBD;
  11656. Limit := $FFFFFFFF;
  11657. end;
  11658. {$endif x86_64}
  11659. else
  11660. Internalerror(2021120302);
  11661. end;
  11662. TransferUsedRegs(TmpUsedRegs);
  11663. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11664. if AndTest then
  11665. begin
  11666. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11667. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11668. end
  11669. else
  11670. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11671. if
  11672. (
  11673. (taicpu(p).opcode = A_MOVZX) and
  11674. (
  11675. (taicpu(hp1).opcode=A_AND) or
  11676. (taicpu(hp1).opcode=A_TEST)
  11677. ) and
  11678. not (
  11679. { If both are references, then the final instruction will have
  11680. both operands as references, which is not allowed }
  11681. (taicpu(p).oper[0]^.typ = top_ref) and
  11682. (taicpu(hp1).oper[0]^.typ = top_ref)
  11683. ) and
  11684. not RegUsed
  11685. ) or
  11686. (
  11687. (
  11688. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11689. not RegUsed
  11690. ) and
  11691. (taicpu(p).oper[0]^.typ = top_reg) and
  11692. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11693. (taicpu(hp1).oper[0]^.typ = top_const) and
  11694. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11695. ) then
  11696. begin
  11697. {$if defined(i386) or defined(i8086)}
  11698. { If the target size is 8-bit, make sure we can actually encode it }
  11699. 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
  11700. Exit;
  11701. {$endif i386 or i8086}
  11702. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11703. taicpu(hp1).opsize := NewSize;
  11704. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11705. if AndTest then
  11706. begin
  11707. RemoveInstruction(hp2);
  11708. if not RegUsed then
  11709. begin
  11710. taicpu(hp1).opcode := A_TEST;
  11711. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11712. begin
  11713. { Make sure the reference is the second operand }
  11714. SwapOper := taicpu(hp1).oper[0];
  11715. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11716. taicpu(hp1).oper[1] := SwapOper;
  11717. end;
  11718. end;
  11719. end;
  11720. case taicpu(hp1).oper[0]^.typ of
  11721. top_reg:
  11722. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11723. top_const:
  11724. { For the AND/TEST case }
  11725. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11726. else
  11727. ;
  11728. end;
  11729. if RegUsed then
  11730. begin
  11731. AsmL.Remove(p);
  11732. AsmL.InsertAfter(p, hp1);
  11733. p := hp1;
  11734. end
  11735. else
  11736. RemoveCurrentP(p, hp1);
  11737. result:=true;
  11738. exit;
  11739. end;
  11740. end;
  11741. end;
  11742. if reg_and_hp1_is_instr and
  11743. (taicpu(p).oper[0]^.typ = top_reg) and
  11744. (
  11745. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11746. ) and
  11747. (taicpu(hp1).oper[0]^.typ = top_const) and
  11748. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11749. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11750. { Minimum shift value allowed is the bit difference between the sizes }
  11751. (taicpu(hp1).oper[0]^.val >=
  11752. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11753. 8 * (
  11754. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11755. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11756. )
  11757. ) then
  11758. begin
  11759. { For:
  11760. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11761. shl/sal ##, %reg1
  11762. Remove the movsx/movzx instruction if the shift overwrites the
  11763. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11764. }
  11765. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11766. RemoveCurrentP(p, hp1);
  11767. Result := True;
  11768. Exit;
  11769. end
  11770. else if reg_and_hp1_is_instr and
  11771. (taicpu(p).oper[0]^.typ = top_reg) and
  11772. (
  11773. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11774. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11775. ) and
  11776. (taicpu(hp1).oper[0]^.typ = top_const) and
  11777. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11778. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11779. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11780. (taicpu(hp1).oper[0]^.val <
  11781. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11782. 8 * (
  11783. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11784. )
  11785. ) then
  11786. begin
  11787. { For:
  11788. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11789. sar ##, %reg1 shr ##, %reg1
  11790. Move the shift to before the movx instruction if the shift value
  11791. is not too large.
  11792. }
  11793. asml.Remove(hp1);
  11794. asml.InsertBefore(hp1, p);
  11795. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11796. case taicpu(p).opsize of
  11797. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11798. taicpu(hp1).opsize := S_B;
  11799. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11800. taicpu(hp1).opsize := S_W;
  11801. {$ifdef x86_64}
  11802. S_LQ:
  11803. taicpu(hp1).opsize := S_L;
  11804. {$endif}
  11805. else
  11806. InternalError(2020112401);
  11807. end;
  11808. if (taicpu(hp1).opcode = A_SHR) then
  11809. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11810. else
  11811. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11812. Result := True;
  11813. end;
  11814. if reg_and_hp1_is_instr and
  11815. (taicpu(p).oper[0]^.typ = top_reg) and
  11816. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11817. (
  11818. (taicpu(hp1).opcode = taicpu(p).opcode)
  11819. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11820. {$ifdef x86_64}
  11821. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11822. {$endif x86_64}
  11823. ) then
  11824. begin
  11825. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11826. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11827. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11828. begin
  11829. {
  11830. For example:
  11831. movzbw %al,%ax
  11832. movzwl %ax,%eax
  11833. Compress into:
  11834. movzbl %al,%eax
  11835. }
  11836. RegUsed := False;
  11837. case taicpu(p).opsize of
  11838. S_BW:
  11839. case taicpu(hp1).opsize of
  11840. S_WL:
  11841. begin
  11842. taicpu(p).opsize := S_BL;
  11843. RegUsed := True;
  11844. end;
  11845. {$ifdef x86_64}
  11846. S_WQ:
  11847. begin
  11848. if taicpu(p).opcode = A_MOVZX then
  11849. begin
  11850. taicpu(p).opsize := S_BL;
  11851. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11852. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11853. end
  11854. else
  11855. taicpu(p).opsize := S_BQ;
  11856. RegUsed := True;
  11857. end;
  11858. {$endif x86_64}
  11859. else
  11860. ;
  11861. end;
  11862. {$ifdef x86_64}
  11863. S_BL:
  11864. case taicpu(hp1).opsize of
  11865. S_LQ:
  11866. begin
  11867. if taicpu(p).opcode = A_MOVZX then
  11868. begin
  11869. taicpu(p).opsize := S_BL;
  11870. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11871. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11872. end
  11873. else
  11874. taicpu(p).opsize := S_BQ;
  11875. RegUsed := True;
  11876. end;
  11877. else
  11878. ;
  11879. end;
  11880. S_WL:
  11881. case taicpu(hp1).opsize of
  11882. S_LQ:
  11883. begin
  11884. if taicpu(p).opcode = A_MOVZX then
  11885. begin
  11886. taicpu(p).opsize := S_WL;
  11887. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11888. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11889. end
  11890. else
  11891. taicpu(p).opsize := S_WQ;
  11892. RegUsed := True;
  11893. end;
  11894. else
  11895. ;
  11896. end;
  11897. {$endif x86_64}
  11898. else
  11899. ;
  11900. end;
  11901. if RegUsed then
  11902. begin
  11903. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11904. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11905. RemoveInstruction(hp1);
  11906. Result := True;
  11907. Exit;
  11908. end;
  11909. end;
  11910. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11911. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11912. GetNextInstruction(hp1, hp2) and
  11913. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11914. (
  11915. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11916. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11917. {$ifdef x86_64}
  11918. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11919. {$endif x86_64}
  11920. ) and
  11921. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11922. (
  11923. (
  11924. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11925. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11926. ) or
  11927. (
  11928. { Only allow the operands in reverse order for TEST instructions }
  11929. (taicpu(hp2).opcode = A_TEST) and
  11930. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11931. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11932. )
  11933. ) then
  11934. begin
  11935. {
  11936. For example:
  11937. movzbl %al,%eax
  11938. movzbl (ref),%edx
  11939. andl %edx,%eax
  11940. (%edx deallocated)
  11941. Change to:
  11942. andb (ref),%al
  11943. movzbl %al,%eax
  11944. Rules are:
  11945. - First two instructions have the same opcode and opsize
  11946. - First instruction's operands are the same super-register
  11947. - Second instruction operates on a different register
  11948. - Third instruction is AND, OR, XOR or TEST
  11949. - Third instruction's operands are the destination registers of the first two instructions
  11950. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11951. - Second instruction's destination register is deallocated afterwards
  11952. }
  11953. TransferUsedRegs(TmpUsedRegs);
  11954. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11955. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11956. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11957. begin
  11958. case taicpu(p).opsize of
  11959. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11960. NewSize := S_B;
  11961. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11962. NewSize := S_W;
  11963. {$ifdef x86_64}
  11964. S_LQ:
  11965. NewSize := S_L;
  11966. {$endif x86_64}
  11967. else
  11968. InternalError(2021120301);
  11969. end;
  11970. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11971. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11972. taicpu(hp2).opsize := NewSize;
  11973. RemoveInstruction(hp1);
  11974. { With TEST, it's best to keep the MOVX instruction at the top }
  11975. if (taicpu(hp2).opcode <> A_TEST) then
  11976. begin
  11977. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11978. asml.Remove(p);
  11979. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11980. asml.InsertAfter(p, hp2);
  11981. p := hp2;
  11982. end
  11983. else
  11984. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11985. Result := True;
  11986. Exit;
  11987. end;
  11988. end;
  11989. end;
  11990. if taicpu(p).opcode=A_MOVZX then
  11991. begin
  11992. { removes superfluous And's after movzx's }
  11993. if reg_and_hp1_is_instr and
  11994. (taicpu(hp1).opcode = A_AND) and
  11995. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11996. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11997. {$ifdef x86_64}
  11998. { check for implicit extension to 64 bit }
  11999. or
  12000. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12001. (taicpu(hp1).opsize=S_Q) and
  12002. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12003. )
  12004. {$endif x86_64}
  12005. )
  12006. then
  12007. begin
  12008. case taicpu(p).opsize Of
  12009. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12010. if (taicpu(hp1).oper[0]^.val = $ff) then
  12011. begin
  12012. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12013. RemoveInstruction(hp1);
  12014. Result:=true;
  12015. exit;
  12016. end;
  12017. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12018. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12019. begin
  12020. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12021. RemoveInstruction(hp1);
  12022. Result:=true;
  12023. exit;
  12024. end;
  12025. {$ifdef x86_64}
  12026. S_LQ:
  12027. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12028. begin
  12029. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12030. RemoveInstruction(hp1);
  12031. Result:=true;
  12032. exit;
  12033. end;
  12034. {$endif x86_64}
  12035. else
  12036. ;
  12037. end;
  12038. { we cannot get rid of the and, but can we get rid of the movz ?}
  12039. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12040. begin
  12041. case taicpu(p).opsize Of
  12042. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12043. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12044. begin
  12045. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12046. RemoveCurrentP(p,hp1);
  12047. Result:=true;
  12048. exit;
  12049. end;
  12050. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12051. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12052. begin
  12053. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12054. RemoveCurrentP(p,hp1);
  12055. Result:=true;
  12056. exit;
  12057. end;
  12058. {$ifdef x86_64}
  12059. S_LQ:
  12060. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12061. begin
  12062. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12063. RemoveCurrentP(p,hp1);
  12064. Result:=true;
  12065. exit;
  12066. end;
  12067. {$endif x86_64}
  12068. else
  12069. ;
  12070. end;
  12071. end;
  12072. end;
  12073. { changes some movzx constructs to faster synonyms (all examples
  12074. are given with eax/ax, but are also valid for other registers)}
  12075. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12076. begin
  12077. case taicpu(p).opsize of
  12078. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12079. (the machine code is equivalent to movzbl %al,%eax), but the
  12080. code generator still generates that assembler instruction and
  12081. it is silently converted. This should probably be checked.
  12082. [Kit] }
  12083. S_BW:
  12084. begin
  12085. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12086. (
  12087. not IsMOVZXAcceptable
  12088. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12089. or (
  12090. (cs_opt_size in current_settings.optimizerswitches) and
  12091. (taicpu(p).oper[1]^.reg = NR_AX)
  12092. )
  12093. ) then
  12094. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12095. begin
  12096. DebugMsg(SPeepholeOptimization + 'var7',p);
  12097. taicpu(p).opcode := A_AND;
  12098. taicpu(p).changeopsize(S_W);
  12099. taicpu(p).loadConst(0,$ff);
  12100. Result := True;
  12101. end
  12102. else if not IsMOVZXAcceptable and
  12103. GetNextInstruction(p, hp1) and
  12104. (tai(hp1).typ = ait_instruction) and
  12105. (taicpu(hp1).opcode = A_AND) and
  12106. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12107. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12108. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12109. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12110. begin
  12111. DebugMsg(SPeepholeOptimization + 'var8',p);
  12112. taicpu(p).opcode := A_MOV;
  12113. taicpu(p).changeopsize(S_W);
  12114. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12115. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12116. Result := True;
  12117. end;
  12118. end;
  12119. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12120. S_BL:
  12121. if not IsMOVZXAcceptable then
  12122. begin
  12123. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12124. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12125. begin
  12126. DebugMsg(SPeepholeOptimization + 'var9',p);
  12127. taicpu(p).opcode := A_AND;
  12128. taicpu(p).changeopsize(S_L);
  12129. taicpu(p).loadConst(0,$ff);
  12130. Result := True;
  12131. end
  12132. else if GetNextInstruction(p, hp1) and
  12133. (tai(hp1).typ = ait_instruction) and
  12134. (taicpu(hp1).opcode = A_AND) and
  12135. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12136. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12137. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12138. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12139. begin
  12140. DebugMsg(SPeepholeOptimization + 'var10',p);
  12141. taicpu(p).opcode := A_MOV;
  12142. taicpu(p).changeopsize(S_L);
  12143. { do not use R_SUBWHOLE
  12144. as movl %rdx,%eax
  12145. is invalid in assembler PM }
  12146. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12147. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12148. Result := True;
  12149. end;
  12150. end;
  12151. {$endif i8086}
  12152. S_WL:
  12153. if not IsMOVZXAcceptable then
  12154. begin
  12155. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12156. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12157. begin
  12158. DebugMsg(SPeepholeOptimization + 'var11',p);
  12159. taicpu(p).opcode := A_AND;
  12160. taicpu(p).changeopsize(S_L);
  12161. taicpu(p).loadConst(0,$ffff);
  12162. Result := True;
  12163. end
  12164. else if GetNextInstruction(p, hp1) and
  12165. (tai(hp1).typ = ait_instruction) and
  12166. (taicpu(hp1).opcode = A_AND) and
  12167. (taicpu(hp1).oper[0]^.typ = top_const) and
  12168. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12169. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12170. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12171. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12172. begin
  12173. DebugMsg(SPeepholeOptimization + 'var12',p);
  12174. taicpu(p).opcode := A_MOV;
  12175. taicpu(p).changeopsize(S_L);
  12176. { do not use R_SUBWHOLE
  12177. as movl %rdx,%eax
  12178. is invalid in assembler PM }
  12179. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12180. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12181. Result := True;
  12182. end;
  12183. end;
  12184. else
  12185. InternalError(2017050705);
  12186. end;
  12187. end
  12188. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12189. begin
  12190. if GetNextInstruction(p, hp1) and
  12191. (tai(hp1).typ = ait_instruction) and
  12192. (taicpu(hp1).opcode = A_AND) and
  12193. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12194. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12195. begin
  12196. //taicpu(p).opcode := A_MOV;
  12197. case taicpu(p).opsize Of
  12198. S_BL:
  12199. begin
  12200. DebugMsg(SPeepholeOptimization + 'var13',p);
  12201. taicpu(hp1).changeopsize(S_L);
  12202. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12203. end;
  12204. S_WL:
  12205. begin
  12206. DebugMsg(SPeepholeOptimization + 'var14',p);
  12207. taicpu(hp1).changeopsize(S_L);
  12208. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12209. end;
  12210. S_BW:
  12211. begin
  12212. DebugMsg(SPeepholeOptimization + 'var15',p);
  12213. taicpu(hp1).changeopsize(S_W);
  12214. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12215. end;
  12216. else
  12217. Internalerror(2017050704)
  12218. end;
  12219. Result := True;
  12220. end;
  12221. end;
  12222. end;
  12223. end;
  12224. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12225. var
  12226. hp1, hp2 : tai;
  12227. MaskLength : Cardinal;
  12228. MaskedBits : TCgInt;
  12229. ActiveReg : TRegister;
  12230. begin
  12231. Result:=false;
  12232. { There are no optimisations for reference targets }
  12233. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12234. Exit;
  12235. while GetNextInstruction(p, hp1) and
  12236. (hp1.typ = ait_instruction) do
  12237. begin
  12238. if (taicpu(p).oper[0]^.typ = top_const) then
  12239. begin
  12240. case taicpu(hp1).opcode of
  12241. A_AND:
  12242. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12243. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12244. { the second register must contain the first one, so compare their subreg types }
  12245. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12246. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12247. { change
  12248. and const1, reg
  12249. and const2, reg
  12250. to
  12251. and (const1 and const2), reg
  12252. }
  12253. begin
  12254. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12255. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12256. RemoveCurrentP(p, hp1);
  12257. Result:=true;
  12258. exit;
  12259. end;
  12260. A_CMP:
  12261. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12262. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12263. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12264. { Just check that the condition on the next instruction is compatible }
  12265. GetNextInstruction(hp1, hp2) and
  12266. (hp2.typ = ait_instruction) and
  12267. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12268. then
  12269. { change
  12270. and 2^n, reg
  12271. cmp 2^n, reg
  12272. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12273. to
  12274. and 2^n, reg
  12275. test reg, reg
  12276. j(~c) / set(~c) / cmov(~c)
  12277. }
  12278. begin
  12279. { Keep TEST instruction in, rather than remove it, because
  12280. it may trigger other optimisations such as MovAndTest2Test }
  12281. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12282. taicpu(hp1).opcode := A_TEST;
  12283. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12284. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12285. Result := True;
  12286. Exit;
  12287. end;
  12288. A_MOVZX:
  12289. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12290. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12291. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12292. (
  12293. (
  12294. (taicpu(p).opsize=S_W) and
  12295. (taicpu(hp1).opsize=S_BW)
  12296. ) or
  12297. (
  12298. (taicpu(p).opsize=S_L) and
  12299. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12300. )
  12301. {$ifdef x86_64}
  12302. or
  12303. (
  12304. (taicpu(p).opsize=S_Q) and
  12305. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12306. )
  12307. {$endif x86_64}
  12308. ) then
  12309. begin
  12310. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12311. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12312. ) or
  12313. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12314. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12315. then
  12316. begin
  12317. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12318. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12319. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12320. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12321. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12322. }
  12323. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12324. RemoveInstruction(hp1);
  12325. { See if there are other optimisations possible }
  12326. Continue;
  12327. end;
  12328. end;
  12329. A_SHL:
  12330. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12331. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12332. begin
  12333. {$ifopt R+}
  12334. {$define RANGE_WAS_ON}
  12335. {$R-}
  12336. {$endif}
  12337. { get length of potential and mask }
  12338. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12339. { really a mask? }
  12340. {$ifdef RANGE_WAS_ON}
  12341. {$R+}
  12342. {$endif}
  12343. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12344. { unmasked part shifted out? }
  12345. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12346. begin
  12347. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12348. RemoveCurrentP(p, hp1);
  12349. Result:=true;
  12350. exit;
  12351. end;
  12352. end;
  12353. A_SHR:
  12354. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12355. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12356. (taicpu(hp1).oper[0]^.val <= 63) then
  12357. begin
  12358. { Does SHR combined with the AND cover all the bits?
  12359. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12360. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12361. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12362. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12363. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12364. begin
  12365. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12366. RemoveCurrentP(p, hp1);
  12367. Result := True;
  12368. Exit;
  12369. end;
  12370. end;
  12371. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12372. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12373. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12374. begin
  12375. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12376. (
  12377. (
  12378. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12379. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12380. ) or (
  12381. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12382. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12383. {$ifdef x86_64}
  12384. ) or (
  12385. (taicpu(hp1).opsize = S_LQ) and
  12386. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12387. {$endif x86_64}
  12388. )
  12389. ) then
  12390. begin
  12391. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12392. begin
  12393. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12394. RemoveInstruction(hp1);
  12395. { See if there are other optimisations possible }
  12396. Continue;
  12397. end;
  12398. { The super-registers are the same though.
  12399. Note that this change by itself doesn't improve
  12400. code speed, but it opens up other optimisations. }
  12401. {$ifdef x86_64}
  12402. { Convert 64-bit register to 32-bit }
  12403. case taicpu(hp1).opsize of
  12404. S_BQ:
  12405. begin
  12406. taicpu(hp1).opsize := S_BL;
  12407. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12408. end;
  12409. S_WQ:
  12410. begin
  12411. taicpu(hp1).opsize := S_WL;
  12412. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12413. end
  12414. else
  12415. ;
  12416. end;
  12417. {$endif x86_64}
  12418. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12419. taicpu(hp1).opcode := A_MOVZX;
  12420. { See if there are other optimisations possible }
  12421. Continue;
  12422. end;
  12423. end;
  12424. else
  12425. ;
  12426. end;
  12427. end
  12428. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12429. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12430. begin
  12431. {$ifdef x86_64}
  12432. if (taicpu(p).opsize = S_Q) then
  12433. begin
  12434. { Never necessary }
  12435. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12436. RemoveCurrentP(p, hp1);
  12437. Result := True;
  12438. Exit;
  12439. end;
  12440. {$endif x86_64}
  12441. { Forward check to determine necessity of and %reg,%reg }
  12442. TransferUsedRegs(TmpUsedRegs);
  12443. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12444. { Saves on a bunch of dereferences }
  12445. ActiveReg := taicpu(p).oper[1]^.reg;
  12446. case taicpu(hp1).opcode of
  12447. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12448. if (
  12449. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12450. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12451. ) and
  12452. (
  12453. (taicpu(hp1).opcode <> A_MOV) or
  12454. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12455. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12456. ) and
  12457. not (
  12458. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12459. (taicpu(hp1).opcode = A_MOV) and
  12460. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12461. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12462. ) and
  12463. (
  12464. (
  12465. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12466. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12467. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12468. ) or
  12469. (
  12470. {$ifdef x86_64}
  12471. (
  12472. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12473. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12474. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12475. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12476. ) and
  12477. {$endif x86_64}
  12478. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12479. )
  12480. ) then
  12481. begin
  12482. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12483. RemoveCurrentP(p, hp1);
  12484. Result := True;
  12485. Exit;
  12486. end;
  12487. A_ADD,
  12488. A_AND,
  12489. A_BSF,
  12490. A_BSR,
  12491. A_BTC,
  12492. A_BTR,
  12493. A_BTS,
  12494. A_OR,
  12495. A_SUB,
  12496. A_XOR:
  12497. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12498. if (
  12499. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12500. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12501. ) and
  12502. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12503. begin
  12504. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12505. RemoveCurrentP(p, hp1);
  12506. Result := True;
  12507. Exit;
  12508. end;
  12509. A_CMP,
  12510. A_TEST:
  12511. if (
  12512. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12513. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12514. ) and
  12515. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12516. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12517. begin
  12518. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12519. RemoveCurrentP(p, hp1);
  12520. Result := True;
  12521. Exit;
  12522. end;
  12523. A_BSWAP,
  12524. A_NEG,
  12525. A_NOT:
  12526. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12527. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12528. begin
  12529. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12530. RemoveCurrentP(p, hp1);
  12531. Result := True;
  12532. Exit;
  12533. end;
  12534. else
  12535. ;
  12536. end;
  12537. end;
  12538. if (taicpu(hp1).is_jmp) and
  12539. (taicpu(hp1).opcode<>A_JMP) and
  12540. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12541. begin
  12542. { change
  12543. and x, reg
  12544. jxx
  12545. to
  12546. test x, reg
  12547. jxx
  12548. if reg is deallocated before the
  12549. jump, but only if it's a conditional jump (PFV)
  12550. }
  12551. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12552. taicpu(p).opcode := A_TEST;
  12553. Exit;
  12554. end;
  12555. Break;
  12556. end;
  12557. { Lone AND tests }
  12558. if (taicpu(p).oper[0]^.typ = top_const) then
  12559. begin
  12560. {
  12561. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12562. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12563. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12564. }
  12565. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12566. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12567. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12568. begin
  12569. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12570. if taicpu(p).opsize = S_L then
  12571. begin
  12572. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12573. Result := True;
  12574. end;
  12575. end;
  12576. end;
  12577. { Backward check to determine necessity of and %reg,%reg }
  12578. if (taicpu(p).oper[0]^.typ = top_reg) and
  12579. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12580. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12581. GetLastInstruction(p, hp2) and
  12582. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12583. { Check size of adjacent instruction to determine if the AND is
  12584. effectively a null operation }
  12585. (
  12586. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12587. { Note: Don't include S_Q }
  12588. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12589. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12590. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12591. ) then
  12592. begin
  12593. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12594. { If GetNextInstruction returned False, hp1 will be nil }
  12595. RemoveCurrentP(p, hp1);
  12596. Result := True;
  12597. Exit;
  12598. end;
  12599. end;
  12600. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12601. var
  12602. hp1, hp2: tai;
  12603. NewRef: TReference;
  12604. Distance: Cardinal;
  12605. TempTracking: TAllUsedRegs;
  12606. { This entire nested function is used in an if-statement below, but we
  12607. want to avoid all the used reg transfers and GetNextInstruction calls
  12608. until we really have to check }
  12609. function MemRegisterNotUsedLater: Boolean; inline;
  12610. var
  12611. hp2: tai;
  12612. begin
  12613. TransferUsedRegs(TmpUsedRegs);
  12614. hp2 := p;
  12615. repeat
  12616. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12617. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12618. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12619. end;
  12620. begin
  12621. Result := False;
  12622. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12623. (taicpu(p).oper[1]^.typ = top_reg) then
  12624. begin
  12625. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12626. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12627. (hp1.typ <> ait_instruction) or
  12628. not
  12629. (
  12630. (cs_opt_level3 in current_settings.optimizerswitches) or
  12631. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12632. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12633. ) then
  12634. Exit;
  12635. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12636. addq $x, %rax
  12637. movq %rax, %rdx
  12638. sarq $63, %rdx
  12639. (%rax still in use)
  12640. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12641. leaq $x(%rax),%rdx
  12642. addq $x, %rax
  12643. sarq $63, %rdx
  12644. ...which is okay since it breaks the dependency chain between
  12645. addq and movq, but if OptPass2MOV is called first:
  12646. addq $x, %rax
  12647. cqto
  12648. ...which is better in all ways, taking only 2 cycles to execute
  12649. and much smaller in code size.
  12650. }
  12651. { The extra register tracking is quite strenuous }
  12652. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12653. MatchInstruction(hp1, A_MOV, []) then
  12654. begin
  12655. { Update the register tracking to the MOV instruction }
  12656. CopyUsedRegs(TempTracking);
  12657. hp2 := p;
  12658. repeat
  12659. UpdateUsedRegs(tai(hp2.Next));
  12660. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12661. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12662. OptPass2ADD get called again }
  12663. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12664. begin
  12665. { Reset the tracking to the current instruction }
  12666. RestoreUsedRegs(TempTracking);
  12667. ReleaseUsedRegs(TempTracking);
  12668. Result := True;
  12669. Exit;
  12670. end;
  12671. { Reset the tracking to the current instruction }
  12672. RestoreUsedRegs(TempTracking);
  12673. ReleaseUsedRegs(TempTracking);
  12674. { If OptPass2MOV returned True, we don't need to set Result to
  12675. True if hp1 didn't change because the ADD instruction didn't
  12676. get modified and we'll be evaluating hp1 again when the
  12677. peephole optimizer reaches it }
  12678. end;
  12679. { Change:
  12680. add %reg2,%reg1
  12681. (%reg2 not modified in between)
  12682. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12683. To:
  12684. mov/s/z #(%reg1,%reg2),%reg1
  12685. }
  12686. if (taicpu(p).oper[0]^.typ = top_reg) and
  12687. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12688. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12689. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12690. (
  12691. (
  12692. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12693. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12694. { r/esp cannot be an index }
  12695. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12696. ) or (
  12697. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12698. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12699. )
  12700. ) and (
  12701. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12702. (
  12703. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12704. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12705. MemRegisterNotUsedLater
  12706. )
  12707. ) then
  12708. begin
  12709. if (
  12710. { Instructions are guaranteed to be adjacent on -O2 and under }
  12711. (cs_opt_level3 in current_settings.optimizerswitches) and
  12712. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12713. ) then
  12714. begin
  12715. { If the other register is used in between, move the MOV
  12716. instruction to right after the ADD instruction so a
  12717. saving can still be made }
  12718. Asml.Remove(hp1);
  12719. Asml.InsertAfter(hp1, p);
  12720. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12721. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12722. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12723. RemoveCurrentp(p, hp1);
  12724. end
  12725. else
  12726. begin
  12727. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12728. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12729. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12730. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12731. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12732. { hp1 may not be the immediate next instruction under -O3 }
  12733. RemoveCurrentp(p)
  12734. else
  12735. RemoveCurrentp(p, hp1);
  12736. end;
  12737. Result := True;
  12738. Exit;
  12739. end;
  12740. { Change:
  12741. addl/q $x,%reg1
  12742. movl/q %reg1,%reg2
  12743. To:
  12744. leal/q $x(%reg1),%reg2
  12745. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12746. Breaks the dependency chain.
  12747. }
  12748. if (taicpu(p).oper[0]^.typ = top_const) and
  12749. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12750. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12751. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12752. (
  12753. { Instructions are guaranteed to be adjacent on -O2 and under }
  12754. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12755. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12756. ) then
  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. if (
  12764. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12765. not (cs_opt_size in current_settings.optimizerswitches) or
  12766. (
  12767. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12768. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12769. )
  12770. ) then
  12771. begin
  12772. { Change the MOV instruction to a LEA instruction, and update the
  12773. first operand }
  12774. reference_reset(NewRef, 1, []);
  12775. NewRef.base := taicpu(p).oper[1]^.reg;
  12776. NewRef.scalefactor := 1;
  12777. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12778. taicpu(hp1).opcode := A_LEA;
  12779. taicpu(hp1).loadref(0, NewRef);
  12780. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12781. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12782. begin
  12783. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12784. { Move what is now the LEA instruction to before the ADD instruction }
  12785. Asml.Remove(hp1);
  12786. Asml.InsertBefore(hp1, p);
  12787. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12788. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12789. p := hp1;
  12790. end
  12791. else
  12792. begin
  12793. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12794. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12795. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12796. { hp1 may not be the immediate next instruction under -O3 }
  12797. RemoveCurrentp(p)
  12798. else
  12799. RemoveCurrentp(p, hp1);
  12800. end;
  12801. Result := True;
  12802. end;
  12803. end;
  12804. end;
  12805. end;
  12806. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12807. var
  12808. SubReg: TSubRegister;
  12809. begin
  12810. Result:=false;
  12811. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12812. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12813. with taicpu(p).oper[0]^.ref^ do
  12814. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12815. begin
  12816. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12817. begin
  12818. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12819. taicpu(p).opcode := A_ADD;
  12820. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12821. Result := True;
  12822. end
  12823. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12824. begin
  12825. if (base <> NR_NO) then
  12826. begin
  12827. if (scalefactor <= 1) then
  12828. begin
  12829. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12830. taicpu(p).opcode := A_ADD;
  12831. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12832. Result := True;
  12833. end;
  12834. end
  12835. else
  12836. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12837. if (scalefactor in [2, 4, 8]) then
  12838. begin
  12839. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12840. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12841. taicpu(p).opcode := A_SHL;
  12842. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12843. Result := True;
  12844. end;
  12845. end;
  12846. end;
  12847. end;
  12848. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12849. var
  12850. hp1, hp2: tai;
  12851. NewRef: TReference;
  12852. Distance: Cardinal;
  12853. TempTracking: TAllUsedRegs;
  12854. begin
  12855. Result := False;
  12856. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12857. MatchOpType(taicpu(p),top_const,top_reg) then
  12858. begin
  12859. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12860. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12861. (hp1.typ <> ait_instruction) or
  12862. not
  12863. (
  12864. (cs_opt_level3 in current_settings.optimizerswitches) or
  12865. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12866. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12867. ) then
  12868. Exit;
  12869. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12870. subq $x, %rax
  12871. movq %rax, %rdx
  12872. sarq $63, %rdx
  12873. (%rax still in use)
  12874. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12875. leaq $-x(%rax),%rdx
  12876. movq $x, %rax
  12877. sarq $63, %rdx
  12878. ...which is okay since it breaks the dependency chain between
  12879. subq and movq, but if OptPass2MOV is called first:
  12880. subq $x, %rax
  12881. cqto
  12882. ...which is better in all ways, taking only 2 cycles to execute
  12883. and much smaller in code size.
  12884. }
  12885. { The extra register tracking is quite strenuous }
  12886. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12887. MatchInstruction(hp1, A_MOV, []) then
  12888. begin
  12889. { Update the register tracking to the MOV instruction }
  12890. CopyUsedRegs(TempTracking);
  12891. hp2 := p;
  12892. repeat
  12893. UpdateUsedRegs(tai(hp2.Next));
  12894. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12895. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12896. OptPass2SUB get called again }
  12897. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12898. begin
  12899. { Reset the tracking to the current instruction }
  12900. RestoreUsedRegs(TempTracking);
  12901. ReleaseUsedRegs(TempTracking);
  12902. Result := True;
  12903. Exit;
  12904. end;
  12905. { Reset the tracking to the current instruction }
  12906. RestoreUsedRegs(TempTracking);
  12907. ReleaseUsedRegs(TempTracking);
  12908. { If OptPass2MOV returned True, we don't need to set Result to
  12909. True if hp1 didn't change because the SUB instruction didn't
  12910. get modified and we'll be evaluating hp1 again when the
  12911. peephole optimizer reaches it }
  12912. end;
  12913. { Change:
  12914. subl/q $x,%reg1
  12915. movl/q %reg1,%reg2
  12916. To:
  12917. leal/q $-x(%reg1),%reg2
  12918. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12919. Breaks the dependency chain and potentially permits the removal of
  12920. a CMP instruction if one follows.
  12921. }
  12922. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12923. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12924. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12925. (
  12926. { Instructions are guaranteed to be adjacent on -O2 and under }
  12927. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12928. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12929. ) then
  12930. begin
  12931. TransferUsedRegs(TmpUsedRegs);
  12932. hp2 := p;
  12933. repeat
  12934. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12935. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12936. if (
  12937. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12938. not (cs_opt_size in current_settings.optimizerswitches) or
  12939. (
  12940. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12941. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12942. )
  12943. ) then
  12944. begin
  12945. { Change the MOV instruction to a LEA instruction, and update the
  12946. first operand }
  12947. reference_reset(NewRef, 1, []);
  12948. NewRef.base := taicpu(p).oper[1]^.reg;
  12949. NewRef.scalefactor := 1;
  12950. NewRef.offset := -taicpu(p).oper[0]^.val;
  12951. taicpu(hp1).opcode := A_LEA;
  12952. taicpu(hp1).loadref(0, NewRef);
  12953. TransferUsedRegs(TmpUsedRegs);
  12954. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12955. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12956. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12957. begin
  12958. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12959. { Move what is now the LEA instruction to before the SUB instruction }
  12960. Asml.Remove(hp1);
  12961. Asml.InsertBefore(hp1, p);
  12962. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12963. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12964. p := hp1;
  12965. end
  12966. else
  12967. begin
  12968. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12969. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12970. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12971. { hp1 may not be the immediate next instruction under -O3 }
  12972. RemoveCurrentp(p)
  12973. else
  12974. RemoveCurrentp(p, hp1);
  12975. end;
  12976. Result := True;
  12977. end;
  12978. end;
  12979. end;
  12980. end;
  12981. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12982. begin
  12983. { we can skip all instructions not messing with the stack pointer }
  12984. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12985. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12986. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12987. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12988. ({(taicpu(hp1).ops=0) or }
  12989. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12990. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12991. ) and }
  12992. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12993. )
  12994. ) do
  12995. GetNextInstruction(hp1,hp1);
  12996. Result:=assigned(hp1);
  12997. end;
  12998. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12999. var
  13000. hp1, hp2, hp3, hp4, hp5: tai;
  13001. begin
  13002. Result:=false;
  13003. hp5:=nil;
  13004. { replace
  13005. leal(q) x(<stackpointer>),<stackpointer>
  13006. call procname
  13007. leal(q) -x(<stackpointer>),<stackpointer>
  13008. ret
  13009. by
  13010. jmp procname
  13011. but do it only on level 4 because it destroys stack back traces
  13012. }
  13013. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13014. MatchOpType(taicpu(p),top_ref,top_reg) and
  13015. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13016. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13017. { the -8 or -24 are not required, but bail out early if possible,
  13018. higher values are unlikely }
  13019. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13020. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13021. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13022. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13023. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13024. GetNextInstruction(p, hp1) and
  13025. { Take a copy of hp1 }
  13026. SetAndTest(hp1, hp4) and
  13027. { trick to skip label }
  13028. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13029. SkipSimpleInstructions(hp1) and
  13030. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13031. GetNextInstruction(hp1, hp2) and
  13032. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13033. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13034. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13035. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13036. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13037. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13038. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13039. { Segment register will be NR_NO }
  13040. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13041. GetNextInstruction(hp2, hp3) and
  13042. { trick to skip label }
  13043. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13044. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13045. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13046. SetAndTest(hp3,hp5) and
  13047. GetNextInstruction(hp3,hp3) and
  13048. MatchInstruction(hp3,A_RET,[S_NO])
  13049. )
  13050. ) and
  13051. (taicpu(hp3).ops=0) then
  13052. begin
  13053. taicpu(hp1).opcode := A_JMP;
  13054. taicpu(hp1).is_jmp := true;
  13055. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13056. RemoveCurrentP(p, hp4);
  13057. RemoveInstruction(hp2);
  13058. RemoveInstruction(hp3);
  13059. if Assigned(hp5) then
  13060. begin
  13061. AsmL.Remove(hp5);
  13062. ASmL.InsertBefore(hp5,hp1)
  13063. end;
  13064. Result:=true;
  13065. end;
  13066. end;
  13067. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13068. {$ifdef x86_64}
  13069. var
  13070. hp1, hp2, hp3, hp4, hp5: tai;
  13071. {$endif x86_64}
  13072. begin
  13073. Result:=false;
  13074. {$ifdef x86_64}
  13075. hp5:=nil;
  13076. { replace
  13077. push %rax
  13078. call procname
  13079. pop %rcx
  13080. ret
  13081. by
  13082. jmp procname
  13083. but do it only on level 4 because it destroys stack back traces
  13084. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13085. for all supported calling conventions
  13086. }
  13087. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13088. MatchOpType(taicpu(p),top_reg) and
  13089. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13090. GetNextInstruction(p, hp1) and
  13091. { Take a copy of hp1 }
  13092. SetAndTest(hp1, hp4) and
  13093. { trick to skip label }
  13094. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13095. SkipSimpleInstructions(hp1) and
  13096. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13097. GetNextInstruction(hp1, hp2) and
  13098. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13099. MatchOpType(taicpu(hp2),top_reg) and
  13100. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13101. GetNextInstruction(hp2, hp3) and
  13102. { trick to skip label }
  13103. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13104. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13105. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13106. SetAndTest(hp3,hp5) and
  13107. GetNextInstruction(hp3,hp3) and
  13108. MatchInstruction(hp3,A_RET,[S_NO])
  13109. )
  13110. ) and
  13111. (taicpu(hp3).ops=0) then
  13112. begin
  13113. taicpu(hp1).opcode := A_JMP;
  13114. taicpu(hp1).is_jmp := true;
  13115. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13116. RemoveCurrentP(p, hp4);
  13117. RemoveInstruction(hp2);
  13118. RemoveInstruction(hp3);
  13119. if Assigned(hp5) then
  13120. begin
  13121. AsmL.Remove(hp5);
  13122. ASmL.InsertBefore(hp5,hp1)
  13123. end;
  13124. Result:=true;
  13125. end;
  13126. {$endif x86_64}
  13127. end;
  13128. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13129. var
  13130. Value, RegName: string;
  13131. begin
  13132. Result:=false;
  13133. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13134. begin
  13135. case taicpu(p).oper[0]^.val of
  13136. 0:
  13137. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13138. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13139. begin
  13140. { change "mov $0,%reg" into "xor %reg,%reg" }
  13141. taicpu(p).opcode := A_XOR;
  13142. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13143. Result := True;
  13144. {$ifdef x86_64}
  13145. end
  13146. else if (taicpu(p).opsize = S_Q) then
  13147. begin
  13148. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13149. { The actual optimization }
  13150. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13151. taicpu(p).changeopsize(S_L);
  13152. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13153. Result := True;
  13154. end;
  13155. $1..$FFFFFFFF:
  13156. begin
  13157. { Code size reduction by J. Gareth "Kit" Moreton }
  13158. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13159. case taicpu(p).opsize of
  13160. S_Q:
  13161. begin
  13162. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13163. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13164. { The actual optimization }
  13165. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13166. taicpu(p).changeopsize(S_L);
  13167. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13168. Result := True;
  13169. end;
  13170. else
  13171. { Do nothing };
  13172. end;
  13173. {$endif x86_64}
  13174. end;
  13175. -1:
  13176. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13177. if (cs_opt_size in current_settings.optimizerswitches) and
  13178. (taicpu(p).opsize <> S_B) and
  13179. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13180. begin
  13181. { change "mov $-1,%reg" into "or $-1,%reg" }
  13182. { NOTES:
  13183. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13184. - This operation creates a false dependency on the register, so only do it when optimising for size
  13185. - 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
  13186. }
  13187. taicpu(p).opcode := A_OR;
  13188. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13189. Result := True;
  13190. end;
  13191. else
  13192. { Do nothing };
  13193. end;
  13194. end;
  13195. end;
  13196. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13197. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13198. begin
  13199. Result := False;
  13200. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13201. Exit;
  13202. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13203. so don't bother optimising }
  13204. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13205. Exit;
  13206. if (taicpu(p).oper[0]^.typ <> top_const) or
  13207. { If the value can fit into an 8-bit signed integer, a smaller
  13208. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13209. falls within this range }
  13210. (
  13211. (taicpu(p).oper[0]^.val > -128) and
  13212. (taicpu(p).oper[0]^.val <= 127)
  13213. ) then
  13214. Exit;
  13215. { If we're optimising for size, this is acceptable }
  13216. if (cs_opt_size in current_settings.optimizerswitches) then
  13217. Exit(True);
  13218. if (taicpu(p).oper[1]^.typ = top_reg) and
  13219. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13220. Exit(True);
  13221. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13222. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13223. Exit(True);
  13224. end;
  13225. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13226. var
  13227. hp1: tai;
  13228. Value: TCGInt;
  13229. begin
  13230. Result := False;
  13231. if MatchOpType(taicpu(p), top_const, top_reg) then
  13232. begin
  13233. { Detect:
  13234. andw x, %ax (0 <= x < $8000)
  13235. ...
  13236. movzwl %ax,%eax
  13237. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13238. }
  13239. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13240. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13241. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13242. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13243. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13244. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13245. begin
  13246. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13247. taicpu(hp1).opcode := A_CWDE;
  13248. taicpu(hp1).clearop(0);
  13249. taicpu(hp1).clearop(1);
  13250. taicpu(hp1).ops := 0;
  13251. { A change was made, but not with p, so don't set Result, but
  13252. notify the compiler that a change was made }
  13253. Include(OptsToCheck, aoc_ForceNewIteration);
  13254. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13255. end;
  13256. end;
  13257. { If "not x" is a power of 2 (popcnt = 1), change:
  13258. and $x, %reg/ref
  13259. To:
  13260. btr lb(x), %reg/ref
  13261. }
  13262. if IsBTXAcceptable(p) and
  13263. (
  13264. { Make sure a TEST doesn't follow that plays with the register }
  13265. not GetNextInstruction(p, hp1) or
  13266. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13267. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13268. ) then
  13269. begin
  13270. {$push}{$R-}{$Q-}
  13271. { Value is a sign-extended 32-bit integer - just correct it
  13272. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13273. checks to see if this operand is an immediate. }
  13274. Value := not taicpu(p).oper[0]^.val;
  13275. {$pop}
  13276. {$ifdef x86_64}
  13277. if taicpu(p).opsize = S_L then
  13278. {$endif x86_64}
  13279. Value := Value and $FFFFFFFF;
  13280. if (PopCnt(QWord(Value)) = 1) then
  13281. begin
  13282. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13283. taicpu(p).opcode := A_BTR;
  13284. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13285. Result := True;
  13286. Exit;
  13287. end;
  13288. end;
  13289. end;
  13290. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13291. begin
  13292. Result := False;
  13293. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13294. Exit;
  13295. { Convert:
  13296. movswl %ax,%eax -> cwtl
  13297. movslq %eax,%rax -> cdqe
  13298. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13299. refer to the same opcode and depends only on the assembler's
  13300. current operand-size attribute. [Kit]
  13301. }
  13302. with taicpu(p) do
  13303. case opsize of
  13304. S_WL:
  13305. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13306. begin
  13307. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13308. opcode := A_CWDE;
  13309. clearop(0);
  13310. clearop(1);
  13311. ops := 0;
  13312. Result := True;
  13313. end;
  13314. {$ifdef x86_64}
  13315. S_LQ:
  13316. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13317. begin
  13318. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13319. opcode := A_CDQE;
  13320. clearop(0);
  13321. clearop(1);
  13322. ops := 0;
  13323. Result := True;
  13324. end;
  13325. {$endif x86_64}
  13326. else
  13327. ;
  13328. end;
  13329. end;
  13330. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13331. var
  13332. hp1, hp2: tai;
  13333. IdentityMask, Shift: TCGInt;
  13334. LimitSize: Topsize;
  13335. DoNotMerge: Boolean;
  13336. begin
  13337. Result := False;
  13338. { All these optimisations work on "shr const,%reg" }
  13339. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13340. Exit;
  13341. DoNotMerge := False;
  13342. Shift := taicpu(p).oper[0]^.val;
  13343. LimitSize := taicpu(p).opsize;
  13344. hp1 := p;
  13345. repeat
  13346. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13347. Break;
  13348. { Detect:
  13349. shr x, %reg
  13350. and y, %reg
  13351. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13352. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13353. }
  13354. case taicpu(hp1).opcode of
  13355. A_AND:
  13356. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13357. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13358. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13359. begin
  13360. { Make sure the FLAGS register isn't in use }
  13361. TransferUsedRegs(TmpUsedRegs);
  13362. hp2 := p;
  13363. repeat
  13364. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13365. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13366. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13367. begin
  13368. { Generate the identity mask }
  13369. case taicpu(p).opsize of
  13370. S_B:
  13371. IdentityMask := $FF shr Shift;
  13372. S_W:
  13373. IdentityMask := $FFFF shr Shift;
  13374. S_L:
  13375. IdentityMask := $FFFFFFFF shr Shift;
  13376. {$ifdef x86_64}
  13377. S_Q:
  13378. { We need to force the operands to be unsigned 64-bit
  13379. integers otherwise the wrong value is generated }
  13380. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13381. {$endif x86_64}
  13382. else
  13383. InternalError(2022081501);
  13384. end;
  13385. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13386. begin
  13387. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13388. { All the possible 1 bits are covered, so we can remove the AND }
  13389. hp2 := tai(hp1.Previous);
  13390. RemoveInstruction(hp1);
  13391. { p wasn't actually changed, so don't set Result to True,
  13392. but a change was nonetheless made elsewhere }
  13393. Include(OptsToCheck, aoc_ForceNewIteration);
  13394. { Do another pass in case other AND or MOVZX instructions
  13395. follow }
  13396. hp1 := hp2;
  13397. Continue;
  13398. end;
  13399. end;
  13400. end;
  13401. A_TEST, A_CMP, A_Jcc:
  13402. { Skip over conditional jumps and relevant comparisons }
  13403. Continue;
  13404. A_MOVZX:
  13405. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13406. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13407. begin
  13408. { Since the original register is being read as is, subsequent
  13409. SHRs must not be merged at this point }
  13410. DoNotMerge := True;
  13411. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13412. begin
  13413. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13414. begin
  13415. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13416. { All the possible 1 bits are covered, so we can remove the AND }
  13417. hp2 := tai(hp1.Previous);
  13418. RemoveInstruction(hp1);
  13419. hp1 := hp2;
  13420. end
  13421. else { Different register target }
  13422. begin
  13423. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13424. taicpu(hp1).opcode := A_MOV;
  13425. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13426. case taicpu(hp1).opsize of
  13427. S_BW:
  13428. taicpu(hp1).opsize := S_W;
  13429. S_BL, S_WL:
  13430. taicpu(hp1).opsize := S_L;
  13431. else
  13432. InternalError(2022081503);
  13433. end;
  13434. end;
  13435. end
  13436. else if (Shift > 0) and
  13437. (taicpu(p).opsize = S_W) and
  13438. (taicpu(hp1).opsize = S_WL) and
  13439. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13440. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13441. begin
  13442. { Detect:
  13443. shr x, %ax (x > 0)
  13444. ...
  13445. movzwl %ax,%eax
  13446. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13447. }
  13448. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13449. taicpu(hp1).opcode := A_CWDE;
  13450. taicpu(hp1).clearop(0);
  13451. taicpu(hp1).clearop(1);
  13452. taicpu(hp1).ops := 0;
  13453. end;
  13454. { Move onto the next instruction }
  13455. Continue;
  13456. end;
  13457. A_SHL, A_SAL, A_SHR:
  13458. if (taicpu(hp1).opsize <= LimitSize) and
  13459. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13460. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13461. begin
  13462. { Make sure the sizes don't exceed the register size limit
  13463. (measured by the shift value falling below the limit) }
  13464. if taicpu(hp1).opsize < LimitSize then
  13465. LimitSize := taicpu(hp1).opsize;
  13466. if taicpu(hp1).opcode = A_SHR then
  13467. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13468. else
  13469. begin
  13470. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13471. DoNotMerge := True;
  13472. end;
  13473. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13474. Break;
  13475. { Since we've established that the combined shift is within
  13476. limits, we can actually combine the adjacent SHR
  13477. instructions even if they're different sizes }
  13478. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13479. begin
  13480. hp2 := tai(hp1.Previous);
  13481. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13482. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13483. RemoveInstruction(hp1);
  13484. hp1 := hp2;
  13485. end;
  13486. { Move onto the next instruction }
  13487. Continue;
  13488. end;
  13489. else
  13490. ;
  13491. end;
  13492. Break;
  13493. until False;
  13494. { Detect the following (looking backwards):
  13495. shr %cl,%reg
  13496. shr x, %reg
  13497. Swap the two SHR instructions to minimise a pipeline stall.
  13498. }
  13499. if GetLastInstruction(p, hp1) and
  13500. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13501. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13502. { First operand will be %cl }
  13503. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13504. { Just to be sure }
  13505. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13506. begin
  13507. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13508. { Moving the entries this way ensures the register tracking remains correct }
  13509. Asml.Remove(p);
  13510. Asml.InsertBefore(p, hp1);
  13511. p := hp1;
  13512. { Don't set Result to True because the current instruction is now
  13513. "shr %cl,%reg" and there's nothing more we can do with it }
  13514. end;
  13515. end;
  13516. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13517. var
  13518. hp1, hp2: tai;
  13519. Opposite, SecondOpposite: TAsmOp;
  13520. NewCond: TAsmCond;
  13521. begin
  13522. Result := False;
  13523. { Change:
  13524. add/sub 128,(dest)
  13525. To:
  13526. sub/add -128,(dest)
  13527. This generaally takes fewer bytes to encode because -128 can be stored
  13528. in a signed byte, whereas +128 cannot.
  13529. }
  13530. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13531. begin
  13532. if taicpu(p).opcode = A_ADD then
  13533. Opposite := A_SUB
  13534. else
  13535. Opposite := A_ADD;
  13536. { Be careful if the flags are in use, because the CF flag inverts
  13537. when changing from ADD to SUB and vice versa }
  13538. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13539. GetNextInstruction(p, hp1) then
  13540. begin
  13541. TransferUsedRegs(TmpUsedRegs);
  13542. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13543. hp2 := hp1;
  13544. { Scan ahead to check if everything's safe }
  13545. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13546. begin
  13547. if (hp1.typ <> ait_instruction) then
  13548. { Probably unsafe since the flags are still in use }
  13549. Exit;
  13550. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13551. { Stop searching at an unconditional jump }
  13552. Break;
  13553. if not
  13554. (
  13555. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13556. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13557. ) and
  13558. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13559. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13560. Exit;
  13561. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13562. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13563. { Move to the next instruction }
  13564. GetNextInstruction(hp1, hp1);
  13565. end;
  13566. while Assigned(hp2) and (hp2 <> hp1) do
  13567. begin
  13568. NewCond := C_None;
  13569. case taicpu(hp2).condition of
  13570. C_A, C_NBE:
  13571. NewCond := C_BE;
  13572. C_B, C_C, C_NAE:
  13573. NewCond := C_AE;
  13574. C_AE, C_NB, C_NC:
  13575. NewCond := C_B;
  13576. C_BE, C_NA:
  13577. NewCond := C_A;
  13578. else
  13579. { No change needed };
  13580. end;
  13581. if NewCond <> C_None then
  13582. begin
  13583. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13584. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13585. taicpu(hp2).condition := NewCond;
  13586. end
  13587. else
  13588. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13589. begin
  13590. { Because of the flipping of the carry bit, to ensure
  13591. the operation remains equivalent, ADC becomes SBB
  13592. and vice versa, and the constant is not-inverted.
  13593. If multiple ADCs or SBBs appear in a row, each one
  13594. changed causes the carry bit to invert, so they all
  13595. need to be flipped }
  13596. if taicpu(hp2).opcode = A_ADC then
  13597. SecondOpposite := A_SBB
  13598. else
  13599. SecondOpposite := A_ADC;
  13600. if taicpu(hp2).oper[0]^.typ <> top_const then
  13601. { Should have broken out of this optimisation already }
  13602. InternalError(2021112901);
  13603. 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]^) + ' -> ' +
  13604. 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);
  13605. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13606. taicpu(hp2).opcode := SecondOpposite;
  13607. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13608. end;
  13609. { Move to the next instruction }
  13610. GetNextInstruction(hp2, hp2);
  13611. end;
  13612. if (hp2 <> hp1) then
  13613. InternalError(2021111501);
  13614. end;
  13615. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13616. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13617. taicpu(p).opcode := Opposite;
  13618. taicpu(p).oper[0]^.val := -128;
  13619. { No further optimisations can be made on this instruction, so move
  13620. onto the next one to save time }
  13621. p := tai(p.Next);
  13622. UpdateUsedRegs(p);
  13623. Result := True;
  13624. Exit;
  13625. end;
  13626. { Detect:
  13627. add/sub %reg2,(dest)
  13628. add/sub x, (dest)
  13629. (dest can be a register or a reference)
  13630. Swap the instructions to minimise a pipeline stall. This reverses the
  13631. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13632. optimisations could be made.
  13633. }
  13634. if (taicpu(p).oper[0]^.typ = top_reg) and
  13635. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13636. (
  13637. (
  13638. (taicpu(p).oper[1]^.typ = top_reg) and
  13639. { We can try searching further ahead if we're writing to a register }
  13640. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13641. ) or
  13642. (
  13643. (taicpu(p).oper[1]^.typ = top_ref) and
  13644. GetNextInstruction(p, hp1)
  13645. )
  13646. ) and
  13647. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13648. (taicpu(hp1).oper[0]^.typ = top_const) and
  13649. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13650. begin
  13651. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13652. TransferUsedRegs(TmpUsedRegs);
  13653. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13654. hp2 := p;
  13655. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13656. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13657. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13658. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13659. begin
  13660. asml.remove(hp1);
  13661. asml.InsertBefore(hp1, p);
  13662. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13663. Result := True;
  13664. end;
  13665. end;
  13666. end;
  13667. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13668. var
  13669. hp1: tai;
  13670. begin
  13671. Result:=false;
  13672. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13673. while GetNextInstruction(p, hp1) and
  13674. TrySwapMovCmp(p, hp1) do
  13675. begin
  13676. if MatchInstruction(hp1, A_MOV, []) then
  13677. begin
  13678. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13679. begin
  13680. { A little hacky, but since CMP doesn't read the flags, only
  13681. modify them, it's safe if they get scrambled by MOV -> XOR }
  13682. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13683. Result := PostPeepholeOptMov(hp1);
  13684. {$ifdef x86_64}
  13685. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13686. { Used to shrink instruction size }
  13687. PostPeepholeOptXor(hp1);
  13688. {$endif x86_64}
  13689. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13690. end
  13691. else
  13692. begin
  13693. Result := PostPeepholeOptMov(hp1);
  13694. {$ifdef x86_64}
  13695. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13696. { Used to shrink instruction size }
  13697. PostPeepholeOptXor(hp1);
  13698. {$endif x86_64}
  13699. end;
  13700. end;
  13701. { Enabling this flag is actually a null operation, but it marks
  13702. the code as 'modified' during this pass }
  13703. Include(OptsToCheck, aoc_ForceNewIteration);
  13704. end;
  13705. { change "cmp $0, %reg" to "test %reg, %reg" }
  13706. if MatchOpType(taicpu(p),top_const,top_reg) and
  13707. (taicpu(p).oper[0]^.val = 0) then
  13708. begin
  13709. taicpu(p).opcode := A_TEST;
  13710. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13711. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13712. Result:=true;
  13713. end;
  13714. end;
  13715. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13716. var
  13717. IsTestConstX, IsValid : Boolean;
  13718. hp1,hp2 : tai;
  13719. begin
  13720. Result:=false;
  13721. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13722. if (taicpu(p).opcode = A_TEST) then
  13723. while GetNextInstruction(p, hp1) and
  13724. TrySwapMovCmp(p, hp1) do
  13725. begin
  13726. if MatchInstruction(hp1, A_MOV, []) then
  13727. begin
  13728. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13729. begin
  13730. { A little hacky, but since TEST doesn't read the flags, only
  13731. modify them, it's safe if they get scrambled by MOV -> XOR }
  13732. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13733. Result := PostPeepholeOptMov(hp1);
  13734. {$ifdef x86_64}
  13735. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13736. { Used to shrink instruction size }
  13737. PostPeepholeOptXor(hp1);
  13738. {$endif x86_64}
  13739. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13740. end
  13741. else
  13742. begin
  13743. Result := PostPeepholeOptMov(hp1);
  13744. {$ifdef x86_64}
  13745. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13746. { Used to shrink instruction size }
  13747. PostPeepholeOptXor(hp1);
  13748. {$endif x86_64}
  13749. end;
  13750. end;
  13751. { Enabling this flag is actually a null operation, but it marks
  13752. the code as 'modified' during this pass }
  13753. Include(OptsToCheck, aoc_ForceNewIteration);
  13754. end;
  13755. { If x is a power of 2 (popcnt = 1), change:
  13756. or $x, %reg/ref
  13757. To:
  13758. bts lb(x), %reg/ref
  13759. }
  13760. if (taicpu(p).opcode = A_OR) and
  13761. IsBTXAcceptable(p) and
  13762. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13763. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13764. (
  13765. { Don't optimise if a test instruction follows }
  13766. not GetNextInstruction(p, hp1) or
  13767. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13768. ) then
  13769. begin
  13770. 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);
  13771. taicpu(p).opcode := A_BTS;
  13772. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13773. Result := True;
  13774. Exit;
  13775. end;
  13776. { If x is a power of 2 (popcnt = 1), change:
  13777. test $x, %reg/ref
  13778. je / sete / cmove (or jne / setne)
  13779. To:
  13780. bt lb(x), %reg/ref
  13781. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13782. }
  13783. if (taicpu(p).opcode = A_TEST) and
  13784. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13785. (taicpu(p).oper[0]^.typ = top_const) and
  13786. (
  13787. (cs_opt_size in current_settings.optimizerswitches) or
  13788. (
  13789. (taicpu(p).oper[1]^.typ = top_reg) and
  13790. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13791. ) or
  13792. (
  13793. (taicpu(p).oper[1]^.typ <> top_reg) and
  13794. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13795. )
  13796. ) and
  13797. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13798. { For sizes less than S_L, the byte size is equal or larger with BT,
  13799. so don't bother optimising }
  13800. (taicpu(p).opsize >= S_L) then
  13801. begin
  13802. IsValid := True;
  13803. { Check the next set of instructions, watching the FLAGS register
  13804. and the conditions used }
  13805. TransferUsedRegs(TmpUsedRegs);
  13806. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13807. hp1 := p;
  13808. hp2 := nil;
  13809. while GetNextInstruction(hp1, hp1) do
  13810. begin
  13811. if not Assigned(hp2) then
  13812. { The first instruction after TEST }
  13813. hp2 := hp1;
  13814. if (hp1.typ <> ait_instruction) then
  13815. begin
  13816. { If the flags are no longer in use, everything is fine }
  13817. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13818. IsValid := False;
  13819. Break;
  13820. end;
  13821. case taicpu(hp1).condition of
  13822. C_None:
  13823. begin
  13824. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13825. { Something is not quite normal, so play safe and don't change }
  13826. IsValid := False;
  13827. Break;
  13828. end;
  13829. C_E, C_Z, C_NE, C_NZ:
  13830. { This is fine };
  13831. else
  13832. begin
  13833. { Unsupported condition }
  13834. IsValid := False;
  13835. Break;
  13836. end;
  13837. end;
  13838. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13839. end;
  13840. if IsValid then
  13841. begin
  13842. while hp2 <> hp1 do
  13843. begin
  13844. case taicpu(hp2).condition of
  13845. C_Z, C_E:
  13846. taicpu(hp2).condition := C_NC;
  13847. C_NZ, C_NE:
  13848. taicpu(hp2).condition := C_C;
  13849. else
  13850. { Should not get this by this point }
  13851. InternalError(2022110701);
  13852. end;
  13853. GetNextInstruction(hp2, hp2);
  13854. end;
  13855. 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);
  13856. taicpu(p).opcode := A_BT;
  13857. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13858. Result := True;
  13859. Exit;
  13860. end;
  13861. end;
  13862. { removes the line marked with (x) from the sequence
  13863. and/or/xor/add/sub/... $x, %y
  13864. test/or %y, %y | test $-1, %y (x)
  13865. j(n)z _Label
  13866. as the first instruction already adjusts the ZF
  13867. %y operand may also be a reference }
  13868. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13869. MatchOperand(taicpu(p).oper[0]^,-1);
  13870. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13871. GetLastInstruction(p, hp1) and
  13872. (tai(hp1).typ = ait_instruction) and
  13873. GetNextInstruction(p,hp2) and
  13874. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13875. case taicpu(hp1).opcode Of
  13876. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13877. { These two instructions set the zero flag if the result is zero }
  13878. A_POPCNT, A_LZCNT:
  13879. begin
  13880. if (
  13881. { With POPCNT, an input of zero will set the zero flag
  13882. because the population count of zero is zero }
  13883. (taicpu(hp1).opcode = A_POPCNT) and
  13884. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13885. (
  13886. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13887. { Faster than going through the second half of the 'or'
  13888. condition below }
  13889. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13890. )
  13891. ) or (
  13892. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13893. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13894. { and in case of carry for A(E)/B(E)/C/NC }
  13895. (
  13896. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13897. (
  13898. (taicpu(hp1).opcode <> A_ADD) and
  13899. (taicpu(hp1).opcode <> A_SUB) and
  13900. (taicpu(hp1).opcode <> A_LZCNT)
  13901. )
  13902. )
  13903. ) then
  13904. begin
  13905. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13906. RemoveCurrentP(p, hp2);
  13907. Result:=true;
  13908. Exit;
  13909. end;
  13910. end;
  13911. A_SHL, A_SAL, A_SHR, A_SAR:
  13912. begin
  13913. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13914. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13915. { therefore, it's only safe to do this optimization for }
  13916. { shifts by a (nonzero) constant }
  13917. (taicpu(hp1).oper[0]^.typ = top_const) and
  13918. (taicpu(hp1).oper[0]^.val <> 0) and
  13919. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13920. { and in case of carry for A(E)/B(E)/C/NC }
  13921. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13922. begin
  13923. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13924. RemoveCurrentP(p, hp2);
  13925. Result:=true;
  13926. Exit;
  13927. end;
  13928. end;
  13929. A_DEC, A_INC, A_NEG:
  13930. begin
  13931. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13932. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13933. { and in case of carry for A(E)/B(E)/C/NC }
  13934. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13935. begin
  13936. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13937. RemoveCurrentP(p, hp2);
  13938. Result:=true;
  13939. Exit;
  13940. end;
  13941. end;
  13942. A_ANDN, A_BZHI:
  13943. begin
  13944. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13945. { Only the zero and sign flags are consistent with what the result is }
  13946. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13947. begin
  13948. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13949. RemoveCurrentP(p, hp2);
  13950. Result:=true;
  13951. Exit;
  13952. end;
  13953. end;
  13954. A_BEXTR:
  13955. begin
  13956. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13957. { Only the zero flag is set }
  13958. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13959. begin
  13960. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13961. RemoveCurrentP(p, hp2);
  13962. Result:=true;
  13963. Exit;
  13964. end;
  13965. end;
  13966. else
  13967. ;
  13968. end; { case }
  13969. { change "test $-1,%reg" into "test %reg,%reg" }
  13970. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13971. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13972. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13973. if MatchInstruction(p, A_OR, []) and
  13974. { Can only match if they're both registers }
  13975. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13976. begin
  13977. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13978. taicpu(p).opcode := A_TEST;
  13979. { No need to set Result to True, as we've done all the optimisations we can }
  13980. end;
  13981. end;
  13982. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13983. var
  13984. hp1,hp3 : tai;
  13985. {$ifndef x86_64}
  13986. hp2 : taicpu;
  13987. {$endif x86_64}
  13988. begin
  13989. Result:=false;
  13990. hp3:=nil;
  13991. {$ifndef x86_64}
  13992. { don't do this on modern CPUs, this really hurts them due to
  13993. broken call/ret pairing }
  13994. if (current_settings.optimizecputype < cpu_Pentium2) and
  13995. not(cs_create_pic in current_settings.moduleswitches) and
  13996. GetNextInstruction(p, hp1) and
  13997. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13998. MatchOpType(taicpu(hp1),top_ref) and
  13999. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14000. begin
  14001. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14002. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14003. InsertLLItem(p.previous, p, hp2);
  14004. taicpu(p).opcode := A_JMP;
  14005. taicpu(p).is_jmp := true;
  14006. RemoveInstruction(hp1);
  14007. Result:=true;
  14008. end
  14009. else
  14010. {$endif x86_64}
  14011. { replace
  14012. call procname
  14013. ret
  14014. by
  14015. jmp procname
  14016. but do it only on level 4 because it destroys stack back traces
  14017. else if the subroutine is marked as no return, remove the ret
  14018. }
  14019. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14020. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14021. GetNextInstruction(p, hp1) and
  14022. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14023. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14024. SetAndTest(hp1,hp3) and
  14025. GetNextInstruction(hp1,hp1) and
  14026. MatchInstruction(hp1,A_RET,[S_NO])
  14027. )
  14028. ) and
  14029. (taicpu(hp1).ops=0) then
  14030. begin
  14031. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14032. { we might destroy stack alignment here if we do not do a call }
  14033. (target_info.stackalign<=sizeof(SizeUInt)) then
  14034. begin
  14035. taicpu(p).opcode := A_JMP;
  14036. taicpu(p).is_jmp := true;
  14037. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14038. end
  14039. else
  14040. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14041. RemoveInstruction(hp1);
  14042. if Assigned(hp3) then
  14043. begin
  14044. AsmL.Remove(hp3);
  14045. AsmL.InsertBefore(hp3,p)
  14046. end;
  14047. Result:=true;
  14048. end;
  14049. end;
  14050. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14051. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14052. begin
  14053. case OpSize of
  14054. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14055. Result := (Val <= $FF) and (Val >= -128);
  14056. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14057. Result := (Val <= $FFFF) and (Val >= -32768);
  14058. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14059. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14060. else
  14061. Result := True;
  14062. end;
  14063. end;
  14064. var
  14065. hp1, hp2 : tai;
  14066. SizeChange: Boolean;
  14067. PreMessage: string;
  14068. begin
  14069. Result := False;
  14070. if (taicpu(p).oper[0]^.typ = top_reg) and
  14071. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14072. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14073. begin
  14074. { Change (using movzbl %al,%eax as an example):
  14075. movzbl %al, %eax movzbl %al, %eax
  14076. cmpl x, %eax testl %eax,%eax
  14077. To:
  14078. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14079. movzbl %al, %eax movzbl %al, %eax
  14080. Smaller instruction and minimises pipeline stall as the CPU
  14081. doesn't have to wait for the register to get zero-extended. [Kit]
  14082. Also allow if the smaller of the two registers is being checked,
  14083. as this still removes the false dependency.
  14084. }
  14085. if
  14086. (
  14087. (
  14088. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14089. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14090. ) or (
  14091. { If MatchOperand returns True, they must both be registers }
  14092. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14093. )
  14094. ) and
  14095. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14096. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14097. begin
  14098. 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);
  14099. asml.Remove(hp1);
  14100. asml.InsertBefore(hp1, p);
  14101. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14102. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14103. begin
  14104. taicpu(hp1).opcode := A_TEST;
  14105. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14106. end;
  14107. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14108. case taicpu(p).opsize of
  14109. S_BW, S_BL:
  14110. begin
  14111. SizeChange := taicpu(hp1).opsize <> S_B;
  14112. taicpu(hp1).changeopsize(S_B);
  14113. end;
  14114. S_WL:
  14115. begin
  14116. SizeChange := taicpu(hp1).opsize <> S_W;
  14117. taicpu(hp1).changeopsize(S_W);
  14118. end
  14119. else
  14120. InternalError(2020112701);
  14121. end;
  14122. UpdateUsedRegs(tai(p.Next));
  14123. { Check if the register is used aferwards - if not, we can
  14124. remove the movzx instruction completely }
  14125. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14126. begin
  14127. { Hp1 is a better position than p for debugging purposes }
  14128. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14129. RemoveCurrentp(p, hp1);
  14130. Result := True;
  14131. end;
  14132. if SizeChange then
  14133. DebugMsg(SPeepholeOptimization + PreMessage +
  14134. 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)
  14135. else
  14136. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14137. Exit;
  14138. end;
  14139. { Change (using movzwl %ax,%eax as an example):
  14140. movzwl %ax, %eax
  14141. movb %al, (dest) (Register is smaller than read register in movz)
  14142. To:
  14143. movb %al, (dest) (Move one back to avoid a false dependency)
  14144. movzwl %ax, %eax
  14145. }
  14146. if (taicpu(hp1).opcode = A_MOV) and
  14147. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14148. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14149. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14150. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14151. begin
  14152. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14153. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14154. asml.Remove(hp1);
  14155. asml.InsertBefore(hp1, p);
  14156. if taicpu(hp1).oper[1]^.typ = top_reg then
  14157. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14158. { Check if the register is used aferwards - if not, we can
  14159. remove the movzx instruction completely }
  14160. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14161. begin
  14162. { Hp1 is a better position than p for debugging purposes }
  14163. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14164. RemoveCurrentp(p, hp1);
  14165. Result := True;
  14166. end;
  14167. Exit;
  14168. end;
  14169. end;
  14170. end;
  14171. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14172. var
  14173. hp1: tai;
  14174. {$ifdef x86_64}
  14175. PreMessage, RegName: string;
  14176. {$endif x86_64}
  14177. begin
  14178. Result := False;
  14179. { If x is a power of 2 (popcnt = 1), change:
  14180. xor $x, %reg/ref
  14181. To:
  14182. btc lb(x), %reg/ref
  14183. }
  14184. if IsBTXAcceptable(p) and
  14185. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14186. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14187. (
  14188. { Don't optimise if a test instruction follows }
  14189. not GetNextInstruction(p, hp1) or
  14190. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14191. ) then
  14192. begin
  14193. 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);
  14194. taicpu(p).opcode := A_BTC;
  14195. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14196. Result := True;
  14197. Exit;
  14198. end;
  14199. {$ifdef x86_64}
  14200. { Code size reduction by J. Gareth "Kit" Moreton }
  14201. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14202. as this removes the REX prefix }
  14203. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14204. Exit;
  14205. if taicpu(p).oper[0]^.typ <> top_reg then
  14206. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14207. InternalError(2018011500);
  14208. case taicpu(p).opsize of
  14209. S_Q:
  14210. begin
  14211. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14212. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14213. { The actual optimization }
  14214. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14215. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14216. taicpu(p).changeopsize(S_L);
  14217. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14218. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14219. end;
  14220. else
  14221. ;
  14222. end;
  14223. {$endif x86_64}
  14224. end;
  14225. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14226. var
  14227. XReg: TRegister;
  14228. begin
  14229. Result := False;
  14230. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14231. Smaller encoding and slightly faster on some platforms (also works for
  14232. ZMM-sized registers) }
  14233. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14234. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14235. begin
  14236. XReg := taicpu(p).oper[0]^.reg;
  14237. if (taicpu(p).oper[1]^.reg = XReg) then
  14238. begin
  14239. taicpu(p).changeopsize(S_XMM);
  14240. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14241. if (cs_opt_size in current_settings.optimizerswitches) then
  14242. begin
  14243. { Change input registers to %xmm0 to reduce size. Note that
  14244. there's a risk of a false dependency doing this, so only
  14245. optimise for size here }
  14246. XReg := NR_XMM0;
  14247. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14248. end
  14249. else
  14250. begin
  14251. setsubreg(XReg, R_SUBMMX);
  14252. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14253. end;
  14254. taicpu(p).oper[0]^.reg := XReg;
  14255. taicpu(p).oper[1]^.reg := XReg;
  14256. Result := True;
  14257. end;
  14258. end;
  14259. end;
  14260. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14261. var
  14262. OperIdx: Integer;
  14263. begin
  14264. for OperIdx := 0 to p.ops - 1 do
  14265. if p.oper[OperIdx]^.typ = top_ref then
  14266. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14267. end;
  14268. end.