aoptx86.pas 575 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444
  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. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM 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 GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p);
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. { Remember that hp1 is not necessarily the immediate
  2106. next instruction }
  2107. RemoveCurrentP(p);
  2108. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2109. RemoveInstruction(hp2);
  2110. result:=true;
  2111. end;
  2112. end
  2113. else if (hp1.typ = ait_instruction) and
  2114. (((taicpu(p).opcode=A_VMOVAPD) and
  2115. (taicpu(hp1).opcode=A_VCOMISD)) or
  2116. ((taicpu(p).opcode=A_VMOVAPS) and
  2117. ((taicpu(hp1).opcode=A_VCOMISS))
  2118. )
  2119. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2120. { change
  2121. movapX reg,reg1
  2122. vcomisX reg1,reg1
  2123. to
  2124. vcomisX reg,reg
  2125. }
  2126. begin
  2127. TransferUsedRegs(TmpUsedRegs);
  2128. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2129. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2130. begin
  2131. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2132. debug_op2str(taicpu(p).opcode)+' '+
  2133. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2134. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2135. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2136. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2137. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2138. RemoveCurrentP(p);
  2139. result:=true;
  2140. exit;
  2141. end;
  2142. end
  2143. end;
  2144. end;
  2145. end;
  2146. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2147. var
  2148. hp1 : tai;
  2149. begin
  2150. result:=false;
  2151. { replace
  2152. V<Op>X %mreg1,%mreg2,%mreg3
  2153. VMovX %mreg3,%mreg4
  2154. dealloc %mreg3
  2155. by
  2156. V<Op>X %mreg1,%mreg2,%mreg4
  2157. ?
  2158. }
  2159. if GetNextInstruction(p,hp1) and
  2160. { we mix single and double operations here because we assume that the compiler
  2161. generates vmovapd only after double operations and vmovaps only after single operations }
  2162. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2163. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2164. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2165. begin
  2166. TransferUsedRegs(TmpUsedRegs);
  2167. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2168. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2169. begin
  2170. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2171. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2172. RemoveInstruction(hp1);
  2173. result:=true;
  2174. end;
  2175. end;
  2176. end;
  2177. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2178. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2179. begin
  2180. Result := False;
  2181. { For safety reasons, only check for exact register matches }
  2182. { Check base register }
  2183. if (ref.base = AOldReg) then
  2184. begin
  2185. ref.base := ANewReg;
  2186. Result := True;
  2187. end;
  2188. { Check index register }
  2189. if (ref.index = AOldReg) then
  2190. begin
  2191. ref.index := ANewReg;
  2192. Result := True;
  2193. end;
  2194. end;
  2195. { Replaces all references to AOldReg in an operand to ANewReg }
  2196. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2197. var
  2198. OldSupReg, NewSupReg: TSuperRegister;
  2199. OldSubReg, NewSubReg: TSubRegister;
  2200. OldRegType: TRegisterType;
  2201. ThisOper: POper;
  2202. begin
  2203. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2204. Result := False;
  2205. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2206. InternalError(2020011801);
  2207. OldSupReg := getsupreg(AOldReg);
  2208. OldSubReg := getsubreg(AOldReg);
  2209. OldRegType := getregtype(AOldReg);
  2210. NewSupReg := getsupreg(ANewReg);
  2211. NewSubReg := getsubreg(ANewReg);
  2212. if OldRegType <> getregtype(ANewReg) then
  2213. InternalError(2020011802);
  2214. if OldSubReg <> NewSubReg then
  2215. InternalError(2020011803);
  2216. case ThisOper^.typ of
  2217. top_reg:
  2218. if (
  2219. (ThisOper^.reg = AOldReg) or
  2220. (
  2221. (OldRegType = R_INTREGISTER) and
  2222. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2223. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2224. (
  2225. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2226. {$ifndef x86_64}
  2227. and (
  2228. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2229. don't have an 8-bit representation }
  2230. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2231. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2232. )
  2233. {$endif x86_64}
  2234. )
  2235. )
  2236. ) then
  2237. begin
  2238. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2239. Result := True;
  2240. end;
  2241. top_ref:
  2242. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2243. Result := True;
  2244. else
  2245. ;
  2246. end;
  2247. end;
  2248. { Replaces all references to AOldReg in an instruction to ANewReg }
  2249. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2250. const
  2251. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2252. var
  2253. OperIdx: Integer;
  2254. begin
  2255. Result := False;
  2256. for OperIdx := 0 to p.ops - 1 do
  2257. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2258. begin
  2259. { The shift and rotate instructions can only use CL }
  2260. if not (
  2261. (OperIdx = 0) and
  2262. { This second condition just helps to avoid unnecessarily
  2263. calling MatchInstruction for 10 different opcodes }
  2264. (p.oper[0]^.reg = NR_CL) and
  2265. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2266. ) then
  2267. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2268. end
  2269. else if p.oper[OperIdx]^.typ = top_ref then
  2270. { It's okay to replace registers in references that get written to }
  2271. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2272. end;
  2273. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2274. begin
  2275. with ref^ do
  2276. Result :=
  2277. (index = NR_NO) and
  2278. (
  2279. {$ifdef x86_64}
  2280. (
  2281. (base = NR_RIP) and
  2282. (refaddr in [addr_pic, addr_pic_no_got])
  2283. ) or
  2284. {$endif x86_64}
  2285. (base = NR_STACK_POINTER_REG) or
  2286. (base = current_procinfo.framepointer)
  2287. );
  2288. end;
  2289. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2290. var
  2291. l: asizeint;
  2292. begin
  2293. Result := False;
  2294. { Should have been checked previously }
  2295. if p.opcode <> A_LEA then
  2296. InternalError(2020072501);
  2297. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2298. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2299. not(cs_opt_size in current_settings.optimizerswitches) then
  2300. exit;
  2301. with p.oper[0]^.ref^ do
  2302. begin
  2303. if (base <> p.oper[1]^.reg) or
  2304. (index <> NR_NO) or
  2305. assigned(symbol) then
  2306. exit;
  2307. l:=offset;
  2308. if (l=1) and UseIncDec then
  2309. begin
  2310. p.opcode:=A_INC;
  2311. p.loadreg(0,p.oper[1]^.reg);
  2312. p.ops:=1;
  2313. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2314. end
  2315. else if (l=-1) and UseIncDec then
  2316. begin
  2317. p.opcode:=A_DEC;
  2318. p.loadreg(0,p.oper[1]^.reg);
  2319. p.ops:=1;
  2320. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2321. end
  2322. else
  2323. begin
  2324. if (l<0) and (l<>-2147483648) then
  2325. begin
  2326. p.opcode:=A_SUB;
  2327. p.loadConst(0,-l);
  2328. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2329. end
  2330. else
  2331. begin
  2332. p.opcode:=A_ADD;
  2333. p.loadConst(0,l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2335. end;
  2336. end;
  2337. end;
  2338. Result := True;
  2339. end;
  2340. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2341. var
  2342. CurrentReg, ReplaceReg: TRegister;
  2343. begin
  2344. Result := False;
  2345. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2346. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2347. case hp.opcode of
  2348. A_FSTSW, A_FNSTSW,
  2349. A_IN, A_INS, A_OUT, A_OUTS,
  2350. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2351. { These routines have explicit operands, but they are restricted in
  2352. what they can be (e.g. IN and OUT can only read from AL, AX or
  2353. EAX. }
  2354. Exit;
  2355. A_IMUL:
  2356. begin
  2357. { The 1-operand version writes to implicit registers
  2358. The 2-operand version reads from the first operator, and reads
  2359. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2360. the 3-operand version reads from a register that it doesn't write to
  2361. }
  2362. case hp.ops of
  2363. 1:
  2364. if (
  2365. (
  2366. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2367. ) or
  2368. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2369. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2370. begin
  2371. Result := True;
  2372. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2373. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2374. end;
  2375. 2:
  2376. { Only modify the first parameter }
  2377. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2378. begin
  2379. Result := True;
  2380. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2381. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2382. end;
  2383. 3:
  2384. { Only modify the second parameter }
  2385. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2386. begin
  2387. Result := True;
  2388. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2389. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2390. end;
  2391. else
  2392. InternalError(2020012901);
  2393. end;
  2394. end;
  2395. else
  2396. if (hp.ops > 0) and
  2397. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2398. begin
  2399. Result := True;
  2400. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2401. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2402. end;
  2403. end;
  2404. end;
  2405. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2406. var
  2407. hp1, hp2, hp3: tai;
  2408. DoOptimisation, TempBool: Boolean;
  2409. {$ifdef x86_64}
  2410. NewConst: TCGInt;
  2411. {$endif x86_64}
  2412. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2413. begin
  2414. if taicpu(hp1).opcode = signed_movop then
  2415. begin
  2416. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2417. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2418. end
  2419. else
  2420. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2421. end;
  2422. function TryConstMerge(var p1, p2: tai): Boolean;
  2423. var
  2424. ThisRef: TReference;
  2425. begin
  2426. Result := False;
  2427. ThisRef := taicpu(p2).oper[1]^.ref^;
  2428. { Only permit writes to the stack, since we can guarantee alignment with that }
  2429. if (ThisRef.index = NR_NO) and
  2430. (
  2431. (ThisRef.base = NR_STACK_POINTER_REG) or
  2432. (ThisRef.base = current_procinfo.framepointer)
  2433. ) then
  2434. begin
  2435. case taicpu(p).opsize of
  2436. S_B:
  2437. begin
  2438. { Word writes must be on a 2-byte boundary }
  2439. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2440. begin
  2441. { Reduce offset of second reference to see if it is sequential with the first }
  2442. Dec(ThisRef.offset, 1);
  2443. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2444. begin
  2445. { Make sure the constants aren't represented as a
  2446. negative number, as these won't merge properly }
  2447. taicpu(p1).opsize := S_W;
  2448. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2449. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2450. RemoveInstruction(p2);
  2451. Result := True;
  2452. end;
  2453. end;
  2454. end;
  2455. S_W:
  2456. begin
  2457. { Longword writes must be on a 4-byte boundary }
  2458. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2459. begin
  2460. { Reduce offset of second reference to see if it is sequential with the first }
  2461. Dec(ThisRef.offset, 2);
  2462. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2463. begin
  2464. { Make sure the constants aren't represented as a
  2465. negative number, as these won't merge properly }
  2466. taicpu(p1).opsize := S_L;
  2467. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2468. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2469. RemoveInstruction(p2);
  2470. Result := True;
  2471. end;
  2472. end;
  2473. end;
  2474. {$ifdef x86_64}
  2475. S_L:
  2476. begin
  2477. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2478. see if the constants can be encoded this way. }
  2479. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2480. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2481. { Quadword writes must be on an 8-byte boundary }
  2482. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2483. begin
  2484. { Reduce offset of second reference to see if it is sequential with the first }
  2485. Dec(ThisRef.offset, 4);
  2486. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2487. begin
  2488. { Make sure the constants aren't represented as a
  2489. negative number, as these won't merge properly }
  2490. taicpu(p1).opsize := S_Q;
  2491. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2492. taicpu(p1).oper[0]^.val := NewConst;
  2493. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2494. RemoveInstruction(p2);
  2495. Result := True;
  2496. end;
  2497. end;
  2498. end;
  2499. {$endif x86_64}
  2500. else
  2501. ;
  2502. end;
  2503. end;
  2504. end;
  2505. var
  2506. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2507. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2508. NewSize: topsize;
  2509. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2510. SourceRef, TargetRef: TReference;
  2511. MovAligned, MovUnaligned: TAsmOp;
  2512. ThisRef: TReference;
  2513. JumpTracking: TLinkedList;
  2514. begin
  2515. Result:=false;
  2516. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2517. { remove mov reg1,reg1? }
  2518. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2519. then
  2520. begin
  2521. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2522. { take care of the register (de)allocs following p }
  2523. RemoveCurrentP(p, hp1);
  2524. Result:=true;
  2525. exit;
  2526. end;
  2527. { All the next optimisations require a next instruction }
  2528. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2529. Exit;
  2530. { Prevent compiler warnings }
  2531. p_TargetReg := NR_NO;
  2532. if taicpu(p).oper[1]^.typ = top_reg then
  2533. begin
  2534. { Saves on a large number of dereferences }
  2535. p_TargetReg := taicpu(p).oper[1]^.reg;
  2536. { Look for:
  2537. mov %reg1,%reg2
  2538. ??? %reg2,r/m
  2539. Change to:
  2540. mov %reg1,%reg2
  2541. ??? %reg1,r/m
  2542. }
  2543. if taicpu(p).oper[0]^.typ = top_reg then
  2544. begin
  2545. if RegReadByInstruction(p_TargetReg, hp1) and
  2546. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2547. begin
  2548. { A change has occurred, just not in p }
  2549. Result := True;
  2550. TransferUsedRegs(TmpUsedRegs);
  2551. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2552. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2553. { Just in case something didn't get modified (e.g. an
  2554. implicit register) }
  2555. not RegReadByInstruction(p_TargetReg, hp1) then
  2556. begin
  2557. { We can remove the original MOV }
  2558. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2559. RemoveCurrentp(p, hp1);
  2560. { UsedRegs got updated by RemoveCurrentp }
  2561. Result := True;
  2562. Exit;
  2563. end;
  2564. { If we know a MOV instruction has become a null operation, we might as well
  2565. get rid of it now to save time. }
  2566. if (taicpu(hp1).opcode = A_MOV) and
  2567. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2568. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2569. { Just being a register is enough to confirm it's a null operation }
  2570. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2571. begin
  2572. Result := True;
  2573. { Speed-up to reduce a pipeline stall... if we had something like...
  2574. movl %eax,%edx
  2575. movw %dx,%ax
  2576. ... the second instruction would change to movw %ax,%ax, but
  2577. given that it is now %ax that's active rather than %eax,
  2578. penalties might occur due to a partial register write, so instead,
  2579. change it to a MOVZX instruction when optimising for speed.
  2580. }
  2581. if not (cs_opt_size in current_settings.optimizerswitches) and
  2582. IsMOVZXAcceptable and
  2583. (taicpu(hp1).opsize < taicpu(p).opsize)
  2584. {$ifdef x86_64}
  2585. { operations already implicitly set the upper 64 bits to zero }
  2586. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2587. {$endif x86_64}
  2588. then
  2589. begin
  2590. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2591. case taicpu(p).opsize of
  2592. S_W:
  2593. if taicpu(hp1).opsize = S_B then
  2594. taicpu(hp1).opsize := S_BL
  2595. else
  2596. InternalError(2020012911);
  2597. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2598. case taicpu(hp1).opsize of
  2599. S_B:
  2600. taicpu(hp1).opsize := S_BL;
  2601. S_W:
  2602. taicpu(hp1).opsize := S_WL;
  2603. else
  2604. InternalError(2020012912);
  2605. end;
  2606. else
  2607. InternalError(2020012910);
  2608. end;
  2609. taicpu(hp1).opcode := A_MOVZX;
  2610. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2611. end
  2612. else
  2613. begin
  2614. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2615. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2616. RemoveInstruction(hp1);
  2617. { The instruction after what was hp1 is now the immediate next instruction,
  2618. so we can continue to make optimisations if it's present }
  2619. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2620. Exit;
  2621. hp1 := hp2;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. end;
  2627. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2628. overwrites the original destination register. e.g.
  2629. movl ###,%reg2d
  2630. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2631. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2632. }
  2633. if (taicpu(p).oper[1]^.typ = top_reg) and
  2634. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2635. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2636. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2637. begin
  2638. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2639. begin
  2640. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2641. case taicpu(p).oper[0]^.typ of
  2642. top_const:
  2643. { We have something like:
  2644. movb $x, %regb
  2645. movzbl %regb,%regd
  2646. Change to:
  2647. movl $x, %regd
  2648. }
  2649. begin
  2650. case taicpu(hp1).opsize of
  2651. S_BW:
  2652. begin
  2653. convert_mov_value(A_MOVSX, $FF);
  2654. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2655. taicpu(p).opsize := S_W;
  2656. end;
  2657. S_BL:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2661. taicpu(p).opsize := S_L;
  2662. end;
  2663. S_WL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FFFF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. {$ifdef x86_64}
  2670. S_BQ:
  2671. begin
  2672. convert_mov_value(A_MOVSX, $FF);
  2673. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2674. taicpu(p).opsize := S_Q;
  2675. end;
  2676. S_WQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FFFF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_LQ:
  2683. begin
  2684. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. {$endif x86_64}
  2689. else
  2690. { If hp1 was a MOV instruction, it should have been
  2691. optimised already }
  2692. InternalError(2020021001);
  2693. end;
  2694. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2695. RemoveInstruction(hp1);
  2696. Result := True;
  2697. Exit;
  2698. end;
  2699. top_ref:
  2700. begin
  2701. { We have something like:
  2702. movb mem, %regb
  2703. movzbl %regb,%regd
  2704. Change to:
  2705. movzbl mem, %regd
  2706. }
  2707. ThisRef := taicpu(p).oper[0]^.ref^;
  2708. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2709. begin
  2710. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2711. taicpu(hp1).loadref(0, ThisRef);
  2712. { Make sure any registers in the references are properly tracked }
  2713. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2714. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2715. if (ThisRef.index <> NR_NO) then
  2716. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2717. RemoveCurrentP(p, hp1);
  2718. Result := True;
  2719. Exit;
  2720. end;
  2721. end;
  2722. else
  2723. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2724. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2725. Exit;
  2726. end;
  2727. end
  2728. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2729. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2730. optimised }
  2731. else
  2732. begin
  2733. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2734. RemoveCurrentP(p, hp1);
  2735. Result := True;
  2736. Exit;
  2737. end;
  2738. end;
  2739. if (taicpu(hp1).opcode = A_AND) and
  2740. (taicpu(p).oper[1]^.typ = top_reg) and
  2741. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2742. begin
  2743. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2744. begin
  2745. case taicpu(p).opsize of
  2746. S_L:
  2747. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2748. begin
  2749. { Optimize out:
  2750. mov x, %reg
  2751. and ffffffffh, %reg
  2752. }
  2753. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2754. RemoveInstruction(hp1);
  2755. Result:=true;
  2756. exit;
  2757. end;
  2758. S_Q: { TODO: Confirm if this is even possible }
  2759. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2760. begin
  2761. { Optimize out:
  2762. mov x, %reg
  2763. and ffffffffffffffffh, %reg
  2764. }
  2765. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2766. RemoveInstruction(hp1);
  2767. Result:=true;
  2768. exit;
  2769. end;
  2770. else
  2771. ;
  2772. end;
  2773. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2774. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2775. GetNextInstruction(hp1,hp2) and
  2776. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2777. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2778. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2779. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2780. GetNextInstruction(hp2,hp3) and
  2781. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2782. (taicpu(hp3).condition in [C_E,C_NE]) then
  2783. begin
  2784. TransferUsedRegs(TmpUsedRegs);
  2785. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2786. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2787. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2788. begin
  2789. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2790. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2791. taicpu(hp1).opcode:=A_TEST;
  2792. RemoveInstruction(hp2);
  2793. RemoveCurrentP(p, hp1);
  2794. Result:=true;
  2795. exit;
  2796. end;
  2797. end;
  2798. end
  2799. else if IsMOVZXAcceptable and
  2800. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2801. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2802. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2803. then
  2804. begin
  2805. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2806. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2807. case taicpu(p).opsize of
  2808. S_B:
  2809. if (taicpu(hp1).oper[0]^.val = $ff) then
  2810. begin
  2811. { Convert:
  2812. movb x, %regl movb x, %regl
  2813. andw ffh, %regw andl ffh, %regd
  2814. To:
  2815. movzbw x, %regd movzbl x, %regd
  2816. (Identical registers, just different sizes)
  2817. }
  2818. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2819. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2820. case taicpu(hp1).opsize of
  2821. S_W: NewSize := S_BW;
  2822. S_L: NewSize := S_BL;
  2823. {$ifdef x86_64}
  2824. S_Q: NewSize := S_BQ;
  2825. {$endif x86_64}
  2826. else
  2827. InternalError(2018011510);
  2828. end;
  2829. end
  2830. else
  2831. NewSize := S_NO;
  2832. S_W:
  2833. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2834. begin
  2835. { Convert:
  2836. movw x, %regw
  2837. andl ffffh, %regd
  2838. To:
  2839. movzwl x, %regd
  2840. (Identical registers, just different sizes)
  2841. }
  2842. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2843. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2844. case taicpu(hp1).opsize of
  2845. S_L: NewSize := S_WL;
  2846. {$ifdef x86_64}
  2847. S_Q: NewSize := S_WQ;
  2848. {$endif x86_64}
  2849. else
  2850. InternalError(2018011511);
  2851. end;
  2852. end
  2853. else
  2854. NewSize := S_NO;
  2855. else
  2856. NewSize := S_NO;
  2857. end;
  2858. if NewSize <> S_NO then
  2859. begin
  2860. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2861. { The actual optimization }
  2862. taicpu(p).opcode := A_MOVZX;
  2863. taicpu(p).changeopsize(NewSize);
  2864. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2865. { Safeguard if "and" is followed by a conditional command }
  2866. TransferUsedRegs(TmpUsedRegs);
  2867. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2868. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2869. begin
  2870. { At this point, the "and" command is effectively equivalent to
  2871. "test %reg,%reg". This will be handled separately by the
  2872. Peephole Optimizer. [Kit] }
  2873. DebugMsg(SPeepholeOptimization + PreMessage +
  2874. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2875. end
  2876. else
  2877. begin
  2878. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2879. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2880. RemoveInstruction(hp1);
  2881. end;
  2882. Result := True;
  2883. Exit;
  2884. end;
  2885. end;
  2886. end;
  2887. if (taicpu(hp1).opcode = A_OR) and
  2888. (taicpu(p).oper[1]^.typ = top_reg) and
  2889. MatchOperand(taicpu(p).oper[0]^, 0) and
  2890. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2891. begin
  2892. { mov 0, %reg
  2893. or ###,%reg
  2894. Change to (only if the flags are not used):
  2895. mov ###,%reg
  2896. }
  2897. TransferUsedRegs(TmpUsedRegs);
  2898. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2899. DoOptimisation := True;
  2900. { Even if the flags are used, we might be able to do the optimisation
  2901. if the conditions are predictable }
  2902. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2903. begin
  2904. { Only perform if ### = %reg (the same register) or equal to 0,
  2905. so %reg is guaranteed to still have a value of zero }
  2906. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2907. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2908. begin
  2909. hp2 := hp1;
  2910. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2911. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2912. GetNextInstruction(hp2, hp3) do
  2913. begin
  2914. { Don't continue modifying if the flags state is getting changed }
  2915. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2916. Break;
  2917. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2918. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2919. begin
  2920. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2921. begin
  2922. { Condition is always true }
  2923. case taicpu(hp3).opcode of
  2924. A_Jcc:
  2925. begin
  2926. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2927. { Check for jump shortcuts before we destroy the condition }
  2928. DoJumpOptimizations(hp3, TempBool);
  2929. MakeUnconditional(taicpu(hp3));
  2930. Result := True;
  2931. end;
  2932. A_CMOVcc:
  2933. begin
  2934. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2935. taicpu(hp3).opcode := A_MOV;
  2936. taicpu(hp3).condition := C_None;
  2937. Result := True;
  2938. end;
  2939. A_SETcc:
  2940. begin
  2941. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2942. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2943. taicpu(hp3).opcode := A_MOV;
  2944. taicpu(hp3).ops := 2;
  2945. taicpu(hp3).condition := C_None;
  2946. taicpu(hp3).opsize := S_B;
  2947. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2948. taicpu(hp3).loadconst(0, 1);
  2949. Result := True;
  2950. end;
  2951. else
  2952. InternalError(2021090701);
  2953. end;
  2954. end
  2955. 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
  2956. begin
  2957. { Condition is always false }
  2958. case taicpu(hp3).opcode of
  2959. A_Jcc:
  2960. begin
  2961. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2962. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2963. RemoveInstruction(hp3);
  2964. Result := True;
  2965. { Since hp3 was deleted, hp2 must not be updated }
  2966. Continue;
  2967. end;
  2968. A_CMOVcc:
  2969. begin
  2970. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2971. RemoveInstruction(hp3);
  2972. Result := True;
  2973. { Since hp3 was deleted, hp2 must not be updated }
  2974. Continue;
  2975. end;
  2976. A_SETcc:
  2977. begin
  2978. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2979. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2980. taicpu(hp3).opcode := A_MOV;
  2981. taicpu(hp3).ops := 2;
  2982. taicpu(hp3).condition := C_None;
  2983. taicpu(hp3).opsize := S_B;
  2984. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2985. taicpu(hp3).loadconst(0, 0);
  2986. Result := True;
  2987. end;
  2988. else
  2989. InternalError(2021090702);
  2990. end;
  2991. end
  2992. else
  2993. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2994. DoOptimisation := False;
  2995. end;
  2996. hp2 := hp3;
  2997. end;
  2998. { Flags are still in use - don't optimise }
  2999. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3000. DoOptimisation := False;
  3001. end
  3002. else
  3003. DoOptimisation := False;
  3004. end;
  3005. if DoOptimisation then
  3006. begin
  3007. {$ifdef x86_64}
  3008. { OR only supports 32-bit sign-extended constants for 64-bit
  3009. instructions, so compensate for this if the constant is
  3010. encoded as a value greater than or equal to 2^31 }
  3011. if (taicpu(hp1).opsize = S_Q) and
  3012. (taicpu(hp1).oper[0]^.typ = top_const) and
  3013. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3014. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3015. {$endif x86_64}
  3016. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3017. taicpu(hp1).opcode := A_MOV;
  3018. RemoveCurrentP(p, hp1);
  3019. Result := True;
  3020. Exit;
  3021. end;
  3022. end;
  3023. { Next instruction is also a MOV ? }
  3024. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3025. begin
  3026. if MatchOpType(taicpu(p), top_const, top_ref) and
  3027. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3028. TryConstMerge(p, hp1) then
  3029. begin
  3030. Result := True;
  3031. { In case we have four byte writes in a row, check for 2 more
  3032. right now so we don't have to wait for another iteration of
  3033. pass 1
  3034. }
  3035. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3036. case taicpu(p).opsize of
  3037. S_W:
  3038. begin
  3039. if GetNextInstruction(p, hp1) and
  3040. MatchInstruction(hp1, A_MOV, [S_B]) and
  3041. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3042. GetNextInstruction(hp1, hp2) and
  3043. MatchInstruction(hp2, A_MOV, [S_B]) and
  3044. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3045. { Try to merge the two bytes }
  3046. TryConstMerge(hp1, hp2) then
  3047. { Now try to merge the two words (hp2 will get deleted) }
  3048. TryConstMerge(p, hp1);
  3049. end;
  3050. S_L:
  3051. begin
  3052. { Though this only really benefits x86_64 and not i386, it
  3053. gets a potential optimisation done faster and hence
  3054. reduces the number of times OptPass1MOV is entered }
  3055. if GetNextInstruction(p, hp1) and
  3056. MatchInstruction(hp1, A_MOV, [S_W]) and
  3057. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3058. GetNextInstruction(hp1, hp2) and
  3059. MatchInstruction(hp2, A_MOV, [S_W]) and
  3060. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3061. { Try to merge the two words }
  3062. TryConstMerge(hp1, hp2) then
  3063. { This will always fail on i386, so don't bother
  3064. calling it unless we're doing x86_64 }
  3065. {$ifdef x86_64}
  3066. { Now try to merge the two longwords (hp2 will get deleted) }
  3067. TryConstMerge(p, hp1)
  3068. {$endif x86_64}
  3069. ;
  3070. end;
  3071. else
  3072. ;
  3073. end;
  3074. Exit;
  3075. end;
  3076. if (taicpu(p).oper[1]^.typ = top_reg) and
  3077. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3078. begin
  3079. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3080. TransferUsedRegs(TmpUsedRegs);
  3081. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3082. { we have
  3083. mov x, %treg
  3084. mov %treg, y
  3085. }
  3086. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3087. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3088. { we've got
  3089. mov x, %treg
  3090. mov %treg, y
  3091. with %treg is not used after }
  3092. case taicpu(p).oper[0]^.typ Of
  3093. { top_reg is covered by DeepMOVOpt }
  3094. top_const:
  3095. begin
  3096. { change
  3097. mov const, %treg
  3098. mov %treg, y
  3099. to
  3100. mov const, y
  3101. }
  3102. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3103. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3104. begin
  3105. if taicpu(hp1).oper[1]^.typ=top_reg then
  3106. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3107. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3108. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3109. RemoveInstruction(hp1);
  3110. Result:=true;
  3111. Exit;
  3112. end;
  3113. end;
  3114. top_ref:
  3115. case taicpu(hp1).oper[1]^.typ of
  3116. top_reg:
  3117. begin
  3118. { change
  3119. mov mem, %treg
  3120. mov %treg, %reg
  3121. to
  3122. mov mem, %reg"
  3123. }
  3124. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3125. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3127. RemoveInstruction(hp1);
  3128. Result:=true;
  3129. Exit;
  3130. end;
  3131. top_ref:
  3132. begin
  3133. {$ifdef x86_64}
  3134. { Look for the following to simplify:
  3135. mov x(mem1), %reg
  3136. mov %reg, y(mem2)
  3137. mov x+8(mem1), %reg
  3138. mov %reg, y+8(mem2)
  3139. Change to:
  3140. movdqu x(mem1), %xmmreg
  3141. movdqu %xmmreg, y(mem2)
  3142. ...but only as long as the memory blocks don't overlap
  3143. }
  3144. SourceRef := taicpu(p).oper[0]^.ref^;
  3145. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3146. if (taicpu(p).opsize = S_Q) and
  3147. GetNextInstruction(hp1, hp2) and
  3148. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3149. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3150. begin
  3151. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3152. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3153. Inc(SourceRef.offset, 8);
  3154. if UseAVX then
  3155. begin
  3156. MovAligned := A_VMOVDQA;
  3157. MovUnaligned := A_VMOVDQU;
  3158. end
  3159. else
  3160. begin
  3161. MovAligned := A_MOVDQA;
  3162. MovUnaligned := A_MOVDQU;
  3163. end;
  3164. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3165. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3166. begin
  3167. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3168. Inc(TargetRef.offset, 8);
  3169. if GetNextInstruction(hp2, hp3) and
  3170. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3171. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3172. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3173. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3174. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3175. begin
  3176. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3177. if NewMMReg <> NR_NO then
  3178. begin
  3179. { Remember that the offsets are 8 ahead }
  3180. if ((SourceRef.offset mod 16) = 8) and
  3181. (
  3182. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3183. (SourceRef.base = current_procinfo.framepointer) or
  3184. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3185. ) then
  3186. taicpu(p).opcode := MovAligned
  3187. else
  3188. taicpu(p).opcode := MovUnaligned;
  3189. taicpu(p).opsize := S_XMM;
  3190. taicpu(p).oper[1]^.reg := NewMMReg;
  3191. if ((TargetRef.offset mod 16) = 8) and
  3192. (
  3193. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3194. (TargetRef.base = current_procinfo.framepointer) or
  3195. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3196. ) then
  3197. taicpu(hp1).opcode := MovAligned
  3198. else
  3199. taicpu(hp1).opcode := MovUnaligned;
  3200. taicpu(hp1).opsize := S_XMM;
  3201. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3202. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3203. RemoveInstruction(hp2);
  3204. RemoveInstruction(hp3);
  3205. Result := True;
  3206. Exit;
  3207. end;
  3208. end;
  3209. end
  3210. else
  3211. begin
  3212. { See if the next references are 8 less rather than 8 greater }
  3213. Dec(SourceRef.offset, 16); { -8 the other way }
  3214. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3215. begin
  3216. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3217. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3218. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3219. GetNextInstruction(hp2, hp3) and
  3220. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3221. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3222. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3223. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3224. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3225. begin
  3226. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3227. if NewMMReg <> NR_NO then
  3228. begin
  3229. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3230. if ((SourceRef.offset mod 16) = 0) and
  3231. (
  3232. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3233. (SourceRef.base = current_procinfo.framepointer) or
  3234. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3235. ) then
  3236. taicpu(hp2).opcode := MovAligned
  3237. else
  3238. taicpu(hp2).opcode := MovUnaligned;
  3239. taicpu(hp2).opsize := S_XMM;
  3240. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3241. if ((TargetRef.offset mod 16) = 0) and
  3242. (
  3243. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3244. (TargetRef.base = current_procinfo.framepointer) or
  3245. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3246. ) then
  3247. taicpu(hp3).opcode := MovAligned
  3248. else
  3249. taicpu(hp3).opcode := MovUnaligned;
  3250. taicpu(hp3).opsize := S_XMM;
  3251. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3252. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3253. RemoveInstruction(hp1);
  3254. RemoveCurrentP(p, hp2);
  3255. Result := True;
  3256. Exit;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. end;
  3262. {$endif x86_64}
  3263. end;
  3264. else
  3265. { The write target should be a reg or a ref }
  3266. InternalError(2021091601);
  3267. end;
  3268. else
  3269. ;
  3270. end
  3271. else
  3272. { %treg is used afterwards, but all eventualities
  3273. other than the first MOV instruction being a constant
  3274. are covered by DeepMOVOpt, so only check for that }
  3275. if (taicpu(p).oper[0]^.typ = top_const) and
  3276. (
  3277. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3278. not (cs_opt_size in current_settings.optimizerswitches) or
  3279. (taicpu(hp1).opsize = S_B)
  3280. ) and
  3281. (
  3282. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3283. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3284. ) then
  3285. begin
  3286. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3287. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3288. end;
  3289. end;
  3290. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3291. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3292. { mov reg1, mem1 or mov mem1, reg1
  3293. mov mem2, reg2 mov reg2, mem2}
  3294. begin
  3295. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3296. { mov reg1, mem1 or mov mem1, reg1
  3297. mov mem2, reg1 mov reg2, mem1}
  3298. begin
  3299. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3300. { Removes the second statement from
  3301. mov reg1, mem1/reg2
  3302. mov mem1/reg2, reg1 }
  3303. begin
  3304. if taicpu(p).oper[0]^.typ=top_reg then
  3305. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3306. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3307. RemoveInstruction(hp1);
  3308. Result:=true;
  3309. exit;
  3310. end
  3311. else
  3312. begin
  3313. TransferUsedRegs(TmpUsedRegs);
  3314. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3315. if (taicpu(p).oper[1]^.typ = top_ref) and
  3316. { mov reg1, mem1
  3317. mov mem2, reg1 }
  3318. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3319. GetNextInstruction(hp1, hp2) and
  3320. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3321. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3322. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3323. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3324. { change to
  3325. mov reg1, mem1 mov reg1, mem1
  3326. mov mem2, reg1 cmp reg1, mem2
  3327. cmp mem1, reg1
  3328. }
  3329. begin
  3330. RemoveInstruction(hp2);
  3331. taicpu(hp1).opcode := A_CMP;
  3332. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3333. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3334. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3335. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3336. end;
  3337. end;
  3338. end
  3339. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3340. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3341. begin
  3342. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3343. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3344. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3345. end
  3346. else
  3347. begin
  3348. TransferUsedRegs(TmpUsedRegs);
  3349. if GetNextInstruction(hp1, hp2) and
  3350. MatchOpType(taicpu(p),top_ref,top_reg) and
  3351. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3352. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3353. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3354. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3355. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3356. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3357. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3358. { mov mem1, %reg1
  3359. mov %reg1, mem2
  3360. mov mem2, reg2
  3361. to:
  3362. mov mem1, reg2
  3363. mov reg2, mem2}
  3364. begin
  3365. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3366. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3367. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3368. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3369. RemoveInstruction(hp2);
  3370. Result := True;
  3371. end
  3372. {$ifdef i386}
  3373. { this is enabled for i386 only, as the rules to create the reg sets below
  3374. are too complicated for x86-64, so this makes this code too error prone
  3375. on x86-64
  3376. }
  3377. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3378. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3379. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3380. { mov mem1, reg1 mov mem1, reg1
  3381. mov reg1, mem2 mov reg1, mem2
  3382. mov mem2, reg2 mov mem2, reg1
  3383. to: to:
  3384. mov mem1, reg1 mov mem1, reg1
  3385. mov mem1, reg2 mov reg1, mem2
  3386. mov reg1, mem2
  3387. or (if mem1 depends on reg1
  3388. and/or if mem2 depends on reg2)
  3389. to:
  3390. mov mem1, reg1
  3391. mov reg1, mem2
  3392. mov reg1, reg2
  3393. }
  3394. begin
  3395. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3396. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3397. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3398. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3399. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3400. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3401. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3402. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3403. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3404. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3405. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3406. end
  3407. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3408. begin
  3409. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3410. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3411. end
  3412. else
  3413. begin
  3414. RemoveInstruction(hp2);
  3415. end
  3416. {$endif i386}
  3417. ;
  3418. end;
  3419. end
  3420. { movl [mem1],reg1
  3421. movl [mem1],reg2
  3422. to
  3423. movl [mem1],reg1
  3424. movl reg1,reg2
  3425. }
  3426. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3427. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3428. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3429. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3430. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3431. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3433. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3434. begin
  3435. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3436. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3437. end;
  3438. { movl const1,[mem1]
  3439. movl [mem1],reg1
  3440. to
  3441. movl const1,reg1
  3442. movl reg1,[mem1]
  3443. }
  3444. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3445. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3446. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3447. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3448. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3449. begin
  3450. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3451. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3452. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3453. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3454. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3455. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3456. Result:=true;
  3457. exit;
  3458. end;
  3459. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3460. { Change:
  3461. movl %reg1,%reg2
  3462. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3463. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3464. To:
  3465. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3466. movl x(%reg1),%reg1
  3467. movl %reg1,%regX
  3468. }
  3469. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3470. begin
  3471. p_SourceReg := taicpu(p).oper[0]^.reg;
  3472. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3473. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3474. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3475. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3476. GetNextInstruction(hp1, hp2) and
  3477. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3478. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3479. begin
  3480. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3481. if RegInRef(p_TargetReg, SourceRef) and
  3482. { If %reg1 also appears in the second reference, then it will
  3483. not refer to the same memory block as the first reference }
  3484. not RegInRef(p_SourceReg, SourceRef) then
  3485. begin
  3486. { Check to see if the references match if %reg2 is changed to %reg1 }
  3487. if SourceRef.base = p_TargetReg then
  3488. SourceRef.base := p_SourceReg;
  3489. if SourceRef.index = p_TargetReg then
  3490. SourceRef.index := p_SourceReg;
  3491. { RefsEqual also checks to ensure both references are non-volatile }
  3492. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3493. begin
  3494. taicpu(hp2).loadreg(0, p_SourceReg);
  3495. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3496. Result := True;
  3497. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3498. begin
  3499. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3500. RemoveCurrentP(p, hp1);
  3501. Exit;
  3502. end
  3503. else
  3504. begin
  3505. { Check to see if %reg2 is no longer in use }
  3506. TransferUsedRegs(TmpUsedRegs);
  3507. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3509. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3510. begin
  3511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3512. RemoveCurrentP(p, hp1);
  3513. Exit;
  3514. end;
  3515. end;
  3516. { If we reach this point, p and hp1 weren't actually modified,
  3517. so we can do a bit more work on this pass }
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. end;
  3523. { search further than the next instruction for a mov (as long as it's not a jump) }
  3524. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3525. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3526. (taicpu(p).oper[1]^.typ = top_reg) and
  3527. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3528. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3529. begin
  3530. { we work with hp2 here, so hp1 can be still used later on when
  3531. checking for GetNextInstruction_p }
  3532. hp3 := hp1;
  3533. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3534. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3535. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3536. TransferUsedRegs(TmpUsedRegs);
  3537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3538. if NotFirstIteration then
  3539. JumpTracking := TLinkedList.Create
  3540. else
  3541. JumpTracking := nil;
  3542. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3543. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3544. (hp2.typ=ait_instruction) do
  3545. begin
  3546. case taicpu(hp2).opcode of
  3547. A_POP:
  3548. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3549. begin
  3550. if not CrossJump and
  3551. not RegUsedBetween(p_TargetReg, p, hp2) then
  3552. begin
  3553. { We can remove the original MOV since the register
  3554. wasn't used between it and its popping from the stack }
  3555. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3556. RemoveCurrentp(p, hp1);
  3557. Result := True;
  3558. JumpTracking.Free;
  3559. Exit;
  3560. end;
  3561. { Can't go any further }
  3562. Break;
  3563. end;
  3564. A_MOV:
  3565. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3566. ((taicpu(p).oper[0]^.typ=top_const) or
  3567. ((taicpu(p).oper[0]^.typ=top_reg) and
  3568. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3569. )
  3570. ) then
  3571. begin
  3572. { we have
  3573. mov x, %treg
  3574. mov %treg, y
  3575. }
  3576. { We don't need to call UpdateUsedRegs for every instruction between
  3577. p and hp2 because the register we're concerned about will not
  3578. become deallocated (otherwise GetNextInstructionUsingReg would
  3579. have stopped at an earlier instruction). [Kit] }
  3580. TempRegUsed :=
  3581. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3582. RegReadByInstruction(p_TargetReg, hp3) or
  3583. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3584. case taicpu(p).oper[0]^.typ Of
  3585. top_reg:
  3586. begin
  3587. { change
  3588. mov %reg, %treg
  3589. mov %treg, y
  3590. to
  3591. mov %reg, y
  3592. }
  3593. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3594. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3595. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3596. begin
  3597. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3598. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3599. if TempRegUsed then
  3600. begin
  3601. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3602. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3603. { Set the start of the next GetNextInstructionUsingRegCond search
  3604. to start at the entry right before hp2 (which is about to be removed) }
  3605. hp3 := tai(hp2.Previous);
  3606. RemoveInstruction(hp2);
  3607. { See if there's more we can optimise }
  3608. Continue;
  3609. end
  3610. else
  3611. begin
  3612. RemoveInstruction(hp2);
  3613. { We can remove the original MOV too }
  3614. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3615. RemoveCurrentP(p, hp1);
  3616. Result:=true;
  3617. JumpTracking.Free;
  3618. Exit;
  3619. end;
  3620. end
  3621. else
  3622. begin
  3623. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3624. taicpu(hp2).loadReg(0, p_SourceReg);
  3625. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3626. { Check to see if the register also appears in the reference }
  3627. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3628. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3629. { Don't remove the first instruction if the temporary register is in use }
  3630. if not TempRegUsed and
  3631. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3632. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3633. begin
  3634. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3635. RemoveCurrentP(p, hp1);
  3636. Result:=true;
  3637. JumpTracking.Free;
  3638. Exit;
  3639. end;
  3640. { No need to set Result to True here. If there's another instruction later
  3641. on that can be optimised, it will be detected when the main Pass 1 loop
  3642. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3643. end;
  3644. end;
  3645. top_const:
  3646. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3647. begin
  3648. { change
  3649. mov const, %treg
  3650. mov %treg, y
  3651. to
  3652. mov const, y
  3653. }
  3654. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3655. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3656. begin
  3657. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3658. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3659. if TempRegUsed then
  3660. begin
  3661. { Don't remove the first instruction if the temporary register is in use }
  3662. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3663. { No need to set Result to True. If there's another instruction later on
  3664. that can be optimised, it will be detected when the main Pass 1 loop
  3665. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3666. end
  3667. else
  3668. begin
  3669. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3670. RemoveCurrentP(p, hp1);
  3671. Result:=true;
  3672. Exit;
  3673. end;
  3674. end;
  3675. end;
  3676. else
  3677. Internalerror(2019103001);
  3678. end;
  3679. end
  3680. else
  3681. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3682. begin
  3683. if not CrossJump and
  3684. not RegUsedBetween(p_TargetReg, p, hp2) and
  3685. not RegReadByInstruction(p_TargetReg, hp2) then
  3686. begin
  3687. { Register is not used before it is overwritten }
  3688. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3689. RemoveCurrentp(p, hp1);
  3690. Result := True;
  3691. Exit;
  3692. end;
  3693. if (taicpu(p).oper[0]^.typ = top_const) and
  3694. (taicpu(hp2).oper[0]^.typ = top_const) then
  3695. begin
  3696. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3697. begin
  3698. { Same value - register hasn't changed }
  3699. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3700. RemoveInstruction(hp2);
  3701. Result := True;
  3702. { See if there's more we can optimise }
  3703. Continue;
  3704. end;
  3705. end;
  3706. end;
  3707. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3708. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3709. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3710. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3711. begin
  3712. {
  3713. Change from:
  3714. mov ###, %reg
  3715. ...
  3716. movs/z %reg,%reg (Same register, just different sizes)
  3717. To:
  3718. movs/z ###, %reg (Longer version)
  3719. ...
  3720. (remove)
  3721. }
  3722. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3723. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3724. { Keep the first instruction as mov if ### is a constant }
  3725. if taicpu(p).oper[0]^.typ = top_const then
  3726. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3727. else
  3728. begin
  3729. taicpu(p).opcode := taicpu(hp2).opcode;
  3730. taicpu(p).opsize := taicpu(hp2).opsize;
  3731. end;
  3732. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3733. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3734. RemoveInstruction(hp2);
  3735. Result := True;
  3736. JumpTracking.Free;
  3737. Exit;
  3738. end;
  3739. else
  3740. { Move down to the MatchOpType if-block below };
  3741. end;
  3742. { Also catches MOV/S/Z instructions that aren't modified }
  3743. if taicpu(p).oper[0]^.typ = top_reg then
  3744. begin
  3745. p_SourceReg := taicpu(p).oper[0]^.reg;
  3746. if
  3747. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3748. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3749. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3750. begin
  3751. Result := True;
  3752. { Just in case something didn't get modified (e.g. an
  3753. implicit register). Also, if it does read from this
  3754. register, then there's no longer an advantage to
  3755. changing the register on subsequent instructions.}
  3756. if not RegReadByInstruction(p_TargetReg, hp2) then
  3757. begin
  3758. { If a conditional jump was crossed, do not delete
  3759. the original MOV no matter what }
  3760. if not CrossJump and
  3761. { RegEndOfLife returns True if the register is
  3762. deallocated before the next instruction or has
  3763. been loaded with a new value }
  3764. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3765. begin
  3766. { We can remove the original MOV }
  3767. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3768. RemoveCurrentp(p, hp1);
  3769. JumpTracking.Free;
  3770. Result := True;
  3771. Exit;
  3772. end;
  3773. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3774. begin
  3775. { See if there's more we can optimise }
  3776. hp3 := hp2;
  3777. Continue;
  3778. end;
  3779. end;
  3780. end;
  3781. end;
  3782. { Break out of the while loop under normal circumstances }
  3783. Break;
  3784. end;
  3785. JumpTracking.Free;
  3786. end;
  3787. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3788. (taicpu(p).oper[1]^.typ = top_reg) and
  3789. (taicpu(p).opsize = S_L) and
  3790. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3791. (hp2.typ = ait_instruction) and
  3792. (taicpu(hp2).opcode = A_AND) and
  3793. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3794. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3795. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3796. ) then
  3797. begin
  3798. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3799. begin
  3800. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3801. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3802. begin
  3803. { Optimize out:
  3804. mov x, %reg
  3805. and ffffffffh, %reg
  3806. }
  3807. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3808. RemoveInstruction(hp2);
  3809. Result:=true;
  3810. exit;
  3811. end;
  3812. end;
  3813. end;
  3814. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3815. x >= RetOffset) as it doesn't do anything (it writes either to a
  3816. parameter or to the temporary storage room for the function
  3817. result)
  3818. }
  3819. if IsExitCode(hp1) and
  3820. (taicpu(p).oper[1]^.typ = top_ref) and
  3821. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3822. (
  3823. (
  3824. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3825. not (
  3826. assigned(current_procinfo.procdef.funcretsym) and
  3827. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3828. )
  3829. ) or
  3830. { Also discard writes to the stack that are below the base pointer,
  3831. as this is temporary storage rather than a function result on the
  3832. stack, say. }
  3833. (
  3834. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3835. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3836. )
  3837. ) then
  3838. begin
  3839. RemoveCurrentp(p, hp1);
  3840. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3841. RemoveLastDeallocForFuncRes(p);
  3842. Result:=true;
  3843. exit;
  3844. end;
  3845. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3846. begin
  3847. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3848. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3849. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3850. begin
  3851. { change
  3852. mov reg1, mem1
  3853. test/cmp x, mem1
  3854. to
  3855. mov reg1, mem1
  3856. test/cmp x, reg1
  3857. }
  3858. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3859. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3860. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3861. Result := True;
  3862. Exit;
  3863. end;
  3864. if DoMovCmpMemOpt(p, hp1, True) then
  3865. begin
  3866. Result := True;
  3867. Exit;
  3868. end;
  3869. end;
  3870. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3871. { If the flags register is in use, don't change the instruction to an
  3872. ADD otherwise this will scramble the flags. [Kit] }
  3873. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3874. begin
  3875. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3876. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3877. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3878. ) or
  3879. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3880. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3881. )
  3882. ) then
  3883. { mov reg1,ref
  3884. lea reg2,[reg1,reg2]
  3885. to
  3886. add reg2,ref}
  3887. begin
  3888. TransferUsedRegs(TmpUsedRegs);
  3889. { reg1 may not be used afterwards }
  3890. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3891. begin
  3892. Taicpu(hp1).opcode:=A_ADD;
  3893. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3894. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3895. RemoveCurrentp(p, hp1);
  3896. result:=true;
  3897. exit;
  3898. end;
  3899. end;
  3900. { If the LEA instruction can be converted into an arithmetic instruction,
  3901. it may be possible to then fold it in the next optimisation, otherwise
  3902. there's nothing more that can be optimised here. }
  3903. if not ConvertLEA(taicpu(hp1)) then
  3904. Exit;
  3905. end;
  3906. if (taicpu(p).oper[1]^.typ = top_reg) and
  3907. (hp1.typ = ait_instruction) and
  3908. GetNextInstruction(hp1, hp2) and
  3909. MatchInstruction(hp2,A_MOV,[]) and
  3910. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3911. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3912. (
  3913. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3914. {$ifdef x86_64}
  3915. or
  3916. (
  3917. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3918. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3919. )
  3920. {$endif x86_64}
  3921. ) then
  3922. begin
  3923. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3924. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3925. { change movsX/movzX reg/ref, reg2
  3926. add/sub/or/... reg3/$const, reg2
  3927. mov reg2 reg/ref
  3928. dealloc reg2
  3929. to
  3930. add/sub/or/... reg3/$const, reg/ref }
  3931. begin
  3932. TransferUsedRegs(TmpUsedRegs);
  3933. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3934. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3935. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3936. begin
  3937. { by example:
  3938. movswl %si,%eax movswl %si,%eax p
  3939. decl %eax addl %edx,%eax hp1
  3940. movw %ax,%si movw %ax,%si hp2
  3941. ->
  3942. movswl %si,%eax movswl %si,%eax p
  3943. decw %eax addw %edx,%eax hp1
  3944. movw %ax,%si movw %ax,%si hp2
  3945. }
  3946. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3947. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3948. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3949. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3950. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3951. {
  3952. ->
  3953. movswl %si,%eax movswl %si,%eax p
  3954. decw %si addw %dx,%si hp1
  3955. movw %ax,%si movw %ax,%si hp2
  3956. }
  3957. case taicpu(hp1).ops of
  3958. 1:
  3959. begin
  3960. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3961. if taicpu(hp1).oper[0]^.typ=top_reg then
  3962. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3963. end;
  3964. 2:
  3965. begin
  3966. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3967. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3968. (taicpu(hp1).opcode<>A_SHL) and
  3969. (taicpu(hp1).opcode<>A_SHR) and
  3970. (taicpu(hp1).opcode<>A_SAR) then
  3971. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3972. end;
  3973. else
  3974. internalerror(2008042701);
  3975. end;
  3976. {
  3977. ->
  3978. decw %si addw %dx,%si p
  3979. }
  3980. RemoveInstruction(hp2);
  3981. RemoveCurrentP(p, hp1);
  3982. Result:=True;
  3983. Exit;
  3984. end;
  3985. end;
  3986. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3987. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3988. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3989. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3990. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3991. )
  3992. {$ifdef i386}
  3993. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3994. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3995. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3996. {$endif i386}
  3997. then
  3998. { change movsX/movzX reg/ref, reg2
  3999. add/sub/or/... regX/$const, reg2
  4000. mov reg2, reg3
  4001. dealloc reg2
  4002. to
  4003. movsX/movzX reg/ref, reg3
  4004. add/sub/or/... reg3/$const, reg3
  4005. }
  4006. begin
  4007. TransferUsedRegs(TmpUsedRegs);
  4008. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4009. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4010. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4011. begin
  4012. { by example:
  4013. movswl %si,%eax movswl %si,%eax p
  4014. decl %eax addl %edx,%eax hp1
  4015. movw %ax,%si movw %ax,%si hp2
  4016. ->
  4017. movswl %si,%eax movswl %si,%eax p
  4018. decw %eax addw %edx,%eax hp1
  4019. movw %ax,%si movw %ax,%si hp2
  4020. }
  4021. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4022. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4023. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4024. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4025. { limit size of constants as well to avoid assembler errors, but
  4026. check opsize to avoid overflow when left shifting the 1 }
  4027. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4028. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4029. {$ifdef x86_64}
  4030. { Be careful of, for example:
  4031. movl %reg1,%reg2
  4032. addl %reg3,%reg2
  4033. movq %reg2,%reg4
  4034. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4035. }
  4036. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4037. begin
  4038. taicpu(hp2).changeopsize(S_L);
  4039. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4040. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4041. end;
  4042. {$endif x86_64}
  4043. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4044. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4045. if taicpu(p).oper[0]^.typ=top_reg then
  4046. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4047. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4048. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4049. {
  4050. ->
  4051. movswl %si,%eax movswl %si,%eax p
  4052. decw %si addw %dx,%si hp1
  4053. movw %ax,%si movw %ax,%si hp2
  4054. }
  4055. case taicpu(hp1).ops of
  4056. 1:
  4057. begin
  4058. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4059. if taicpu(hp1).oper[0]^.typ=top_reg then
  4060. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4061. end;
  4062. 2:
  4063. begin
  4064. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4065. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4066. (taicpu(hp1).opcode<>A_SHL) and
  4067. (taicpu(hp1).opcode<>A_SHR) and
  4068. (taicpu(hp1).opcode<>A_SAR) then
  4069. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4070. end;
  4071. else
  4072. internalerror(2018111801);
  4073. end;
  4074. {
  4075. ->
  4076. decw %si addw %dx,%si p
  4077. }
  4078. RemoveInstruction(hp2);
  4079. end;
  4080. end;
  4081. end;
  4082. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4083. GetNextInstruction(hp1, hp2) and
  4084. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4085. MatchOperand(Taicpu(p).oper[0]^,0) and
  4086. (Taicpu(p).oper[1]^.typ = top_reg) and
  4087. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4088. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4089. { mov reg1,0
  4090. bts reg1,operand1 --> mov reg1,operand2
  4091. or reg1,operand2 bts reg1,operand1}
  4092. begin
  4093. Taicpu(hp2).opcode:=A_MOV;
  4094. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4095. asml.remove(hp1);
  4096. insertllitem(hp2,hp2.next,hp1);
  4097. RemoveCurrentp(p, hp1);
  4098. Result:=true;
  4099. exit;
  4100. end;
  4101. {
  4102. mov ref,reg0
  4103. <op> reg0,reg1
  4104. dealloc reg0
  4105. to
  4106. <op> ref,reg1
  4107. }
  4108. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4110. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4111. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4112. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4113. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4114. begin
  4115. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4116. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4117. RemoveCurrentp(p, hp1);
  4118. Result:=true;
  4119. exit;
  4120. end;
  4121. {$ifdef x86_64}
  4122. { Convert:
  4123. movq x(ref),%reg64
  4124. shrq y,%reg64
  4125. To:
  4126. movl x+4(ref),%reg32
  4127. shrl y-32,%reg32 (Remove if y = 32)
  4128. }
  4129. if (taicpu(p).opsize = S_Q) and
  4130. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4131. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4132. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4133. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4134. (taicpu(hp1).oper[0]^.val >= 32) and
  4135. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4136. begin
  4137. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4138. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4139. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4140. { Convert to 32-bit }
  4141. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4142. taicpu(p).opsize := S_L;
  4143. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4144. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4145. if (taicpu(hp1).oper[0]^.val = 32) then
  4146. begin
  4147. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4148. RemoveInstruction(hp1);
  4149. end
  4150. else
  4151. begin
  4152. { This will potentially open up more arithmetic operations since
  4153. the peephole optimizer now has a big hint that only the lower
  4154. 32 bits are currently in use (and opcodes are smaller in size) }
  4155. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4156. taicpu(hp1).opsize := S_L;
  4157. Dec(taicpu(hp1).oper[0]^.val, 32);
  4158. DebugMsg(SPeepholeOptimization + PreMessage +
  4159. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4160. end;
  4161. Result := True;
  4162. Exit;
  4163. end;
  4164. {$endif x86_64}
  4165. { Backward optimisation. If we have:
  4166. func. %reg1,%reg2
  4167. mov %reg2,%reg3
  4168. (dealloc %reg2)
  4169. Change to:
  4170. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4171. }
  4172. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4173. begin
  4174. p_SourceReg := taicpu(p).oper[0]^.reg;
  4175. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4176. TransferUsedRegs(TmpUsedRegs);
  4177. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4178. GetLastInstruction(p, hp2) and
  4179. (hp2.typ = ait_instruction) and
  4180. { Have to make sure it's an instruction that only reads from
  4181. operand 1 and only writes (not reads or modifies) from operand 2;
  4182. in essence, a one-operand pure function such as BSR or POPCNT }
  4183. (taicpu(hp2).ops = 2) and
  4184. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4185. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4186. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4187. begin
  4188. case taicpu(hp2).opcode of
  4189. A_FSTSW, A_FNSTSW,
  4190. A_IN, A_INS, A_OUT, A_OUTS,
  4191. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4192. { These routines have explicit operands, but they are restricted in
  4193. what they can be (e.g. IN and OUT can only read from AL, AX or
  4194. EAX. }
  4195. ;
  4196. else
  4197. begin
  4198. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4199. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4200. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4201. RemoveCurrentp(p, hp1);
  4202. Result := True;
  4203. Exit;
  4204. end;
  4205. end;
  4206. end;
  4207. end;
  4208. end;
  4209. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4210. var
  4211. hp1 : tai;
  4212. begin
  4213. Result:=false;
  4214. if taicpu(p).ops <> 2 then
  4215. exit;
  4216. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4217. GetNextInstruction(p,hp1) then
  4218. begin
  4219. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4220. (taicpu(hp1).ops = 2) then
  4221. begin
  4222. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4223. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4224. { movXX reg1, mem1 or movXX mem1, reg1
  4225. movXX mem2, reg2 movXX reg2, mem2}
  4226. begin
  4227. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4228. { movXX reg1, mem1 or movXX mem1, reg1
  4229. movXX mem2, reg1 movXX reg2, mem1}
  4230. begin
  4231. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4232. begin
  4233. { Removes the second statement from
  4234. movXX reg1, mem1/reg2
  4235. movXX mem1/reg2, reg1
  4236. }
  4237. if taicpu(p).oper[0]^.typ=top_reg then
  4238. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4239. { Removes the second statement from
  4240. movXX mem1/reg1, reg2
  4241. movXX reg2, mem1/reg1
  4242. }
  4243. if (taicpu(p).oper[1]^.typ=top_reg) and
  4244. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4245. begin
  4246. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4247. RemoveInstruction(hp1);
  4248. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4249. Result:=true;
  4250. exit;
  4251. end
  4252. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4253. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4254. begin
  4255. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4256. RemoveInstruction(hp1);
  4257. Result:=true;
  4258. exit;
  4259. end;
  4260. end
  4261. end;
  4262. end;
  4263. end;
  4264. end;
  4265. end;
  4266. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4267. var
  4268. hp1 : tai;
  4269. begin
  4270. result:=false;
  4271. { replace
  4272. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4273. MovX %mreg2,%mreg1
  4274. dealloc %mreg2
  4275. by
  4276. <Op>X %mreg2,%mreg1
  4277. ?
  4278. }
  4279. if GetNextInstruction(p,hp1) and
  4280. { we mix single and double opperations here because we assume that the compiler
  4281. generates vmovapd only after double operations and vmovaps only after single operations }
  4282. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4283. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4284. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4285. (taicpu(p).oper[0]^.typ=top_reg) then
  4286. begin
  4287. TransferUsedRegs(TmpUsedRegs);
  4288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4289. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4290. begin
  4291. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4292. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4293. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4294. RemoveInstruction(hp1);
  4295. result:=true;
  4296. end;
  4297. end;
  4298. end;
  4299. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4300. var
  4301. hp1, p_label, p_dist, hp1_dist: tai;
  4302. JumpLabel, JumpLabel_dist: TAsmLabel;
  4303. FirstValue, SecondValue: TCGInt;
  4304. begin
  4305. Result := False;
  4306. if (taicpu(p).oper[0]^.typ = top_const) and
  4307. (taicpu(p).oper[0]^.val <> -1) then
  4308. begin
  4309. { Convert unsigned maximum constants to -1 to aid optimisation }
  4310. case taicpu(p).opsize of
  4311. S_B:
  4312. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4313. begin
  4314. taicpu(p).oper[0]^.val := -1;
  4315. Result := True;
  4316. Exit;
  4317. end;
  4318. S_W:
  4319. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4320. begin
  4321. taicpu(p).oper[0]^.val := -1;
  4322. Result := True;
  4323. Exit;
  4324. end;
  4325. S_L:
  4326. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4327. begin
  4328. taicpu(p).oper[0]^.val := -1;
  4329. Result := True;
  4330. Exit;
  4331. end;
  4332. {$ifdef x86_64}
  4333. S_Q:
  4334. { Storing anything greater than $7FFFFFFF is not possible so do
  4335. nothing };
  4336. {$endif x86_64}
  4337. else
  4338. InternalError(2021121001);
  4339. end;
  4340. end;
  4341. if GetNextInstruction(p, hp1) and
  4342. TrySwapMovCmp(p, hp1) then
  4343. begin
  4344. Result := True;
  4345. Exit;
  4346. end;
  4347. { Search for:
  4348. test $x,(reg/ref)
  4349. jne @lbl1
  4350. test $y,(reg/ref) (same register or reference)
  4351. jne @lbl1
  4352. Change to:
  4353. test $(x or y),(reg/ref)
  4354. jne @lbl1
  4355. (Note, this doesn't work with je instead of jne)
  4356. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4357. Also search for:
  4358. test $x,(reg/ref)
  4359. je @lbl1
  4360. test $y,(reg/ref)
  4361. je/jne @lbl2
  4362. If (x or y) = x, then the second jump is deterministic
  4363. }
  4364. if (
  4365. (
  4366. (taicpu(p).oper[0]^.typ = top_const) or
  4367. (
  4368. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4369. (taicpu(p).oper[0]^.typ = top_reg) and
  4370. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4371. )
  4372. ) and
  4373. MatchInstruction(hp1, A_JCC, [])
  4374. ) then
  4375. begin
  4376. if (taicpu(p).oper[0]^.typ = top_reg) and
  4377. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4378. FirstValue := -1
  4379. else
  4380. FirstValue := taicpu(p).oper[0]^.val;
  4381. { If we have several test/jne's in a row, it might be the case that
  4382. the second label doesn't go to the same location, but the one
  4383. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4384. so accommodate for this with a while loop.
  4385. }
  4386. hp1_dist := hp1;
  4387. if GetNextInstruction(hp1, p_dist) and
  4388. (p_dist.typ = ait_instruction) and
  4389. (
  4390. (
  4391. (taicpu(p_dist).opcode = A_TEST) and
  4392. (
  4393. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4394. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4395. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4396. )
  4397. ) or
  4398. (
  4399. { cmp 0,%reg = test %reg,%reg }
  4400. (taicpu(p_dist).opcode = A_CMP) and
  4401. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4402. )
  4403. ) and
  4404. { Make sure the destination operands are actually the same }
  4405. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4406. GetNextInstruction(p_dist, hp1_dist) and
  4407. MatchInstruction(hp1_dist, A_JCC, []) then
  4408. begin
  4409. if
  4410. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4411. (
  4412. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4413. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4414. ) then
  4415. SecondValue := -1
  4416. else
  4417. SecondValue := taicpu(p_dist).oper[0]^.val;
  4418. { If both of the TEST constants are identical, delete the second
  4419. TEST that is unnecessary. }
  4420. if (FirstValue = SecondValue) then
  4421. begin
  4422. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4423. RemoveInstruction(p_dist);
  4424. { Don't let the flags register become deallocated and reallocated between the jumps }
  4425. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4426. Result := True;
  4427. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4428. begin
  4429. { Since the second jump's condition is a subset of the first, we
  4430. know it will never branch because the first jump dominates it.
  4431. Get it out of the way now rather than wait for the jump
  4432. optimisations for a speed boost. }
  4433. if IsJumpToLabel(taicpu(hp1_dist)) then
  4434. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4435. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4436. RemoveInstruction(hp1_dist);
  4437. end
  4438. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4439. begin
  4440. { If the inverse of the first condition is a subset of the second,
  4441. the second one will definitely branch if the first one doesn't }
  4442. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4443. MakeUnconditional(taicpu(hp1_dist));
  4444. RemoveDeadCodeAfterJump(hp1_dist);
  4445. end;
  4446. Exit;
  4447. end;
  4448. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4449. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4450. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4451. then the second jump will never branch, so it can also be
  4452. removed regardless of where it goes }
  4453. (
  4454. (FirstValue = -1) or
  4455. (SecondValue = -1) or
  4456. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4457. ) then
  4458. begin
  4459. { Same jump location... can be a register since nothing's changed }
  4460. { If any of the entries are equivalent to test %reg,%reg, then the
  4461. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4462. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4463. if IsJumpToLabel(taicpu(hp1_dist)) then
  4464. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4465. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4466. RemoveInstruction(hp1_dist);
  4467. { Only remove the second test if no jumps or other conditional instructions follow }
  4468. TransferUsedRegs(TmpUsedRegs);
  4469. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4470. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4471. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4472. RemoveInstruction(p_dist);
  4473. Result := True;
  4474. Exit;
  4475. end;
  4476. end;
  4477. end;
  4478. { Search for:
  4479. test %reg,%reg
  4480. j(c1) @lbl1
  4481. ...
  4482. @lbl:
  4483. test %reg,%reg (same register)
  4484. j(c2) @lbl2
  4485. If c2 is a subset of c1, change to:
  4486. test %reg,%reg
  4487. j(c1) @lbl2
  4488. (@lbl1 may become a dead label as a result)
  4489. }
  4490. if (taicpu(p).oper[1]^.typ = top_reg) and
  4491. (taicpu(p).oper[0]^.typ = top_reg) and
  4492. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4493. MatchInstruction(hp1, A_JCC, []) and
  4494. IsJumpToLabel(taicpu(hp1)) then
  4495. begin
  4496. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4497. p_label := nil;
  4498. if Assigned(JumpLabel) then
  4499. p_label := getlabelwithsym(JumpLabel);
  4500. if Assigned(p_label) and
  4501. GetNextInstruction(p_label, p_dist) and
  4502. MatchInstruction(p_dist, A_TEST, []) and
  4503. { It's fine if the second test uses smaller sub-registers }
  4504. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4505. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4506. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4507. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4508. GetNextInstruction(p_dist, hp1_dist) and
  4509. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4510. begin
  4511. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4512. if JumpLabel = JumpLabel_dist then
  4513. { This is an infinite loop }
  4514. Exit;
  4515. { Best optimisation when the first condition is a subset (or equal) of the second }
  4516. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4517. begin
  4518. { Any registers used here will already be allocated }
  4519. if Assigned(JumpLabel_dist) then
  4520. JumpLabel_dist.IncRefs;
  4521. if Assigned(JumpLabel) then
  4522. JumpLabel.DecRefs;
  4523. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4524. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4525. Result := True;
  4526. Exit;
  4527. end;
  4528. end;
  4529. end;
  4530. end;
  4531. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4532. var
  4533. hp1, hp2: tai;
  4534. ActiveReg: TRegister;
  4535. OldOffset: asizeint;
  4536. ThisConst: TCGInt;
  4537. function RegDeallocated: Boolean;
  4538. begin
  4539. TransferUsedRegs(TmpUsedRegs);
  4540. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4541. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4542. end;
  4543. begin
  4544. result:=false;
  4545. hp1 := nil;
  4546. { replace
  4547. addX const,%reg1
  4548. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4549. dealloc %reg1
  4550. by
  4551. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4552. }
  4553. if MatchOpType(taicpu(p),top_const,top_reg) then
  4554. begin
  4555. ActiveReg := taicpu(p).oper[1]^.reg;
  4556. { Ensures the entire register was updated }
  4557. if (taicpu(p).opsize >= S_L) and
  4558. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4559. MatchInstruction(hp1,A_LEA,[]) and
  4560. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4561. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4562. (
  4563. { Cover the case where the register in the reference is also the destination register }
  4564. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4565. (
  4566. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4567. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4568. RegDeallocated
  4569. )
  4570. ) then
  4571. begin
  4572. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4573. {$push}
  4574. {$R-}{$Q-}
  4575. { Explicitly disable overflow checking for these offset calculation
  4576. as those do not matter for the final result }
  4577. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4579. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4580. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4581. {$pop}
  4582. {$ifdef x86_64}
  4583. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4584. begin
  4585. { Overflow; abort }
  4586. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4587. end
  4588. else
  4589. {$endif x86_64}
  4590. begin
  4591. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4592. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4593. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4594. RemoveCurrentP(p, hp1)
  4595. else
  4596. RemoveCurrentP(p);
  4597. result:=true;
  4598. Exit;
  4599. end;
  4600. end;
  4601. if (
  4602. { Save calling GetNextInstructionUsingReg again }
  4603. Assigned(hp1) or
  4604. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4605. ) and
  4606. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4607. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4608. begin
  4609. if taicpu(hp1).oper[0]^.typ = top_const then
  4610. begin
  4611. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4612. if taicpu(hp1).opcode = A_ADD then
  4613. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4614. else
  4615. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4616. Result := True;
  4617. { Handle any overflows }
  4618. case taicpu(p).opsize of
  4619. S_B:
  4620. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4621. S_W:
  4622. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4623. S_L:
  4624. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4625. {$ifdef x86_64}
  4626. S_Q:
  4627. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4628. { Overflow; abort }
  4629. Result := False
  4630. else
  4631. taicpu(p).oper[0]^.val := ThisConst;
  4632. {$endif x86_64}
  4633. else
  4634. InternalError(2021102610);
  4635. end;
  4636. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4637. if Result then
  4638. begin
  4639. if (taicpu(p).oper[0]^.val < 0) and
  4640. (
  4641. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4642. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4643. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4644. ) then
  4645. begin
  4646. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4647. taicpu(p).opcode := A_SUB;
  4648. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4649. end
  4650. else
  4651. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4652. RemoveInstruction(hp1);
  4653. end;
  4654. end
  4655. else
  4656. begin
  4657. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4658. TransferUsedRegs(TmpUsedRegs);
  4659. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4660. hp2 := p;
  4661. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4662. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4663. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4664. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4665. begin
  4666. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4667. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4668. Asml.Remove(p);
  4669. Asml.InsertAfter(p, hp1);
  4670. p := hp1;
  4671. Result := True;
  4672. end;
  4673. end;
  4674. end;
  4675. end;
  4676. end;
  4677. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4678. var
  4679. hp1: tai;
  4680. ref: Integer;
  4681. saveref: treference;
  4682. Multiple: TCGInt;
  4683. Adjacent: Boolean;
  4684. begin
  4685. Result:=false;
  4686. { play save and throw an error if LEA uses a seg register prefix,
  4687. this is most likely an error somewhere else }
  4688. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4689. internalerror(2022022001);
  4690. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4691. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4692. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4693. (
  4694. { do not mess with leas accessing the stack pointer
  4695. unless it's a null operation }
  4696. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4697. (
  4698. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4699. (taicpu(p).oper[0]^.ref^.offset = 0)
  4700. )
  4701. ) and
  4702. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4703. begin
  4704. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4705. begin
  4706. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4707. begin
  4708. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4709. taicpu(p).oper[1]^.reg);
  4710. InsertLLItem(p.previous,p.next, hp1);
  4711. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4712. p.free;
  4713. p:=hp1;
  4714. end
  4715. else
  4716. begin
  4717. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4718. RemoveCurrentP(p);
  4719. end;
  4720. Result:=true;
  4721. exit;
  4722. end
  4723. else if (
  4724. { continue to use lea to adjust the stack pointer,
  4725. it is the recommended way, but only if not optimizing for size }
  4726. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4727. (cs_opt_size in current_settings.optimizerswitches)
  4728. ) and
  4729. { If the flags register is in use, don't change the instruction
  4730. to an ADD otherwise this will scramble the flags. [Kit] }
  4731. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4732. ConvertLEA(taicpu(p)) then
  4733. begin
  4734. Result:=true;
  4735. exit;
  4736. end;
  4737. end;
  4738. { Don't optimise if the stack or frame pointer is the destination register }
  4739. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4740. Exit;
  4741. if GetNextInstruction(p,hp1) and
  4742. (hp1.typ=ait_instruction) then
  4743. begin
  4744. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4745. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4746. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4747. begin
  4748. TransferUsedRegs(TmpUsedRegs);
  4749. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4750. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4751. begin
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. exit;
  4757. end;
  4758. end;
  4759. { changes
  4760. lea <ref1>, reg1
  4761. <op> ...,<ref. with reg1>,...
  4762. to
  4763. <op> ...,<ref1>,... }
  4764. { find a reference which uses reg1 }
  4765. 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
  4766. ref:=0
  4767. 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
  4768. ref:=1
  4769. else
  4770. ref:=-1;
  4771. if (ref<>-1) and
  4772. { reg1 must be either the base or the index }
  4773. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4774. begin
  4775. { reg1 can be removed from the reference }
  4776. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4777. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4778. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4779. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4780. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4781. else
  4782. Internalerror(2019111201);
  4783. { check if the can insert all data of the lea into the second instruction }
  4784. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4785. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4786. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4787. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4788. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4789. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4790. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4791. {$ifdef x86_64}
  4792. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4793. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4794. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4795. )
  4796. {$endif x86_64}
  4797. then
  4798. begin
  4799. { reg1 might not used by the second instruction after it is remove from the reference }
  4800. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4801. begin
  4802. TransferUsedRegs(TmpUsedRegs);
  4803. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4804. { reg1 is not updated so it might not be used afterwards }
  4805. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4806. begin
  4807. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4808. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4809. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4810. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4811. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4812. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4813. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4814. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4815. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4816. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4817. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4818. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4819. RemoveCurrentP(p, hp1);
  4820. result:=true;
  4821. exit;
  4822. end
  4823. end;
  4824. end;
  4825. { recover }
  4826. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4827. end;
  4828. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4829. if Adjacent or
  4830. { Check further ahead (up to 2 instructions ahead for -O2) }
  4831. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4832. begin
  4833. { Check common LEA/LEA conditions }
  4834. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4835. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4836. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4837. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4838. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4839. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4840. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4841. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4842. (
  4843. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4844. calling it (since it calls GetNextInstruction) }
  4845. Adjacent or
  4846. (
  4847. (
  4848. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4849. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4850. ) and (
  4851. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4852. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4853. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4854. )
  4855. )
  4856. ) then
  4857. begin
  4858. { changes
  4859. lea (regX,scale), reg1
  4860. lea offset(reg1,reg1), reg1
  4861. to
  4862. lea offset(regX,scale*2), reg1
  4863. and
  4864. lea (regX,scale1), reg1
  4865. lea offset(reg1,scale2), reg1
  4866. to
  4867. lea offset(regX,scale1*scale2), reg1
  4868. ... so long as the final scale does not exceed 8
  4869. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4870. }
  4871. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4872. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4873. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4874. (
  4875. (
  4876. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4877. ) or (
  4878. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4879. (
  4880. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4881. (
  4882. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4883. Adjacent or
  4884. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4885. )
  4886. )
  4887. )
  4888. ) and (
  4889. (
  4890. { lea (reg1,scale2), reg1 variant }
  4891. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4892. (
  4893. (
  4894. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4895. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4896. ) or (
  4897. { lea (regX,regX), reg1 variant }
  4898. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4899. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4900. )
  4901. )
  4902. ) or (
  4903. { lea (reg1,reg1), reg1 variant }
  4904. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4905. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4906. )
  4907. ) then
  4908. begin
  4909. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4910. { Make everything homogeneous to make calculations easier }
  4911. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4912. begin
  4913. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4914. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4915. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4916. else
  4917. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4918. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4919. end;
  4920. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4921. begin
  4922. { Just to prevent miscalculations }
  4923. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4924. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4925. else
  4926. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4927. end
  4928. else
  4929. begin
  4930. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4931. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4932. end;
  4933. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4934. RemoveCurrentP(p);
  4935. result:=true;
  4936. exit;
  4937. end
  4938. { changes
  4939. lea offset1(regX), reg1
  4940. lea offset2(reg1), reg1
  4941. to
  4942. lea offset1+offset2(regX), reg1 }
  4943. else if
  4944. (
  4945. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4946. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4947. ) or (
  4948. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4949. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4950. (
  4951. (
  4952. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4953. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4954. ) or (
  4955. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4956. (
  4957. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4958. (
  4959. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4960. (
  4961. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4962. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4963. )
  4964. )
  4965. )
  4966. )
  4967. )
  4968. ) then
  4969. begin
  4970. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4971. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4972. begin
  4973. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4974. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4975. { if the register is used as index and base, we have to increase for base as well
  4976. and adapt base }
  4977. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4978. begin
  4979. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4980. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4981. end;
  4982. end
  4983. else
  4984. begin
  4985. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4986. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4987. end;
  4988. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4989. begin
  4990. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4991. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4992. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4993. end;
  4994. RemoveCurrentP(p);
  4995. result:=true;
  4996. exit;
  4997. end;
  4998. end;
  4999. { Change:
  5000. leal/q $x(%reg1),%reg2
  5001. ...
  5002. shll/q $y,%reg2
  5003. To:
  5004. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5005. }
  5006. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5007. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5008. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5009. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5010. (taicpu(hp1).oper[0]^.val <= 3) then
  5011. begin
  5012. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5013. TransferUsedRegs(TmpUsedRegs);
  5014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5015. if
  5016. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5017. (this works even if scalefactor is zero) }
  5018. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5019. { Ensure offset doesn't go out of bounds }
  5020. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5021. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5022. (
  5023. (
  5024. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5025. (
  5026. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5027. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5028. (
  5029. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5030. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5031. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5032. )
  5033. )
  5034. ) or (
  5035. (
  5036. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5037. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5038. ) and
  5039. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5040. )
  5041. ) then
  5042. begin
  5043. repeat
  5044. with taicpu(p).oper[0]^.ref^ do
  5045. begin
  5046. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5047. if index = base then
  5048. begin
  5049. if Multiple > 4 then
  5050. { Optimisation will no longer work because resultant
  5051. scale factor will exceed 8 }
  5052. Break;
  5053. base := NR_NO;
  5054. scalefactor := 2;
  5055. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5056. end
  5057. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5058. begin
  5059. { Scale factor only works on the index register }
  5060. index := base;
  5061. base := NR_NO;
  5062. end;
  5063. { For safety }
  5064. if scalefactor <= 1 then
  5065. begin
  5066. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5067. scalefactor := Multiple;
  5068. end
  5069. else
  5070. begin
  5071. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5072. scalefactor := scalefactor * Multiple;
  5073. end;
  5074. offset := offset * Multiple;
  5075. end;
  5076. RemoveInstruction(hp1);
  5077. Result := True;
  5078. Exit;
  5079. { This repeat..until loop exists for the benefit of Break }
  5080. until True;
  5081. end;
  5082. end;
  5083. end;
  5084. end;
  5085. end;
  5086. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5087. var
  5088. hp1 : tai;
  5089. begin
  5090. DoSubAddOpt := False;
  5091. if taicpu(p).oper[0]^.typ <> top_const then
  5092. { Should have been confirmed before calling }
  5093. InternalError(2021102601);
  5094. if GetLastInstruction(p, hp1) and
  5095. (hp1.typ = ait_instruction) and
  5096. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5097. case taicpu(hp1).opcode Of
  5098. A_DEC:
  5099. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5100. begin
  5101. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5102. RemoveInstruction(hp1);
  5103. end;
  5104. A_SUB:
  5105. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5106. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5107. begin
  5108. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5109. RemoveInstruction(hp1);
  5110. end;
  5111. A_ADD:
  5112. begin
  5113. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5114. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5115. begin
  5116. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5117. RemoveInstruction(hp1);
  5118. if (taicpu(p).oper[0]^.val = 0) then
  5119. begin
  5120. hp1 := tai(p.next);
  5121. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5122. if not GetLastInstruction(hp1, p) then
  5123. p := hp1;
  5124. DoSubAddOpt := True;
  5125. end
  5126. end;
  5127. end;
  5128. else
  5129. ;
  5130. end;
  5131. end;
  5132. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5133. begin
  5134. Result := False;
  5135. if UpdateTmpUsedRegs then
  5136. TransferUsedRegs(TmpUsedRegs);
  5137. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5138. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5139. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5140. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5141. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5142. (
  5143. (
  5144. (taicpu(hp1).opcode = A_TEST)
  5145. ) or (
  5146. (taicpu(hp1).opcode = A_CMP) and
  5147. { A sanity check more than anything }
  5148. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5149. )
  5150. ) then
  5151. begin
  5152. { change
  5153. mov mem, %reg
  5154. cmp/test x, %reg / test %reg,%reg
  5155. (reg deallocated)
  5156. to
  5157. cmp/test x, mem / cmp 0, mem
  5158. }
  5159. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5161. begin
  5162. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5163. if (taicpu(hp1).opcode = A_TEST) and
  5164. (
  5165. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5166. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5167. ) then
  5168. begin
  5169. taicpu(hp1).opcode := A_CMP;
  5170. taicpu(hp1).loadconst(0, 0);
  5171. end;
  5172. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5173. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5174. RemoveCurrentP(p, hp1);
  5175. Result := True;
  5176. Exit;
  5177. end;
  5178. end;
  5179. end;
  5180. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5181. var
  5182. hp2, hp3, hp4, hp5, hp6: tai;
  5183. ThisReg: TRegister;
  5184. JumpLoc: TAsmLabel;
  5185. begin
  5186. Result := False;
  5187. {
  5188. Convert:
  5189. j<c> .L1
  5190. .L2:
  5191. mov 1,reg
  5192. jmp .L3 (or ret, although it might not be a RET yet)
  5193. .L1:
  5194. mov 0,reg
  5195. jmp .L3 (or ret)
  5196. ( As long as .L3 <> .L1 or .L2)
  5197. To:
  5198. mov 0,reg
  5199. set<not(c)> reg
  5200. jmp .L3 (or ret)
  5201. .L2:
  5202. mov 1,reg
  5203. jmp .L3 (or ret)
  5204. .L1:
  5205. mov 0,reg
  5206. jmp .L3 (or ret)
  5207. }
  5208. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5209. Exit;
  5210. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5211. if GetNextInstruction(hp_label, hp2) and
  5212. MatchInstruction(hp2,A_MOV,[]) and
  5213. (taicpu(hp2).oper[0]^.typ = top_const) and
  5214. (
  5215. (
  5216. (taicpu(hp2).oper[1]^.typ = top_reg)
  5217. {$ifdef i386}
  5218. { Under i386, ESI, EDI, EBP and ESP
  5219. don't have an 8-bit representation }
  5220. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5221. {$endif i386}
  5222. ) or (
  5223. {$ifdef i386}
  5224. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5225. {$endif i386}
  5226. (taicpu(hp2).opsize = S_B)
  5227. )
  5228. ) and
  5229. GetNextInstruction(hp2, hp3) and
  5230. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5231. (
  5232. (taicpu(hp3).opcode=A_RET) or
  5233. (
  5234. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5235. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5236. )
  5237. ) and
  5238. GetNextInstruction(hp3, hp4) and
  5239. SkipAligns(hp4, hp4) and
  5240. (hp4.typ=ait_label) and
  5241. (tai_label(hp4).labsym=JumpLoc) and
  5242. (
  5243. not (cs_opt_size in current_settings.optimizerswitches) or
  5244. { If the initial jump is the label's only reference, then it will
  5245. become a dead label if the other conditions are met and hence
  5246. remove at least 2 instructions, including a jump }
  5247. (JumpLoc.getrefs = 1)
  5248. ) and
  5249. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5250. that will be optimised out }
  5251. GetNextInstruction(hp4, hp5) and
  5252. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5253. (taicpu(hp5).oper[0]^.typ = top_const) and
  5254. (
  5255. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5256. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5257. ) and
  5258. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5259. GetNextInstruction(hp5,hp6) and
  5260. (
  5261. (hp6.typ<>ait_label) or
  5262. SkipLabels(hp6, hp6)
  5263. ) and
  5264. (hp6.typ=ait_instruction) then
  5265. begin
  5266. { First, let's look at the two jumps that are hp3 and hp6 }
  5267. if not
  5268. (
  5269. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5270. (
  5271. (taicpu(hp6).opcode=A_RET) or
  5272. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5273. )
  5274. ) then
  5275. { If condition is False, then the JMP/RET instructions matched conventionally }
  5276. begin
  5277. { See if one of the jumps can be instantly converted into a RET }
  5278. if (taicpu(hp3).opcode=A_JMP) then
  5279. begin
  5280. { Reuse hp5 }
  5281. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5282. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5283. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5284. Exit;
  5285. if MatchInstruction(hp5, A_RET, []) then
  5286. begin
  5287. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5288. ConvertJumpToRET(hp3, hp5);
  5289. Result := True;
  5290. end
  5291. else
  5292. Exit;
  5293. end;
  5294. if (taicpu(hp6).opcode=A_JMP) then
  5295. begin
  5296. { Reuse hp5 }
  5297. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5298. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5299. Exit;
  5300. if MatchInstruction(hp5, A_RET, []) then
  5301. begin
  5302. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5303. ConvertJumpToRET(hp6, hp5);
  5304. Result := True;
  5305. end
  5306. else
  5307. Exit;
  5308. end;
  5309. if not
  5310. (
  5311. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5312. (
  5313. (taicpu(hp6).opcode=A_RET) or
  5314. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5315. )
  5316. ) then
  5317. { Still doesn't match }
  5318. Exit;
  5319. end;
  5320. if (taicpu(hp2).oper[0]^.val = 1) then
  5321. begin
  5322. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5323. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5324. end
  5325. else
  5326. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5327. if taicpu(hp2).opsize=S_B then
  5328. begin
  5329. if taicpu(hp2).oper[1]^.typ = top_reg then
  5330. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5331. else
  5332. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5333. hp2 := p;
  5334. end
  5335. else
  5336. begin
  5337. { Will be a register because the size can't be S_B otherwise }
  5338. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5339. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5340. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5341. { Inserting it right before p will guarantee that the flags are also tracked }
  5342. Asml.InsertBefore(hp2, p);
  5343. end;
  5344. taicpu(hp4).condition:=taicpu(p).condition;
  5345. asml.InsertBefore(hp4, hp2);
  5346. JumpLoc.decrefs;
  5347. if taicpu(hp3).opcode = A_JMP then
  5348. begin
  5349. MakeUnconditional(taicpu(p));
  5350. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5351. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5352. end
  5353. else
  5354. begin
  5355. taicpu(p).condition := C_None;
  5356. taicpu(p).opcode := A_RET;
  5357. taicpu(p).clearop(0);
  5358. taicpu(p).ops := 0;
  5359. end;
  5360. if (JumpLoc.getrefs = 0) then
  5361. RemoveDeadCodeAfterJump(hp3);
  5362. Result:=true;
  5363. exit;
  5364. end;
  5365. end;
  5366. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5367. var
  5368. hp1, hp2: tai;
  5369. ActiveReg: TRegister;
  5370. OldOffset: asizeint;
  5371. ThisConst: TCGInt;
  5372. function RegDeallocated: Boolean;
  5373. begin
  5374. TransferUsedRegs(TmpUsedRegs);
  5375. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5376. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5377. end;
  5378. begin
  5379. Result:=false;
  5380. hp1 := nil;
  5381. { replace
  5382. subX const,%reg1
  5383. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5384. dealloc %reg1
  5385. by
  5386. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5387. }
  5388. if MatchOpType(taicpu(p),top_const,top_reg) then
  5389. begin
  5390. ActiveReg := taicpu(p).oper[1]^.reg;
  5391. { Ensures the entire register was updated }
  5392. if (taicpu(p).opsize >= S_L) and
  5393. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5394. MatchInstruction(hp1,A_LEA,[]) and
  5395. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5396. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5397. (
  5398. { Cover the case where the register in the reference is also the destination register }
  5399. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5400. (
  5401. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5402. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5403. RegDeallocated
  5404. )
  5405. ) then
  5406. begin
  5407. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5408. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5409. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5410. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5411. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5412. {$ifdef x86_64}
  5413. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5414. begin
  5415. { Overflow; abort }
  5416. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5417. end
  5418. else
  5419. {$endif x86_64}
  5420. begin
  5421. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5422. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5423. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5424. RemoveCurrentP(p, hp1)
  5425. else
  5426. RemoveCurrentP(p);
  5427. result:=true;
  5428. Exit;
  5429. end;
  5430. end;
  5431. if (
  5432. { Save calling GetNextInstructionUsingReg again }
  5433. Assigned(hp1) or
  5434. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5435. ) and
  5436. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5437. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5438. begin
  5439. if taicpu(hp1).oper[0]^.typ = top_const then
  5440. begin
  5441. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5442. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5443. Result := True;
  5444. { Handle any overflows }
  5445. case taicpu(p).opsize of
  5446. S_B:
  5447. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5448. S_W:
  5449. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5450. S_L:
  5451. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5452. {$ifdef x86_64}
  5453. S_Q:
  5454. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5455. { Overflow; abort }
  5456. Result := False
  5457. else
  5458. taicpu(p).oper[0]^.val := ThisConst;
  5459. {$endif x86_64}
  5460. else
  5461. InternalError(2021102610);
  5462. end;
  5463. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5464. if Result then
  5465. begin
  5466. if (taicpu(p).oper[0]^.val < 0) and
  5467. (
  5468. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5469. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5470. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5471. ) then
  5472. begin
  5473. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5474. taicpu(p).opcode := A_SUB;
  5475. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5476. end
  5477. else
  5478. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5479. RemoveInstruction(hp1);
  5480. end;
  5481. end
  5482. else
  5483. begin
  5484. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5485. TransferUsedRegs(TmpUsedRegs);
  5486. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5487. hp2 := p;
  5488. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5489. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5490. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5491. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5492. begin
  5493. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5494. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5495. Asml.Remove(p);
  5496. Asml.InsertAfter(p, hp1);
  5497. p := hp1;
  5498. Result := True;
  5499. Exit;
  5500. end;
  5501. end;
  5502. end;
  5503. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5504. { * change "sub/add const1, reg" or "dec reg" followed by
  5505. "sub const2, reg" to one "sub ..., reg" }
  5506. {$ifdef i386}
  5507. if (taicpu(p).oper[0]^.val = 2) and
  5508. (ActiveReg = NR_ESP) and
  5509. { Don't do the sub/push optimization if the sub }
  5510. { comes from setting up the stack frame (JM) }
  5511. (not(GetLastInstruction(p,hp1)) or
  5512. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5513. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5514. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5515. begin
  5516. hp1 := tai(p.next);
  5517. while Assigned(hp1) and
  5518. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5519. not RegReadByInstruction(NR_ESP,hp1) and
  5520. not RegModifiedByInstruction(NR_ESP,hp1) do
  5521. hp1 := tai(hp1.next);
  5522. if Assigned(hp1) and
  5523. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5524. begin
  5525. taicpu(hp1).changeopsize(S_L);
  5526. if taicpu(hp1).oper[0]^.typ=top_reg then
  5527. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5528. hp1 := tai(p.next);
  5529. RemoveCurrentp(p, hp1);
  5530. Result:=true;
  5531. exit;
  5532. end;
  5533. end;
  5534. {$endif i386}
  5535. if DoSubAddOpt(p) then
  5536. Result:=true;
  5537. end;
  5538. end;
  5539. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5540. var
  5541. TmpBool1,TmpBool2 : Boolean;
  5542. tmpref : treference;
  5543. hp1,hp2: tai;
  5544. mask: tcgint;
  5545. begin
  5546. Result:=false;
  5547. { All these optimisations work on "shl/sal const,%reg" }
  5548. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5549. Exit;
  5550. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5551. (taicpu(p).oper[0]^.val <= 3) then
  5552. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5553. begin
  5554. { should we check the next instruction? }
  5555. TmpBool1 := True;
  5556. { have we found an add/sub which could be
  5557. integrated in the lea? }
  5558. TmpBool2 := False;
  5559. reference_reset(tmpref,2,[]);
  5560. TmpRef.index := taicpu(p).oper[1]^.reg;
  5561. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5562. while TmpBool1 and
  5563. GetNextInstruction(p, hp1) and
  5564. (tai(hp1).typ = ait_instruction) and
  5565. ((((taicpu(hp1).opcode = A_ADD) or
  5566. (taicpu(hp1).opcode = A_SUB)) and
  5567. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5568. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5569. (((taicpu(hp1).opcode = A_INC) or
  5570. (taicpu(hp1).opcode = A_DEC)) and
  5571. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5572. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5573. ((taicpu(hp1).opcode = A_LEA) and
  5574. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5575. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5576. (not GetNextInstruction(hp1,hp2) or
  5577. not instrReadsFlags(hp2)) Do
  5578. begin
  5579. TmpBool1 := False;
  5580. if taicpu(hp1).opcode=A_LEA then
  5581. begin
  5582. if (TmpRef.base = NR_NO) and
  5583. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5584. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5585. { Segment register isn't a concern here }
  5586. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5587. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5588. begin
  5589. TmpBool1 := True;
  5590. TmpBool2 := True;
  5591. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5592. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5593. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5594. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5595. RemoveInstruction(hp1);
  5596. end
  5597. end
  5598. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5599. begin
  5600. TmpBool1 := True;
  5601. TmpBool2 := True;
  5602. case taicpu(hp1).opcode of
  5603. A_ADD:
  5604. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5605. A_SUB:
  5606. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5607. else
  5608. internalerror(2019050536);
  5609. end;
  5610. RemoveInstruction(hp1);
  5611. end
  5612. else
  5613. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5614. (((taicpu(hp1).opcode = A_ADD) and
  5615. (TmpRef.base = NR_NO)) or
  5616. (taicpu(hp1).opcode = A_INC) or
  5617. (taicpu(hp1).opcode = A_DEC)) then
  5618. begin
  5619. TmpBool1 := True;
  5620. TmpBool2 := True;
  5621. case taicpu(hp1).opcode of
  5622. A_ADD:
  5623. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5624. A_INC:
  5625. inc(TmpRef.offset);
  5626. A_DEC:
  5627. dec(TmpRef.offset);
  5628. else
  5629. internalerror(2019050535);
  5630. end;
  5631. RemoveInstruction(hp1);
  5632. end;
  5633. end;
  5634. if TmpBool2
  5635. {$ifndef x86_64}
  5636. or
  5637. ((current_settings.optimizecputype < cpu_Pentium2) and
  5638. (taicpu(p).oper[0]^.val <= 3) and
  5639. not(cs_opt_size in current_settings.optimizerswitches))
  5640. {$endif x86_64}
  5641. then
  5642. begin
  5643. if not(TmpBool2) and
  5644. (taicpu(p).oper[0]^.val=1) then
  5645. begin
  5646. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5647. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5648. end
  5649. else
  5650. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5651. taicpu(p).oper[1]^.reg);
  5652. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5653. InsertLLItem(p.previous, p.next, hp1);
  5654. p.free;
  5655. p := hp1;
  5656. end;
  5657. end
  5658. {$ifndef x86_64}
  5659. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5660. begin
  5661. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5662. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5663. (unlike shl, which is only Tairable in the U pipe) }
  5664. if taicpu(p).oper[0]^.val=1 then
  5665. begin
  5666. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5667. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5668. InsertLLItem(p.previous, p.next, hp1);
  5669. p.free;
  5670. p := hp1;
  5671. end
  5672. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5673. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5674. else if (taicpu(p).opsize = S_L) and
  5675. (taicpu(p).oper[0]^.val<= 3) then
  5676. begin
  5677. reference_reset(tmpref,2,[]);
  5678. TmpRef.index := taicpu(p).oper[1]^.reg;
  5679. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5680. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5681. InsertLLItem(p.previous, p.next, hp1);
  5682. p.free;
  5683. p := hp1;
  5684. end;
  5685. end
  5686. {$endif x86_64}
  5687. else if
  5688. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5689. (
  5690. (
  5691. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5692. SetAndTest(hp1, hp2)
  5693. {$ifdef x86_64}
  5694. ) or
  5695. (
  5696. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5697. GetNextInstruction(hp1, hp2) and
  5698. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5699. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5700. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5701. {$endif x86_64}
  5702. )
  5703. ) and
  5704. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5705. begin
  5706. { Change:
  5707. shl x, %reg1
  5708. mov -(1<<x), %reg2
  5709. and %reg2, %reg1
  5710. Or:
  5711. shl x, %reg1
  5712. and -(1<<x), %reg1
  5713. To just:
  5714. shl x, %reg1
  5715. Since the and operation only zeroes bits that are already zero from the shl operation
  5716. }
  5717. case taicpu(p).oper[0]^.val of
  5718. 8:
  5719. mask:=$FFFFFFFFFFFFFF00;
  5720. 16:
  5721. mask:=$FFFFFFFFFFFF0000;
  5722. 32:
  5723. mask:=$FFFFFFFF00000000;
  5724. 63:
  5725. { Constant pre-calculated to prevent overflow errors with Int64 }
  5726. mask:=$8000000000000000;
  5727. else
  5728. begin
  5729. if taicpu(p).oper[0]^.val >= 64 then
  5730. { Shouldn't happen realistically, since the register
  5731. is guaranteed to be set to zero at this point }
  5732. mask := 0
  5733. else
  5734. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5735. end;
  5736. end;
  5737. if taicpu(hp1).oper[0]^.val = mask then
  5738. begin
  5739. { Everything checks out, perform the optimisation, as long as
  5740. the FLAGS register isn't being used}
  5741. TransferUsedRegs(TmpUsedRegs);
  5742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5743. {$ifdef x86_64}
  5744. if (hp1 <> hp2) then
  5745. begin
  5746. { "shl/mov/and" version }
  5747. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5748. { Don't do the optimisation if the FLAGS register is in use }
  5749. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5750. begin
  5751. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5752. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5753. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5754. begin
  5755. RemoveInstruction(hp1);
  5756. Result := True;
  5757. end;
  5758. { Only set Result to True if the 'mov' instruction was removed }
  5759. RemoveInstruction(hp2);
  5760. end;
  5761. end
  5762. else
  5763. {$endif x86_64}
  5764. begin
  5765. { "shl/and" version }
  5766. { Don't do the optimisation if the FLAGS register is in use }
  5767. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5768. begin
  5769. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5770. RemoveInstruction(hp1);
  5771. Result := True;
  5772. end;
  5773. end;
  5774. Exit;
  5775. end
  5776. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5777. begin
  5778. { Even if the mask doesn't allow for its removal, we might be
  5779. able to optimise the mask for the "shl/and" version, which
  5780. may permit other peephole optimisations }
  5781. {$ifdef DEBUG_AOPTCPU}
  5782. mask := taicpu(hp1).oper[0]^.val and mask;
  5783. if taicpu(hp1).oper[0]^.val <> mask then
  5784. begin
  5785. DebugMsg(
  5786. SPeepholeOptimization +
  5787. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5788. ' to $' + debug_tostr(mask) +
  5789. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5790. taicpu(hp1).oper[0]^.val := mask;
  5791. end;
  5792. {$else DEBUG_AOPTCPU}
  5793. { If debugging is off, just set the operand even if it's the same }
  5794. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5795. {$endif DEBUG_AOPTCPU}
  5796. end;
  5797. end;
  5798. {
  5799. change
  5800. shl/sal const,reg
  5801. <op> ...(...,reg,1),...
  5802. into
  5803. <op> ...(...,reg,1 shl const),...
  5804. if const in 1..3
  5805. }
  5806. if MatchOpType(taicpu(p), top_const, top_reg) and
  5807. (taicpu(p).oper[0]^.val in [1..3]) and
  5808. GetNextInstruction(p, hp1) and
  5809. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5810. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5811. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5812. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5813. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5814. begin
  5815. TransferUsedRegs(TmpUsedRegs);
  5816. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5817. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5818. begin
  5819. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5820. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5821. RemoveCurrentP(p);
  5822. Result:=true;
  5823. end;
  5824. end;
  5825. end;
  5826. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5827. var
  5828. CurrentRef: TReference;
  5829. FullReg: TRegister;
  5830. hp1, hp2: tai;
  5831. begin
  5832. Result := False;
  5833. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5834. Exit;
  5835. { We assume you've checked if the operand is actually a reference by
  5836. this point. If it isn't, you'll most likely get an access violation }
  5837. CurrentRef := first_mov.oper[1]^.ref^;
  5838. { Memory must be aligned }
  5839. if (CurrentRef.offset mod 4) <> 0 then
  5840. Exit;
  5841. Inc(CurrentRef.offset);
  5842. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5843. if MatchOperand(second_mov.oper[0]^, 0) and
  5844. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5845. GetNextInstruction(second_mov, hp1) and
  5846. (hp1.typ = ait_instruction) and
  5847. (taicpu(hp1).opcode = A_MOV) and
  5848. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5849. (taicpu(hp1).oper[0]^.val = 0) then
  5850. begin
  5851. Inc(CurrentRef.offset);
  5852. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5853. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5854. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5855. begin
  5856. case taicpu(hp1).opsize of
  5857. S_B:
  5858. if GetNextInstruction(hp1, hp2) and
  5859. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5860. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5861. (taicpu(hp2).oper[0]^.val = 0) then
  5862. begin
  5863. Inc(CurrentRef.offset);
  5864. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5865. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5866. (taicpu(hp2).opsize = S_B) then
  5867. begin
  5868. RemoveInstruction(hp1);
  5869. RemoveInstruction(hp2);
  5870. first_mov.opsize := S_L;
  5871. if first_mov.oper[0]^.typ = top_reg then
  5872. begin
  5873. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5874. { Reuse second_mov as a MOVZX instruction }
  5875. second_mov.opcode := A_MOVZX;
  5876. second_mov.opsize := S_BL;
  5877. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5878. second_mov.loadreg(1, FullReg);
  5879. first_mov.oper[0]^.reg := FullReg;
  5880. asml.Remove(second_mov);
  5881. asml.InsertBefore(second_mov, first_mov);
  5882. end
  5883. else
  5884. { It's a value }
  5885. begin
  5886. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5887. RemoveInstruction(second_mov);
  5888. end;
  5889. Result := True;
  5890. Exit;
  5891. end;
  5892. end;
  5893. S_W:
  5894. begin
  5895. RemoveInstruction(hp1);
  5896. first_mov.opsize := S_L;
  5897. if first_mov.oper[0]^.typ = top_reg then
  5898. begin
  5899. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5900. { Reuse second_mov as a MOVZX instruction }
  5901. second_mov.opcode := A_MOVZX;
  5902. second_mov.opsize := S_BL;
  5903. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5904. second_mov.loadreg(1, FullReg);
  5905. first_mov.oper[0]^.reg := FullReg;
  5906. asml.Remove(second_mov);
  5907. asml.InsertBefore(second_mov, first_mov);
  5908. end
  5909. else
  5910. { It's a value }
  5911. begin
  5912. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5913. RemoveInstruction(second_mov);
  5914. end;
  5915. Result := True;
  5916. Exit;
  5917. end;
  5918. else
  5919. ;
  5920. end;
  5921. end;
  5922. end;
  5923. end;
  5924. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5925. { returns true if a "continue" should be done after this optimization }
  5926. var
  5927. hp1, hp2: tai;
  5928. begin
  5929. Result := false;
  5930. if MatchOpType(taicpu(p),top_ref) and
  5931. GetNextInstruction(p, hp1) and
  5932. (hp1.typ = ait_instruction) and
  5933. (((taicpu(hp1).opcode = A_FLD) and
  5934. (taicpu(p).opcode = A_FSTP)) or
  5935. ((taicpu(p).opcode = A_FISTP) and
  5936. (taicpu(hp1).opcode = A_FILD))) and
  5937. MatchOpType(taicpu(hp1),top_ref) and
  5938. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5939. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5940. begin
  5941. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5942. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5943. GetNextInstruction(hp1, hp2) and
  5944. (hp2.typ = ait_instruction) and
  5945. IsExitCode(hp2) and
  5946. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5947. not(assigned(current_procinfo.procdef.funcretsym) and
  5948. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5949. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5950. begin
  5951. RemoveInstruction(hp1);
  5952. RemoveCurrentP(p, hp2);
  5953. RemoveLastDeallocForFuncRes(p);
  5954. Result := true;
  5955. end
  5956. else
  5957. { we can do this only in fast math mode as fstp is rounding ...
  5958. ... still disabled as it breaks the compiler and/or rtl }
  5959. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5960. { ... or if another fstp equal to the first one follows }
  5961. (GetNextInstruction(hp1,hp2) and
  5962. (hp2.typ = ait_instruction) and
  5963. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5964. (taicpu(p).opsize=taicpu(hp2).opsize))
  5965. ) and
  5966. { fst can't store an extended/comp value }
  5967. (taicpu(p).opsize <> S_FX) and
  5968. (taicpu(p).opsize <> S_IQ) then
  5969. begin
  5970. if (taicpu(p).opcode = A_FSTP) then
  5971. taicpu(p).opcode := A_FST
  5972. else
  5973. taicpu(p).opcode := A_FIST;
  5974. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5975. RemoveInstruction(hp1);
  5976. end;
  5977. end;
  5978. end;
  5979. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5980. var
  5981. hp1, hp2: tai;
  5982. begin
  5983. result:=false;
  5984. if MatchOpType(taicpu(p),top_reg) and
  5985. GetNextInstruction(p, hp1) and
  5986. (hp1.typ = Ait_Instruction) and
  5987. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5988. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5989. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5990. { change to
  5991. fld reg fxxx reg,st
  5992. fxxxp st, st1 (hp1)
  5993. Remark: non commutative operations must be reversed!
  5994. }
  5995. begin
  5996. case taicpu(hp1).opcode Of
  5997. A_FMULP,A_FADDP,
  5998. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5999. begin
  6000. case taicpu(hp1).opcode Of
  6001. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6002. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6003. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6004. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6005. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6006. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6007. else
  6008. internalerror(2019050534);
  6009. end;
  6010. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6011. taicpu(hp1).oper[1]^.reg := NR_ST;
  6012. RemoveCurrentP(p, hp1);
  6013. Result:=true;
  6014. exit;
  6015. end;
  6016. else
  6017. ;
  6018. end;
  6019. end
  6020. else
  6021. if MatchOpType(taicpu(p),top_ref) and
  6022. GetNextInstruction(p, hp2) and
  6023. (hp2.typ = Ait_Instruction) and
  6024. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6025. (taicpu(p).opsize in [S_FS, S_FL]) and
  6026. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6027. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6028. if GetLastInstruction(p, hp1) and
  6029. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6030. MatchOpType(taicpu(hp1),top_ref) and
  6031. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6032. if ((taicpu(hp2).opcode = A_FMULP) or
  6033. (taicpu(hp2).opcode = A_FADDP)) then
  6034. { change to
  6035. fld/fst mem1 (hp1) fld/fst mem1
  6036. fld mem1 (p) fadd/
  6037. faddp/ fmul st, st
  6038. fmulp st, st1 (hp2) }
  6039. begin
  6040. RemoveCurrentP(p, hp1);
  6041. if (taicpu(hp2).opcode = A_FADDP) then
  6042. taicpu(hp2).opcode := A_FADD
  6043. else
  6044. taicpu(hp2).opcode := A_FMUL;
  6045. taicpu(hp2).oper[1]^.reg := NR_ST;
  6046. end
  6047. else
  6048. { change to
  6049. fld/fst mem1 (hp1) fld/fst mem1
  6050. fld mem1 (p) fld st}
  6051. begin
  6052. taicpu(p).changeopsize(S_FL);
  6053. taicpu(p).loadreg(0,NR_ST);
  6054. end
  6055. else
  6056. begin
  6057. case taicpu(hp2).opcode Of
  6058. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6059. { change to
  6060. fld/fst mem1 (hp1) fld/fst mem1
  6061. fld mem2 (p) fxxx mem2
  6062. fxxxp st, st1 (hp2) }
  6063. begin
  6064. case taicpu(hp2).opcode Of
  6065. A_FADDP: taicpu(p).opcode := A_FADD;
  6066. A_FMULP: taicpu(p).opcode := A_FMUL;
  6067. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6068. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6069. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6070. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6071. else
  6072. internalerror(2019050533);
  6073. end;
  6074. RemoveInstruction(hp2);
  6075. end
  6076. else
  6077. ;
  6078. end
  6079. end
  6080. end;
  6081. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6082. begin
  6083. Result := condition_in(cond1, cond2) or
  6084. { Not strictly subsets due to the actual flags checked, but because we're
  6085. comparing integers, E is a subset of AE and GE and their aliases }
  6086. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6087. end;
  6088. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6089. var
  6090. v: TCGInt;
  6091. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6092. FirstMatch: Boolean;
  6093. NewReg: TRegister;
  6094. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6095. begin
  6096. Result:=false;
  6097. { All these optimisations need a next instruction }
  6098. if not GetNextInstruction(p, hp1) then
  6099. Exit;
  6100. { Search for:
  6101. cmp ###,###
  6102. j(c1) @lbl1
  6103. ...
  6104. @lbl:
  6105. cmp ###.### (same comparison as above)
  6106. j(c2) @lbl2
  6107. If c1 is a subset of c2, change to:
  6108. cmp ###,###
  6109. j(c2) @lbl2
  6110. (@lbl1 may become a dead label as a result)
  6111. }
  6112. { Also handle cases where there are multiple jumps in a row }
  6113. p_jump := hp1;
  6114. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6115. begin
  6116. if IsJumpToLabel(taicpu(p_jump)) then
  6117. begin
  6118. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6119. p_label := nil;
  6120. if Assigned(JumpLabel) then
  6121. p_label := getlabelwithsym(JumpLabel);
  6122. if Assigned(p_label) and
  6123. GetNextInstruction(p_label, p_dist) and
  6124. MatchInstruction(p_dist, A_CMP, []) and
  6125. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6126. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6127. GetNextInstruction(p_dist, hp1_dist) and
  6128. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6129. begin
  6130. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6131. if JumpLabel = JumpLabel_dist then
  6132. { This is an infinite loop }
  6133. Exit;
  6134. { Best optimisation when the first condition is a subset (or equal) of the second }
  6135. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6136. begin
  6137. { Any registers used here will already be allocated }
  6138. if Assigned(JumpLabel_dist) then
  6139. JumpLabel_dist.IncRefs;
  6140. if Assigned(JumpLabel) then
  6141. JumpLabel.DecRefs;
  6142. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6143. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  6144. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  6145. Result := True;
  6146. { Don't exit yet. Since p and p_jump haven't actually been
  6147. removed, we can check for more on this iteration }
  6148. end
  6149. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6150. GetNextInstruction(hp1_dist, hp1_label) and
  6151. SkipAligns(hp1_label, hp1_label) and
  6152. (hp1_label.typ = ait_label) then
  6153. begin
  6154. JumpLabel_far := tai_label(hp1_label).labsym;
  6155. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6156. { This is an infinite loop }
  6157. Exit;
  6158. if Assigned(JumpLabel_far) then
  6159. begin
  6160. { In this situation, if the first jump branches, the second one will never,
  6161. branch so change the destination label to after the second jump }
  6162. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6163. if Assigned(JumpLabel) then
  6164. JumpLabel.DecRefs;
  6165. JumpLabel_far.IncRefs;
  6166. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6167. Result := True;
  6168. { Don't exit yet. Since p and p_jump haven't actually been
  6169. removed, we can check for more on this iteration }
  6170. Continue;
  6171. end;
  6172. end;
  6173. end;
  6174. end;
  6175. { Search for:
  6176. cmp ###,###
  6177. j(c1) @lbl1
  6178. cmp ###,### (same as first)
  6179. Remove second cmp
  6180. }
  6181. if GetNextInstruction(p_jump, hp2) and
  6182. (
  6183. (
  6184. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6185. (
  6186. (
  6187. MatchOpType(taicpu(p), top_const, top_reg) and
  6188. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6189. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6190. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6191. ) or (
  6192. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6193. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6194. )
  6195. )
  6196. ) or (
  6197. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6198. MatchOperand(taicpu(p).oper[0]^, 0) and
  6199. (taicpu(p).oper[1]^.typ = top_reg) and
  6200. MatchInstruction(hp2, A_TEST, []) and
  6201. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6202. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6203. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6204. )
  6205. ) then
  6206. begin
  6207. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6208. RemoveInstruction(hp2);
  6209. Result := True;
  6210. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6211. end;
  6212. GetNextInstruction(p_jump, p_jump);
  6213. end;
  6214. {
  6215. Try to optimise the following:
  6216. cmp $x,### ($x and $y can be registers or constants)
  6217. je @lbl1 (only reference)
  6218. cmp $y,### (### are identical)
  6219. @Lbl:
  6220. sete %reg1
  6221. Change to:
  6222. cmp $x,###
  6223. sete %reg2 (allocate new %reg2)
  6224. cmp $y,###
  6225. sete %reg1
  6226. orb %reg2,%reg1
  6227. (dealloc %reg2)
  6228. This adds an instruction (so don't perform under -Os), but it removes
  6229. a conditional branch.
  6230. }
  6231. if not (cs_opt_size in current_settings.optimizerswitches) and
  6232. (
  6233. (hp1 = p_jump) or
  6234. GetNextInstruction(p, hp1)
  6235. ) and
  6236. MatchInstruction(hp1, A_Jcc, []) and
  6237. IsJumpToLabel(taicpu(hp1)) and
  6238. (taicpu(hp1).condition in [C_E, C_Z]) and
  6239. GetNextInstruction(hp1, hp2) and
  6240. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6241. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6242. { The first operand of CMP instructions can only be a register or
  6243. immediate anyway, so no need to check }
  6244. GetNextInstruction(hp2, p_label) and
  6245. (
  6246. (p_label.typ = ait_label) or
  6247. (
  6248. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6249. to potentially cut down on the iterations of Pass 1 }
  6250. MatchInstruction(p_label, A_Jcc, []) and
  6251. IsJumpToLabel(taicpu(p_label)) and
  6252. { Use p_dist to hold the jump briefly }
  6253. SetAndTest(p_label, p_dist) and
  6254. GetNextInstruction(p_dist, p_label) and
  6255. (p_label.typ = ait_label) and
  6256. (tai_label(p_label).labsym.getrefs >= 2) and
  6257. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6258. { We might as well collapse the jump now }
  6259. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6260. )
  6261. ) and
  6262. (tai_label(p_label).labsym.getrefs = 1) and
  6263. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6264. GetNextInstruction(p_label, p_dist) and
  6265. MatchInstruction(p_dist, A_SETcc, []) and
  6266. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6267. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6268. { Get the instruction after the SETcc instruction so we can
  6269. allocate a new register over the entire range }
  6270. GetNextInstruction(p_dist, hp1_dist) then
  6271. begin
  6272. TransferUsedRegs(TmpUsedRegs);
  6273. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6274. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6275. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6276. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6277. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6278. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6279. begin
  6280. { Register can appear in p if it's not used afterwards, so only
  6281. allocate between hp1 and hp1_dist }
  6282. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6283. if NewReg <> NR_NO then
  6284. begin
  6285. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6286. { Change the jump instruction into a SETcc instruction }
  6287. taicpu(hp1).opcode := A_SETcc;
  6288. taicpu(hp1).opsize := S_B;
  6289. taicpu(hp1).loadreg(0, NewReg);
  6290. { This is now a dead label }
  6291. tai_label(p_label).labsym.decrefs;
  6292. { Prefer adding before the next instruction so the FLAGS
  6293. register is deallocated first }
  6294. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6295. AsmL.InsertBefore(
  6296. hp2,
  6297. hp1_dist
  6298. );
  6299. { Make sure the new register is in use over the new instruction
  6300. (long-winded, but things work best when the FLAGS register
  6301. is not allocated here) }
  6302. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6303. Result := True;
  6304. { Don't exit yet, as p wasn't changed and hp1, while
  6305. modified, is still intact and might be optimised by the
  6306. SETcc optimisation below }
  6307. end;
  6308. end;
  6309. end;
  6310. if taicpu(p).oper[0]^.typ = top_const then
  6311. begin
  6312. if (taicpu(p).oper[0]^.val = 0) and
  6313. (taicpu(p).oper[1]^.typ = top_reg) and
  6314. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6315. begin
  6316. hp2 := p;
  6317. FirstMatch := True;
  6318. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6319. anything meaningful once it's converted to "test %reg,%reg";
  6320. additionally, some jumps will always (or never) branch, so
  6321. evaluate every jump immediately following the
  6322. comparison, optimising the conditions if possible.
  6323. Similarly with SETcc... those that are always set to 0 or 1
  6324. are changed to MOV instructions }
  6325. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6326. (
  6327. GetNextInstruction(hp2, hp1) and
  6328. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6329. ) do
  6330. begin
  6331. FirstMatch := False;
  6332. case taicpu(hp1).condition of
  6333. C_B, C_C, C_NAE, C_O:
  6334. { For B/NAE:
  6335. Will never branch since an unsigned integer can never be below zero
  6336. For C/O:
  6337. Result cannot overflow because 0 is being subtracted
  6338. }
  6339. begin
  6340. if taicpu(hp1).opcode = A_Jcc then
  6341. begin
  6342. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6343. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6344. RemoveInstruction(hp1);
  6345. { Since hp1 was deleted, hp2 must not be updated }
  6346. Continue;
  6347. end
  6348. else
  6349. begin
  6350. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6351. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6352. taicpu(hp1).opcode := A_MOV;
  6353. taicpu(hp1).ops := 2;
  6354. taicpu(hp1).condition := C_None;
  6355. taicpu(hp1).opsize := S_B;
  6356. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6357. taicpu(hp1).loadconst(0, 0);
  6358. end;
  6359. end;
  6360. C_BE, C_NA:
  6361. begin
  6362. { Will only branch if equal to zero }
  6363. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6364. taicpu(hp1).condition := C_E;
  6365. end;
  6366. C_A, C_NBE:
  6367. begin
  6368. { Will only branch if not equal to zero }
  6369. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6370. taicpu(hp1).condition := C_NE;
  6371. end;
  6372. C_AE, C_NB, C_NC, C_NO:
  6373. begin
  6374. { Will always branch }
  6375. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6376. if taicpu(hp1).opcode = A_Jcc then
  6377. begin
  6378. MakeUnconditional(taicpu(hp1));
  6379. { Any jumps/set that follow will now be dead code }
  6380. RemoveDeadCodeAfterJump(taicpu(hp1));
  6381. Break;
  6382. end
  6383. else
  6384. begin
  6385. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6386. taicpu(hp1).opcode := A_MOV;
  6387. taicpu(hp1).ops := 2;
  6388. taicpu(hp1).condition := C_None;
  6389. taicpu(hp1).opsize := S_B;
  6390. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6391. taicpu(hp1).loadconst(0, 1);
  6392. end;
  6393. end;
  6394. C_None:
  6395. InternalError(2020012201);
  6396. C_P, C_PE, C_NP, C_PO:
  6397. { We can't handle parity checks and they should never be generated
  6398. after a general-purpose CMP (it's used in some floating-point
  6399. comparisons that don't use CMP) }
  6400. InternalError(2020012202);
  6401. else
  6402. { Zero/Equality, Sign, their complements and all of the
  6403. signed comparisons do not need to be converted };
  6404. end;
  6405. hp2 := hp1;
  6406. end;
  6407. { Convert the instruction to a TEST }
  6408. taicpu(p).opcode := A_TEST;
  6409. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6410. Result := True;
  6411. Exit;
  6412. end
  6413. else if (taicpu(p).oper[0]^.val = 1) and
  6414. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6415. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6416. begin
  6417. { Convert; To:
  6418. cmp $1,r/m cmp $0,r/m
  6419. jl @lbl jle @lbl
  6420. }
  6421. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6422. taicpu(p).oper[0]^.val := 0;
  6423. taicpu(hp1).condition := C_LE;
  6424. { If the instruction is now "cmp $0,%reg", convert it to a
  6425. TEST (and effectively do the work of the "cmp $0,%reg" in
  6426. the block above)
  6427. If it's a reference, we can get away with not setting
  6428. Result to True because he haven't evaluated the jump
  6429. in this pass yet.
  6430. }
  6431. if (taicpu(p).oper[1]^.typ = top_reg) then
  6432. begin
  6433. taicpu(p).opcode := A_TEST;
  6434. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6435. Result := True;
  6436. end;
  6437. Exit;
  6438. end
  6439. else if (taicpu(p).oper[1]^.typ = top_reg)
  6440. {$ifdef x86_64}
  6441. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6442. {$endif x86_64}
  6443. then
  6444. begin
  6445. { cmp register,$8000 neg register
  6446. je target --> jo target
  6447. .... only if register is deallocated before jump.}
  6448. case Taicpu(p).opsize of
  6449. S_B: v:=$80;
  6450. S_W: v:=$8000;
  6451. S_L: v:=qword($80000000);
  6452. else
  6453. internalerror(2013112905);
  6454. end;
  6455. if (taicpu(p).oper[0]^.val=v) and
  6456. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6457. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6458. begin
  6459. TransferUsedRegs(TmpUsedRegs);
  6460. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6461. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6464. Taicpu(p).opcode:=A_NEG;
  6465. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6466. Taicpu(p).clearop(1);
  6467. Taicpu(p).ops:=1;
  6468. if Taicpu(hp1).condition=C_E then
  6469. Taicpu(hp1).condition:=C_O
  6470. else
  6471. Taicpu(hp1).condition:=C_NO;
  6472. Result:=true;
  6473. exit;
  6474. end;
  6475. end;
  6476. end;
  6477. end;
  6478. if TrySwapMovCmp(p, hp1) then
  6479. begin
  6480. Result := True;
  6481. Exit;
  6482. end;
  6483. end;
  6484. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6485. var
  6486. hp1: tai;
  6487. begin
  6488. {
  6489. remove the second (v)pxor from
  6490. pxor reg,reg
  6491. ...
  6492. pxor reg,reg
  6493. }
  6494. Result:=false;
  6495. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6496. MatchOpType(taicpu(p),top_reg,top_reg) and
  6497. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6498. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6499. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6500. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6501. begin
  6502. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6503. RemoveInstruction(hp1);
  6504. Result:=true;
  6505. Exit;
  6506. end
  6507. {
  6508. replace
  6509. pxor reg1,reg1
  6510. movapd/s reg1,reg2
  6511. dealloc reg1
  6512. by
  6513. pxor reg2,reg2
  6514. }
  6515. else if GetNextInstruction(p,hp1) and
  6516. { we mix single and double opperations here because we assume that the compiler
  6517. generates vmovapd only after double operations and vmovaps only after single operations }
  6518. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6519. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6520. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6521. (taicpu(p).oper[0]^.typ=top_reg) then
  6522. begin
  6523. TransferUsedRegs(TmpUsedRegs);
  6524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6525. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6526. begin
  6527. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6528. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6529. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6530. RemoveInstruction(hp1);
  6531. result:=true;
  6532. end;
  6533. end;
  6534. end;
  6535. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6536. var
  6537. hp1: tai;
  6538. begin
  6539. {
  6540. remove the second (v)pxor from
  6541. (v)pxor reg,reg
  6542. ...
  6543. (v)pxor reg,reg
  6544. }
  6545. Result:=false;
  6546. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6547. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6548. begin
  6549. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6550. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6551. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6552. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6553. begin
  6554. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6555. RemoveInstruction(hp1);
  6556. Result:=true;
  6557. Exit;
  6558. end;
  6559. {$ifdef x86_64}
  6560. if GetNextInstruction(p,hp1) and
  6561. MatchInstruction(hp1,A_VMOVSD,[]) and
  6562. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6563. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6564. begin
  6565. TransferUsedRegs(TmpUsedRegs);
  6566. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6567. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6568. begin
  6569. taicpu(hp1).loadconst(0,0);
  6570. taicpu(hp1).opcode:=A_MOV;
  6571. taicpu(hp1).opsize:=S_Q;
  6572. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6573. RemoveCurrentP(p);
  6574. result:=true;
  6575. Exit;
  6576. end;
  6577. end;
  6578. {$endif x86_64}
  6579. end
  6580. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6581. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6582. begin
  6583. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6584. { avoid unncessary data dependency }
  6585. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6586. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6587. result:=true;
  6588. exit;
  6589. end;
  6590. Result:=OptPass1VOP(p);
  6591. end;
  6592. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6593. var
  6594. hp1 : tai;
  6595. begin
  6596. result:=false;
  6597. { replace
  6598. IMul const,%mreg1,%mreg2
  6599. Mov %reg2,%mreg3
  6600. dealloc %mreg3
  6601. by
  6602. Imul const,%mreg1,%mreg23
  6603. }
  6604. if (taicpu(p).ops=3) and
  6605. GetNextInstruction(p,hp1) and
  6606. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6607. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6608. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6609. begin
  6610. TransferUsedRegs(TmpUsedRegs);
  6611. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6612. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6613. begin
  6614. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6615. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6616. RemoveInstruction(hp1);
  6617. result:=true;
  6618. end;
  6619. end;
  6620. end;
  6621. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6622. var
  6623. hp1 : tai;
  6624. begin
  6625. result:=false;
  6626. { replace
  6627. IMul %reg0,%reg1,%reg2
  6628. Mov %reg2,%reg3
  6629. dealloc %reg2
  6630. by
  6631. Imul %reg0,%reg1,%reg3
  6632. }
  6633. if GetNextInstruction(p,hp1) and
  6634. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6635. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6636. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6637. begin
  6638. TransferUsedRegs(TmpUsedRegs);
  6639. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6640. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6641. begin
  6642. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6643. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6644. RemoveInstruction(hp1);
  6645. result:=true;
  6646. end;
  6647. end;
  6648. end;
  6649. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6650. var
  6651. hp1: tai;
  6652. begin
  6653. Result:=false;
  6654. { get rid of
  6655. (v)cvtss2sd reg0,<reg1,>reg2
  6656. (v)cvtss2sd reg2,<reg2,>reg0
  6657. }
  6658. if GetNextInstruction(p,hp1) and
  6659. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6660. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6661. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6662. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6663. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6664. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6665. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6666. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6667. )
  6668. ) then
  6669. begin
  6670. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6671. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6672. begin
  6673. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6674. RemoveCurrentP(p);
  6675. RemoveInstruction(hp1);
  6676. end
  6677. else
  6678. begin
  6679. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6680. if taicpu(hp1).opcode=A_CVTSD2SS then
  6681. begin
  6682. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6683. taicpu(p).opcode:=A_MOVAPS;
  6684. end
  6685. else
  6686. begin
  6687. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6688. taicpu(p).opcode:=A_VMOVAPS;
  6689. end;
  6690. taicpu(p).ops:=2;
  6691. RemoveInstruction(hp1);
  6692. end;
  6693. Result:=true;
  6694. Exit;
  6695. end;
  6696. end;
  6697. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6698. var
  6699. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6700. ThisReg: TRegister;
  6701. begin
  6702. Result := False;
  6703. if not GetNextInstruction(p,hp1) then
  6704. Exit;
  6705. {
  6706. convert
  6707. j<c> .L1
  6708. mov 1,reg
  6709. jmp .L2
  6710. .L1
  6711. mov 0,reg
  6712. .L2
  6713. into
  6714. mov 0,reg
  6715. set<not(c)> reg
  6716. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6717. would destroy the flag contents
  6718. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6719. executed at the same time as a previous comparison.
  6720. set<not(c)> reg
  6721. movzx reg, reg
  6722. }
  6723. if MatchInstruction(hp1,A_MOV,[]) and
  6724. (taicpu(hp1).oper[0]^.typ = top_const) and
  6725. (
  6726. (
  6727. (taicpu(hp1).oper[1]^.typ = top_reg)
  6728. {$ifdef i386}
  6729. { Under i386, ESI, EDI, EBP and ESP
  6730. don't have an 8-bit representation }
  6731. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6732. {$endif i386}
  6733. ) or (
  6734. {$ifdef i386}
  6735. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6736. {$endif i386}
  6737. (taicpu(hp1).opsize = S_B)
  6738. )
  6739. ) and
  6740. GetNextInstruction(hp1,hp2) and
  6741. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6742. GetNextInstruction(hp2,hp3) and
  6743. SkipAligns(hp3, hp3) and
  6744. (hp3.typ=ait_label) and
  6745. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6746. GetNextInstruction(hp3,hp4) and
  6747. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6748. (taicpu(hp4).oper[0]^.typ = top_const) and
  6749. (
  6750. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6751. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6752. ) and
  6753. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6754. GetNextInstruction(hp4,hp5) and
  6755. SkipAligns(hp5, hp5) and
  6756. (hp5.typ=ait_label) and
  6757. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6758. begin
  6759. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6760. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6761. tai_label(hp3).labsym.DecRefs;
  6762. { If this isn't the only reference to the middle label, we can
  6763. still make a saving - only that the first jump and everything
  6764. that follows will remain. }
  6765. if (tai_label(hp3).labsym.getrefs = 0) then
  6766. begin
  6767. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6768. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6769. else
  6770. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6771. { remove jump, first label and second MOV (also catching any aligns) }
  6772. repeat
  6773. if not GetNextInstruction(hp2, hp3) then
  6774. InternalError(2021040810);
  6775. RemoveInstruction(hp2);
  6776. hp2 := hp3;
  6777. until hp2 = hp5;
  6778. { Don't decrement reference count before the removal loop
  6779. above, otherwise GetNextInstruction won't stop on the
  6780. the label }
  6781. tai_label(hp5).labsym.DecRefs;
  6782. end
  6783. else
  6784. begin
  6785. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6786. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6787. else
  6788. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6789. end;
  6790. taicpu(p).opcode:=A_SETcc;
  6791. taicpu(p).opsize:=S_B;
  6792. taicpu(p).is_jmp:=False;
  6793. if taicpu(hp1).opsize=S_B then
  6794. begin
  6795. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6796. if taicpu(hp1).oper[1]^.typ = top_reg then
  6797. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6798. RemoveInstruction(hp1);
  6799. end
  6800. else
  6801. begin
  6802. { Will be a register because the size can't be S_B otherwise }
  6803. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6804. taicpu(p).loadreg(0, ThisReg);
  6805. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6806. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6807. begin
  6808. case taicpu(hp1).opsize of
  6809. S_W:
  6810. taicpu(hp1).opsize := S_BW;
  6811. S_L:
  6812. taicpu(hp1).opsize := S_BL;
  6813. {$ifdef x86_64}
  6814. S_Q:
  6815. begin
  6816. taicpu(hp1).opsize := S_BL;
  6817. { Change the destination register to 32-bit }
  6818. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6819. end;
  6820. {$endif x86_64}
  6821. else
  6822. InternalError(2021040820);
  6823. end;
  6824. taicpu(hp1).opcode := A_MOVZX;
  6825. taicpu(hp1).loadreg(0, ThisReg);
  6826. end
  6827. else
  6828. begin
  6829. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6830. { hp1 is already a MOV instruction with the correct register }
  6831. taicpu(hp1).loadconst(0, 0);
  6832. { Inserting it right before p will guarantee that the flags are also tracked }
  6833. asml.Remove(hp1);
  6834. asml.InsertBefore(hp1, p);
  6835. end;
  6836. end;
  6837. Result:=true;
  6838. exit;
  6839. end
  6840. else if (hp1.typ = ait_label) then
  6841. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6842. end;
  6843. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6844. var
  6845. hp1, hp2, hp3: tai;
  6846. SourceRef, TargetRef: TReference;
  6847. CurrentReg: TRegister;
  6848. begin
  6849. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6850. if not UseAVX then
  6851. InternalError(2021100501);
  6852. Result := False;
  6853. { Look for the following to simplify:
  6854. vmovdqa/u x(mem1), %xmmreg
  6855. vmovdqa/u %xmmreg, y(mem2)
  6856. vmovdqa/u x+16(mem1), %xmmreg
  6857. vmovdqa/u %xmmreg, y+16(mem2)
  6858. Change to:
  6859. vmovdqa/u x(mem1), %ymmreg
  6860. vmovdqa/u %ymmreg, y(mem2)
  6861. vpxor %ymmreg, %ymmreg, %ymmreg
  6862. ( The VPXOR instruction is to zero the upper half, thus removing the
  6863. need to call the potentially expensive VZEROUPPER instruction. Other
  6864. peephole optimisations can remove VPXOR if it's unnecessary )
  6865. }
  6866. TransferUsedRegs(TmpUsedRegs);
  6867. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6868. { NOTE: In the optimisations below, if the references dictate that an
  6869. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6870. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6871. if (taicpu(p).opsize = S_XMM) and
  6872. MatchOpType(taicpu(p), top_ref, top_reg) and
  6873. GetNextInstruction(p, hp1) and
  6874. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6875. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6876. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6877. begin
  6878. SourceRef := taicpu(p).oper[0]^.ref^;
  6879. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6880. if GetNextInstruction(hp1, hp2) and
  6881. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6882. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6883. begin
  6884. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6885. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6886. Inc(SourceRef.offset, 16);
  6887. { Reuse the register in the first block move }
  6888. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6889. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6890. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6891. begin
  6892. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6893. Inc(TargetRef.offset, 16);
  6894. if GetNextInstruction(hp2, hp3) and
  6895. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6896. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6897. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6898. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6899. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6900. begin
  6901. { Update the register tracking to the new size }
  6902. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6903. { Remember that the offsets are 16 ahead }
  6904. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6905. if not (
  6906. ((SourceRef.offset mod 32) = 16) and
  6907. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6908. ) then
  6909. taicpu(p).opcode := A_VMOVDQU;
  6910. taicpu(p).opsize := S_YMM;
  6911. taicpu(p).oper[1]^.reg := CurrentReg;
  6912. if not (
  6913. ((TargetRef.offset mod 32) = 16) and
  6914. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6915. ) then
  6916. taicpu(hp1).opcode := A_VMOVDQU;
  6917. taicpu(hp1).opsize := S_YMM;
  6918. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6919. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6920. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6921. if (pi_uses_ymm in current_procinfo.flags) then
  6922. RemoveInstruction(hp2)
  6923. else
  6924. begin
  6925. taicpu(hp2).opcode := A_VPXOR;
  6926. taicpu(hp2).opsize := S_YMM;
  6927. taicpu(hp2).loadreg(0, CurrentReg);
  6928. taicpu(hp2).loadreg(1, CurrentReg);
  6929. taicpu(hp2).loadreg(2, CurrentReg);
  6930. taicpu(hp2).ops := 3;
  6931. end;
  6932. RemoveInstruction(hp3);
  6933. Result := True;
  6934. Exit;
  6935. end;
  6936. end
  6937. else
  6938. begin
  6939. { See if the next references are 16 less rather than 16 greater }
  6940. Dec(SourceRef.offset, 32); { -16 the other way }
  6941. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6942. begin
  6943. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6944. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6945. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6946. GetNextInstruction(hp2, hp3) and
  6947. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6948. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6949. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6950. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6951. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6952. begin
  6953. { Update the register tracking to the new size }
  6954. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6955. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6956. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6957. if not(
  6958. ((SourceRef.offset mod 32) = 0) and
  6959. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6960. ) then
  6961. taicpu(hp2).opcode := A_VMOVDQU;
  6962. taicpu(hp2).opsize := S_YMM;
  6963. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6964. if not (
  6965. ((TargetRef.offset mod 32) = 0) and
  6966. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6967. ) then
  6968. taicpu(hp3).opcode := A_VMOVDQU;
  6969. taicpu(hp3).opsize := S_YMM;
  6970. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6971. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6972. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6973. if (pi_uses_ymm in current_procinfo.flags) then
  6974. RemoveInstruction(hp1)
  6975. else
  6976. begin
  6977. taicpu(hp1).opcode := A_VPXOR;
  6978. taicpu(hp1).opsize := S_YMM;
  6979. taicpu(hp1).loadreg(0, CurrentReg);
  6980. taicpu(hp1).loadreg(1, CurrentReg);
  6981. taicpu(hp1).loadreg(2, CurrentReg);
  6982. taicpu(hp1).ops := 3;
  6983. Asml.Remove(hp1);
  6984. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6985. end;
  6986. RemoveCurrentP(p, hp2);
  6987. Result := True;
  6988. Exit;
  6989. end;
  6990. end;
  6991. end;
  6992. end;
  6993. end;
  6994. end;
  6995. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6996. var
  6997. hp2, hp3, first_assignment: tai;
  6998. IncCount, OperIdx: Integer;
  6999. OrigLabel: TAsmLabel;
  7000. begin
  7001. Count := 0;
  7002. Result := False;
  7003. first_assignment := nil;
  7004. if (LoopCount >= 20) then
  7005. begin
  7006. { Guard against infinite loops }
  7007. Exit;
  7008. end;
  7009. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7010. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7011. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7012. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7013. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7014. Exit;
  7015. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7016. {
  7017. change
  7018. jmp .L1
  7019. ...
  7020. .L1:
  7021. mov ##, ## ( multiple movs possible )
  7022. jmp/ret
  7023. into
  7024. mov ##, ##
  7025. jmp/ret
  7026. }
  7027. if not Assigned(hp1) then
  7028. begin
  7029. hp1 := GetLabelWithSym(OrigLabel);
  7030. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7031. Exit;
  7032. end;
  7033. hp2 := hp1;
  7034. while Assigned(hp2) do
  7035. begin
  7036. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7037. SkipLabels(hp2,hp2);
  7038. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7039. Break;
  7040. case taicpu(hp2).opcode of
  7041. A_MOVSS:
  7042. begin
  7043. if taicpu(hp2).ops = 0 then
  7044. { Wrong MOVSS }
  7045. Break;
  7046. Inc(Count);
  7047. if Count >= 5 then
  7048. { Too many to be worthwhile }
  7049. Break;
  7050. GetNextInstruction(hp2, hp2);
  7051. Continue;
  7052. end;
  7053. A_MOV,
  7054. A_MOVD,
  7055. A_MOVQ,
  7056. A_MOVSX,
  7057. {$ifdef x86_64}
  7058. A_MOVSXD,
  7059. {$endif x86_64}
  7060. A_MOVZX,
  7061. A_MOVAPS,
  7062. A_MOVUPS,
  7063. A_MOVSD,
  7064. A_MOVAPD,
  7065. A_MOVUPD,
  7066. A_MOVDQA,
  7067. A_MOVDQU,
  7068. A_VMOVSS,
  7069. A_VMOVAPS,
  7070. A_VMOVUPS,
  7071. A_VMOVSD,
  7072. A_VMOVAPD,
  7073. A_VMOVUPD,
  7074. A_VMOVDQA,
  7075. A_VMOVDQU:
  7076. begin
  7077. Inc(Count);
  7078. if Count >= 5 then
  7079. { Too many to be worthwhile }
  7080. Break;
  7081. GetNextInstruction(hp2, hp2);
  7082. Continue;
  7083. end;
  7084. A_JMP:
  7085. begin
  7086. { Guard against infinite loops }
  7087. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7088. Exit;
  7089. { Analyse this jump first in case it also duplicates assignments }
  7090. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7091. begin
  7092. { Something did change! }
  7093. Result := True;
  7094. Inc(Count, IncCount);
  7095. if Count >= 5 then
  7096. begin
  7097. { Too many to be worthwhile }
  7098. Exit;
  7099. end;
  7100. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7101. Break;
  7102. end;
  7103. Result := True;
  7104. Break;
  7105. end;
  7106. A_RET:
  7107. begin
  7108. Result := True;
  7109. Break;
  7110. end;
  7111. else
  7112. Break;
  7113. end;
  7114. end;
  7115. if Result then
  7116. begin
  7117. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7118. if Count = 0 then
  7119. begin
  7120. Result := False;
  7121. Exit;
  7122. end;
  7123. hp3 := p;
  7124. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7125. while True do
  7126. begin
  7127. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7128. SkipLabels(hp1,hp1);
  7129. if (hp1.typ <> ait_instruction) then
  7130. InternalError(2021040720);
  7131. case taicpu(hp1).opcode of
  7132. A_JMP:
  7133. begin
  7134. { Change the original jump to the new destination }
  7135. OrigLabel.decrefs;
  7136. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7137. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7138. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7139. if not Assigned(first_assignment) then
  7140. InternalError(2021040810)
  7141. else
  7142. p := first_assignment;
  7143. Exit;
  7144. end;
  7145. A_RET:
  7146. begin
  7147. { Now change the jump into a RET instruction }
  7148. ConvertJumpToRET(p, hp1);
  7149. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7150. if not Assigned(first_assignment) then
  7151. InternalError(2021040811)
  7152. else
  7153. p := first_assignment;
  7154. Exit;
  7155. end;
  7156. else
  7157. begin
  7158. { Duplicate the MOV instruction }
  7159. hp3:=tai(hp1.getcopy);
  7160. if first_assignment = nil then
  7161. first_assignment := hp3;
  7162. asml.InsertBefore(hp3, p);
  7163. { Make sure the compiler knows about any final registers written here }
  7164. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7165. with taicpu(hp3).oper[OperIdx]^ do
  7166. begin
  7167. case typ of
  7168. top_ref:
  7169. begin
  7170. if (ref^.base <> NR_NO) and
  7171. (getsupreg(ref^.base) <> RS_ESP) and
  7172. (getsupreg(ref^.base) <> RS_EBP)
  7173. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7174. then
  7175. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7176. if (ref^.index <> NR_NO) and
  7177. (getsupreg(ref^.index) <> RS_ESP) and
  7178. (getsupreg(ref^.index) <> RS_EBP)
  7179. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7180. (ref^.index <> ref^.base) then
  7181. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7182. end;
  7183. top_reg:
  7184. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7185. else
  7186. ;
  7187. end;
  7188. end;
  7189. end;
  7190. end;
  7191. if not GetNextInstruction(hp1, hp1) then
  7192. { Should have dropped out earlier }
  7193. InternalError(2021040710);
  7194. end;
  7195. end;
  7196. end;
  7197. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7198. var
  7199. hp2: tai;
  7200. X: Integer;
  7201. const
  7202. WriteOp: array[0..3] of set of TInsChange = (
  7203. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7204. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7205. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7206. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7207. RegWriteFlags: array[0..7] of set of TInsChange = (
  7208. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7209. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7210. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7211. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7212. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7213. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7214. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7215. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7216. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7217. begin
  7218. { If we have something like:
  7219. cmp ###,%reg1
  7220. mov 0,%reg2
  7221. And no modified registers are shared, move the instruction to before
  7222. the comparison as this means it can be optimised without worrying
  7223. about the FLAGS register. (CMP/MOV is generated by
  7224. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7225. As long as the second instruction doesn't use the flags or one of the
  7226. registers used by CMP or TEST (also check any references that use the
  7227. registers), then it can be moved prior to the comparison.
  7228. }
  7229. Result := False;
  7230. if (hp1.typ <> ait_instruction) or
  7231. taicpu(hp1).is_jmp or
  7232. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7233. Exit;
  7234. { NOP is a pipeline fence, likely marking the beginning of the function
  7235. epilogue, so drop out. Similarly, drop out if POP or RET are
  7236. encountered }
  7237. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7238. Exit;
  7239. if (taicpu(hp1).opcode = A_MOVSS) and
  7240. (taicpu(hp1).ops = 0) then
  7241. { Wrong MOVSS }
  7242. Exit;
  7243. { Check for writes to specific registers first }
  7244. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7245. for X := 0 to 7 do
  7246. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7247. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7248. Exit;
  7249. for X := 0 to taicpu(hp1).ops - 1 do
  7250. begin
  7251. { Check to see if this operand writes to something }
  7252. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7253. { And matches something in the CMP/TEST instruction }
  7254. (
  7255. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7256. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7257. (
  7258. { If it's a register, make sure the register written to doesn't
  7259. appear in the cmp instruction as part of a reference }
  7260. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7261. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7262. )
  7263. ) then
  7264. Exit;
  7265. end;
  7266. { The instruction can be safely moved }
  7267. asml.Remove(hp1);
  7268. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7269. can be optimised into "xor %reg,%reg" later }
  7270. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7271. asml.InsertBefore(hp1, hp2)
  7272. else
  7273. { Note, if p.Previous is nil (even if it should logically never be the
  7274. case), FindRegAllocBackward immediately exits with False and so we
  7275. safely land here (we can't just pass p because FindRegAllocBackward
  7276. immediately exits on an instruction). [Kit] }
  7277. asml.InsertBefore(hp1, p);
  7278. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7279. for X := 0 to taicpu(hp1).ops - 1 do
  7280. case taicpu(hp1).oper[X]^.typ of
  7281. top_reg:
  7282. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7283. top_ref:
  7284. begin
  7285. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7286. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7287. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7288. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7289. end;
  7290. else
  7291. ;
  7292. end;
  7293. if taicpu(hp1).opcode = A_LEA then
  7294. { The flags will be overwritten by the CMP/TEST instruction }
  7295. ConvertLEA(taicpu(hp1));
  7296. Result := True;
  7297. end;
  7298. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7299. function IsXCHGAcceptable: Boolean; inline;
  7300. begin
  7301. { Always accept if optimising for size }
  7302. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7303. (
  7304. {$ifdef x86_64}
  7305. { XCHG takes 3 cycles on AMD Athlon64 }
  7306. (current_settings.optimizecputype >= cpu_core_i)
  7307. {$else x86_64}
  7308. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7309. than 3, so it becomes a saving compared to three MOVs with two of
  7310. them able to execute simultaneously. [Kit] }
  7311. (current_settings.optimizecputype >= cpu_PentiumM)
  7312. {$endif x86_64}
  7313. );
  7314. end;
  7315. var
  7316. NewRef: TReference;
  7317. hp1, hp2, hp3, hp4: Tai;
  7318. {$ifndef x86_64}
  7319. OperIdx: Integer;
  7320. {$endif x86_64}
  7321. NewInstr : Taicpu;
  7322. NewAligh : Tai_align;
  7323. DestLabel: TAsmLabel;
  7324. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7325. var
  7326. NextInstr: tai;
  7327. begin
  7328. Result := False;
  7329. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7330. if not GetNextInstruction(InputInstr, NextInstr) or
  7331. (
  7332. { The FLAGS register isn't always tracked properly, so do not
  7333. perform this optimisation if a conditional statement follows }
  7334. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7335. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7336. ) then
  7337. begin
  7338. reference_reset(NewRef, 1, []);
  7339. NewRef.base := taicpu(p).oper[0]^.reg;
  7340. NewRef.scalefactor := 1;
  7341. if taicpu(InputInstr).opcode = A_ADD then
  7342. begin
  7343. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7344. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7345. end
  7346. else
  7347. begin
  7348. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7349. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7350. end;
  7351. taicpu(p).opcode := A_LEA;
  7352. taicpu(p).loadref(0, NewRef);
  7353. RemoveInstruction(InputInstr);
  7354. Result := True;
  7355. end;
  7356. end;
  7357. begin
  7358. Result:=false;
  7359. { This optimisation adds an instruction, so only do it for speed }
  7360. if not (cs_opt_size in current_settings.optimizerswitches) and
  7361. MatchOpType(taicpu(p), top_const, top_reg) and
  7362. (taicpu(p).oper[0]^.val = 0) then
  7363. begin
  7364. { To avoid compiler warning }
  7365. DestLabel := nil;
  7366. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7367. InternalError(2021040750);
  7368. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7369. Exit;
  7370. case hp1.typ of
  7371. ait_label:
  7372. begin
  7373. { Change:
  7374. mov $0,%reg mov $0,%reg
  7375. @Lbl1: @Lbl1:
  7376. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7377. je @Lbl2 jne @Lbl2
  7378. To: To:
  7379. mov $0,%reg mov $0,%reg
  7380. jmp @Lbl2 jmp @Lbl3
  7381. (align) (align)
  7382. @Lbl1: @Lbl1:
  7383. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7384. je @Lbl2 je @Lbl2
  7385. @Lbl3: <-- Only if label exists
  7386. (Not if it's optimised for size)
  7387. }
  7388. if not GetNextInstruction(hp1, hp2) then
  7389. Exit;
  7390. if not (cs_opt_size in current_settings.optimizerswitches) and
  7391. (hp2.typ = ait_instruction) and
  7392. (
  7393. { Register sizes must exactly match }
  7394. (
  7395. (taicpu(hp2).opcode = A_CMP) and
  7396. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7397. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7398. ) or (
  7399. (taicpu(hp2).opcode = A_TEST) and
  7400. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7401. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7402. )
  7403. ) and GetNextInstruction(hp2, hp3) and
  7404. (hp3.typ = ait_instruction) and
  7405. (taicpu(hp3).opcode = A_JCC) and
  7406. (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
  7407. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7408. begin
  7409. { Check condition of jump }
  7410. { Always true? }
  7411. if condition_in(C_E, taicpu(hp3).condition) then
  7412. begin
  7413. { Copy label symbol and obtain matching label entry for the
  7414. conditional jump, as this will be our destination}
  7415. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7416. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7417. Result := True;
  7418. end
  7419. { Always false? }
  7420. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7421. begin
  7422. { This is only worth it if there's a jump to take }
  7423. case hp2.typ of
  7424. ait_instruction:
  7425. begin
  7426. if taicpu(hp2).opcode = A_JMP then
  7427. begin
  7428. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7429. { An unconditional jump follows the conditional jump which will always be false,
  7430. so use this jump's destination for the new jump }
  7431. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7432. Result := True;
  7433. end
  7434. else if taicpu(hp2).opcode = A_JCC then
  7435. begin
  7436. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7437. if condition_in(C_E, taicpu(hp2).condition) then
  7438. begin
  7439. { A second conditional jump follows the conditional jump which will always be false,
  7440. while the second jump is always True, so use this jump's destination for the new jump }
  7441. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7442. Result := True;
  7443. end;
  7444. { Don't risk it if the jump isn't always true (Result remains False) }
  7445. end;
  7446. end;
  7447. else
  7448. { If anything else don't optimise };
  7449. end;
  7450. end;
  7451. if Result then
  7452. begin
  7453. { Just so we have something to insert as a paremeter}
  7454. reference_reset(NewRef, 1, []);
  7455. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7456. { Now actually load the correct parameter (this also
  7457. increases the reference count) }
  7458. NewInstr.loadsymbol(0, DestLabel, 0);
  7459. { Get instruction before original label (may not be p under -O3) }
  7460. if not GetLastInstruction(hp1, hp2) then
  7461. { Shouldn't fail here }
  7462. InternalError(2021040701);
  7463. AsmL.InsertAfter(NewInstr, hp2);
  7464. { Add new alignment field }
  7465. (* AsmL.InsertAfter(
  7466. cai_align.create_max(
  7467. current_settings.alignment.jumpalign,
  7468. current_settings.alignment.jumpalignskipmax
  7469. ),
  7470. NewInstr
  7471. ); *)
  7472. end;
  7473. Exit;
  7474. end;
  7475. end;
  7476. else
  7477. ;
  7478. end;
  7479. end;
  7480. if not GetNextInstruction(p, hp1) then
  7481. Exit;
  7482. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7483. and DoMovCmpMemOpt(p, hp1, True) then
  7484. begin
  7485. Result := True;
  7486. Exit;
  7487. end
  7488. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7489. begin
  7490. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7491. further, but we can't just put this jump optimisation in pass 1
  7492. because it tends to perform worse when conditional jumps are
  7493. nearby (e.g. when converting CMOV instructions). [Kit] }
  7494. if OptPass2JMP(hp1) then
  7495. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7496. Result := OptPass1MOV(p)
  7497. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7498. returned True and the instruction is still a MOV, thus checking
  7499. the optimisations below }
  7500. { If OptPass2JMP returned False, no optimisations were done to
  7501. the jump and there are no further optimisations that can be done
  7502. to the MOV instruction on this pass }
  7503. end
  7504. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7505. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7506. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7507. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7508. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7509. begin
  7510. { Change:
  7511. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7512. addl/q $x,%reg2 subl/q $x,%reg2
  7513. To:
  7514. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7515. }
  7516. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7517. { be lazy, checking separately for sub would be slightly better }
  7518. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7519. begin
  7520. TransferUsedRegs(TmpUsedRegs);
  7521. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7522. if TryMovArith2Lea(hp1) then
  7523. begin
  7524. Result := True;
  7525. Exit;
  7526. end
  7527. end
  7528. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7529. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7530. { Same as above, but also adds or subtracts to %reg2 in between.
  7531. It's still valid as long as the flags aren't in use }
  7532. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7533. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7534. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7535. { be lazy, checking separately for sub would be slightly better }
  7536. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7537. begin
  7538. TransferUsedRegs(TmpUsedRegs);
  7539. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7541. if TryMovArith2Lea(hp2) then
  7542. begin
  7543. Result := True;
  7544. Exit;
  7545. end;
  7546. end;
  7547. end
  7548. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7549. {$ifdef x86_64}
  7550. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7551. {$else x86_64}
  7552. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7553. {$endif x86_64}
  7554. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7555. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7556. { mov reg1, reg2 mov reg1, reg2
  7557. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7558. begin
  7559. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7560. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7561. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7562. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7563. TransferUsedRegs(TmpUsedRegs);
  7564. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7565. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7566. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7567. then
  7568. begin
  7569. RemoveCurrentP(p, hp1);
  7570. Result:=true;
  7571. end;
  7572. exit;
  7573. end
  7574. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7575. IsXCHGAcceptable and
  7576. { XCHG doesn't support 8-byte registers }
  7577. (taicpu(p).opsize <> S_B) and
  7578. MatchInstruction(hp1, A_MOV, []) and
  7579. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7580. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7581. GetNextInstruction(hp1, hp2) and
  7582. MatchInstruction(hp2, A_MOV, []) and
  7583. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7584. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7585. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7586. begin
  7587. { mov %reg1,%reg2
  7588. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7589. mov %reg2,%reg3
  7590. (%reg2 not used afterwards)
  7591. Note that xchg takes 3 cycles to execute, and generally mov's take
  7592. only one cycle apiece, but the first two mov's can be executed in
  7593. parallel, only taking 2 cycles overall. Older processors should
  7594. therefore only optimise for size. [Kit]
  7595. }
  7596. TransferUsedRegs(TmpUsedRegs);
  7597. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7598. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7599. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7600. begin
  7601. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7602. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7603. taicpu(hp1).opcode := A_XCHG;
  7604. RemoveCurrentP(p, hp1);
  7605. RemoveInstruction(hp2);
  7606. Result := True;
  7607. Exit;
  7608. end;
  7609. end
  7610. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7611. MatchInstruction(hp1, A_SAR, []) then
  7612. begin
  7613. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7614. begin
  7615. { the use of %edx also covers the opsize being S_L }
  7616. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7617. begin
  7618. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7619. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7620. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7621. begin
  7622. { Change:
  7623. movl %eax,%edx
  7624. sarl $31,%edx
  7625. To:
  7626. cltd
  7627. }
  7628. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7629. RemoveInstruction(hp1);
  7630. taicpu(p).opcode := A_CDQ;
  7631. taicpu(p).opsize := S_NO;
  7632. taicpu(p).clearop(1);
  7633. taicpu(p).clearop(0);
  7634. taicpu(p).ops:=0;
  7635. Result := True;
  7636. end
  7637. else if (cs_opt_size in current_settings.optimizerswitches) and
  7638. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7639. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7640. begin
  7641. { Change:
  7642. movl %edx,%eax
  7643. sarl $31,%edx
  7644. To:
  7645. movl %edx,%eax
  7646. cltd
  7647. Note that this creates a dependency between the two instructions,
  7648. so only perform if optimising for size.
  7649. }
  7650. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7651. taicpu(hp1).opcode := A_CDQ;
  7652. taicpu(hp1).opsize := S_NO;
  7653. taicpu(hp1).clearop(1);
  7654. taicpu(hp1).clearop(0);
  7655. taicpu(hp1).ops:=0;
  7656. end;
  7657. {$ifndef x86_64}
  7658. end
  7659. { Don't bother if CMOV is supported, because a more optimal
  7660. sequence would have been generated for the Abs() intrinsic }
  7661. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7662. { the use of %eax also covers the opsize being S_L }
  7663. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7664. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7665. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7666. GetNextInstruction(hp1, hp2) and
  7667. MatchInstruction(hp2, A_XOR, [S_L]) and
  7668. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7669. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7670. GetNextInstruction(hp2, hp3) and
  7671. MatchInstruction(hp3, A_SUB, [S_L]) and
  7672. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7673. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7674. begin
  7675. { Change:
  7676. movl %eax,%edx
  7677. sarl $31,%eax
  7678. xorl %eax,%edx
  7679. subl %eax,%edx
  7680. (Instruction that uses %edx)
  7681. (%eax deallocated)
  7682. (%edx deallocated)
  7683. To:
  7684. cltd
  7685. xorl %edx,%eax <-- Note the registers have swapped
  7686. subl %edx,%eax
  7687. (Instruction that uses %eax) <-- %eax rather than %edx
  7688. }
  7689. TransferUsedRegs(TmpUsedRegs);
  7690. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7691. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7692. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7693. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7694. begin
  7695. if GetNextInstruction(hp3, hp4) and
  7696. not RegModifiedByInstruction(NR_EDX, hp4) and
  7697. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7698. begin
  7699. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7700. taicpu(p).opcode := A_CDQ;
  7701. taicpu(p).clearop(1);
  7702. taicpu(p).clearop(0);
  7703. taicpu(p).ops:=0;
  7704. RemoveInstruction(hp1);
  7705. taicpu(hp2).loadreg(0, NR_EDX);
  7706. taicpu(hp2).loadreg(1, NR_EAX);
  7707. taicpu(hp3).loadreg(0, NR_EDX);
  7708. taicpu(hp3).loadreg(1, NR_EAX);
  7709. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7710. { Convert references in the following instruction (hp4) from %edx to %eax }
  7711. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7712. with taicpu(hp4).oper[OperIdx]^ do
  7713. case typ of
  7714. top_reg:
  7715. if getsupreg(reg) = RS_EDX then
  7716. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7717. top_ref:
  7718. begin
  7719. if getsupreg(reg) = RS_EDX then
  7720. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7721. if getsupreg(reg) = RS_EDX then
  7722. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7723. end;
  7724. else
  7725. ;
  7726. end;
  7727. end;
  7728. end;
  7729. {$else x86_64}
  7730. end;
  7731. end
  7732. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7733. { the use of %rdx also covers the opsize being S_Q }
  7734. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7735. begin
  7736. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7737. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7738. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7739. begin
  7740. { Change:
  7741. movq %rax,%rdx
  7742. sarq $63,%rdx
  7743. To:
  7744. cqto
  7745. }
  7746. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7747. RemoveInstruction(hp1);
  7748. taicpu(p).opcode := A_CQO;
  7749. taicpu(p).opsize := S_NO;
  7750. taicpu(p).clearop(1);
  7751. taicpu(p).clearop(0);
  7752. taicpu(p).ops:=0;
  7753. Result := True;
  7754. end
  7755. else if (cs_opt_size in current_settings.optimizerswitches) and
  7756. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7757. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7758. begin
  7759. { Change:
  7760. movq %rdx,%rax
  7761. sarq $63,%rdx
  7762. To:
  7763. movq %rdx,%rax
  7764. cqto
  7765. Note that this creates a dependency between the two instructions,
  7766. so only perform if optimising for size.
  7767. }
  7768. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7769. taicpu(hp1).opcode := A_CQO;
  7770. taicpu(hp1).opsize := S_NO;
  7771. taicpu(hp1).clearop(1);
  7772. taicpu(hp1).clearop(0);
  7773. taicpu(hp1).ops:=0;
  7774. {$endif x86_64}
  7775. end;
  7776. end;
  7777. end
  7778. else if MatchInstruction(hp1, A_MOV, []) and
  7779. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7780. { Though "GetNextInstruction" could be factored out, along with
  7781. the instructions that depend on hp2, it is an expensive call that
  7782. should be delayed for as long as possible, hence we do cheaper
  7783. checks first that are likely to be False. [Kit] }
  7784. begin
  7785. if (
  7786. (
  7787. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7788. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7789. (
  7790. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7791. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7792. )
  7793. ) or
  7794. (
  7795. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7796. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7797. (
  7798. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7799. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7800. )
  7801. )
  7802. ) and
  7803. GetNextInstruction(hp1, hp2) and
  7804. MatchInstruction(hp2, A_SAR, []) and
  7805. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7806. begin
  7807. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7808. begin
  7809. { Change:
  7810. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7811. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7812. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7813. To:
  7814. movl r/m,%eax <- Note the change in register
  7815. cltd
  7816. }
  7817. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7818. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7819. taicpu(p).loadreg(1, NR_EAX);
  7820. taicpu(hp1).opcode := A_CDQ;
  7821. taicpu(hp1).clearop(1);
  7822. taicpu(hp1).clearop(0);
  7823. taicpu(hp1).ops:=0;
  7824. RemoveInstruction(hp2);
  7825. (*
  7826. {$ifdef x86_64}
  7827. end
  7828. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7829. { This code sequence does not get generated - however it might become useful
  7830. if and when 128-bit signed integer types make an appearance, so the code
  7831. is kept here for when it is eventually needed. [Kit] }
  7832. (
  7833. (
  7834. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7835. (
  7836. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7837. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7838. )
  7839. ) or
  7840. (
  7841. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7842. (
  7843. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7844. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7845. )
  7846. )
  7847. ) and
  7848. GetNextInstruction(hp1, hp2) and
  7849. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7850. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7851. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7852. begin
  7853. { Change:
  7854. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7855. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7856. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7857. To:
  7858. movq r/m,%rax <- Note the change in register
  7859. cqto
  7860. }
  7861. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7862. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7863. taicpu(p).loadreg(1, NR_RAX);
  7864. taicpu(hp1).opcode := A_CQO;
  7865. taicpu(hp1).clearop(1);
  7866. taicpu(hp1).clearop(0);
  7867. taicpu(hp1).ops:=0;
  7868. RemoveInstruction(hp2);
  7869. {$endif x86_64}
  7870. *)
  7871. end;
  7872. end;
  7873. {$ifdef x86_64}
  7874. end
  7875. else if (taicpu(p).opsize = S_L) and
  7876. (taicpu(p).oper[1]^.typ = top_reg) and
  7877. (
  7878. MatchInstruction(hp1, A_MOV,[]) and
  7879. (taicpu(hp1).opsize = S_L) and
  7880. (taicpu(hp1).oper[1]^.typ = top_reg)
  7881. ) and (
  7882. GetNextInstruction(hp1, hp2) and
  7883. (tai(hp2).typ=ait_instruction) and
  7884. (taicpu(hp2).opsize = S_Q) and
  7885. (
  7886. (
  7887. MatchInstruction(hp2, A_ADD,[]) and
  7888. (taicpu(hp2).opsize = S_Q) and
  7889. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7890. (
  7891. (
  7892. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7893. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7894. ) or (
  7895. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7896. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7897. )
  7898. )
  7899. ) or (
  7900. MatchInstruction(hp2, A_LEA,[]) and
  7901. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7902. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7903. (
  7904. (
  7905. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7906. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7907. ) or (
  7908. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7909. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7910. )
  7911. ) and (
  7912. (
  7913. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7914. ) or (
  7915. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7916. )
  7917. )
  7918. )
  7919. )
  7920. ) and (
  7921. GetNextInstruction(hp2, hp3) and
  7922. MatchInstruction(hp3, A_SHR,[]) and
  7923. (taicpu(hp3).opsize = S_Q) and
  7924. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7925. (taicpu(hp3).oper[0]^.val = 1) and
  7926. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7927. ) then
  7928. begin
  7929. { Change movl x, reg1d movl x, reg1d
  7930. movl y, reg2d movl y, reg2d
  7931. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7932. shrq $1, reg1q shrq $1, reg1q
  7933. ( reg1d and reg2d can be switched around in the first two instructions )
  7934. To movl x, reg1d
  7935. addl y, reg1d
  7936. rcrl $1, reg1d
  7937. This corresponds to the common expression (x + y) shr 1, where
  7938. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7939. smaller code, but won't account for x + y causing an overflow). [Kit]
  7940. }
  7941. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7942. { Change first MOV command to have the same register as the final output }
  7943. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7944. else
  7945. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7946. { Change second MOV command to an ADD command. This is easier than
  7947. converting the existing command because it means we don't have to
  7948. touch 'y', which might be a complicated reference, and also the
  7949. fact that the third command might either be ADD or LEA. [Kit] }
  7950. taicpu(hp1).opcode := A_ADD;
  7951. { Delete old ADD/LEA instruction }
  7952. RemoveInstruction(hp2);
  7953. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7954. taicpu(hp3).opcode := A_RCR;
  7955. taicpu(hp3).changeopsize(S_L);
  7956. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7957. {$endif x86_64}
  7958. end;
  7959. end;
  7960. {$push}
  7961. {$q-}{$r-}
  7962. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7963. var
  7964. ThisReg: TRegister;
  7965. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7966. TargetSubReg: TSubRegister;
  7967. hp1, hp2: tai;
  7968. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7969. { Store list of found instructions so we don't have to call
  7970. GetNextInstructionUsingReg multiple times }
  7971. InstrList: array of taicpu;
  7972. InstrMax, Index: Integer;
  7973. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7974. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7975. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7976. WorkingValue: TCgInt;
  7977. PreMessage: string;
  7978. { Data flow analysis }
  7979. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7980. BitwiseOnly, OrXorUsed,
  7981. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7982. function CheckOverflowConditions: Boolean;
  7983. begin
  7984. Result := True;
  7985. if (TestValSignedMax > SignedUpperLimit) then
  7986. UpperSignedOverflow := True;
  7987. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7988. LowerSignedOverflow := True;
  7989. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7990. LowerUnsignedOverflow := True;
  7991. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7992. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7993. begin
  7994. { Absolute overflow }
  7995. Result := False;
  7996. Exit;
  7997. end;
  7998. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7999. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8000. ShiftDownOverflow := True;
  8001. if (TestValMin < 0) or (TestValMax < 0) then
  8002. begin
  8003. LowerUnsignedOverflow := True;
  8004. UpperUnsignedOverflow := True;
  8005. end;
  8006. end;
  8007. function AdjustInitialLoadAndSize: Boolean;
  8008. begin
  8009. Result := False;
  8010. if not p_removed then
  8011. begin
  8012. if TargetSize = MinSize then
  8013. begin
  8014. { Convert the input MOVZX to a MOV }
  8015. if (taicpu(p).oper[0]^.typ = top_reg) and
  8016. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8017. begin
  8018. { Or remove it completely! }
  8019. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8020. RemoveCurrentP(p);
  8021. p_removed := True;
  8022. end
  8023. else
  8024. begin
  8025. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8026. taicpu(p).opcode := A_MOV;
  8027. taicpu(p).oper[1]^.reg := ThisReg;
  8028. taicpu(p).opsize := TargetSize;
  8029. end;
  8030. Result := True;
  8031. end
  8032. else if TargetSize <> MaxSize then
  8033. begin
  8034. case MaxSize of
  8035. S_L:
  8036. if TargetSize = S_W then
  8037. begin
  8038. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8039. taicpu(p).opsize := S_BW;
  8040. taicpu(p).oper[1]^.reg := ThisReg;
  8041. Result := True;
  8042. end
  8043. else
  8044. InternalError(2020112341);
  8045. S_W:
  8046. if TargetSize = S_L then
  8047. begin
  8048. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8049. taicpu(p).opsize := S_BL;
  8050. taicpu(p).oper[1]^.reg := ThisReg;
  8051. Result := True;
  8052. end
  8053. else
  8054. InternalError(2020112342);
  8055. else
  8056. ;
  8057. end;
  8058. end
  8059. else if not hp1_removed and not RegInUse then
  8060. begin
  8061. { If we have something like:
  8062. movzbl (oper),%regd
  8063. add x, %regd
  8064. movzbl %regb, %regd
  8065. We can reduce the register size to the input of the final
  8066. movzbl instruction. Overflows won't have any effect.
  8067. }
  8068. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8069. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8070. begin
  8071. TargetSize := S_B;
  8072. setsubreg(ThisReg, R_SUBL);
  8073. Result := True;
  8074. end
  8075. else if (taicpu(p).opsize = S_WL) and
  8076. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8077. begin
  8078. TargetSize := S_W;
  8079. setsubreg(ThisReg, R_SUBW);
  8080. Result := True;
  8081. end;
  8082. if Result then
  8083. begin
  8084. { Convert the input MOVZX to a MOV }
  8085. if (taicpu(p).oper[0]^.typ = top_reg) and
  8086. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8087. begin
  8088. { Or remove it completely! }
  8089. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8090. RemoveCurrentP(p);
  8091. p_removed := True;
  8092. end
  8093. else
  8094. begin
  8095. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8096. taicpu(p).opcode := A_MOV;
  8097. taicpu(p).oper[1]^.reg := ThisReg;
  8098. taicpu(p).opsize := TargetSize;
  8099. end;
  8100. end;
  8101. end;
  8102. end;
  8103. end;
  8104. procedure AdjustFinalLoad;
  8105. begin
  8106. if not LowerUnsignedOverflow then
  8107. begin
  8108. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8109. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8110. begin
  8111. { Convert the output MOVZX to a MOV }
  8112. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8113. begin
  8114. { Or remove it completely! }
  8115. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8116. { Be careful; if p = hp1 and p was also removed, p
  8117. will become a dangling pointer }
  8118. if p = hp1 then
  8119. begin
  8120. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8121. p_removed := True;
  8122. end
  8123. else
  8124. RemoveInstruction(hp1);
  8125. hp1_removed := True;
  8126. end
  8127. else
  8128. begin
  8129. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8130. taicpu(hp1).opcode := A_MOV;
  8131. taicpu(hp1).oper[0]^.reg := ThisReg;
  8132. taicpu(hp1).opsize := TargetSize;
  8133. end;
  8134. end
  8135. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8136. begin
  8137. { Need to change the size of the output }
  8138. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8139. taicpu(hp1).oper[0]^.reg := ThisReg;
  8140. taicpu(hp1).opsize := S_BL;
  8141. end;
  8142. end;
  8143. end;
  8144. function CompressInstructions: Boolean;
  8145. var
  8146. LocalIndex: Integer;
  8147. begin
  8148. Result := False;
  8149. { The objective here is to try to find a combination that
  8150. removes one of the MOV/Z instructions. }
  8151. if (
  8152. (taicpu(p).oper[0]^.typ <> top_reg) or
  8153. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8154. ) and
  8155. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8156. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8157. begin
  8158. { Make a preference to remove the second MOVZX instruction }
  8159. case taicpu(hp1).opsize of
  8160. S_BL, S_WL:
  8161. begin
  8162. TargetSize := S_L;
  8163. TargetSubReg := R_SUBD;
  8164. end;
  8165. S_BW:
  8166. begin
  8167. TargetSize := S_W;
  8168. TargetSubReg := R_SUBW;
  8169. end;
  8170. else
  8171. InternalError(2020112302);
  8172. end;
  8173. end
  8174. else
  8175. begin
  8176. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8177. begin
  8178. { Exceeded lower bound but not upper bound }
  8179. TargetSize := MaxSize;
  8180. end
  8181. else if not LowerUnsignedOverflow then
  8182. begin
  8183. { Size didn't exceed lower bound }
  8184. TargetSize := MinSize;
  8185. end
  8186. else
  8187. Exit;
  8188. end;
  8189. case TargetSize of
  8190. S_B:
  8191. TargetSubReg := R_SUBL;
  8192. S_W:
  8193. TargetSubReg := R_SUBW;
  8194. S_L:
  8195. TargetSubReg := R_SUBD;
  8196. else
  8197. InternalError(2020112350);
  8198. end;
  8199. { Update the register to its new size }
  8200. setsubreg(ThisReg, TargetSubReg);
  8201. RegInUse := False;
  8202. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8203. begin
  8204. { Check to see if the active register is used afterwards;
  8205. if not, we can change it and make a saving. }
  8206. TransferUsedRegs(TmpUsedRegs);
  8207. { The target register may be marked as in use to cross
  8208. a jump to a distant label, so exclude it }
  8209. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8210. hp2 := p;
  8211. repeat
  8212. { Explicitly check for the excluded register (don't include the first
  8213. instruction as it may be reading from here }
  8214. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8215. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8216. begin
  8217. RegInUse := True;
  8218. Break;
  8219. end;
  8220. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8221. if not GetNextInstruction(hp2, hp2) then
  8222. InternalError(2020112340);
  8223. until (hp2 = hp1);
  8224. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8225. { We might still be able to get away with this }
  8226. RegInUse := not
  8227. (
  8228. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8229. (hp2.typ = ait_instruction) and
  8230. (
  8231. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8232. instruction that doesn't actually contain ThisReg }
  8233. (cs_opt_level3 in current_settings.optimizerswitches) or
  8234. RegInInstruction(ThisReg, hp2)
  8235. ) and
  8236. RegLoadedWithNewValue(ThisReg, hp2)
  8237. );
  8238. if not RegInUse then
  8239. begin
  8240. { Force the register size to the same as this instruction so it can be removed}
  8241. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8242. begin
  8243. TargetSize := S_L;
  8244. TargetSubReg := R_SUBD;
  8245. end
  8246. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8247. begin
  8248. TargetSize := S_W;
  8249. TargetSubReg := R_SUBW;
  8250. end;
  8251. ThisReg := taicpu(hp1).oper[1]^.reg;
  8252. setsubreg(ThisReg, TargetSubReg);
  8253. RegChanged := True;
  8254. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8255. TransferUsedRegs(TmpUsedRegs);
  8256. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8257. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8258. if p = hp1 then
  8259. begin
  8260. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8261. p_removed := True;
  8262. end
  8263. else
  8264. RemoveInstruction(hp1);
  8265. hp1_removed := True;
  8266. { Instruction will become "mov %reg,%reg" }
  8267. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8268. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8269. begin
  8270. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8271. RemoveCurrentP(p);
  8272. p_removed := True;
  8273. end
  8274. else
  8275. taicpu(p).oper[1]^.reg := ThisReg;
  8276. Result := True;
  8277. end
  8278. else
  8279. begin
  8280. if TargetSize <> MaxSize then
  8281. begin
  8282. { Since the register is in use, we have to force it to
  8283. MaxSize otherwise part of it may become undefined later on }
  8284. TargetSize := MaxSize;
  8285. case TargetSize of
  8286. S_B:
  8287. TargetSubReg := R_SUBL;
  8288. S_W:
  8289. TargetSubReg := R_SUBW;
  8290. S_L:
  8291. TargetSubReg := R_SUBD;
  8292. else
  8293. InternalError(2020112351);
  8294. end;
  8295. setsubreg(ThisReg, TargetSubReg);
  8296. end;
  8297. AdjustFinalLoad;
  8298. end;
  8299. end
  8300. else
  8301. AdjustFinalLoad;
  8302. Result := AdjustInitialLoadAndSize or Result;
  8303. { Now go through every instruction we found and change the
  8304. size. If TargetSize = MaxSize, then almost no changes are
  8305. needed and Result can remain False if it hasn't been set
  8306. yet.
  8307. If RegChanged is True, then the register requires changing
  8308. and so the point about TargetSize = MaxSize doesn't apply. }
  8309. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8310. begin
  8311. for LocalIndex := 0 to InstrMax do
  8312. begin
  8313. { If p_removed is true, then the original MOV/Z was removed
  8314. and removing the AND instruction may not be safe if it
  8315. appears first }
  8316. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8317. InternalError(2020112310);
  8318. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8319. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8320. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8321. InstrList[LocalIndex].opsize := TargetSize;
  8322. end;
  8323. Result := True;
  8324. end;
  8325. end;
  8326. begin
  8327. Result := False;
  8328. p_removed := False;
  8329. hp1_removed := False;
  8330. ThisReg := taicpu(p).oper[1]^.reg;
  8331. { Check for:
  8332. movs/z ###,%ecx (or %cx or %rcx)
  8333. ...
  8334. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8335. (dealloc %ecx)
  8336. Change to:
  8337. mov ###,%cl (if ### = %cl, then remove completely)
  8338. ...
  8339. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8340. }
  8341. if (getsupreg(ThisReg) = RS_ECX) and
  8342. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8343. (hp1.typ = ait_instruction) and
  8344. (
  8345. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8346. instruction that doesn't actually contain ECX }
  8347. (cs_opt_level3 in current_settings.optimizerswitches) or
  8348. RegInInstruction(NR_ECX, hp1) or
  8349. (
  8350. { It's common for the shift/rotate's read/write register to be
  8351. initialised in between, so under -O2 and under, search ahead
  8352. one more instruction
  8353. }
  8354. GetNextInstruction(hp1, hp1) and
  8355. (hp1.typ = ait_instruction) and
  8356. RegInInstruction(NR_ECX, hp1)
  8357. )
  8358. ) and
  8359. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8360. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8361. begin
  8362. TransferUsedRegs(TmpUsedRegs);
  8363. hp2 := p;
  8364. repeat
  8365. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8366. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8367. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8368. begin
  8369. case taicpu(p).opsize of
  8370. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8371. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8372. begin
  8373. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8374. RemoveCurrentP(p);
  8375. end
  8376. else
  8377. begin
  8378. taicpu(p).opcode := A_MOV;
  8379. taicpu(p).opsize := S_B;
  8380. taicpu(p).oper[1]^.reg := NR_CL;
  8381. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8382. end;
  8383. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8384. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8385. begin
  8386. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8387. RemoveCurrentP(p);
  8388. end
  8389. else
  8390. begin
  8391. taicpu(p).opcode := A_MOV;
  8392. taicpu(p).opsize := S_W;
  8393. taicpu(p).oper[1]^.reg := NR_CX;
  8394. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8395. end;
  8396. {$ifdef x86_64}
  8397. S_LQ:
  8398. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8399. begin
  8400. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8401. RemoveCurrentP(p);
  8402. end
  8403. else
  8404. begin
  8405. taicpu(p).opcode := A_MOV;
  8406. taicpu(p).opsize := S_L;
  8407. taicpu(p).oper[1]^.reg := NR_ECX;
  8408. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8409. end;
  8410. {$endif x86_64}
  8411. else
  8412. InternalError(2021120401);
  8413. end;
  8414. Result := True;
  8415. Exit;
  8416. end;
  8417. end;
  8418. { This is anything but quick! }
  8419. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8420. Exit;
  8421. SetLength(InstrList, 0);
  8422. InstrMax := -1;
  8423. case taicpu(p).opsize of
  8424. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8425. begin
  8426. {$if defined(i386) or defined(i8086)}
  8427. { If the target size is 8-bit, make sure we can actually encode it }
  8428. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8429. Exit;
  8430. {$endif i386 or i8086}
  8431. LowerLimit := $FF;
  8432. SignedLowerLimit := $7F;
  8433. SignedLowerLimitBottom := -128;
  8434. MinSize := S_B;
  8435. if taicpu(p).opsize = S_BW then
  8436. begin
  8437. MaxSize := S_W;
  8438. UpperLimit := $FFFF;
  8439. SignedUpperLimit := $7FFF;
  8440. SignedUpperLimitBottom := -32768;
  8441. end
  8442. else
  8443. begin
  8444. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8445. MaxSize := S_L;
  8446. UpperLimit := $FFFFFFFF;
  8447. SignedUpperLimit := $7FFFFFFF;
  8448. SignedUpperLimitBottom := -2147483648;
  8449. end;
  8450. end;
  8451. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8452. begin
  8453. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8454. LowerLimit := $FFFF;
  8455. SignedLowerLimit := $7FFF;
  8456. SignedLowerLimitBottom := -32768;
  8457. UpperLimit := $FFFFFFFF;
  8458. SignedUpperLimit := $7FFFFFFF;
  8459. SignedUpperLimitBottom := -2147483648;
  8460. MinSize := S_W;
  8461. MaxSize := S_L;
  8462. end;
  8463. {$ifdef x86_64}
  8464. S_LQ:
  8465. begin
  8466. { Both the lower and upper limits are set to 32-bit. If a limit
  8467. is breached, then optimisation is impossible }
  8468. LowerLimit := $FFFFFFFF;
  8469. SignedLowerLimit := $7FFFFFFF;
  8470. SignedLowerLimitBottom := -2147483648;
  8471. UpperLimit := $FFFFFFFF;
  8472. SignedUpperLimit := $7FFFFFFF;
  8473. SignedUpperLimitBottom := -2147483648;
  8474. MinSize := S_L;
  8475. MaxSize := S_L;
  8476. end;
  8477. {$endif x86_64}
  8478. else
  8479. InternalError(2020112301);
  8480. end;
  8481. TestValMin := 0;
  8482. TestValMax := LowerLimit;
  8483. TestValSignedMax := SignedLowerLimit;
  8484. TryShiftDownLimit := LowerLimit;
  8485. TryShiftDown := S_NO;
  8486. ShiftDownOverflow := False;
  8487. RegChanged := False;
  8488. BitwiseOnly := True;
  8489. OrXorUsed := False;
  8490. UpperSignedOverflow := False;
  8491. LowerSignedOverflow := False;
  8492. UpperUnsignedOverflow := False;
  8493. LowerUnsignedOverflow := False;
  8494. hp1 := p;
  8495. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8496. (hp1.typ = ait_instruction) and
  8497. (
  8498. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8499. instruction that doesn't actually contain ThisReg }
  8500. (cs_opt_level3 in current_settings.optimizerswitches) or
  8501. { This allows this Movx optimisation to work through the SETcc instructions
  8502. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8503. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8504. skip over these SETcc instructions). }
  8505. (taicpu(hp1).opcode = A_SETcc) or
  8506. RegInInstruction(ThisReg, hp1)
  8507. ) do
  8508. begin
  8509. case taicpu(hp1).opcode of
  8510. A_INC,A_DEC:
  8511. begin
  8512. { Has to be an exact match on the register }
  8513. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8514. Break;
  8515. if taicpu(hp1).opcode = A_INC then
  8516. begin
  8517. Inc(TestValMin);
  8518. Inc(TestValMax);
  8519. Inc(TestValSignedMax);
  8520. end
  8521. else
  8522. begin
  8523. Dec(TestValMin);
  8524. Dec(TestValMax);
  8525. Dec(TestValSignedMax);
  8526. end;
  8527. end;
  8528. A_TEST, A_CMP:
  8529. begin
  8530. if (
  8531. { Too high a risk of non-linear behaviour that breaks DFA
  8532. here, unless it's cmp $0,%reg, which is equivalent to
  8533. test %reg,%reg }
  8534. OrXorUsed and
  8535. (taicpu(hp1).opcode = A_CMP) and
  8536. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8537. ) or
  8538. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8539. { Has to be an exact match on the register }
  8540. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8541. (
  8542. { Permit "test %reg,%reg" }
  8543. (taicpu(hp1).opcode = A_TEST) and
  8544. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8545. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8546. ) or
  8547. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8548. { Make sure the comparison value is not smaller than the
  8549. smallest allowed signed value for the minimum size (e.g.
  8550. -128 for 8-bit) }
  8551. not (
  8552. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8553. { Is it in the negative range? }
  8554. (
  8555. (taicpu(hp1).oper[0]^.val < 0) and
  8556. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8557. )
  8558. ) then
  8559. Break;
  8560. { Check to see if the active register is used afterwards }
  8561. TransferUsedRegs(TmpUsedRegs);
  8562. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8563. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8564. begin
  8565. { Make sure the comparison or any previous instructions
  8566. hasn't pushed the test values outside of the range of
  8567. MinSize }
  8568. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8569. begin
  8570. { Exceeded lower bound but not upper bound }
  8571. Exit;
  8572. end
  8573. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8574. begin
  8575. { Size didn't exceed lower bound }
  8576. TargetSize := MinSize;
  8577. end
  8578. else
  8579. Break;
  8580. case TargetSize of
  8581. S_B:
  8582. TargetSubReg := R_SUBL;
  8583. S_W:
  8584. TargetSubReg := R_SUBW;
  8585. S_L:
  8586. TargetSubReg := R_SUBD;
  8587. else
  8588. InternalError(2021051002);
  8589. end;
  8590. if TargetSize <> MaxSize then
  8591. begin
  8592. { Update the register to its new size }
  8593. setsubreg(ThisReg, TargetSubReg);
  8594. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8595. taicpu(hp1).oper[1]^.reg := ThisReg;
  8596. taicpu(hp1).opsize := TargetSize;
  8597. { Convert the input MOVZX to a MOV if necessary }
  8598. AdjustInitialLoadAndSize;
  8599. if (InstrMax >= 0) then
  8600. begin
  8601. for Index := 0 to InstrMax do
  8602. begin
  8603. { If p_removed is true, then the original MOV/Z was removed
  8604. and removing the AND instruction may not be safe if it
  8605. appears first }
  8606. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8607. InternalError(2020112311);
  8608. if InstrList[Index].oper[0]^.typ = top_reg then
  8609. InstrList[Index].oper[0]^.reg := ThisReg;
  8610. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8611. InstrList[Index].opsize := MinSize;
  8612. end;
  8613. end;
  8614. Result := True;
  8615. end;
  8616. Exit;
  8617. end;
  8618. end;
  8619. A_SETcc:
  8620. begin
  8621. { This allows this Movx optimisation to work through the SETcc instructions
  8622. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8623. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8624. skip over these SETcc instructions). }
  8625. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8626. { Of course, break out if the current register is used }
  8627. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8628. Break
  8629. else
  8630. { We must use Continue so the instruction doesn't get added
  8631. to InstrList }
  8632. Continue;
  8633. end;
  8634. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8635. begin
  8636. if
  8637. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8638. { Has to be an exact match on the register }
  8639. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8640. (
  8641. (
  8642. (taicpu(hp1).oper[0]^.typ = top_const) and
  8643. (
  8644. (
  8645. (taicpu(hp1).opcode = A_SHL) and
  8646. (
  8647. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8648. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8649. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8650. )
  8651. ) or (
  8652. (taicpu(hp1).opcode <> A_SHL) and
  8653. (
  8654. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8655. { Is it in the negative range? }
  8656. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8657. )
  8658. )
  8659. )
  8660. ) or (
  8661. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8662. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8663. )
  8664. ) then
  8665. Break;
  8666. { Only process OR and XOR if there are only bitwise operations,
  8667. since otherwise they can too easily fool the data flow
  8668. analysis (they can cause non-linear behaviour) }
  8669. case taicpu(hp1).opcode of
  8670. A_ADD:
  8671. begin
  8672. if OrXorUsed then
  8673. { Too high a risk of non-linear behaviour that breaks DFA here }
  8674. Break
  8675. else
  8676. BitwiseOnly := False;
  8677. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8678. begin
  8679. TestValMin := TestValMin * 2;
  8680. TestValMax := TestValMax * 2;
  8681. TestValSignedMax := TestValSignedMax * 2;
  8682. end
  8683. else
  8684. begin
  8685. WorkingValue := taicpu(hp1).oper[0]^.val;
  8686. TestValMin := TestValMin + WorkingValue;
  8687. TestValMax := TestValMax + WorkingValue;
  8688. TestValSignedMax := TestValSignedMax + WorkingValue;
  8689. end;
  8690. end;
  8691. A_SUB:
  8692. begin
  8693. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8694. begin
  8695. TestValMin := 0;
  8696. TestValMax := 0;
  8697. TestValSignedMax := 0;
  8698. end
  8699. else
  8700. begin
  8701. if OrXorUsed then
  8702. { Too high a risk of non-linear behaviour that breaks DFA here }
  8703. Break
  8704. else
  8705. BitwiseOnly := False;
  8706. WorkingValue := taicpu(hp1).oper[0]^.val;
  8707. TestValMin := TestValMin - WorkingValue;
  8708. TestValMax := TestValMax - WorkingValue;
  8709. TestValSignedMax := TestValSignedMax - WorkingValue;
  8710. end;
  8711. end;
  8712. A_AND:
  8713. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8714. begin
  8715. { we might be able to go smaller if AND appears first }
  8716. if InstrMax = -1 then
  8717. case MinSize of
  8718. S_B:
  8719. ;
  8720. S_W:
  8721. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8722. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8723. begin
  8724. TryShiftDown := S_B;
  8725. TryShiftDownLimit := $FF;
  8726. end;
  8727. S_L:
  8728. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8729. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8730. begin
  8731. TryShiftDown := S_B;
  8732. TryShiftDownLimit := $FF;
  8733. end
  8734. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8735. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8736. begin
  8737. TryShiftDown := S_W;
  8738. TryShiftDownLimit := $FFFF;
  8739. end;
  8740. else
  8741. InternalError(2020112320);
  8742. end;
  8743. WorkingValue := taicpu(hp1).oper[0]^.val;
  8744. TestValMin := TestValMin and WorkingValue;
  8745. TestValMax := TestValMax and WorkingValue;
  8746. TestValSignedMax := TestValSignedMax and WorkingValue;
  8747. end;
  8748. A_OR:
  8749. begin
  8750. if not BitwiseOnly then
  8751. Break;
  8752. OrXorUsed := True;
  8753. WorkingValue := taicpu(hp1).oper[0]^.val;
  8754. TestValMin := TestValMin or WorkingValue;
  8755. TestValMax := TestValMax or WorkingValue;
  8756. TestValSignedMax := TestValSignedMax or WorkingValue;
  8757. end;
  8758. A_XOR:
  8759. begin
  8760. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8761. begin
  8762. TestValMin := 0;
  8763. TestValMax := 0;
  8764. TestValSignedMax := 0;
  8765. end
  8766. else
  8767. begin
  8768. if not BitwiseOnly then
  8769. Break;
  8770. OrXorUsed := True;
  8771. WorkingValue := taicpu(hp1).oper[0]^.val;
  8772. TestValMin := TestValMin xor WorkingValue;
  8773. TestValMax := TestValMax xor WorkingValue;
  8774. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8775. end;
  8776. end;
  8777. A_SHL:
  8778. begin
  8779. BitwiseOnly := False;
  8780. WorkingValue := taicpu(hp1).oper[0]^.val;
  8781. TestValMin := TestValMin shl WorkingValue;
  8782. TestValMax := TestValMax shl WorkingValue;
  8783. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8784. end;
  8785. A_SHR,
  8786. { The first instruction was MOVZX, so the value won't be negative }
  8787. A_SAR:
  8788. begin
  8789. if InstrMax <> -1 then
  8790. BitwiseOnly := False
  8791. else
  8792. { we might be able to go smaller if SHR appears first }
  8793. case MinSize of
  8794. S_B:
  8795. ;
  8796. S_W:
  8797. if (taicpu(hp1).oper[0]^.val >= 8) then
  8798. begin
  8799. TryShiftDown := S_B;
  8800. TryShiftDownLimit := $FF;
  8801. TryShiftDownSignedLimit := $7F;
  8802. TryShiftDownSignedLimitLower := -128;
  8803. end;
  8804. S_L:
  8805. if (taicpu(hp1).oper[0]^.val >= 24) then
  8806. begin
  8807. TryShiftDown := S_B;
  8808. TryShiftDownLimit := $FF;
  8809. TryShiftDownSignedLimit := $7F;
  8810. TryShiftDownSignedLimitLower := -128;
  8811. end
  8812. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8813. begin
  8814. TryShiftDown := S_W;
  8815. TryShiftDownLimit := $FFFF;
  8816. TryShiftDownSignedLimit := $7FFF;
  8817. TryShiftDownSignedLimitLower := -32768;
  8818. end;
  8819. else
  8820. InternalError(2020112321);
  8821. end;
  8822. WorkingValue := taicpu(hp1).oper[0]^.val;
  8823. if taicpu(hp1).opcode = A_SAR then
  8824. begin
  8825. TestValMin := SarInt64(TestValMin, WorkingValue);
  8826. TestValMax := SarInt64(TestValMax, WorkingValue);
  8827. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8828. end
  8829. else
  8830. begin
  8831. TestValMin := TestValMin shr WorkingValue;
  8832. TestValMax := TestValMax shr WorkingValue;
  8833. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8834. end;
  8835. end;
  8836. else
  8837. InternalError(2020112303);
  8838. end;
  8839. end;
  8840. (*
  8841. A_IMUL:
  8842. case taicpu(hp1).ops of
  8843. 2:
  8844. begin
  8845. if not MatchOpType(hp1, top_reg, top_reg) or
  8846. { Has to be an exact match on the register }
  8847. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8848. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8849. Break;
  8850. TestValMin := TestValMin * TestValMin;
  8851. TestValMax := TestValMax * TestValMax;
  8852. TestValSignedMax := TestValSignedMax * TestValMax;
  8853. end;
  8854. 3:
  8855. begin
  8856. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8857. { Has to be an exact match on the register }
  8858. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8859. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8860. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8861. { Is it in the negative range? }
  8862. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8863. Break;
  8864. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8865. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8866. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8867. end;
  8868. else
  8869. Break;
  8870. end;
  8871. A_IDIV:
  8872. case taicpu(hp1).ops of
  8873. 3:
  8874. begin
  8875. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8876. { Has to be an exact match on the register }
  8877. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8878. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8879. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8880. { Is it in the negative range? }
  8881. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8882. Break;
  8883. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8884. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8885. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8886. end;
  8887. else
  8888. Break;
  8889. end;
  8890. *)
  8891. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8892. begin
  8893. { If there are no instructions in between, then we might be able to make a saving }
  8894. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8895. Break;
  8896. { We have something like:
  8897. movzbw %dl,%dx
  8898. ...
  8899. movswl %dx,%edx
  8900. Change the latter to a zero-extension then enter the
  8901. A_MOVZX case branch.
  8902. }
  8903. {$ifdef x86_64}
  8904. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8905. begin
  8906. { this becomes a zero extension from 32-bit to 64-bit, but
  8907. the upper 32 bits are already zero, so just delete the
  8908. instruction }
  8909. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8910. RemoveInstruction(hp1);
  8911. Result := True;
  8912. Exit;
  8913. end
  8914. else
  8915. {$endif x86_64}
  8916. begin
  8917. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8918. taicpu(hp1).opcode := A_MOVZX;
  8919. {$ifdef x86_64}
  8920. case taicpu(hp1).opsize of
  8921. S_BQ:
  8922. begin
  8923. taicpu(hp1).opsize := S_BL;
  8924. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8925. end;
  8926. S_WQ:
  8927. begin
  8928. taicpu(hp1).opsize := S_WL;
  8929. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8930. end;
  8931. S_LQ:
  8932. begin
  8933. taicpu(hp1).opcode := A_MOV;
  8934. taicpu(hp1).opsize := S_L;
  8935. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8936. { In this instance, we need to break out because the
  8937. instruction is no longer MOVZX or MOVSXD }
  8938. Result := True;
  8939. Exit;
  8940. end;
  8941. else
  8942. ;
  8943. end;
  8944. {$endif x86_64}
  8945. Result := CompressInstructions;
  8946. Exit;
  8947. end;
  8948. end;
  8949. A_MOVZX:
  8950. begin
  8951. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8952. Break;
  8953. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8954. begin
  8955. if (InstrMax = -1) and
  8956. { Will return false if the second parameter isn't ThisReg
  8957. (can happen on -O2 and under) }
  8958. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8959. begin
  8960. { The two MOVZX instructions are adjacent, so remove the first one }
  8961. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8962. RemoveCurrentP(p);
  8963. Result := True;
  8964. Exit;
  8965. end;
  8966. Break;
  8967. end;
  8968. Result := CompressInstructions;
  8969. Exit;
  8970. end;
  8971. else
  8972. { This includes ADC, SBB and IDIV }
  8973. Break;
  8974. end;
  8975. if not CheckOverflowConditions then
  8976. Break;
  8977. { Contains highest index (so instruction count - 1) }
  8978. Inc(InstrMax);
  8979. if InstrMax > High(InstrList) then
  8980. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8981. InstrList[InstrMax] := taicpu(hp1);
  8982. end;
  8983. end;
  8984. {$pop}
  8985. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8986. var
  8987. hp1 : tai;
  8988. begin
  8989. Result:=false;
  8990. if (taicpu(p).ops >= 2) and
  8991. ((taicpu(p).oper[0]^.typ = top_const) or
  8992. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8993. (taicpu(p).oper[1]^.typ = top_reg) and
  8994. ((taicpu(p).ops = 2) or
  8995. ((taicpu(p).oper[2]^.typ = top_reg) and
  8996. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8997. GetLastInstruction(p,hp1) and
  8998. MatchInstruction(hp1,A_MOV,[]) and
  8999. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9000. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9001. begin
  9002. TransferUsedRegs(TmpUsedRegs);
  9003. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9004. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9005. { change
  9006. mov reg1,reg2
  9007. imul y,reg2 to imul y,reg1,reg2 }
  9008. begin
  9009. taicpu(p).ops := 3;
  9010. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9011. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9012. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9013. RemoveInstruction(hp1);
  9014. result:=true;
  9015. end;
  9016. end;
  9017. end;
  9018. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9019. var
  9020. ThisLabel: TAsmLabel;
  9021. begin
  9022. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9023. ThisLabel.decrefs;
  9024. taicpu(p).opcode := A_RET;
  9025. taicpu(p).is_jmp := false;
  9026. taicpu(p).ops := taicpu(ret_p).ops;
  9027. case taicpu(ret_p).ops of
  9028. 0:
  9029. taicpu(p).clearop(0);
  9030. 1:
  9031. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9032. else
  9033. internalerror(2016041301);
  9034. end;
  9035. { If the original label is now dead, it might turn out that the label
  9036. immediately follows p. As a result, everything beyond it, which will
  9037. be just some final register configuration and a RET instruction, is
  9038. now dead code. [Kit] }
  9039. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9040. running RemoveDeadCodeAfterJump for each RET instruction, because
  9041. this optimisation rarely happens and most RETs appear at the end of
  9042. routines where there is nothing that can be stripped. [Kit] }
  9043. if not ThisLabel.is_used then
  9044. RemoveDeadCodeAfterJump(p);
  9045. end;
  9046. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9047. var
  9048. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9049. Unconditional, PotentialModified: Boolean;
  9050. OperPtr: POper;
  9051. NewRef: TReference;
  9052. InstrList: array of taicpu;
  9053. InstrMax, Index: Integer;
  9054. const
  9055. {$ifdef DEBUG_AOPTCPU}
  9056. SNoFlags: shortstring = ' so the flags aren''t modified';
  9057. {$else DEBUG_AOPTCPU}
  9058. SNoFlags = '';
  9059. {$endif DEBUG_AOPTCPU}
  9060. begin
  9061. Result:=false;
  9062. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9063. begin
  9064. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9065. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9066. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9067. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9068. GetNextInstruction(hp1, hp2) and
  9069. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9070. { Change from: To:
  9071. set(C) %reg j(~C) label
  9072. test %reg,%reg/cmp $0,%reg
  9073. je label
  9074. set(C) %reg j(C) label
  9075. test %reg,%reg/cmp $0,%reg
  9076. jne label
  9077. (Also do something similar with sete/setne instead of je/jne)
  9078. }
  9079. begin
  9080. { Before we do anything else, we need to check the instructions
  9081. in between SETcc and TEST to make sure they don't modify the
  9082. FLAGS register - if -O2 or under, there won't be any
  9083. instructions between SET and TEST }
  9084. TransferUsedRegs(TmpUsedRegs);
  9085. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9086. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9087. begin
  9088. next := p;
  9089. SetLength(InstrList, 0);
  9090. InstrMax := -1;
  9091. PotentialModified := False;
  9092. { Make a note of every instruction that modifies the FLAGS
  9093. register }
  9094. while GetNextInstruction(next, next) and (next <> hp1) do
  9095. begin
  9096. if next.typ <> ait_instruction then
  9097. { GetNextInstructionUsingReg should have returned False }
  9098. InternalError(2021051701);
  9099. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9100. begin
  9101. case taicpu(next).opcode of
  9102. A_SETcc,
  9103. A_CMOVcc,
  9104. A_Jcc:
  9105. begin
  9106. if PotentialModified then
  9107. { Not safe because the flags were modified earlier }
  9108. Exit
  9109. else
  9110. { Condition is the same as the initial SETcc, so this is safe
  9111. (don't add to instruction list though) }
  9112. Continue;
  9113. end;
  9114. A_ADD:
  9115. begin
  9116. if (taicpu(next).opsize = S_B) or
  9117. { LEA doesn't support 8-bit operands }
  9118. (taicpu(next).oper[1]^.typ <> top_reg) or
  9119. { Must write to a register }
  9120. (taicpu(next).oper[0]^.typ = top_ref) then
  9121. { Require a constant or a register }
  9122. Exit;
  9123. PotentialModified := True;
  9124. end;
  9125. A_SUB:
  9126. begin
  9127. if (taicpu(next).opsize = S_B) or
  9128. { LEA doesn't support 8-bit operands }
  9129. (taicpu(next).oper[1]^.typ <> top_reg) or
  9130. { Must write to a register }
  9131. (taicpu(next).oper[0]^.typ <> top_const) or
  9132. (taicpu(next).oper[0]^.val = $80000000) then
  9133. { Can't subtract a register with LEA - also
  9134. check that the value isn't -2^31, as this
  9135. can't be negated }
  9136. Exit;
  9137. PotentialModified := True;
  9138. end;
  9139. A_SAL,
  9140. A_SHL:
  9141. begin
  9142. if (taicpu(next).opsize = S_B) or
  9143. { LEA doesn't support 8-bit operands }
  9144. (taicpu(next).oper[1]^.typ <> top_reg) or
  9145. { Must write to a register }
  9146. (taicpu(next).oper[0]^.typ <> top_const) or
  9147. (taicpu(next).oper[0]^.val < 0) or
  9148. (taicpu(next).oper[0]^.val > 3) then
  9149. Exit;
  9150. PotentialModified := True;
  9151. end;
  9152. A_IMUL:
  9153. begin
  9154. if (taicpu(next).ops <> 3) or
  9155. (taicpu(next).oper[1]^.typ <> top_reg) or
  9156. { Must write to a register }
  9157. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9158. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9159. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9160. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9161. Exit
  9162. else
  9163. PotentialModified := True;
  9164. end;
  9165. else
  9166. { Don't know how to change this, so abort }
  9167. Exit;
  9168. end;
  9169. { Contains highest index (so instruction count - 1) }
  9170. Inc(InstrMax);
  9171. if InstrMax > High(InstrList) then
  9172. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9173. InstrList[InstrMax] := taicpu(next);
  9174. end;
  9175. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9176. end;
  9177. if not Assigned(next) or (next <> hp1) then
  9178. { It should be equal to hp1 }
  9179. InternalError(2021051702);
  9180. { Cycle through each instruction and check to see if we can
  9181. change them to versions that don't modify the flags }
  9182. if (InstrMax >= 0) then
  9183. begin
  9184. for Index := 0 to InstrMax do
  9185. case InstrList[Index].opcode of
  9186. A_ADD:
  9187. begin
  9188. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9189. InstrList[Index].opcode := A_LEA;
  9190. reference_reset(NewRef, 1, []);
  9191. NewRef.base := InstrList[Index].oper[1]^.reg;
  9192. if InstrList[Index].oper[0]^.typ = top_reg then
  9193. begin
  9194. NewRef.index := InstrList[Index].oper[0]^.reg;
  9195. NewRef.scalefactor := 1;
  9196. end
  9197. else
  9198. NewRef.offset := InstrList[Index].oper[0]^.val;
  9199. InstrList[Index].loadref(0, NewRef);
  9200. end;
  9201. A_SUB:
  9202. begin
  9203. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9204. InstrList[Index].opcode := A_LEA;
  9205. reference_reset(NewRef, 1, []);
  9206. NewRef.base := InstrList[Index].oper[1]^.reg;
  9207. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9208. InstrList[Index].loadref(0, NewRef);
  9209. end;
  9210. A_SHL,
  9211. A_SAL:
  9212. begin
  9213. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9214. InstrList[Index].opcode := A_LEA;
  9215. reference_reset(NewRef, 1, []);
  9216. NewRef.index := InstrList[Index].oper[1]^.reg;
  9217. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9218. InstrList[Index].loadref(0, NewRef);
  9219. end;
  9220. A_IMUL:
  9221. begin
  9222. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9223. InstrList[Index].opcode := A_LEA;
  9224. reference_reset(NewRef, 1, []);
  9225. NewRef.index := InstrList[Index].oper[1]^.reg;
  9226. case InstrList[Index].oper[0]^.val of
  9227. 2, 4, 8:
  9228. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9229. else {3, 5 and 9}
  9230. begin
  9231. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9232. NewRef.base := InstrList[Index].oper[1]^.reg;
  9233. end;
  9234. end;
  9235. InstrList[Index].loadref(0, NewRef);
  9236. end;
  9237. else
  9238. InternalError(2021051710);
  9239. end;
  9240. end;
  9241. { Mark the FLAGS register as used across this whole block }
  9242. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9243. end;
  9244. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9245. JumpC := taicpu(hp2).condition;
  9246. Unconditional := False;
  9247. if conditions_equal(JumpC, C_E) then
  9248. SetC := inverse_cond(taicpu(p).condition)
  9249. else if conditions_equal(JumpC, C_NE) then
  9250. SetC := taicpu(p).condition
  9251. else
  9252. { We've got something weird here (and inefficent) }
  9253. begin
  9254. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9255. SetC := C_NONE;
  9256. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9257. if condition_in(C_AE, JumpC) then
  9258. Unconditional := True
  9259. else
  9260. { Not sure what to do with this jump - drop out }
  9261. Exit;
  9262. end;
  9263. RemoveInstruction(hp1);
  9264. if Unconditional then
  9265. MakeUnconditional(taicpu(hp2))
  9266. else
  9267. begin
  9268. if SetC = C_NONE then
  9269. InternalError(2018061402);
  9270. taicpu(hp2).SetCondition(SetC);
  9271. end;
  9272. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9273. TmpUsedRegs }
  9274. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9275. begin
  9276. RemoveCurrentp(p, hp2);
  9277. if taicpu(hp2).opcode = A_SETcc then
  9278. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9279. else
  9280. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9281. end
  9282. else
  9283. if taicpu(hp2).opcode = A_SETcc then
  9284. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9285. else
  9286. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9287. Result := True;
  9288. end
  9289. else if
  9290. { Make sure the instructions are adjacent }
  9291. (
  9292. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9293. GetNextInstruction(p, hp1)
  9294. ) and
  9295. MatchInstruction(hp1, A_MOV, [S_B]) and
  9296. { Writing to memory is allowed }
  9297. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9298. begin
  9299. {
  9300. Watch out for sequences such as:
  9301. set(c)b %regb
  9302. movb %regb,(ref)
  9303. movb $0,1(ref)
  9304. movb $0,2(ref)
  9305. movb $0,3(ref)
  9306. Much more efficient to turn it into:
  9307. movl $0,%regl
  9308. set(c)b %regb
  9309. movl %regl,(ref)
  9310. Or:
  9311. set(c)b %regb
  9312. movzbl %regb,%regl
  9313. movl %regl,(ref)
  9314. }
  9315. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9316. GetNextInstruction(hp1, hp2) and
  9317. MatchInstruction(hp2, A_MOV, [S_B]) and
  9318. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9319. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9320. begin
  9321. { Don't do anything else except set Result to True }
  9322. end
  9323. else
  9324. begin
  9325. if taicpu(p).oper[0]^.typ = top_reg then
  9326. begin
  9327. TransferUsedRegs(TmpUsedRegs);
  9328. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9329. end;
  9330. { If it's not a register, it's a memory address }
  9331. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9332. begin
  9333. { Even if the register is still in use, we can minimise the
  9334. pipeline stall by changing the MOV into another SETcc. }
  9335. taicpu(hp1).opcode := A_SETcc;
  9336. taicpu(hp1).condition := taicpu(p).condition;
  9337. if taicpu(hp1).oper[1]^.typ = top_ref then
  9338. begin
  9339. { Swapping the operand pointers like this is probably a
  9340. bit naughty, but it is far faster than using loadoper
  9341. to transfer the reference from oper[1] to oper[0] if
  9342. you take into account the extra procedure calls and
  9343. the memory allocation and deallocation required }
  9344. OperPtr := taicpu(hp1).oper[1];
  9345. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9346. taicpu(hp1).oper[0] := OperPtr;
  9347. end
  9348. else
  9349. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9350. taicpu(hp1).clearop(1);
  9351. taicpu(hp1).ops := 1;
  9352. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9353. end
  9354. else
  9355. begin
  9356. if taicpu(hp1).oper[1]^.typ = top_reg then
  9357. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9358. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9359. RemoveInstruction(hp1);
  9360. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9361. end
  9362. end;
  9363. Result := True;
  9364. end;
  9365. end;
  9366. end;
  9367. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9368. var
  9369. hp1: tai;
  9370. Count: Integer;
  9371. OrigLabel: TAsmLabel;
  9372. begin
  9373. result := False;
  9374. { Sometimes, the optimisations below can permit this }
  9375. RemoveDeadCodeAfterJump(p);
  9376. 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
  9377. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9378. begin
  9379. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9380. { Also a side-effect of optimisations }
  9381. if CollapseZeroDistJump(p, OrigLabel) then
  9382. begin
  9383. Result := True;
  9384. Exit;
  9385. end;
  9386. hp1 := GetLabelWithSym(OrigLabel);
  9387. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9388. begin
  9389. if taicpu(hp1).opcode = A_RET then
  9390. begin
  9391. {
  9392. change
  9393. jmp .L1
  9394. ...
  9395. .L1:
  9396. ret
  9397. into
  9398. ret
  9399. }
  9400. begin
  9401. ConvertJumpToRET(p, hp1);
  9402. result:=true;
  9403. end;
  9404. end
  9405. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9406. not (cs_opt_size in current_settings.optimizerswitches) and
  9407. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9408. begin
  9409. Result := True;
  9410. Exit;
  9411. end;
  9412. end;
  9413. end;
  9414. end;
  9415. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9416. begin
  9417. CanBeCMOV:=assigned(p) and
  9418. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9419. { we can't use cmov ref,reg because
  9420. ref could be nil and cmov still throws an exception
  9421. if ref=nil but the mov isn't done (FK)
  9422. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9423. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9424. }
  9425. (taicpu(p).oper[1]^.typ = top_reg) and
  9426. (
  9427. (taicpu(p).oper[0]^.typ = top_reg) or
  9428. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9429. it is not expected that this can cause a seg. violation }
  9430. (
  9431. (taicpu(p).oper[0]^.typ = top_ref) and
  9432. IsRefSafe(taicpu(p).oper[0]^.ref)
  9433. )
  9434. );
  9435. end;
  9436. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9437. var
  9438. hp1,hp2: tai;
  9439. {$ifndef i8086}
  9440. hp3,hp4,hpmov2, hp5: tai;
  9441. l : Longint;
  9442. condition : TAsmCond;
  9443. {$endif i8086}
  9444. carryadd_opcode : TAsmOp;
  9445. symbol: TAsmSymbol;
  9446. increg, tmpreg: TRegister;
  9447. begin
  9448. result:=false;
  9449. if GetNextInstruction(p,hp1) then
  9450. begin
  9451. if (hp1.typ=ait_label) then
  9452. begin
  9453. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9454. Exit;
  9455. end
  9456. else if (hp1.typ<>ait_instruction) then
  9457. Exit;
  9458. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9459. if (
  9460. (
  9461. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9462. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9463. (Taicpu(hp1).oper[0]^.val=1)
  9464. ) or
  9465. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9466. ) and
  9467. GetNextInstruction(hp1,hp2) and
  9468. SkipAligns(hp2, hp2) and
  9469. (hp2.typ = ait_label) and
  9470. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9471. { jb @@1 cmc
  9472. inc/dec operand --> adc/sbb operand,0
  9473. @@1:
  9474. ... and ...
  9475. jnb @@1
  9476. inc/dec operand --> adc/sbb operand,0
  9477. @@1: }
  9478. begin
  9479. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9480. begin
  9481. case taicpu(hp1).opcode of
  9482. A_INC,
  9483. A_ADD:
  9484. carryadd_opcode:=A_ADC;
  9485. A_DEC,
  9486. A_SUB:
  9487. carryadd_opcode:=A_SBB;
  9488. else
  9489. InternalError(2021011001);
  9490. end;
  9491. Taicpu(p).clearop(0);
  9492. Taicpu(p).ops:=0;
  9493. Taicpu(p).is_jmp:=false;
  9494. Taicpu(p).opcode:=A_CMC;
  9495. Taicpu(p).condition:=C_NONE;
  9496. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9497. Taicpu(hp1).ops:=2;
  9498. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9499. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9500. else
  9501. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9502. Taicpu(hp1).loadconst(0,0);
  9503. Taicpu(hp1).opcode:=carryadd_opcode;
  9504. result:=true;
  9505. exit;
  9506. end
  9507. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9508. begin
  9509. case taicpu(hp1).opcode of
  9510. A_INC,
  9511. A_ADD:
  9512. carryadd_opcode:=A_ADC;
  9513. A_DEC,
  9514. A_SUB:
  9515. carryadd_opcode:=A_SBB;
  9516. else
  9517. InternalError(2021011002);
  9518. end;
  9519. Taicpu(hp1).ops:=2;
  9520. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9521. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9522. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9523. else
  9524. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9525. Taicpu(hp1).loadconst(0,0);
  9526. Taicpu(hp1).opcode:=carryadd_opcode;
  9527. RemoveCurrentP(p, hp1);
  9528. result:=true;
  9529. exit;
  9530. end
  9531. {
  9532. jcc @@1 setcc tmpreg
  9533. inc/dec/add/sub operand -> (movzx tmpreg)
  9534. @@1: add/sub tmpreg,operand
  9535. While this increases code size slightly, it makes the code much faster if the
  9536. jump is unpredictable
  9537. }
  9538. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9539. begin
  9540. { search for an available register which is volatile }
  9541. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9542. if increg <> NR_NO then
  9543. begin
  9544. { We don't need to check if tmpreg is in hp1 or not, because
  9545. it will be marked as in use at p (if not, this is
  9546. indictive of a compiler bug). }
  9547. TAsmLabel(symbol).decrefs;
  9548. Taicpu(p).clearop(0);
  9549. Taicpu(p).ops:=1;
  9550. Taicpu(p).is_jmp:=false;
  9551. Taicpu(p).opcode:=A_SETcc;
  9552. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9553. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9554. Taicpu(p).loadreg(0,increg);
  9555. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9556. begin
  9557. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9558. R_SUBW:
  9559. begin
  9560. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9561. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9562. end;
  9563. R_SUBD:
  9564. begin
  9565. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9566. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9567. end;
  9568. {$ifdef x86_64}
  9569. R_SUBQ:
  9570. begin
  9571. { MOVZX doesn't have a 64-bit variant, because
  9572. the 32-bit version implicitly zeroes the
  9573. upper 32-bits of the destination register }
  9574. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9575. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9576. setsubreg(tmpreg, R_SUBQ);
  9577. end;
  9578. {$endif x86_64}
  9579. else
  9580. Internalerror(2020030601);
  9581. end;
  9582. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9583. asml.InsertAfter(hp2,p);
  9584. end
  9585. else
  9586. tmpreg := increg;
  9587. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9588. begin
  9589. Taicpu(hp1).ops:=2;
  9590. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9591. end;
  9592. Taicpu(hp1).loadreg(0,tmpreg);
  9593. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9594. Result := True;
  9595. { p is no longer a Jcc instruction, so exit }
  9596. Exit;
  9597. end;
  9598. end;
  9599. end;
  9600. { Detect the following:
  9601. jmp<cond> @Lbl1
  9602. jmp @Lbl2
  9603. ...
  9604. @Lbl1:
  9605. ret
  9606. Change to:
  9607. jmp<inv_cond> @Lbl2
  9608. ret
  9609. }
  9610. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9611. begin
  9612. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9613. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9614. MatchInstruction(hp2,A_RET,[S_NO]) then
  9615. begin
  9616. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9617. { Change label address to that of the unconditional jump }
  9618. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9619. TAsmLabel(symbol).DecRefs;
  9620. taicpu(hp1).opcode := A_RET;
  9621. taicpu(hp1).is_jmp := false;
  9622. taicpu(hp1).ops := taicpu(hp2).ops;
  9623. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9624. case taicpu(hp2).ops of
  9625. 0:
  9626. taicpu(hp1).clearop(0);
  9627. 1:
  9628. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9629. else
  9630. internalerror(2016041302);
  9631. end;
  9632. end;
  9633. {$ifndef i8086}
  9634. end
  9635. {
  9636. convert
  9637. j<c> .L1
  9638. mov 1,reg
  9639. jmp .L2
  9640. .L1
  9641. mov 0,reg
  9642. .L2
  9643. into
  9644. mov 0,reg
  9645. set<not(c)> reg
  9646. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9647. would destroy the flag contents
  9648. }
  9649. else if MatchInstruction(hp1,A_MOV,[]) and
  9650. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9651. {$ifdef i386}
  9652. (
  9653. { Under i386, ESI, EDI, EBP and ESP
  9654. don't have an 8-bit representation }
  9655. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9656. ) and
  9657. {$endif i386}
  9658. (taicpu(hp1).oper[0]^.val=1) and
  9659. GetNextInstruction(hp1,hp2) and
  9660. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9661. GetNextInstruction(hp2,hp3) and
  9662. { skip align }
  9663. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9664. (hp3.typ=ait_label) and
  9665. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9666. (tai_label(hp3).labsym.getrefs=1) and
  9667. GetNextInstruction(hp3,hp4) and
  9668. MatchInstruction(hp4,A_MOV,[]) and
  9669. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9670. (taicpu(hp4).oper[0]^.val=0) and
  9671. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9672. GetNextInstruction(hp4,hp5) and
  9673. (hp5.typ=ait_label) and
  9674. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9675. (tai_label(hp5).labsym.getrefs=1) then
  9676. begin
  9677. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9678. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9679. { remove last label }
  9680. RemoveInstruction(hp5);
  9681. { remove second label }
  9682. RemoveInstruction(hp3);
  9683. { if align is present remove it }
  9684. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9685. RemoveInstruction(hp3);
  9686. { remove jmp }
  9687. RemoveInstruction(hp2);
  9688. if taicpu(hp1).opsize=S_B then
  9689. RemoveInstruction(hp1)
  9690. else
  9691. taicpu(hp1).loadconst(0,0);
  9692. taicpu(hp4).opcode:=A_SETcc;
  9693. taicpu(hp4).opsize:=S_B;
  9694. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9695. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9696. taicpu(hp4).opercnt:=1;
  9697. taicpu(hp4).ops:=1;
  9698. taicpu(hp4).freeop(1);
  9699. RemoveCurrentP(p);
  9700. Result:=true;
  9701. exit;
  9702. end
  9703. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9704. begin
  9705. { check for
  9706. jCC xxx
  9707. <several movs>
  9708. xxx:
  9709. Also spot:
  9710. Jcc xxx
  9711. <several movs>
  9712. jmp xxx
  9713. Change to:
  9714. <several cmovs with inverted condition>
  9715. jmp xxx
  9716. }
  9717. l:=0;
  9718. while assigned(hp1) and
  9719. CanBeCMOV(hp1) and
  9720. { stop on labels }
  9721. not(hp1.typ=ait_label) do
  9722. begin
  9723. inc(l);
  9724. hp5 := hp1;
  9725. GetNextInstruction(hp1,hp1);
  9726. end;
  9727. if assigned(hp1) then
  9728. begin
  9729. TransferUsedRegs(TmpUsedRegs);
  9730. if (
  9731. MatchInstruction(hp1, A_JMP, []) and
  9732. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9733. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9734. ) or
  9735. FindLabel(tasmlabel(symbol),hp1) then
  9736. begin
  9737. if (l<=4) and (l>0) then
  9738. begin
  9739. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9740. condition:=inverse_cond(taicpu(p).condition);
  9741. UpdateUsedRegs(tai(p.next));
  9742. GetNextInstruction(p,hp1);
  9743. repeat
  9744. if not Assigned(hp1) then
  9745. InternalError(2018062900);
  9746. taicpu(hp1).opcode:=A_CMOVcc;
  9747. taicpu(hp1).condition:=condition;
  9748. UpdateUsedRegs(tai(hp1.next));
  9749. GetNextInstruction(hp1,hp1);
  9750. until not(CanBeCMOV(hp1));
  9751. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9752. hp2 := hp1;
  9753. repeat
  9754. if not Assigned(hp2) then
  9755. InternalError(2018062910);
  9756. case hp2.typ of
  9757. ait_label:
  9758. { What we expected - break out of the loop (it won't be a dead label at the top of
  9759. a cluster because that was optimised at an earlier stage) }
  9760. Break;
  9761. ait_align:
  9762. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9763. begin
  9764. hp2 := tai(hp2.Next);
  9765. Continue;
  9766. end;
  9767. ait_instruction:
  9768. begin
  9769. if taicpu(hp2).opcode<>A_JMP then
  9770. InternalError(2018062912);
  9771. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9772. Break;
  9773. end
  9774. else
  9775. begin
  9776. { Might be a comment or temporary allocation entry }
  9777. if not (hp2.typ in SkipInstr) then
  9778. InternalError(2018062911);
  9779. hp2 := tai(hp2.Next);
  9780. Continue;
  9781. end;
  9782. end;
  9783. until False;
  9784. { Now we can safely decrement the reference count }
  9785. tasmlabel(symbol).decrefs;
  9786. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9787. { Remove the original jump }
  9788. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9789. if hp2.typ=ait_instruction then
  9790. begin
  9791. p:=hp2;
  9792. Result:=True;
  9793. end
  9794. else
  9795. begin
  9796. UpdateUsedRegs(tai(hp2.next));
  9797. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9798. { Remove the label if this is its final reference }
  9799. if (tasmlabel(symbol).getrefs=0) then
  9800. StripLabelFast(hp1);
  9801. end;
  9802. exit;
  9803. end;
  9804. end
  9805. else
  9806. begin
  9807. { check further for
  9808. jCC xxx
  9809. <several movs 1>
  9810. jmp yyy
  9811. xxx:
  9812. <several movs 2>
  9813. yyy:
  9814. }
  9815. { hp2 points to jmp yyy }
  9816. hp2:=hp1;
  9817. { skip hp1 to xxx (or an align right before it) }
  9818. GetNextInstruction(hp1, hp1);
  9819. if assigned(hp2) and
  9820. assigned(hp1) and
  9821. (l<=3) and
  9822. (hp2.typ=ait_instruction) and
  9823. (taicpu(hp2).is_jmp) and
  9824. (taicpu(hp2).condition=C_None) and
  9825. { real label and jump, no further references to the
  9826. label are allowed }
  9827. (tasmlabel(symbol).getrefs=1) and
  9828. FindLabel(tasmlabel(symbol),hp1) then
  9829. begin
  9830. l:=0;
  9831. { skip hp1 to <several moves 2> }
  9832. if (hp1.typ = ait_align) then
  9833. GetNextInstruction(hp1, hp1);
  9834. GetNextInstruction(hp1, hpmov2);
  9835. hp1 := hpmov2;
  9836. while assigned(hp1) and
  9837. CanBeCMOV(hp1) do
  9838. begin
  9839. inc(l);
  9840. hp5 := hp1;
  9841. GetNextInstruction(hp1, hp1);
  9842. end;
  9843. { hp1 points to yyy (or an align right before it) }
  9844. hp3 := hp1;
  9845. if assigned(hp1) and
  9846. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9847. begin
  9848. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9849. condition:=inverse_cond(taicpu(p).condition);
  9850. UpdateUsedRegs(tai(p.next));
  9851. GetNextInstruction(p,hp1);
  9852. repeat
  9853. taicpu(hp1).opcode:=A_CMOVcc;
  9854. taicpu(hp1).condition:=condition;
  9855. UpdateUsedRegs(tai(hp1.next));
  9856. GetNextInstruction(hp1,hp1);
  9857. until not(assigned(hp1)) or
  9858. not(CanBeCMOV(hp1));
  9859. condition:=inverse_cond(condition);
  9860. if GetLastInstruction(hpmov2,hp1) then
  9861. UpdateUsedRegs(tai(hp1.next));
  9862. hp1 := hpmov2;
  9863. { hp1 is now at <several movs 2> }
  9864. while Assigned(hp1) and CanBeCMOV(hp1) do
  9865. begin
  9866. taicpu(hp1).opcode:=A_CMOVcc;
  9867. taicpu(hp1).condition:=condition;
  9868. UpdateUsedRegs(tai(hp1.next));
  9869. GetNextInstruction(hp1,hp1);
  9870. end;
  9871. hp1 := p;
  9872. { Get first instruction after label }
  9873. UpdateUsedRegs(tai(hp3.next));
  9874. GetNextInstruction(hp3, p);
  9875. if assigned(p) and (hp3.typ = ait_align) then
  9876. GetNextInstruction(p, p);
  9877. { Don't dereference yet, as doing so will cause
  9878. GetNextInstruction to skip the label and
  9879. optional align marker. [Kit] }
  9880. GetNextInstruction(hp2, hp4);
  9881. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9882. { remove jCC }
  9883. RemoveInstruction(hp1);
  9884. { Now we can safely decrement it }
  9885. tasmlabel(symbol).decrefs;
  9886. { Remove label xxx (it will have a ref of zero due to the initial check }
  9887. StripLabelFast(hp4);
  9888. { remove jmp }
  9889. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9890. RemoveInstruction(hp2);
  9891. { As before, now we can safely decrement it }
  9892. tasmlabel(symbol).decrefs;
  9893. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9894. if tasmlabel(symbol).getrefs = 0 then
  9895. StripLabelFast(hp3);
  9896. if Assigned(p) then
  9897. result:=true;
  9898. exit;
  9899. end;
  9900. end;
  9901. end;
  9902. end;
  9903. {$endif i8086}
  9904. end;
  9905. end;
  9906. end;
  9907. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9908. var
  9909. hp1,hp2,hp3: tai;
  9910. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9911. NewSize: TOpSize;
  9912. NewRegSize: TSubRegister;
  9913. Limit: TCgInt;
  9914. SwapOper: POper;
  9915. begin
  9916. result:=false;
  9917. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9918. GetNextInstruction(p,hp1) and
  9919. (hp1.typ = ait_instruction);
  9920. if reg_and_hp1_is_instr and
  9921. (
  9922. (taicpu(hp1).opcode <> A_LEA) or
  9923. { If the LEA instruction can be converted into an arithmetic instruction,
  9924. it may be possible to then fold it. }
  9925. (
  9926. { If the flags register is in use, don't change the instruction
  9927. to an ADD otherwise this will scramble the flags. [Kit] }
  9928. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9929. ConvertLEA(taicpu(hp1))
  9930. )
  9931. ) and
  9932. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9933. GetNextInstruction(hp1,hp2) and
  9934. MatchInstruction(hp2,A_MOV,[]) and
  9935. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9936. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9937. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9938. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9939. {$ifdef i386}
  9940. { not all registers have byte size sub registers on i386 }
  9941. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9942. {$endif i386}
  9943. (((taicpu(hp1).ops=2) and
  9944. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9945. ((taicpu(hp1).ops=1) and
  9946. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9947. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9948. begin
  9949. { change movsX/movzX reg/ref, reg2
  9950. add/sub/or/... reg3/$const, reg2
  9951. mov reg2 reg/ref
  9952. to add/sub/or/... reg3/$const, reg/ref }
  9953. { by example:
  9954. movswl %si,%eax movswl %si,%eax p
  9955. decl %eax addl %edx,%eax hp1
  9956. movw %ax,%si movw %ax,%si hp2
  9957. ->
  9958. movswl %si,%eax movswl %si,%eax p
  9959. decw %eax addw %edx,%eax hp1
  9960. movw %ax,%si movw %ax,%si hp2
  9961. }
  9962. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9963. {
  9964. ->
  9965. movswl %si,%eax movswl %si,%eax p
  9966. decw %si addw %dx,%si hp1
  9967. movw %ax,%si movw %ax,%si hp2
  9968. }
  9969. case taicpu(hp1).ops of
  9970. 1:
  9971. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9972. 2:
  9973. begin
  9974. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9975. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9976. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9977. end;
  9978. else
  9979. internalerror(2008042702);
  9980. end;
  9981. {
  9982. ->
  9983. decw %si addw %dx,%si p
  9984. }
  9985. DebugMsg(SPeepholeOptimization + 'var3',p);
  9986. RemoveCurrentP(p, hp1);
  9987. RemoveInstruction(hp2);
  9988. Result := True;
  9989. Exit;
  9990. end;
  9991. if reg_and_hp1_is_instr and
  9992. (taicpu(hp1).opcode = A_MOV) and
  9993. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9994. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9995. {$ifdef x86_64}
  9996. { check for implicit extension to 64 bit }
  9997. or
  9998. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9999. (taicpu(hp1).opsize=S_Q) and
  10000. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10001. )
  10002. {$endif x86_64}
  10003. )
  10004. then
  10005. begin
  10006. { change
  10007. movx %reg1,%reg2
  10008. mov %reg2,%reg3
  10009. dealloc %reg2
  10010. into
  10011. movx %reg,%reg3
  10012. }
  10013. TransferUsedRegs(TmpUsedRegs);
  10014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10015. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10016. begin
  10017. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10018. {$ifdef x86_64}
  10019. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10020. (taicpu(hp1).opsize=S_Q) then
  10021. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10022. else
  10023. {$endif x86_64}
  10024. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10025. RemoveInstruction(hp1);
  10026. Result := True;
  10027. Exit;
  10028. end;
  10029. end;
  10030. if reg_and_hp1_is_instr and
  10031. ((taicpu(hp1).opcode=A_MOV) or
  10032. (taicpu(hp1).opcode=A_ADD) or
  10033. (taicpu(hp1).opcode=A_SUB) or
  10034. (taicpu(hp1).opcode=A_CMP) or
  10035. (taicpu(hp1).opcode=A_OR) or
  10036. (taicpu(hp1).opcode=A_XOR) or
  10037. (taicpu(hp1).opcode=A_AND)
  10038. ) and
  10039. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10040. begin
  10041. AndTest := (taicpu(hp1).opcode=A_AND) and
  10042. GetNextInstruction(hp1, hp2) and
  10043. (hp2.typ = ait_instruction) and
  10044. (
  10045. (
  10046. (taicpu(hp2).opcode=A_TEST) and
  10047. (
  10048. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10049. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10050. (
  10051. { If the AND and TEST instructions share a constant, this is also valid }
  10052. (taicpu(hp1).oper[0]^.typ = top_const) and
  10053. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10054. )
  10055. ) and
  10056. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10057. ) or
  10058. (
  10059. (taicpu(hp2).opcode=A_CMP) and
  10060. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10061. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10062. )
  10063. );
  10064. { change
  10065. movx (oper),%reg2
  10066. and $x,%reg2
  10067. test %reg2,%reg2
  10068. dealloc %reg2
  10069. into
  10070. op %reg1,%reg3
  10071. if the second op accesses only the bits stored in reg1
  10072. }
  10073. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10074. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10075. (taicpu(hp1).oper[0]^.typ = top_const) and
  10076. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10077. AndTest then
  10078. begin
  10079. { Check if the AND constant is in range }
  10080. case taicpu(p).opsize of
  10081. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10082. begin
  10083. NewSize := S_B;
  10084. Limit := $FF;
  10085. end;
  10086. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10087. begin
  10088. NewSize := S_W;
  10089. Limit := $FFFF;
  10090. end;
  10091. {$ifdef x86_64}
  10092. S_LQ:
  10093. begin
  10094. NewSize := S_L;
  10095. Limit := $FFFFFFFF;
  10096. end;
  10097. {$endif x86_64}
  10098. else
  10099. InternalError(2021120303);
  10100. end;
  10101. if (
  10102. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10103. { Check for negative operands }
  10104. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10105. ) and
  10106. GetNextInstruction(hp2,hp3) and
  10107. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10108. (taicpu(hp3).condition in [C_E,C_NE]) then
  10109. begin
  10110. TransferUsedRegs(TmpUsedRegs);
  10111. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10113. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10114. begin
  10115. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10116. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10117. taicpu(hp1).opcode := A_TEST;
  10118. taicpu(hp1).opsize := NewSize;
  10119. RemoveInstruction(hp2);
  10120. RemoveCurrentP(p, hp1);
  10121. Result:=true;
  10122. exit;
  10123. end;
  10124. end;
  10125. end;
  10126. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10127. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10128. (taicpu(hp1).opsize=S_B)) or
  10129. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10130. (taicpu(hp1).opsize=S_W))
  10131. {$ifdef x86_64}
  10132. or ((taicpu(p).opsize=S_LQ) and
  10133. (taicpu(hp1).opsize=S_L))
  10134. {$endif x86_64}
  10135. ) and
  10136. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10137. begin
  10138. { change
  10139. movx %reg1,%reg2
  10140. op %reg2,%reg3
  10141. dealloc %reg2
  10142. into
  10143. op %reg1,%reg3
  10144. if the second op accesses only the bits stored in reg1
  10145. }
  10146. TransferUsedRegs(TmpUsedRegs);
  10147. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10148. if AndTest then
  10149. begin
  10150. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10151. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10152. end
  10153. else
  10154. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10155. if not RegUsed then
  10156. begin
  10157. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10158. if taicpu(p).oper[0]^.typ=top_reg then
  10159. begin
  10160. case taicpu(hp1).opsize of
  10161. S_B:
  10162. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10163. S_W:
  10164. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10165. S_L:
  10166. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10167. else
  10168. Internalerror(2020102301);
  10169. end;
  10170. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10171. end
  10172. else
  10173. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10174. RemoveCurrentP(p);
  10175. if AndTest then
  10176. RemoveInstruction(hp2);
  10177. result:=true;
  10178. exit;
  10179. end;
  10180. end
  10181. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10182. (
  10183. { Bitwise operations only }
  10184. (taicpu(hp1).opcode=A_AND) or
  10185. (taicpu(hp1).opcode=A_TEST) or
  10186. (
  10187. (taicpu(hp1).oper[0]^.typ = top_const) and
  10188. (
  10189. (taicpu(hp1).opcode=A_OR) or
  10190. (taicpu(hp1).opcode=A_XOR)
  10191. )
  10192. )
  10193. ) and
  10194. (
  10195. (taicpu(hp1).oper[0]^.typ = top_const) or
  10196. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10197. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10198. ) then
  10199. begin
  10200. { change
  10201. movx %reg2,%reg2
  10202. op const,%reg2
  10203. into
  10204. op const,%reg2 (smaller version)
  10205. movx %reg2,%reg2
  10206. also change
  10207. movx %reg1,%reg2
  10208. and/test (oper),%reg2
  10209. dealloc %reg2
  10210. into
  10211. and/test (oper),%reg1
  10212. }
  10213. case taicpu(p).opsize of
  10214. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10215. begin
  10216. NewSize := S_B;
  10217. NewRegSize := R_SUBL;
  10218. Limit := $FF;
  10219. end;
  10220. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10221. begin
  10222. NewSize := S_W;
  10223. NewRegSize := R_SUBW;
  10224. Limit := $FFFF;
  10225. end;
  10226. {$ifdef x86_64}
  10227. S_LQ:
  10228. begin
  10229. NewSize := S_L;
  10230. NewRegSize := R_SUBD;
  10231. Limit := $FFFFFFFF;
  10232. end;
  10233. {$endif x86_64}
  10234. else
  10235. Internalerror(2021120302);
  10236. end;
  10237. TransferUsedRegs(TmpUsedRegs);
  10238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10239. if AndTest then
  10240. begin
  10241. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10242. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10243. end
  10244. else
  10245. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10246. if
  10247. (
  10248. (taicpu(p).opcode = A_MOVZX) and
  10249. (
  10250. (taicpu(hp1).opcode=A_AND) or
  10251. (taicpu(hp1).opcode=A_TEST)
  10252. ) and
  10253. not (
  10254. { If both are references, then the final instruction will have
  10255. both operands as references, which is not allowed }
  10256. (taicpu(p).oper[0]^.typ = top_ref) and
  10257. (taicpu(hp1).oper[0]^.typ = top_ref)
  10258. ) and
  10259. not RegUsed
  10260. ) or
  10261. (
  10262. (
  10263. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10264. not RegUsed
  10265. ) and
  10266. (taicpu(p).oper[0]^.typ = top_reg) and
  10267. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10268. (taicpu(hp1).oper[0]^.typ = top_const) and
  10269. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10270. ) then
  10271. begin
  10272. {$if defined(i386) or defined(i8086)}
  10273. { If the target size is 8-bit, make sure we can actually encode it }
  10274. 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
  10275. Exit;
  10276. {$endif i386 or i8086}
  10277. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10278. taicpu(hp1).opsize := NewSize;
  10279. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10280. if AndTest then
  10281. begin
  10282. RemoveInstruction(hp2);
  10283. if not RegUsed then
  10284. begin
  10285. taicpu(hp1).opcode := A_TEST;
  10286. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10287. begin
  10288. { Make sure the reference is the second operand }
  10289. SwapOper := taicpu(hp1).oper[0];
  10290. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10291. taicpu(hp1).oper[1] := SwapOper;
  10292. end;
  10293. end;
  10294. end;
  10295. case taicpu(hp1).oper[0]^.typ of
  10296. top_reg:
  10297. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10298. top_const:
  10299. { For the AND/TEST case }
  10300. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10301. else
  10302. ;
  10303. end;
  10304. if RegUsed then
  10305. begin
  10306. AsmL.Remove(p);
  10307. AsmL.InsertAfter(p, hp1);
  10308. p := hp1;
  10309. end
  10310. else
  10311. RemoveCurrentP(p, hp1);
  10312. result:=true;
  10313. exit;
  10314. end;
  10315. end;
  10316. end;
  10317. if reg_and_hp1_is_instr and
  10318. (taicpu(p).oper[0]^.typ = top_reg) and
  10319. (
  10320. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10321. ) and
  10322. (taicpu(hp1).oper[0]^.typ = top_const) and
  10323. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10324. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10325. { Minimum shift value allowed is the bit difference between the sizes }
  10326. (taicpu(hp1).oper[0]^.val >=
  10327. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10328. 8 * (
  10329. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10330. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10331. )
  10332. ) then
  10333. begin
  10334. { For:
  10335. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10336. shl/sal ##, %reg1
  10337. Remove the movsx/movzx instruction if the shift overwrites the
  10338. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10339. }
  10340. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10341. RemoveCurrentP(p, hp1);
  10342. Result := True;
  10343. Exit;
  10344. end
  10345. else if reg_and_hp1_is_instr and
  10346. (taicpu(p).oper[0]^.typ = top_reg) and
  10347. (
  10348. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10349. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10350. ) and
  10351. (taicpu(hp1).oper[0]^.typ = top_const) and
  10352. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10353. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10354. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10355. (taicpu(hp1).oper[0]^.val <
  10356. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10357. 8 * (
  10358. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10359. )
  10360. ) then
  10361. begin
  10362. { For:
  10363. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10364. sar ##, %reg1 shr ##, %reg1
  10365. Move the shift to before the movx instruction if the shift value
  10366. is not too large.
  10367. }
  10368. asml.Remove(hp1);
  10369. asml.InsertBefore(hp1, p);
  10370. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10371. case taicpu(p).opsize of
  10372. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10373. taicpu(hp1).opsize := S_B;
  10374. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10375. taicpu(hp1).opsize := S_W;
  10376. {$ifdef x86_64}
  10377. S_LQ:
  10378. taicpu(hp1).opsize := S_L;
  10379. {$endif}
  10380. else
  10381. InternalError(2020112401);
  10382. end;
  10383. if (taicpu(hp1).opcode = A_SHR) then
  10384. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10385. else
  10386. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10387. Result := True;
  10388. end;
  10389. if reg_and_hp1_is_instr and
  10390. (taicpu(p).oper[0]^.typ = top_reg) and
  10391. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10392. (
  10393. (taicpu(hp1).opcode = taicpu(p).opcode)
  10394. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10395. {$ifdef x86_64}
  10396. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10397. {$endif x86_64}
  10398. ) then
  10399. begin
  10400. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10401. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10402. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10403. begin
  10404. {
  10405. For example:
  10406. movzbw %al,%ax
  10407. movzwl %ax,%eax
  10408. Compress into:
  10409. movzbl %al,%eax
  10410. }
  10411. RegUsed := False;
  10412. case taicpu(p).opsize of
  10413. S_BW:
  10414. case taicpu(hp1).opsize of
  10415. S_WL:
  10416. begin
  10417. taicpu(p).opsize := S_BL;
  10418. RegUsed := True;
  10419. end;
  10420. {$ifdef x86_64}
  10421. S_WQ:
  10422. begin
  10423. if taicpu(p).opcode = A_MOVZX then
  10424. begin
  10425. taicpu(p).opsize := S_BL;
  10426. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10427. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10428. end
  10429. else
  10430. taicpu(p).opsize := S_BQ;
  10431. RegUsed := True;
  10432. end;
  10433. {$endif x86_64}
  10434. else
  10435. ;
  10436. end;
  10437. {$ifdef x86_64}
  10438. S_BL:
  10439. case taicpu(hp1).opsize of
  10440. S_LQ:
  10441. begin
  10442. if taicpu(p).opcode = A_MOVZX then
  10443. begin
  10444. taicpu(p).opsize := S_BL;
  10445. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10446. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10447. end
  10448. else
  10449. taicpu(p).opsize := S_BQ;
  10450. RegUsed := True;
  10451. end;
  10452. else
  10453. ;
  10454. end;
  10455. S_WL:
  10456. case taicpu(hp1).opsize of
  10457. S_LQ:
  10458. begin
  10459. if taicpu(p).opcode = A_MOVZX then
  10460. begin
  10461. taicpu(p).opsize := S_WL;
  10462. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10463. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10464. end
  10465. else
  10466. taicpu(p).opsize := S_WQ;
  10467. RegUsed := True;
  10468. end;
  10469. else
  10470. ;
  10471. end;
  10472. {$endif x86_64}
  10473. else
  10474. ;
  10475. end;
  10476. if RegUsed then
  10477. begin
  10478. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10479. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10480. RemoveInstruction(hp1);
  10481. Result := True;
  10482. Exit;
  10483. end;
  10484. end;
  10485. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10486. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10487. GetNextInstruction(hp1, hp2) and
  10488. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10489. (
  10490. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10491. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10492. {$ifdef x86_64}
  10493. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10494. {$endif x86_64}
  10495. ) and
  10496. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10497. (
  10498. (
  10499. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10500. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10501. ) or
  10502. (
  10503. { Only allow the operands in reverse order for TEST instructions }
  10504. (taicpu(hp2).opcode = A_TEST) and
  10505. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10506. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10507. )
  10508. ) then
  10509. begin
  10510. {
  10511. For example:
  10512. movzbl %al,%eax
  10513. movzbl (ref),%edx
  10514. andl %edx,%eax
  10515. (%edx deallocated)
  10516. Change to:
  10517. andb (ref),%al
  10518. movzbl %al,%eax
  10519. Rules are:
  10520. - First two instructions have the same opcode and opsize
  10521. - First instruction's operands are the same super-register
  10522. - Second instruction operates on a different register
  10523. - Third instruction is AND, OR, XOR or TEST
  10524. - Third instruction's operands are the destination registers of the first two instructions
  10525. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10526. - Second instruction's destination register is deallocated afterwards
  10527. }
  10528. TransferUsedRegs(TmpUsedRegs);
  10529. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10530. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10531. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10532. begin
  10533. case taicpu(p).opsize of
  10534. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10535. NewSize := S_B;
  10536. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10537. NewSize := S_W;
  10538. {$ifdef x86_64}
  10539. S_LQ:
  10540. NewSize := S_L;
  10541. {$endif x86_64}
  10542. else
  10543. InternalError(2021120301);
  10544. end;
  10545. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10546. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10547. taicpu(hp2).opsize := NewSize;
  10548. RemoveInstruction(hp1);
  10549. { With TEST, it's best to keep the MOVX instruction at the top }
  10550. if (taicpu(hp2).opcode <> A_TEST) then
  10551. begin
  10552. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10553. asml.Remove(p);
  10554. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10555. asml.InsertAfter(p, hp2);
  10556. p := hp2;
  10557. end
  10558. else
  10559. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10560. Result := True;
  10561. Exit;
  10562. end;
  10563. end;
  10564. end;
  10565. if taicpu(p).opcode=A_MOVZX then
  10566. begin
  10567. { removes superfluous And's after movzx's }
  10568. if reg_and_hp1_is_instr and
  10569. (taicpu(hp1).opcode = A_AND) and
  10570. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10571. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10572. {$ifdef x86_64}
  10573. { check for implicit extension to 64 bit }
  10574. or
  10575. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10576. (taicpu(hp1).opsize=S_Q) and
  10577. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10578. )
  10579. {$endif x86_64}
  10580. )
  10581. then
  10582. begin
  10583. case taicpu(p).opsize Of
  10584. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10585. if (taicpu(hp1).oper[0]^.val = $ff) then
  10586. begin
  10587. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10588. RemoveInstruction(hp1);
  10589. Result:=true;
  10590. exit;
  10591. end;
  10592. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10593. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10594. begin
  10595. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10596. RemoveInstruction(hp1);
  10597. Result:=true;
  10598. exit;
  10599. end;
  10600. {$ifdef x86_64}
  10601. S_LQ:
  10602. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10603. begin
  10604. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10605. RemoveInstruction(hp1);
  10606. Result:=true;
  10607. exit;
  10608. end;
  10609. {$endif x86_64}
  10610. else
  10611. ;
  10612. end;
  10613. { we cannot get rid of the and, but can we get rid of the movz ?}
  10614. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10615. begin
  10616. case taicpu(p).opsize Of
  10617. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10618. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10619. begin
  10620. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10621. RemoveCurrentP(p,hp1);
  10622. Result:=true;
  10623. exit;
  10624. end;
  10625. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10626. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10627. begin
  10628. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10629. RemoveCurrentP(p,hp1);
  10630. Result:=true;
  10631. exit;
  10632. end;
  10633. {$ifdef x86_64}
  10634. S_LQ:
  10635. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10636. begin
  10637. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10638. RemoveCurrentP(p,hp1);
  10639. Result:=true;
  10640. exit;
  10641. end;
  10642. {$endif x86_64}
  10643. else
  10644. ;
  10645. end;
  10646. end;
  10647. end;
  10648. { changes some movzx constructs to faster synonyms (all examples
  10649. are given with eax/ax, but are also valid for other registers)}
  10650. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10651. begin
  10652. case taicpu(p).opsize of
  10653. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10654. (the machine code is equivalent to movzbl %al,%eax), but the
  10655. code generator still generates that assembler instruction and
  10656. it is silently converted. This should probably be checked.
  10657. [Kit] }
  10658. S_BW:
  10659. begin
  10660. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10661. (
  10662. not IsMOVZXAcceptable
  10663. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10664. or (
  10665. (cs_opt_size in current_settings.optimizerswitches) and
  10666. (taicpu(p).oper[1]^.reg = NR_AX)
  10667. )
  10668. ) then
  10669. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10670. begin
  10671. DebugMsg(SPeepholeOptimization + 'var7',p);
  10672. taicpu(p).opcode := A_AND;
  10673. taicpu(p).changeopsize(S_W);
  10674. taicpu(p).loadConst(0,$ff);
  10675. Result := True;
  10676. end
  10677. else if not IsMOVZXAcceptable and
  10678. GetNextInstruction(p, hp1) and
  10679. (tai(hp1).typ = ait_instruction) and
  10680. (taicpu(hp1).opcode = A_AND) and
  10681. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10682. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10683. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10684. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10685. begin
  10686. DebugMsg(SPeepholeOptimization + 'var8',p);
  10687. taicpu(p).opcode := A_MOV;
  10688. taicpu(p).changeopsize(S_W);
  10689. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10690. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10691. Result := True;
  10692. end;
  10693. end;
  10694. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10695. S_BL:
  10696. begin
  10697. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10698. (
  10699. not IsMOVZXAcceptable
  10700. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10701. or (
  10702. (cs_opt_size in current_settings.optimizerswitches) and
  10703. (taicpu(p).oper[1]^.reg = NR_EAX)
  10704. )
  10705. ) then
  10706. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10707. begin
  10708. DebugMsg(SPeepholeOptimization + 'var9',p);
  10709. taicpu(p).opcode := A_AND;
  10710. taicpu(p).changeopsize(S_L);
  10711. taicpu(p).loadConst(0,$ff);
  10712. Result := True;
  10713. end
  10714. else if not IsMOVZXAcceptable and
  10715. GetNextInstruction(p, hp1) and
  10716. (tai(hp1).typ = ait_instruction) and
  10717. (taicpu(hp1).opcode = A_AND) and
  10718. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10719. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10720. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10721. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10722. begin
  10723. DebugMsg(SPeepholeOptimization + 'var10',p);
  10724. taicpu(p).opcode := A_MOV;
  10725. taicpu(p).changeopsize(S_L);
  10726. { do not use R_SUBWHOLE
  10727. as movl %rdx,%eax
  10728. is invalid in assembler PM }
  10729. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10730. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10731. Result := True;
  10732. end;
  10733. end;
  10734. {$endif i8086}
  10735. S_WL:
  10736. if not IsMOVZXAcceptable then
  10737. begin
  10738. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10739. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10740. begin
  10741. DebugMsg(SPeepholeOptimization + 'var11',p);
  10742. taicpu(p).opcode := A_AND;
  10743. taicpu(p).changeopsize(S_L);
  10744. taicpu(p).loadConst(0,$ffff);
  10745. Result := True;
  10746. end
  10747. else if GetNextInstruction(p, hp1) and
  10748. (tai(hp1).typ = ait_instruction) and
  10749. (taicpu(hp1).opcode = A_AND) and
  10750. (taicpu(hp1).oper[0]^.typ = top_const) and
  10751. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10752. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10753. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10754. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10755. begin
  10756. DebugMsg(SPeepholeOptimization + 'var12',p);
  10757. taicpu(p).opcode := A_MOV;
  10758. taicpu(p).changeopsize(S_L);
  10759. { do not use R_SUBWHOLE
  10760. as movl %rdx,%eax
  10761. is invalid in assembler PM }
  10762. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10763. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10764. Result := True;
  10765. end;
  10766. end;
  10767. else
  10768. InternalError(2017050705);
  10769. end;
  10770. end
  10771. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10772. begin
  10773. if GetNextInstruction(p, hp1) and
  10774. (tai(hp1).typ = ait_instruction) and
  10775. (taicpu(hp1).opcode = A_AND) and
  10776. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10777. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10778. begin
  10779. //taicpu(p).opcode := A_MOV;
  10780. case taicpu(p).opsize Of
  10781. S_BL:
  10782. begin
  10783. DebugMsg(SPeepholeOptimization + 'var13',p);
  10784. taicpu(hp1).changeopsize(S_L);
  10785. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10786. end;
  10787. S_WL:
  10788. begin
  10789. DebugMsg(SPeepholeOptimization + 'var14',p);
  10790. taicpu(hp1).changeopsize(S_L);
  10791. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10792. end;
  10793. S_BW:
  10794. begin
  10795. DebugMsg(SPeepholeOptimization + 'var15',p);
  10796. taicpu(hp1).changeopsize(S_W);
  10797. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10798. end;
  10799. else
  10800. Internalerror(2017050704)
  10801. end;
  10802. Result := True;
  10803. end;
  10804. end;
  10805. end;
  10806. end;
  10807. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10808. var
  10809. hp1, hp2 : tai;
  10810. MaskLength : Cardinal;
  10811. MaskedBits : TCgInt;
  10812. ActiveReg : TRegister;
  10813. begin
  10814. Result:=false;
  10815. { There are no optimisations for reference targets }
  10816. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10817. Exit;
  10818. while GetNextInstruction(p, hp1) and
  10819. (hp1.typ = ait_instruction) do
  10820. begin
  10821. if (taicpu(p).oper[0]^.typ = top_const) then
  10822. begin
  10823. case taicpu(hp1).opcode of
  10824. A_AND:
  10825. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10826. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10827. { the second register must contain the first one, so compare their subreg types }
  10828. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10829. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10830. { change
  10831. and const1, reg
  10832. and const2, reg
  10833. to
  10834. and (const1 and const2), reg
  10835. }
  10836. begin
  10837. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10838. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10839. RemoveCurrentP(p, hp1);
  10840. Result:=true;
  10841. exit;
  10842. end;
  10843. A_CMP:
  10844. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10845. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10846. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10847. { Just check that the condition on the next instruction is compatible }
  10848. GetNextInstruction(hp1, hp2) and
  10849. (hp2.typ = ait_instruction) and
  10850. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10851. then
  10852. { change
  10853. and 2^n, reg
  10854. cmp 2^n, reg
  10855. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10856. to
  10857. and 2^n, reg
  10858. test reg, reg
  10859. j(~c) / set(~c) / cmov(~c)
  10860. }
  10861. begin
  10862. { Keep TEST instruction in, rather than remove it, because
  10863. it may trigger other optimisations such as MovAndTest2Test }
  10864. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10865. taicpu(hp1).opcode := A_TEST;
  10866. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10867. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10868. Result := True;
  10869. Exit;
  10870. end;
  10871. A_MOVZX:
  10872. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10873. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10874. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10875. (
  10876. (
  10877. (taicpu(p).opsize=S_W) and
  10878. (taicpu(hp1).opsize=S_BW)
  10879. ) or
  10880. (
  10881. (taicpu(p).opsize=S_L) and
  10882. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10883. )
  10884. {$ifdef x86_64}
  10885. or
  10886. (
  10887. (taicpu(p).opsize=S_Q) and
  10888. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10889. )
  10890. {$endif x86_64}
  10891. ) then
  10892. begin
  10893. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10894. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10895. ) or
  10896. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10897. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10898. then
  10899. begin
  10900. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10901. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10902. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10903. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10904. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10905. }
  10906. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10907. RemoveInstruction(hp1);
  10908. { See if there are other optimisations possible }
  10909. Continue;
  10910. end;
  10911. end;
  10912. A_SHL:
  10913. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10914. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10915. begin
  10916. {$ifopt R+}
  10917. {$define RANGE_WAS_ON}
  10918. {$R-}
  10919. {$endif}
  10920. { get length of potential and mask }
  10921. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10922. { really a mask? }
  10923. {$ifdef RANGE_WAS_ON}
  10924. {$R+}
  10925. {$endif}
  10926. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10927. { unmasked part shifted out? }
  10928. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10929. begin
  10930. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10931. RemoveCurrentP(p, hp1);
  10932. Result:=true;
  10933. exit;
  10934. end;
  10935. end;
  10936. A_SHR:
  10937. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10938. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10939. (taicpu(hp1).oper[0]^.val <= 63) then
  10940. begin
  10941. { Does SHR combined with the AND cover all the bits?
  10942. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10943. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10944. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10945. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10946. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10947. begin
  10948. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10949. RemoveCurrentP(p, hp1);
  10950. Result := True;
  10951. Exit;
  10952. end;
  10953. end;
  10954. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10955. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10956. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10957. begin
  10958. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10959. (
  10960. (
  10961. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10962. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10963. ) or (
  10964. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10965. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10966. {$ifdef x86_64}
  10967. ) or (
  10968. (taicpu(hp1).opsize = S_LQ) and
  10969. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10970. {$endif x86_64}
  10971. )
  10972. ) then
  10973. begin
  10974. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10975. begin
  10976. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10977. RemoveInstruction(hp1);
  10978. { See if there are other optimisations possible }
  10979. Continue;
  10980. end;
  10981. { The super-registers are the same though.
  10982. Note that this change by itself doesn't improve
  10983. code speed, but it opens up other optimisations. }
  10984. {$ifdef x86_64}
  10985. { Convert 64-bit register to 32-bit }
  10986. case taicpu(hp1).opsize of
  10987. S_BQ:
  10988. begin
  10989. taicpu(hp1).opsize := S_BL;
  10990. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10991. end;
  10992. S_WQ:
  10993. begin
  10994. taicpu(hp1).opsize := S_WL;
  10995. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10996. end
  10997. else
  10998. ;
  10999. end;
  11000. {$endif x86_64}
  11001. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11002. taicpu(hp1).opcode := A_MOVZX;
  11003. { See if there are other optimisations possible }
  11004. Continue;
  11005. end;
  11006. end;
  11007. else
  11008. ;
  11009. end;
  11010. end
  11011. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11012. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11013. begin
  11014. {$ifdef x86_64}
  11015. if (taicpu(p).opsize = S_Q) then
  11016. begin
  11017. { Never necessary }
  11018. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11019. RemoveCurrentP(p, hp1);
  11020. Result := True;
  11021. Exit;
  11022. end;
  11023. {$endif x86_64}
  11024. { Forward check to determine necessity of and %reg,%reg }
  11025. TransferUsedRegs(TmpUsedRegs);
  11026. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11027. { Saves on a bunch of dereferences }
  11028. ActiveReg := taicpu(p).oper[1]^.reg;
  11029. case taicpu(hp1).opcode of
  11030. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11031. if (
  11032. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11033. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11034. ) and
  11035. (
  11036. (taicpu(hp1).opcode <> A_MOV) or
  11037. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11038. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11039. ) and
  11040. not (
  11041. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11042. (taicpu(hp1).opcode = A_MOV) and
  11043. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11044. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11045. ) and
  11046. (
  11047. (
  11048. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11049. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11050. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11051. ) or
  11052. (
  11053. {$ifdef x86_64}
  11054. (
  11055. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11056. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11057. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11058. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11059. ) and
  11060. {$endif x86_64}
  11061. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11062. )
  11063. ) then
  11064. begin
  11065. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11066. RemoveCurrentP(p, hp1);
  11067. Result := True;
  11068. Exit;
  11069. end;
  11070. A_ADD,
  11071. A_AND,
  11072. A_BSF,
  11073. A_BSR,
  11074. A_BTC,
  11075. A_BTR,
  11076. A_BTS,
  11077. A_OR,
  11078. A_SUB,
  11079. A_XOR:
  11080. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11081. if (
  11082. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11083. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11084. ) and
  11085. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11086. begin
  11087. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11088. RemoveCurrentP(p, hp1);
  11089. Result := True;
  11090. Exit;
  11091. end;
  11092. A_CMP,
  11093. A_TEST:
  11094. if (
  11095. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11096. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11097. ) and
  11098. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11099. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11100. begin
  11101. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11102. RemoveCurrentP(p, hp1);
  11103. Result := True;
  11104. Exit;
  11105. end;
  11106. A_BSWAP,
  11107. A_NEG,
  11108. A_NOT:
  11109. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11110. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11111. begin
  11112. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11113. RemoveCurrentP(p, hp1);
  11114. Result := True;
  11115. Exit;
  11116. end;
  11117. else
  11118. ;
  11119. end;
  11120. end;
  11121. if (taicpu(hp1).is_jmp) and
  11122. (taicpu(hp1).opcode<>A_JMP) and
  11123. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11124. begin
  11125. { change
  11126. and x, reg
  11127. jxx
  11128. to
  11129. test x, reg
  11130. jxx
  11131. if reg is deallocated before the
  11132. jump, but only if it's a conditional jump (PFV)
  11133. }
  11134. taicpu(p).opcode := A_TEST;
  11135. Exit;
  11136. end;
  11137. Break;
  11138. end;
  11139. { Lone AND tests }
  11140. if (taicpu(p).oper[0]^.typ = top_const) then
  11141. begin
  11142. {
  11143. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11144. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11145. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11146. }
  11147. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11148. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11149. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11150. begin
  11151. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11152. if taicpu(p).opsize = S_L then
  11153. begin
  11154. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11155. Result := True;
  11156. end;
  11157. end;
  11158. end;
  11159. { Backward check to determine necessity of and %reg,%reg }
  11160. if (taicpu(p).oper[0]^.typ = top_reg) and
  11161. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11162. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11163. GetLastInstruction(p, hp2) and
  11164. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11165. { Check size of adjacent instruction to determine if the AND is
  11166. effectively a null operation }
  11167. (
  11168. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11169. { Note: Don't include S_Q }
  11170. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11171. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11172. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11173. ) then
  11174. begin
  11175. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11176. { If GetNextInstruction returned False, hp1 will be nil }
  11177. RemoveCurrentP(p, hp1);
  11178. Result := True;
  11179. Exit;
  11180. end;
  11181. end;
  11182. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11183. var
  11184. hp1: tai; NewRef: TReference;
  11185. { This entire nested function is used in an if-statement below, but we
  11186. want to avoid all the used reg transfers and GetNextInstruction calls
  11187. until we really have to check }
  11188. function MemRegisterNotUsedLater: Boolean; inline;
  11189. var
  11190. hp2: tai;
  11191. begin
  11192. TransferUsedRegs(TmpUsedRegs);
  11193. hp2 := p;
  11194. repeat
  11195. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11196. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11197. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11198. end;
  11199. begin
  11200. Result := False;
  11201. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11202. Exit;
  11203. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11204. begin
  11205. { Change:
  11206. add %reg2,%reg1
  11207. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11208. To:
  11209. mov/s/z #(%reg1,%reg2),%reg1
  11210. }
  11211. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11212. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11213. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11214. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11215. (
  11216. (
  11217. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11218. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11219. { r/esp cannot be an index }
  11220. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11221. ) or (
  11222. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11223. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11224. )
  11225. ) and (
  11226. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11227. (
  11228. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11229. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11230. MemRegisterNotUsedLater
  11231. )
  11232. ) then
  11233. begin
  11234. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11235. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11236. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11237. RemoveCurrentp(p, hp1);
  11238. Result := True;
  11239. Exit;
  11240. end;
  11241. { Change:
  11242. addl/q $x,%reg1
  11243. movl/q %reg1,%reg2
  11244. To:
  11245. leal/q $x(%reg1),%reg2
  11246. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11247. Breaks the dependency chain.
  11248. }
  11249. if MatchOpType(taicpu(p),top_const,top_reg) and
  11250. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11251. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11252. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11253. (
  11254. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11255. not (cs_opt_size in current_settings.optimizerswitches) or
  11256. (
  11257. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11258. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11259. )
  11260. ) then
  11261. begin
  11262. { Change the MOV instruction to a LEA instruction, and update the
  11263. first operand }
  11264. reference_reset(NewRef, 1, []);
  11265. NewRef.base := taicpu(p).oper[1]^.reg;
  11266. NewRef.scalefactor := 1;
  11267. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11268. taicpu(hp1).opcode := A_LEA;
  11269. taicpu(hp1).loadref(0, NewRef);
  11270. TransferUsedRegs(TmpUsedRegs);
  11271. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11272. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11273. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11274. begin
  11275. { Move what is now the LEA instruction to before the SUB instruction }
  11276. Asml.Remove(hp1);
  11277. Asml.InsertBefore(hp1, p);
  11278. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11279. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11280. p := hp1;
  11281. end
  11282. else
  11283. begin
  11284. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11285. RemoveCurrentP(p, hp1);
  11286. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11287. end;
  11288. Result := True;
  11289. end;
  11290. end;
  11291. end;
  11292. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11293. var
  11294. SubReg: TSubRegister;
  11295. begin
  11296. Result:=false;
  11297. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11298. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11299. with taicpu(p).oper[0]^.ref^ do
  11300. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11301. begin
  11302. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11303. begin
  11304. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11305. taicpu(p).opcode := A_ADD;
  11306. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11307. Result := True;
  11308. end
  11309. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11310. begin
  11311. if (base <> NR_NO) then
  11312. begin
  11313. if (scalefactor <= 1) then
  11314. begin
  11315. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11316. taicpu(p).opcode := A_ADD;
  11317. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11318. Result := True;
  11319. end;
  11320. end
  11321. else
  11322. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11323. if (scalefactor in [2, 4, 8]) then
  11324. begin
  11325. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11326. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11327. taicpu(p).opcode := A_SHL;
  11328. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11329. Result := True;
  11330. end;
  11331. end;
  11332. end;
  11333. end;
  11334. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11335. var
  11336. hp1: tai; NewRef: TReference;
  11337. begin
  11338. { Change:
  11339. subl/q $x,%reg1
  11340. movl/q %reg1,%reg2
  11341. To:
  11342. leal/q $-x(%reg1),%reg2
  11343. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11344. Breaks the dependency chain and potentially permits the removal of
  11345. a CMP instruction if one follows.
  11346. }
  11347. Result := False;
  11348. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11349. MatchOpType(taicpu(p),top_const,top_reg) and
  11350. GetNextInstruction(p, hp1) and
  11351. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11352. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11353. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11354. (
  11355. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11356. not (cs_opt_size in current_settings.optimizerswitches) or
  11357. (
  11358. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11359. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11360. )
  11361. ) then
  11362. begin
  11363. { Change the MOV instruction to a LEA instruction, and update the
  11364. first operand }
  11365. reference_reset(NewRef, 1, []);
  11366. NewRef.base := taicpu(p).oper[1]^.reg;
  11367. NewRef.scalefactor := 1;
  11368. NewRef.offset := -taicpu(p).oper[0]^.val;
  11369. taicpu(hp1).opcode := A_LEA;
  11370. taicpu(hp1).loadref(0, NewRef);
  11371. TransferUsedRegs(TmpUsedRegs);
  11372. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11373. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11374. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11375. begin
  11376. { Move what is now the LEA instruction to before the SUB instruction }
  11377. Asml.Remove(hp1);
  11378. Asml.InsertBefore(hp1, p);
  11379. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11380. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11381. p := hp1;
  11382. end
  11383. else
  11384. begin
  11385. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11386. RemoveCurrentP(p, hp1);
  11387. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11388. end;
  11389. Result := True;
  11390. end;
  11391. end;
  11392. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11393. begin
  11394. { we can skip all instructions not messing with the stack pointer }
  11395. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11396. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11397. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11398. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11399. ({(taicpu(hp1).ops=0) or }
  11400. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11401. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11402. ) and }
  11403. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11404. )
  11405. ) do
  11406. GetNextInstruction(hp1,hp1);
  11407. Result:=assigned(hp1);
  11408. end;
  11409. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11410. var
  11411. hp1, hp2, hp3, hp4, hp5: tai;
  11412. begin
  11413. Result:=false;
  11414. hp5:=nil;
  11415. { replace
  11416. leal(q) x(<stackpointer>),<stackpointer>
  11417. call procname
  11418. leal(q) -x(<stackpointer>),<stackpointer>
  11419. ret
  11420. by
  11421. jmp procname
  11422. but do it only on level 4 because it destroys stack back traces
  11423. }
  11424. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11425. MatchOpType(taicpu(p),top_ref,top_reg) and
  11426. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11427. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11428. { the -8 or -24 are not required, but bail out early if possible,
  11429. higher values are unlikely }
  11430. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11431. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11432. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11433. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11434. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11435. GetNextInstruction(p, hp1) and
  11436. { Take a copy of hp1 }
  11437. SetAndTest(hp1, hp4) and
  11438. { trick to skip label }
  11439. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11440. SkipSimpleInstructions(hp1) and
  11441. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11442. GetNextInstruction(hp1, hp2) and
  11443. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11444. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11445. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11446. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11447. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11448. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11449. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11450. { Segment register will be NR_NO }
  11451. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11452. GetNextInstruction(hp2, hp3) and
  11453. { trick to skip label }
  11454. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11455. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11456. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11457. SetAndTest(hp3,hp5) and
  11458. GetNextInstruction(hp3,hp3) and
  11459. MatchInstruction(hp3,A_RET,[S_NO])
  11460. )
  11461. ) and
  11462. (taicpu(hp3).ops=0) then
  11463. begin
  11464. taicpu(hp1).opcode := A_JMP;
  11465. taicpu(hp1).is_jmp := true;
  11466. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11467. RemoveCurrentP(p, hp4);
  11468. RemoveInstruction(hp2);
  11469. RemoveInstruction(hp3);
  11470. if Assigned(hp5) then
  11471. begin
  11472. AsmL.Remove(hp5);
  11473. ASmL.InsertBefore(hp5,hp1)
  11474. end;
  11475. Result:=true;
  11476. end;
  11477. end;
  11478. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11479. {$ifdef x86_64}
  11480. var
  11481. hp1, hp2, hp3, hp4, hp5: tai;
  11482. {$endif x86_64}
  11483. begin
  11484. Result:=false;
  11485. {$ifdef x86_64}
  11486. hp5:=nil;
  11487. { replace
  11488. push %rax
  11489. call procname
  11490. pop %rcx
  11491. ret
  11492. by
  11493. jmp procname
  11494. but do it only on level 4 because it destroys stack back traces
  11495. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11496. for all supported calling conventions
  11497. }
  11498. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11499. MatchOpType(taicpu(p),top_reg) and
  11500. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11501. GetNextInstruction(p, hp1) and
  11502. { Take a copy of hp1 }
  11503. SetAndTest(hp1, hp4) and
  11504. { trick to skip label }
  11505. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11506. SkipSimpleInstructions(hp1) and
  11507. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11508. GetNextInstruction(hp1, hp2) and
  11509. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11510. MatchOpType(taicpu(hp2),top_reg) and
  11511. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11512. GetNextInstruction(hp2, hp3) and
  11513. { trick to skip label }
  11514. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11515. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11516. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11517. SetAndTest(hp3,hp5) and
  11518. GetNextInstruction(hp3,hp3) and
  11519. MatchInstruction(hp3,A_RET,[S_NO])
  11520. )
  11521. ) and
  11522. (taicpu(hp3).ops=0) then
  11523. begin
  11524. taicpu(hp1).opcode := A_JMP;
  11525. taicpu(hp1).is_jmp := true;
  11526. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11527. RemoveCurrentP(p, hp4);
  11528. RemoveInstruction(hp2);
  11529. RemoveInstruction(hp3);
  11530. if Assigned(hp5) then
  11531. begin
  11532. AsmL.Remove(hp5);
  11533. ASmL.InsertBefore(hp5,hp1)
  11534. end;
  11535. Result:=true;
  11536. end;
  11537. {$endif x86_64}
  11538. end;
  11539. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11540. var
  11541. Value, RegName: string;
  11542. begin
  11543. Result:=false;
  11544. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11545. begin
  11546. case taicpu(p).oper[0]^.val of
  11547. 0:
  11548. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11549. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11550. begin
  11551. { change "mov $0,%reg" into "xor %reg,%reg" }
  11552. taicpu(p).opcode := A_XOR;
  11553. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11554. Result := True;
  11555. {$ifdef x86_64}
  11556. end
  11557. else if (taicpu(p).opsize = S_Q) then
  11558. begin
  11559. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11560. { The actual optimization }
  11561. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11562. taicpu(p).changeopsize(S_L);
  11563. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11564. Result := True;
  11565. end;
  11566. $1..$FFFFFFFF:
  11567. begin
  11568. { Code size reduction by J. Gareth "Kit" Moreton }
  11569. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11570. case taicpu(p).opsize of
  11571. S_Q:
  11572. begin
  11573. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11574. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11575. { The actual optimization }
  11576. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11577. taicpu(p).changeopsize(S_L);
  11578. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11579. Result := True;
  11580. end;
  11581. else
  11582. { Do nothing };
  11583. end;
  11584. {$endif x86_64}
  11585. end;
  11586. -1:
  11587. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11588. if (cs_opt_size in current_settings.optimizerswitches) and
  11589. (taicpu(p).opsize <> S_B) and
  11590. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11591. begin
  11592. { change "mov $-1,%reg" into "or $-1,%reg" }
  11593. { NOTES:
  11594. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11595. - This operation creates a false dependency on the register, so only do it when optimising for size
  11596. - 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
  11597. }
  11598. taicpu(p).opcode := A_OR;
  11599. Result := True;
  11600. end;
  11601. else
  11602. { Do nothing };
  11603. end;
  11604. end;
  11605. end;
  11606. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11607. var
  11608. hp1: tai;
  11609. begin
  11610. { Detect:
  11611. andw x, %ax (0 <= x < $8000)
  11612. ...
  11613. movzwl %ax,%eax
  11614. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11615. }
  11616. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11617. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11618. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11619. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11620. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11621. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11622. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11623. begin
  11624. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11625. taicpu(hp1).opcode := A_CWDE;
  11626. taicpu(hp1).clearop(0);
  11627. taicpu(hp1).clearop(1);
  11628. taicpu(hp1).ops := 0;
  11629. { A change was made, but not with p, so move forward 1 }
  11630. p := tai(p.Next);
  11631. Result := True;
  11632. end;
  11633. end;
  11634. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11635. begin
  11636. Result := False;
  11637. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11638. Exit;
  11639. { Convert:
  11640. movswl %ax,%eax -> cwtl
  11641. movslq %eax,%rax -> cdqe
  11642. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11643. refer to the same opcode and depends only on the assembler's
  11644. current operand-size attribute. [Kit]
  11645. }
  11646. with taicpu(p) do
  11647. case opsize of
  11648. S_WL:
  11649. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11650. begin
  11651. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11652. opcode := A_CWDE;
  11653. clearop(0);
  11654. clearop(1);
  11655. ops := 0;
  11656. Result := True;
  11657. end;
  11658. {$ifdef x86_64}
  11659. S_LQ:
  11660. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11661. begin
  11662. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11663. opcode := A_CDQE;
  11664. clearop(0);
  11665. clearop(1);
  11666. ops := 0;
  11667. Result := True;
  11668. end;
  11669. {$endif x86_64}
  11670. else
  11671. ;
  11672. end;
  11673. end;
  11674. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11675. var
  11676. hp1: tai;
  11677. begin
  11678. { Detect:
  11679. shr x, %ax (x > 0)
  11680. ...
  11681. movzwl %ax,%eax
  11682. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11683. }
  11684. Result := False;
  11685. if MatchOpType(taicpu(p), top_const, top_reg) and
  11686. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11687. (taicpu(p).oper[0]^.val > 0) and
  11688. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11689. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11690. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11691. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11692. begin
  11693. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11694. taicpu(hp1).opcode := A_CWDE;
  11695. taicpu(hp1).clearop(0);
  11696. taicpu(hp1).clearop(1);
  11697. taicpu(hp1).ops := 0;
  11698. { A change was made, but not with p, so move forward 1 }
  11699. p := tai(p.Next);
  11700. Result := True;
  11701. end;
  11702. end;
  11703. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11704. var
  11705. hp1, hp2: tai;
  11706. Opposite, SecondOpposite: TAsmOp;
  11707. NewCond: TAsmCond;
  11708. begin
  11709. Result := False;
  11710. { Change:
  11711. add/sub 128,(dest)
  11712. To:
  11713. sub/add -128,(dest)
  11714. This generaally takes fewer bytes to encode because -128 can be stored
  11715. in a signed byte, whereas +128 cannot.
  11716. }
  11717. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11718. begin
  11719. if taicpu(p).opcode = A_ADD then
  11720. Opposite := A_SUB
  11721. else
  11722. Opposite := A_ADD;
  11723. { Be careful if the flags are in use, because the CF flag inverts
  11724. when changing from ADD to SUB and vice versa }
  11725. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11726. GetNextInstruction(p, hp1) then
  11727. begin
  11728. TransferUsedRegs(TmpUsedRegs);
  11729. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11730. hp2 := hp1;
  11731. { Scan ahead to check if everything's safe }
  11732. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11733. begin
  11734. if (hp1.typ <> ait_instruction) then
  11735. { Probably unsafe since the flags are still in use }
  11736. Exit;
  11737. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11738. { Stop searching at an unconditional jump }
  11739. Break;
  11740. if not
  11741. (
  11742. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11743. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11744. ) and
  11745. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11746. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11747. Exit;
  11748. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11749. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11750. { Move to the next instruction }
  11751. GetNextInstruction(hp1, hp1);
  11752. end;
  11753. while Assigned(hp2) and (hp2 <> hp1) do
  11754. begin
  11755. NewCond := C_None;
  11756. case taicpu(hp2).condition of
  11757. C_A, C_NBE:
  11758. NewCond := C_BE;
  11759. C_B, C_C, C_NAE:
  11760. NewCond := C_AE;
  11761. C_AE, C_NB, C_NC:
  11762. NewCond := C_B;
  11763. C_BE, C_NA:
  11764. NewCond := C_A;
  11765. else
  11766. { No change needed };
  11767. end;
  11768. if NewCond <> C_None then
  11769. begin
  11770. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11771. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11772. taicpu(hp2).condition := NewCond;
  11773. end
  11774. else
  11775. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11776. begin
  11777. { Because of the flipping of the carry bit, to ensure
  11778. the operation remains equivalent, ADC becomes SBB
  11779. and vice versa, and the constant is not-inverted.
  11780. If multiple ADCs or SBBs appear in a row, each one
  11781. changed causes the carry bit to invert, so they all
  11782. need to be flipped }
  11783. if taicpu(hp2).opcode = A_ADC then
  11784. SecondOpposite := A_SBB
  11785. else
  11786. SecondOpposite := A_ADC;
  11787. if taicpu(hp2).oper[0]^.typ <> top_const then
  11788. { Should have broken out of this optimisation already }
  11789. InternalError(2021112901);
  11790. 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]^) + ' -> ' +
  11791. 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);
  11792. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11793. taicpu(hp2).opcode := SecondOpposite;
  11794. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11795. end;
  11796. { Move to the next instruction }
  11797. GetNextInstruction(hp2, hp2);
  11798. end;
  11799. if (hp2 <> hp1) then
  11800. InternalError(2021111501);
  11801. end;
  11802. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11803. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11804. taicpu(p).opcode := Opposite;
  11805. taicpu(p).oper[0]^.val := -128;
  11806. { No further optimisations can be made on this instruction, so move
  11807. onto the next one to save time }
  11808. p := tai(p.Next);
  11809. UpdateUsedRegs(p);
  11810. Result := True;
  11811. Exit;
  11812. end;
  11813. { Detect:
  11814. add/sub %reg2,(dest)
  11815. add/sub x, (dest)
  11816. (dest can be a register or a reference)
  11817. Swap the instructions to minimise a pipeline stall. This reverses the
  11818. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11819. optimisations could be made.
  11820. }
  11821. if (taicpu(p).oper[0]^.typ = top_reg) and
  11822. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11823. (
  11824. (
  11825. (taicpu(p).oper[1]^.typ = top_reg) and
  11826. { We can try searching further ahead if we're writing to a register }
  11827. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11828. ) or
  11829. (
  11830. (taicpu(p).oper[1]^.typ = top_ref) and
  11831. GetNextInstruction(p, hp1)
  11832. )
  11833. ) and
  11834. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11835. (taicpu(hp1).oper[0]^.typ = top_const) and
  11836. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11837. begin
  11838. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11839. TransferUsedRegs(TmpUsedRegs);
  11840. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11841. hp2 := p;
  11842. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11843. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11844. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11845. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11846. begin
  11847. asml.remove(hp1);
  11848. asml.InsertBefore(hp1, p);
  11849. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11850. Result := True;
  11851. end;
  11852. end;
  11853. end;
  11854. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11855. begin
  11856. Result:=false;
  11857. { change "cmp $0, %reg" to "test %reg, %reg" }
  11858. if MatchOpType(taicpu(p),top_const,top_reg) and
  11859. (taicpu(p).oper[0]^.val = 0) then
  11860. begin
  11861. taicpu(p).opcode := A_TEST;
  11862. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11863. Result:=true;
  11864. end;
  11865. end;
  11866. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11867. var
  11868. IsTestConstX : Boolean;
  11869. hp1,hp2 : tai;
  11870. begin
  11871. Result:=false;
  11872. { removes the line marked with (x) from the sequence
  11873. and/or/xor/add/sub/... $x, %y
  11874. test/or %y, %y | test $-1, %y (x)
  11875. j(n)z _Label
  11876. as the first instruction already adjusts the ZF
  11877. %y operand may also be a reference }
  11878. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11879. MatchOperand(taicpu(p).oper[0]^,-1);
  11880. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11881. GetLastInstruction(p, hp1) and
  11882. (tai(hp1).typ = ait_instruction) and
  11883. GetNextInstruction(p,hp2) and
  11884. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11885. case taicpu(hp1).opcode Of
  11886. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11887. { These two instructions set the zero flag if the result is zero }
  11888. A_POPCNT, A_LZCNT:
  11889. begin
  11890. if (
  11891. { With POPCNT, an input of zero will set the zero flag
  11892. because the population count of zero is zero }
  11893. (taicpu(hp1).opcode = A_POPCNT) and
  11894. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11895. (
  11896. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11897. { Faster than going through the second half of the 'or'
  11898. condition below }
  11899. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11900. )
  11901. ) or (
  11902. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11903. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11904. { and in case of carry for A(E)/B(E)/C/NC }
  11905. (
  11906. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11907. (
  11908. (taicpu(hp1).opcode <> A_ADD) and
  11909. (taicpu(hp1).opcode <> A_SUB) and
  11910. (taicpu(hp1).opcode <> A_LZCNT)
  11911. )
  11912. )
  11913. ) then
  11914. begin
  11915. RemoveCurrentP(p, hp2);
  11916. Result:=true;
  11917. Exit;
  11918. end;
  11919. end;
  11920. A_SHL, A_SAL, A_SHR, A_SAR:
  11921. begin
  11922. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11923. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11924. { therefore, it's only safe to do this optimization for }
  11925. { shifts by a (nonzero) constant }
  11926. (taicpu(hp1).oper[0]^.typ = top_const) and
  11927. (taicpu(hp1).oper[0]^.val <> 0) and
  11928. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11929. { and in case of carry for A(E)/B(E)/C/NC }
  11930. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11931. begin
  11932. RemoveCurrentP(p, hp2);
  11933. Result:=true;
  11934. Exit;
  11935. end;
  11936. end;
  11937. A_DEC, A_INC, A_NEG:
  11938. begin
  11939. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11940. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11941. { and in case of carry for A(E)/B(E)/C/NC }
  11942. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11943. begin
  11944. RemoveCurrentP(p, hp2);
  11945. Result:=true;
  11946. Exit;
  11947. end;
  11948. end
  11949. else
  11950. ;
  11951. end; { case }
  11952. { change "test $-1,%reg" into "test %reg,%reg" }
  11953. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11954. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11955. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11956. if MatchInstruction(p, A_OR, []) and
  11957. { Can only match if they're both registers }
  11958. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11959. begin
  11960. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11961. taicpu(p).opcode := A_TEST;
  11962. { No need to set Result to True, as we've done all the optimisations we can }
  11963. end;
  11964. end;
  11965. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11966. var
  11967. hp1,hp3 : tai;
  11968. {$ifndef x86_64}
  11969. hp2 : taicpu;
  11970. {$endif x86_64}
  11971. begin
  11972. Result:=false;
  11973. hp3:=nil;
  11974. {$ifndef x86_64}
  11975. { don't do this on modern CPUs, this really hurts them due to
  11976. broken call/ret pairing }
  11977. if (current_settings.optimizecputype < cpu_Pentium2) and
  11978. not(cs_create_pic in current_settings.moduleswitches) and
  11979. GetNextInstruction(p, hp1) and
  11980. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11981. MatchOpType(taicpu(hp1),top_ref) and
  11982. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11983. begin
  11984. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11985. InsertLLItem(p.previous, p, hp2);
  11986. taicpu(p).opcode := A_JMP;
  11987. taicpu(p).is_jmp := true;
  11988. RemoveInstruction(hp1);
  11989. Result:=true;
  11990. end
  11991. else
  11992. {$endif x86_64}
  11993. { replace
  11994. call procname
  11995. ret
  11996. by
  11997. jmp procname
  11998. but do it only on level 4 because it destroys stack back traces
  11999. else if the subroutine is marked as no return, remove the ret
  12000. }
  12001. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12002. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12003. GetNextInstruction(p, hp1) and
  12004. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12005. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12006. SetAndTest(hp1,hp3) and
  12007. GetNextInstruction(hp1,hp1) and
  12008. MatchInstruction(hp1,A_RET,[S_NO])
  12009. )
  12010. ) and
  12011. (taicpu(hp1).ops=0) then
  12012. begin
  12013. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12014. { we might destroy stack alignment here if we do not do a call }
  12015. (target_info.stackalign<=sizeof(SizeUInt)) then
  12016. begin
  12017. taicpu(p).opcode := A_JMP;
  12018. taicpu(p).is_jmp := true;
  12019. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12020. end
  12021. else
  12022. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12023. RemoveInstruction(hp1);
  12024. if Assigned(hp3) then
  12025. begin
  12026. AsmL.Remove(hp3);
  12027. AsmL.InsertBefore(hp3,p)
  12028. end;
  12029. Result:=true;
  12030. end;
  12031. end;
  12032. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12033. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12034. begin
  12035. case OpSize of
  12036. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12037. Result := (Val <= $FF) and (Val >= -128);
  12038. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12039. Result := (Val <= $FFFF) and (Val >= -32768);
  12040. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12041. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12042. else
  12043. Result := True;
  12044. end;
  12045. end;
  12046. var
  12047. hp1, hp2 : tai;
  12048. SizeChange: Boolean;
  12049. PreMessage: string;
  12050. begin
  12051. Result := False;
  12052. if (taicpu(p).oper[0]^.typ = top_reg) and
  12053. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12054. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12055. begin
  12056. { Change (using movzbl %al,%eax as an example):
  12057. movzbl %al, %eax movzbl %al, %eax
  12058. cmpl x, %eax testl %eax,%eax
  12059. To:
  12060. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12061. movzbl %al, %eax movzbl %al, %eax
  12062. Smaller instruction and minimises pipeline stall as the CPU
  12063. doesn't have to wait for the register to get zero-extended. [Kit]
  12064. Also allow if the smaller of the two registers is being checked,
  12065. as this still removes the false dependency.
  12066. }
  12067. if
  12068. (
  12069. (
  12070. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12071. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12072. ) or (
  12073. { If MatchOperand returns True, they must both be registers }
  12074. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12075. )
  12076. ) and
  12077. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12078. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12079. begin
  12080. 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);
  12081. asml.Remove(hp1);
  12082. asml.InsertBefore(hp1, p);
  12083. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12084. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12085. begin
  12086. taicpu(hp1).opcode := A_TEST;
  12087. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12088. end;
  12089. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12090. case taicpu(p).opsize of
  12091. S_BW, S_BL:
  12092. begin
  12093. SizeChange := taicpu(hp1).opsize <> S_B;
  12094. taicpu(hp1).changeopsize(S_B);
  12095. end;
  12096. S_WL:
  12097. begin
  12098. SizeChange := taicpu(hp1).opsize <> S_W;
  12099. taicpu(hp1).changeopsize(S_W);
  12100. end
  12101. else
  12102. InternalError(2020112701);
  12103. end;
  12104. UpdateUsedRegs(tai(p.Next));
  12105. { Check if the register is used aferwards - if not, we can
  12106. remove the movzx instruction completely }
  12107. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12108. begin
  12109. { Hp1 is a better position than p for debugging purposes }
  12110. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12111. RemoveCurrentp(p, hp1);
  12112. Result := True;
  12113. end;
  12114. if SizeChange then
  12115. DebugMsg(SPeepholeOptimization + PreMessage +
  12116. 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)
  12117. else
  12118. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12119. Exit;
  12120. end;
  12121. { Change (using movzwl %ax,%eax as an example):
  12122. movzwl %ax, %eax
  12123. movb %al, (dest) (Register is smaller than read register in movz)
  12124. To:
  12125. movb %al, (dest) (Move one back to avoid a false dependency)
  12126. movzwl %ax, %eax
  12127. }
  12128. if (taicpu(hp1).opcode = A_MOV) and
  12129. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12130. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12131. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12132. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12133. begin
  12134. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12135. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12136. asml.Remove(hp1);
  12137. asml.InsertBefore(hp1, p);
  12138. if taicpu(hp1).oper[1]^.typ = top_reg then
  12139. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12140. { Check if the register is used aferwards - if not, we can
  12141. remove the movzx instruction completely }
  12142. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12143. begin
  12144. { Hp1 is a better position than p for debugging purposes }
  12145. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12146. RemoveCurrentp(p, hp1);
  12147. Result := True;
  12148. end;
  12149. Exit;
  12150. end;
  12151. end;
  12152. end;
  12153. {$ifdef x86_64}
  12154. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12155. var
  12156. PreMessage, RegName: string;
  12157. begin
  12158. { Code size reduction by J. Gareth "Kit" Moreton }
  12159. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12160. as this removes the REX prefix }
  12161. Result := False;
  12162. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12163. Exit;
  12164. if taicpu(p).oper[0]^.typ <> top_reg then
  12165. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12166. InternalError(2018011500);
  12167. case taicpu(p).opsize of
  12168. S_Q:
  12169. begin
  12170. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12171. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12172. { The actual optimization }
  12173. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12174. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12175. taicpu(p).changeopsize(S_L);
  12176. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12177. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12178. end;
  12179. else
  12180. ;
  12181. end;
  12182. end;
  12183. {$endif}
  12184. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12185. var
  12186. XReg: TRegister;
  12187. begin
  12188. Result := False;
  12189. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12190. Smaller encoding and slightly faster on some platforms (also works for
  12191. ZMM-sized registers) }
  12192. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12193. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12194. begin
  12195. XReg := taicpu(p).oper[0]^.reg;
  12196. if (taicpu(p).oper[1]^.reg = XReg) then
  12197. begin
  12198. taicpu(p).changeopsize(S_XMM);
  12199. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12200. if (cs_opt_size in current_settings.optimizerswitches) then
  12201. begin
  12202. { Change input registers to %xmm0 to reduce size. Note that
  12203. there's a risk of a false dependency doing this, so only
  12204. optimise for size here }
  12205. XReg := NR_XMM0;
  12206. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12207. end
  12208. else
  12209. begin
  12210. setsubreg(XReg, R_SUBMMX);
  12211. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12212. end;
  12213. taicpu(p).oper[0]^.reg := XReg;
  12214. taicpu(p).oper[1]^.reg := XReg;
  12215. Result := True;
  12216. end;
  12217. end;
  12218. end;
  12219. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12220. var
  12221. OperIdx: Integer;
  12222. begin
  12223. for OperIdx := 0 to p.ops - 1 do
  12224. if p.oper[OperIdx]^.typ = top_ref then
  12225. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12226. end;
  12227. end.