aoptx86.pas 536 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function PrePeepholeOptSxx(var p : tai) : boolean;
  107. function PrePeepholeOptIMUL(var p : tai) : boolean;
  108. function PrePeepholeOptAND(var p : tai) : boolean;
  109. function OptPass1Test(var p: tai): boolean;
  110. function OptPass1Add(var p: tai): boolean;
  111. function OptPass1AND(var p : tai) : boolean;
  112. function OptPass1_V_MOVAP(var p : tai) : boolean;
  113. function OptPass1VOP(var p : tai) : boolean;
  114. function OptPass1MOV(var p : tai) : boolean;
  115. function OptPass1Movx(var p : tai) : boolean;
  116. function OptPass1MOVXX(var p : tai) : boolean;
  117. function OptPass1OP(var p : tai) : boolean;
  118. function OptPass1LEA(var p : tai) : boolean;
  119. function OptPass1Sub(var p : tai) : boolean;
  120. function OptPass1SHLSAL(var p : tai) : boolean;
  121. function OptPass1FSTP(var p : tai) : boolean;
  122. function OptPass1FLD(var p : tai) : boolean;
  123. function OptPass1Cmp(var p : tai) : boolean;
  124. function OptPass1PXor(var p : tai) : boolean;
  125. function OptPass1VPXor(var p: tai): boolean;
  126. function OptPass1Imul(var p : tai) : boolean;
  127. function OptPass1Jcc(var p : tai) : boolean;
  128. function OptPass1SHXX(var p: tai): boolean;
  129. function OptPass1VMOVDQ(var p: tai): Boolean;
  130. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  131. function OptPass2Movx(var p : tai): Boolean;
  132. function OptPass2MOV(var p : tai) : boolean;
  133. function OptPass2Imul(var p : tai) : boolean;
  134. function OptPass2Jmp(var p : tai) : boolean;
  135. function OptPass2Jcc(var p : tai) : boolean;
  136. function OptPass2Lea(var p: tai): Boolean;
  137. function OptPass2SUB(var p: tai): Boolean;
  138. function OptPass2ADD(var p : tai): Boolean;
  139. function OptPass2SETcc(var p : tai) : boolean;
  140. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  141. function PostPeepholeOptMov(var p : tai) : Boolean;
  142. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  143. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  144. function PostPeepholeOptXor(var p : tai) : Boolean;
  145. {$endif x86_64}
  146. function PostPeepholeOptAnd(var p : tai) : boolean;
  147. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  148. function PostPeepholeOptCmp(var p : tai) : Boolean;
  149. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  150. function PostPeepholeOptCall(var p : tai) : Boolean;
  151. function PostPeepholeOptLea(var p : tai) : Boolean;
  152. function PostPeepholeOptPush(var p: tai): Boolean;
  153. function PostPeepholeOptShr(var p : tai) : boolean;
  154. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  155. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  156. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  157. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  158. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  159. { Processor-dependent reference optimisation }
  160. class procedure OptimizeRefs(var p: taicpu); static;
  161. end;
  162. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  163. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  166. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  167. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  168. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  169. {$if max_operands>2}
  170. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  171. {$endif max_operands>2}
  172. function RefsEqual(const r1, r2: treference): boolean;
  173. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  174. { returns true, if ref is a reference using only the registers passed as base and index
  175. and having an offset }
  176. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  177. implementation
  178. uses
  179. cutils,verbose,
  180. systems,
  181. globals,
  182. cpuinfo,
  183. procinfo,
  184. paramgr,
  185. aasmbase,
  186. aoptbase,aoptutils,
  187. symconst,symsym,
  188. cgx86,
  189. itcpugas;
  190. {$ifdef DEBUG_AOPTCPU}
  191. const
  192. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  193. {$else DEBUG_AOPTCPU}
  194. { Empty strings help the optimizer to remove string concatenations that won't
  195. ever appear to the user on release builds. [Kit] }
  196. const
  197. SPeepholeOptimization = '';
  198. {$endif DEBUG_AOPTCPU}
  199. LIST_STEP_SIZE = 4;
  200. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. (taicpu(instr).opcode = op) and
  205. ((opsize = []) or (taicpu(instr).opsize in opsize));
  206. end;
  207. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  208. begin
  209. result :=
  210. (instr.typ = ait_instruction) and
  211. ((taicpu(instr).opcode = op1) or
  212. (taicpu(instr).opcode = op2)
  213. ) and
  214. ((opsize = []) or (taicpu(instr).opsize in opsize));
  215. end;
  216. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  217. begin
  218. result :=
  219. (instr.typ = ait_instruction) and
  220. ((taicpu(instr).opcode = op1) or
  221. (taicpu(instr).opcode = op2) or
  222. (taicpu(instr).opcode = op3)
  223. ) and
  224. ((opsize = []) or (taicpu(instr).opsize in opsize));
  225. end;
  226. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  227. const opsize : topsizes) : boolean;
  228. var
  229. op : TAsmOp;
  230. begin
  231. result:=false;
  232. if (instr.typ <> ait_instruction) or
  233. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  234. exit;
  235. for op in ops do
  236. begin
  237. if taicpu(instr).opcode = op then
  238. begin
  239. result:=true;
  240. exit;
  241. end;
  242. end;
  243. end;
  244. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  245. begin
  246. result := (oper.typ = top_reg) and (oper.reg = reg);
  247. end;
  248. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  249. begin
  250. result := (oper.typ = top_const) and (oper.val = a);
  251. end;
  252. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  253. begin
  254. result := oper1.typ = oper2.typ;
  255. if result then
  256. case oper1.typ of
  257. top_const:
  258. Result:=oper1.val = oper2.val;
  259. top_reg:
  260. Result:=oper1.reg = oper2.reg;
  261. top_ref:
  262. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  263. else
  264. internalerror(2013102801);
  265. end
  266. end;
  267. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  268. begin
  269. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  270. if result then
  271. case oper1.typ of
  272. top_const:
  273. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  274. top_reg:
  275. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  276. top_ref:
  277. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  278. else
  279. internalerror(2020052401);
  280. end
  281. end;
  282. function RefsEqual(const r1, r2: treference): boolean;
  283. begin
  284. RefsEqual :=
  285. (r1.offset = r2.offset) and
  286. (r1.segment = r2.segment) and (r1.base = r2.base) and
  287. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  288. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  289. (r1.relsymbol = r2.relsymbol) and
  290. (r1.volatility=[]) and
  291. (r2.volatility=[]);
  292. end;
  293. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  294. begin
  295. Result:=(ref.offset=0) and
  296. (ref.scalefactor in [0,1]) and
  297. (ref.segment=NR_NO) and
  298. (ref.symbol=nil) and
  299. (ref.relsymbol=nil) and
  300. ((base=NR_INVALID) or
  301. (ref.base=base)) and
  302. ((index=NR_INVALID) or
  303. (ref.index=index)) and
  304. (ref.volatility=[]);
  305. end;
  306. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  307. begin
  308. Result:=(ref.scalefactor in [0,1]) and
  309. (ref.segment=NR_NO) and
  310. (ref.symbol=nil) and
  311. (ref.relsymbol=nil) and
  312. ((base=NR_INVALID) or
  313. (ref.base=base)) and
  314. ((index=NR_INVALID) or
  315. (ref.index=index)) and
  316. (ref.volatility=[]);
  317. end;
  318. function InstrReadsFlags(p: tai): boolean;
  319. begin
  320. InstrReadsFlags := true;
  321. case p.typ of
  322. ait_instruction:
  323. if InsProp[taicpu(p).opcode].Ch*
  324. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  325. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  326. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  327. exit;
  328. ait_label:
  329. exit;
  330. else
  331. ;
  332. end;
  333. InstrReadsFlags := false;
  334. end;
  335. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  336. begin
  337. Next:=Current;
  338. repeat
  339. Result:=GetNextInstruction(Next,Next);
  340. until not (Result) or
  341. not(cs_opt_level3 in current_settings.optimizerswitches) or
  342. (Next.typ<>ait_instruction) or
  343. RegInInstruction(reg,Next) or
  344. is_calljmp(taicpu(Next).opcode);
  345. end;
  346. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  347. begin
  348. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  349. Next := Current;
  350. repeat
  351. Result := GetNextInstruction(Next,Next);
  352. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  353. if is_calljmpuncondret(taicpu(Next).opcode) then
  354. begin
  355. Result := False;
  356. Exit;
  357. end
  358. else
  359. CrossJump := True;
  360. until not Result or
  361. not (cs_opt_level3 in current_settings.optimizerswitches) or
  362. (Next.typ <> ait_instruction) or
  363. RegInInstruction(reg,Next);
  364. end;
  365. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  366. begin
  367. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  368. begin
  369. Result:=GetNextInstruction(Current,Next);
  370. exit;
  371. end;
  372. Next:=tai(Current.Next);
  373. Result:=false;
  374. while assigned(Next) do
  375. begin
  376. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  377. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  378. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  379. exit
  380. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  381. begin
  382. Result:=true;
  383. exit;
  384. end;
  385. Next:=tai(Next.Next);
  386. end;
  387. end;
  388. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  389. begin
  390. Result:=RegReadByInstruction(reg,hp);
  391. end;
  392. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  393. var
  394. p: taicpu;
  395. opcount: longint;
  396. begin
  397. RegReadByInstruction := false;
  398. if hp.typ <> ait_instruction then
  399. exit;
  400. p := taicpu(hp);
  401. case p.opcode of
  402. A_CALL:
  403. regreadbyinstruction := true;
  404. A_IMUL:
  405. case p.ops of
  406. 1:
  407. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  408. (
  409. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  410. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  411. );
  412. 2,3:
  413. regReadByInstruction :=
  414. reginop(reg,p.oper[0]^) or
  415. reginop(reg,p.oper[1]^);
  416. else
  417. InternalError(2019112801);
  418. end;
  419. A_MUL:
  420. begin
  421. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  422. (
  423. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  424. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  425. );
  426. end;
  427. A_IDIV,A_DIV:
  428. begin
  429. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  430. (
  431. (getregtype(reg)=R_INTREGISTER) and
  432. (
  433. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  434. )
  435. );
  436. end;
  437. else
  438. begin
  439. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  440. begin
  441. RegReadByInstruction := false;
  442. exit;
  443. end;
  444. for opcount := 0 to p.ops-1 do
  445. if (p.oper[opCount]^.typ = top_ref) and
  446. RegInRef(reg,p.oper[opcount]^.ref^) then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. { special handling for SSE MOVSD }
  452. if (p.opcode=A_MOVSD) and (p.ops>0) then
  453. begin
  454. if p.ops<>2 then
  455. internalerror(2017042702);
  456. regReadByInstruction := reginop(reg,p.oper[0]^) or
  457. (
  458. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  459. );
  460. exit;
  461. end;
  462. with insprop[p.opcode] do
  463. begin
  464. case getregtype(reg) of
  465. R_INTREGISTER:
  466. begin
  467. case getsupreg(reg) of
  468. RS_EAX:
  469. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ECX:
  475. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EDX:
  481. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_EBX:
  487. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_ESP:
  493. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. RS_EBP:
  499. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  500. begin
  501. RegReadByInstruction := true;
  502. exit
  503. end;
  504. RS_ESI:
  505. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  506. begin
  507. RegReadByInstruction := true;
  508. exit
  509. end;
  510. RS_EDI:
  511. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  512. begin
  513. RegReadByInstruction := true;
  514. exit
  515. end;
  516. end;
  517. end;
  518. R_MMREGISTER:
  519. begin
  520. case getsupreg(reg) of
  521. RS_XMM0:
  522. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  523. begin
  524. RegReadByInstruction := true;
  525. exit
  526. end;
  527. end;
  528. end;
  529. else
  530. ;
  531. end;
  532. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  533. begin
  534. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  535. begin
  536. case p.condition of
  537. C_A,C_NBE, { CF=0 and ZF=0 }
  538. C_BE,C_NA: { CF=1 or ZF=1 }
  539. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  540. C_AE,C_NB,C_NC, { CF=0 }
  541. C_B,C_NAE,C_C: { CF=1 }
  542. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  543. C_NE,C_NZ, { ZF=0 }
  544. C_E,C_Z: { ZF=1 }
  545. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  546. C_G,C_NLE, { ZF=0 and SF=OF }
  547. C_LE,C_NG: { ZF=1 or SF<>OF }
  548. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  549. C_GE,C_NL, { SF=OF }
  550. C_L,C_NGE: { SF<>OF }
  551. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  552. C_NO, { OF=0 }
  553. C_O: { OF=1 }
  554. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  555. C_NP,C_PO, { PF=0 }
  556. C_P,C_PE: { PF=1 }
  557. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  558. C_NS, { SF=0 }
  559. C_S: { SF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  561. else
  562. internalerror(2017042701);
  563. end;
  564. if RegReadByInstruction then
  565. exit;
  566. end;
  567. case getsubreg(reg) of
  568. R_SUBW,R_SUBD,R_SUBQ:
  569. RegReadByInstruction :=
  570. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  571. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  572. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  573. R_SUBFLAGCARRY:
  574. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGPARITY:
  576. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGAUXILIARY:
  578. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGZERO:
  580. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGSIGN:
  582. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGOVERFLOW:
  584. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGINTERRUPT:
  586. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. R_SUBFLAGDIRECTION:
  588. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  589. else
  590. internalerror(2017042601);
  591. end;
  592. exit;
  593. end;
  594. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  595. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  596. (p.oper[0]^.reg=p.oper[1]^.reg) then
  597. exit;
  598. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  599. begin
  600. RegReadByInstruction := true;
  601. exit
  602. end;
  603. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  604. begin
  605. RegReadByInstruction := true;
  606. exit
  607. end;
  608. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  609. begin
  610. RegReadByInstruction := true;
  611. exit
  612. end;
  613. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  614. begin
  615. RegReadByInstruction := true;
  616. exit
  617. end;
  618. end;
  619. end;
  620. end;
  621. end;
  622. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  623. begin
  624. result:=false;
  625. if p1.typ<>ait_instruction then
  626. exit;
  627. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  628. exit(true);
  629. if (getregtype(reg)=R_INTREGISTER) and
  630. { change information for xmm movsd are not correct }
  631. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  632. begin
  633. case getsupreg(reg) of
  634. { RS_EAX = RS_RAX on x86-64 }
  635. RS_EAX:
  636. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_ECX:
  638. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_EDX:
  640. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EBX:
  642. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_ESP:
  644. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_EBP:
  646. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_ESI:
  648. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. RS_EDI:
  650. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. else
  652. ;
  653. end;
  654. if result then
  655. exit;
  656. end
  657. else if getregtype(reg)=R_MMREGISTER then
  658. begin
  659. case getsupreg(reg) of
  660. RS_XMM0:
  661. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. else
  663. ;
  664. end;
  665. if result then
  666. exit;
  667. end
  668. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  669. begin
  670. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  671. exit(true);
  672. case getsubreg(reg) of
  673. R_SUBFLAGCARRY:
  674. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGPARITY:
  676. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGAUXILIARY:
  678. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGZERO:
  680. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGSIGN:
  682. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGOVERFLOW:
  684. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGINTERRUPT:
  686. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBFLAGDIRECTION:
  688. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  689. R_SUBW,R_SUBD,R_SUBQ:
  690. { Everything except the direction bits }
  691. Result:=
  692. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  693. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  694. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  695. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  696. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  697. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  698. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  699. else
  700. ;
  701. end;
  702. if result then
  703. exit;
  704. end
  705. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  706. exit(true);
  707. Result:=inherited RegInInstruction(Reg, p1);
  708. end;
  709. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  710. const
  711. WriteOps: array[0..3] of set of TInsChange =
  712. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  713. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  714. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  715. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  716. var
  717. OperIdx: Integer;
  718. begin
  719. Result := False;
  720. if p1.typ <> ait_instruction then
  721. exit;
  722. with insprop[taicpu(p1).opcode] do
  723. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  724. begin
  725. case getsubreg(reg) of
  726. R_SUBW,R_SUBD,R_SUBQ:
  727. Result :=
  728. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  729. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  730. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  731. R_SUBFLAGCARRY:
  732. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGPARITY:
  734. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGAUXILIARY:
  736. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGZERO:
  738. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGSIGN:
  740. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGOVERFLOW:
  742. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGINTERRUPT:
  744. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. R_SUBFLAGDIRECTION:
  746. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  747. else
  748. internalerror(2017042602);
  749. end;
  750. exit;
  751. end;
  752. case taicpu(p1).opcode of
  753. A_CALL:
  754. { We could potentially set Result to False if the register in
  755. question is non-volatile for the subroutine's calling convention,
  756. but this would require detecting the calling convention in use and
  757. also assuming that the routine doesn't contain malformed assembly
  758. language, for example... so it could only be done under -O4 as it
  759. would be considered a side-effect. [Kit] }
  760. Result := True;
  761. A_MOVSD:
  762. { special handling for SSE MOVSD }
  763. if (taicpu(p1).ops>0) then
  764. begin
  765. if taicpu(p1).ops<>2 then
  766. internalerror(2017042703);
  767. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  768. end;
  769. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  770. so fix it here (FK)
  771. }
  772. A_VMOVSS,
  773. A_VMOVSD:
  774. begin
  775. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  776. exit;
  777. end;
  778. A_IMUL:
  779. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  780. else
  781. ;
  782. end;
  783. if Result then
  784. exit;
  785. with insprop[taicpu(p1).opcode] do
  786. begin
  787. if getregtype(reg)=R_INTREGISTER then
  788. begin
  789. case getsupreg(reg) of
  790. RS_EAX:
  791. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  792. begin
  793. Result := True;
  794. exit
  795. end;
  796. RS_ECX:
  797. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  798. begin
  799. Result := True;
  800. exit
  801. end;
  802. RS_EDX:
  803. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  804. begin
  805. Result := True;
  806. exit
  807. end;
  808. RS_EBX:
  809. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  810. begin
  811. Result := True;
  812. exit
  813. end;
  814. RS_ESP:
  815. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  816. begin
  817. Result := True;
  818. exit
  819. end;
  820. RS_EBP:
  821. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  822. begin
  823. Result := True;
  824. exit
  825. end;
  826. RS_ESI:
  827. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  828. begin
  829. Result := True;
  830. exit
  831. end;
  832. RS_EDI:
  833. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  834. begin
  835. Result := True;
  836. exit
  837. end;
  838. end;
  839. end;
  840. for OperIdx := 0 to taicpu(p1).ops - 1 do
  841. if (WriteOps[OperIdx]*Ch<>[]) and
  842. { The register doesn't get modified inside a reference }
  843. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  844. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  845. begin
  846. Result := true;
  847. exit
  848. end;
  849. end;
  850. end;
  851. {$ifdef DEBUG_AOPTCPU}
  852. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  853. begin
  854. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  855. end;
  856. function debug_tostr(i: tcgint): string; inline;
  857. begin
  858. Result := tostr(i);
  859. end;
  860. function debug_regname(r: TRegister): string; inline;
  861. begin
  862. Result := '%' + std_regname(r);
  863. end;
  864. { Debug output function - creates a string representation of an operator }
  865. function debug_operstr(oper: TOper): string;
  866. begin
  867. case oper.typ of
  868. top_const:
  869. Result := '$' + debug_tostr(oper.val);
  870. top_reg:
  871. Result := debug_regname(oper.reg);
  872. top_ref:
  873. begin
  874. if oper.ref^.offset <> 0 then
  875. Result := debug_tostr(oper.ref^.offset) + '('
  876. else
  877. Result := '(';
  878. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  879. begin
  880. Result := Result + debug_regname(oper.ref^.base);
  881. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  882. Result := Result + ',' + debug_regname(oper.ref^.index);
  883. end
  884. else
  885. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  886. Result := Result + debug_regname(oper.ref^.index);
  887. if (oper.ref^.scalefactor > 1) then
  888. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  889. else
  890. Result := Result + ')';
  891. end;
  892. else
  893. Result := '[UNKNOWN]';
  894. end;
  895. end;
  896. function debug_op2str(opcode: tasmop): string; inline;
  897. begin
  898. Result := std_op2str[opcode];
  899. end;
  900. function debug_opsize2str(opsize: topsize): string; inline;
  901. begin
  902. Result := gas_opsize2str[opsize];
  903. end;
  904. {$else DEBUG_AOPTCPU}
  905. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  906. begin
  907. end;
  908. function debug_tostr(i: tcgint): string; inline;
  909. begin
  910. Result := '';
  911. end;
  912. function debug_regname(r: TRegister): string; inline;
  913. begin
  914. Result := '';
  915. end;
  916. function debug_operstr(oper: TOper): string; inline;
  917. begin
  918. Result := '';
  919. end;
  920. function debug_op2str(opcode: tasmop): string; inline;
  921. begin
  922. Result := '';
  923. end;
  924. function debug_opsize2str(opsize: topsize): string; inline;
  925. begin
  926. Result := '';
  927. end;
  928. {$endif DEBUG_AOPTCPU}
  929. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  930. begin
  931. {$ifdef x86_64}
  932. { Always fine on x86-64 }
  933. Result := True;
  934. {$else x86_64}
  935. Result :=
  936. {$ifdef i8086}
  937. (current_settings.cputype >= cpu_386) and
  938. {$endif i8086}
  939. (
  940. { Always accept if optimising for size }
  941. (cs_opt_size in current_settings.optimizerswitches) or
  942. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  943. (current_settings.optimizecputype >= cpu_Pentium2)
  944. );
  945. {$endif x86_64}
  946. end;
  947. { Attempts to allocate a volatile integer register for use between p and hp,
  948. using AUsedRegs for the current register usage information. Returns NR_NO
  949. if no free register could be found }
  950. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  951. var
  952. RegSet: TCPURegisterSet;
  953. CurrentSuperReg: Integer;
  954. CurrentReg: TRegister;
  955. Currentp: tai;
  956. Breakout: Boolean;
  957. begin
  958. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  959. Result := NR_NO;
  960. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  961. for CurrentSuperReg in RegSet do
  962. begin
  963. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  964. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  965. begin
  966. Currentp := p;
  967. Breakout := False;
  968. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  969. begin
  970. case Currentp.typ of
  971. ait_instruction:
  972. begin
  973. if RegInInstruction(CurrentReg, Currentp) then
  974. begin
  975. Breakout := True;
  976. Break;
  977. end;
  978. { Cannot allocate across an unconditional jump }
  979. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  980. Exit;
  981. end;
  982. ait_marker:
  983. { Don't try anything more if a marker is hit }
  984. Exit;
  985. ait_regalloc:
  986. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  987. begin
  988. Breakout := True;
  989. Break;
  990. end;
  991. else
  992. ;
  993. end;
  994. end;
  995. if Breakout then
  996. { Try the next register }
  997. Continue;
  998. { We have a free register available }
  999. Result := CurrentReg;
  1000. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1001. Exit;
  1002. end;
  1003. end;
  1004. end;
  1005. { Attempts to allocate a volatile MM register for use between p and hp,
  1006. using AUsedRegs for the current register usage information. Returns NR_NO
  1007. if no free register could be found }
  1008. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1009. var
  1010. RegSet: TCPURegisterSet;
  1011. CurrentSuperReg: Integer;
  1012. CurrentReg: TRegister;
  1013. Currentp: tai;
  1014. Breakout: Boolean;
  1015. begin
  1016. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1017. Result := NR_NO;
  1018. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1019. for CurrentSuperReg in RegSet do
  1020. begin
  1021. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1022. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1023. begin
  1024. Currentp := p;
  1025. Breakout := False;
  1026. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1027. begin
  1028. case Currentp.typ of
  1029. ait_instruction:
  1030. begin
  1031. if RegInInstruction(CurrentReg, Currentp) then
  1032. begin
  1033. Breakout := True;
  1034. Break;
  1035. end;
  1036. { Cannot allocate across an unconditional jump }
  1037. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1038. Exit;
  1039. end;
  1040. ait_marker:
  1041. { Don't try anything more if a marker is hit }
  1042. Exit;
  1043. ait_regalloc:
  1044. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. else
  1050. ;
  1051. end;
  1052. end;
  1053. if Breakout then
  1054. { Try the next register }
  1055. Continue;
  1056. { We have a free register available }
  1057. Result := CurrentReg;
  1058. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1059. Exit;
  1060. end;
  1061. end;
  1062. end;
  1063. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1064. begin
  1065. if not SuperRegistersEqual(reg1,reg2) then
  1066. exit(false);
  1067. if getregtype(reg1)<>R_INTREGISTER then
  1068. exit(true); {because SuperRegisterEqual is true}
  1069. case getsubreg(reg1) of
  1070. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1071. higher, it preserves the high bits, so the new value depends on
  1072. reg2's previous value. In other words, it is equivalent to doing:
  1073. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1074. R_SUBL:
  1075. exit(getsubreg(reg2)=R_SUBL);
  1076. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1077. higher, it actually does a:
  1078. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1079. R_SUBH:
  1080. exit(getsubreg(reg2)=R_SUBH);
  1081. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1082. bits of reg2:
  1083. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1084. R_SUBW:
  1085. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1086. { a write to R_SUBD always overwrites every other subregister,
  1087. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1088. R_SUBD,
  1089. R_SUBQ:
  1090. exit(true);
  1091. else
  1092. internalerror(2017042801);
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1096. begin
  1097. if not SuperRegistersEqual(reg1,reg2) then
  1098. exit(false);
  1099. if getregtype(reg1)<>R_INTREGISTER then
  1100. exit(true); {because SuperRegisterEqual is true}
  1101. case getsubreg(reg1) of
  1102. R_SUBL:
  1103. exit(getsubreg(reg2)<>R_SUBH);
  1104. R_SUBH:
  1105. exit(getsubreg(reg2)<>R_SUBL);
  1106. R_SUBW,
  1107. R_SUBD,
  1108. R_SUBQ:
  1109. exit(true);
  1110. else
  1111. internalerror(2017042802);
  1112. end;
  1113. end;
  1114. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1115. var
  1116. hp1 : tai;
  1117. l : TCGInt;
  1118. begin
  1119. result:=false;
  1120. { changes the code sequence
  1121. shr/sar const1, x
  1122. shl const2, x
  1123. to
  1124. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1125. if GetNextInstruction(p, hp1) and
  1126. MatchInstruction(hp1,A_SHL,[]) and
  1127. (taicpu(p).oper[0]^.typ = top_const) and
  1128. (taicpu(hp1).oper[0]^.typ = top_const) and
  1129. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1130. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1131. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1132. begin
  1133. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1134. not(cs_opt_size in current_settings.optimizerswitches) then
  1135. begin
  1136. { shr/sar const1, %reg
  1137. shl const2, %reg
  1138. with const1 > const2 }
  1139. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1140. taicpu(hp1).opcode := A_AND;
  1141. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1142. case taicpu(p).opsize Of
  1143. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1144. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1145. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1146. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1147. else
  1148. Internalerror(2017050703)
  1149. end;
  1150. end
  1151. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1152. not(cs_opt_size in current_settings.optimizerswitches) then
  1153. begin
  1154. { shr/sar const1, %reg
  1155. shl const2, %reg
  1156. with const1 < const2 }
  1157. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1158. taicpu(p).opcode := A_AND;
  1159. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1160. case taicpu(p).opsize Of
  1161. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1162. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1163. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1164. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1165. else
  1166. Internalerror(2017050702)
  1167. end;
  1168. end
  1169. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1170. begin
  1171. { shr/sar const1, %reg
  1172. shl const2, %reg
  1173. with const1 = const2 }
  1174. taicpu(p).opcode := A_AND;
  1175. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1176. case taicpu(p).opsize Of
  1177. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1178. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1179. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1180. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1181. else
  1182. Internalerror(2017050701)
  1183. end;
  1184. RemoveInstruction(hp1);
  1185. end;
  1186. end;
  1187. end;
  1188. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1189. var
  1190. opsize : topsize;
  1191. hp1 : tai;
  1192. tmpref : treference;
  1193. ShiftValue : Cardinal;
  1194. BaseValue : TCGInt;
  1195. begin
  1196. result:=false;
  1197. opsize:=taicpu(p).opsize;
  1198. { changes certain "imul const, %reg"'s to lea sequences }
  1199. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1200. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1201. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1202. if (taicpu(p).oper[0]^.val = 1) then
  1203. if (taicpu(p).ops = 2) then
  1204. { remove "imul $1, reg" }
  1205. begin
  1206. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1207. Result := RemoveCurrentP(p);
  1208. end
  1209. else
  1210. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1211. begin
  1212. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1213. InsertLLItem(p.previous, p.next, hp1);
  1214. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1215. p.free;
  1216. p := hp1;
  1217. end
  1218. else if ((taicpu(p).ops <= 2) or
  1219. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1220. not(cs_opt_size in current_settings.optimizerswitches) and
  1221. (not(GetNextInstruction(p, hp1)) or
  1222. not((tai(hp1).typ = ait_instruction) and
  1223. ((taicpu(hp1).opcode=A_Jcc) and
  1224. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1225. begin
  1226. {
  1227. imul X, reg1, reg2 to
  1228. lea (reg1,reg1,Y), reg2
  1229. shl ZZ,reg2
  1230. imul XX, reg1 to
  1231. lea (reg1,reg1,YY), reg1
  1232. shl ZZ,reg2
  1233. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1234. it does not exist as a separate optimization target in FPC though.
  1235. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1236. at most two zeros
  1237. }
  1238. reference_reset(tmpref,1,[]);
  1239. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1240. begin
  1241. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1242. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1243. TmpRef.base := taicpu(p).oper[1]^.reg;
  1244. TmpRef.index := taicpu(p).oper[1]^.reg;
  1245. if not(BaseValue in [3,5,9]) then
  1246. Internalerror(2018110101);
  1247. TmpRef.ScaleFactor := BaseValue-1;
  1248. if (taicpu(p).ops = 2) then
  1249. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1250. else
  1251. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1252. AsmL.InsertAfter(hp1,p);
  1253. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1254. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1255. RemoveCurrentP(p, hp1);
  1256. if ShiftValue>0 then
  1257. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1258. end;
  1259. end;
  1260. end;
  1261. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1262. begin
  1263. Result := False;
  1264. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1265. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1266. begin
  1267. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1268. taicpu(p).opcode := A_MOV;
  1269. Result := True;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1273. var
  1274. p: taicpu absolute hp;
  1275. i: Integer;
  1276. begin
  1277. Result := False;
  1278. if not assigned(hp) or
  1279. (hp.typ <> ait_instruction) then
  1280. Exit;
  1281. // p := taicpu(hp);
  1282. Prefetch(insprop[p.opcode]);
  1283. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1284. with insprop[p.opcode] do
  1285. begin
  1286. case getsubreg(reg) of
  1287. R_SUBW,R_SUBD,R_SUBQ:
  1288. Result:=
  1289. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1290. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1291. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1292. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1293. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1294. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1295. R_SUBFLAGCARRY:
  1296. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1297. R_SUBFLAGPARITY:
  1298. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1299. R_SUBFLAGAUXILIARY:
  1300. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1301. R_SUBFLAGZERO:
  1302. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1303. R_SUBFLAGSIGN:
  1304. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1305. R_SUBFLAGOVERFLOW:
  1306. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1307. R_SUBFLAGINTERRUPT:
  1308. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGDIRECTION:
  1310. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1311. else
  1312. begin
  1313. writeln(getsubreg(reg));
  1314. internalerror(2017050501);
  1315. end;
  1316. end;
  1317. exit;
  1318. end;
  1319. { Handle special cases first }
  1320. case p.opcode of
  1321. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1322. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1323. begin
  1324. Result :=
  1325. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1326. (p.oper[1]^.typ = top_reg) and
  1327. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1328. (
  1329. (p.oper[0]^.typ = top_const) or
  1330. (
  1331. (p.oper[0]^.typ = top_reg) and
  1332. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1333. ) or (
  1334. (p.oper[0]^.typ = top_ref) and
  1335. not RegInRef(reg,p.oper[0]^.ref^)
  1336. )
  1337. );
  1338. end;
  1339. A_MUL, A_IMUL:
  1340. Result :=
  1341. (
  1342. (p.ops=3) and { IMUL only }
  1343. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1344. (
  1345. (
  1346. (p.oper[1]^.typ=top_reg) and
  1347. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1348. ) or (
  1349. (p.oper[1]^.typ=top_ref) and
  1350. not RegInRef(reg,p.oper[1]^.ref^)
  1351. )
  1352. )
  1353. ) or (
  1354. (
  1355. (p.ops=1) and
  1356. (
  1357. (
  1358. (
  1359. (p.oper[0]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1361. )
  1362. ) or (
  1363. (p.oper[0]^.typ=top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. ) and (
  1367. (
  1368. (p.opsize=S_B) and
  1369. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1370. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1371. ) or (
  1372. (p.opsize=S_W) and
  1373. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1374. ) or (
  1375. (p.opsize=S_L) and
  1376. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1377. {$ifdef x86_64}
  1378. ) or (
  1379. (p.opsize=S_Q) and
  1380. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1381. {$endif x86_64}
  1382. )
  1383. )
  1384. )
  1385. );
  1386. A_CBW:
  1387. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1388. {$ifndef x86_64}
  1389. A_LDS:
  1390. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1391. A_LES:
  1392. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1393. {$endif not x86_64}
  1394. A_LFS:
  1395. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1396. A_LGS:
  1397. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1398. A_LSS:
  1399. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1401. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1402. A_LODSB:
  1403. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1404. A_LODSW:
  1405. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1406. {$ifdef x86_64}
  1407. A_LODSQ:
  1408. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1409. {$endif x86_64}
  1410. A_LODSD:
  1411. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1412. A_FSTSW, A_FNSTSW:
  1413. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1414. else
  1415. begin
  1416. with insprop[p.opcode] do
  1417. begin
  1418. if (
  1419. { xor %reg,%reg etc. is classed as a new value }
  1420. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1421. MatchOpType(p, top_reg, top_reg) and
  1422. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1423. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1424. ) then
  1425. begin
  1426. Result := True;
  1427. Exit;
  1428. end;
  1429. { Make sure the entire register is overwritten }
  1430. if (getregtype(reg) = R_INTREGISTER) then
  1431. begin
  1432. if (p.ops > 0) then
  1433. begin
  1434. if RegInOp(reg, p.oper[0]^) then
  1435. begin
  1436. if (p.oper[0]^.typ = top_ref) then
  1437. begin
  1438. if RegInRef(reg, p.oper[0]^.ref^) then
  1439. begin
  1440. Result := False;
  1441. Exit;
  1442. end;
  1443. end
  1444. else if (p.oper[0]^.typ = top_reg) then
  1445. begin
  1446. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1447. begin
  1448. Result := False;
  1449. Exit;
  1450. end
  1451. else if ([Ch_WOp1]*Ch<>[]) then
  1452. begin
  1453. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1454. Result := True
  1455. else
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end;
  1460. end;
  1461. end;
  1462. end;
  1463. if (p.ops > 1) then
  1464. begin
  1465. if RegInOp(reg, p.oper[1]^) then
  1466. begin
  1467. if (p.oper[1]^.typ = top_ref) then
  1468. begin
  1469. if RegInRef(reg, p.oper[1]^.ref^) then
  1470. begin
  1471. Result := False;
  1472. Exit;
  1473. end;
  1474. end
  1475. else if (p.oper[1]^.typ = top_reg) then
  1476. begin
  1477. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1478. begin
  1479. Result := False;
  1480. Exit;
  1481. end
  1482. else if ([Ch_WOp2]*Ch<>[]) then
  1483. begin
  1484. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1485. Result := True
  1486. else
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end;
  1491. end;
  1492. end;
  1493. end;
  1494. if (p.ops > 2) then
  1495. begin
  1496. if RegInOp(reg, p.oper[2]^) then
  1497. begin
  1498. if (p.oper[2]^.typ = top_ref) then
  1499. begin
  1500. if RegInRef(reg, p.oper[2]^.ref^) then
  1501. begin
  1502. Result := False;
  1503. Exit;
  1504. end;
  1505. end
  1506. else if (p.oper[2]^.typ = top_reg) then
  1507. begin
  1508. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1509. begin
  1510. Result := False;
  1511. Exit;
  1512. end
  1513. else if ([Ch_WOp3]*Ch<>[]) then
  1514. begin
  1515. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1516. Result := True
  1517. else
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end;
  1522. end;
  1523. end;
  1524. end;
  1525. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1526. begin
  1527. if (p.oper[3]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[3]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[3]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp4]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. end;
  1555. end;
  1556. end;
  1557. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1558. case getsupreg(reg) of
  1559. RS_EAX:
  1560. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1561. begin
  1562. Result := True;
  1563. Exit;
  1564. end;
  1565. RS_ECX:
  1566. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1567. begin
  1568. Result := True;
  1569. Exit;
  1570. end;
  1571. RS_EDX:
  1572. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1573. begin
  1574. Result := True;
  1575. Exit;
  1576. end;
  1577. RS_EBX:
  1578. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1579. begin
  1580. Result := True;
  1581. Exit;
  1582. end;
  1583. RS_ESP:
  1584. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1585. begin
  1586. Result := True;
  1587. Exit;
  1588. end;
  1589. RS_EBP:
  1590. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1591. begin
  1592. Result := True;
  1593. Exit;
  1594. end;
  1595. RS_ESI:
  1596. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1597. begin
  1598. Result := True;
  1599. Exit;
  1600. end;
  1601. RS_EDI:
  1602. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1603. begin
  1604. Result := True;
  1605. Exit;
  1606. end;
  1607. else
  1608. ;
  1609. end;
  1610. end;
  1611. end;
  1612. end;
  1613. end;
  1614. end;
  1615. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1616. var
  1617. hp2,hp3 : tai;
  1618. begin
  1619. { some x86-64 issue a NOP before the real exit code }
  1620. if MatchInstruction(p,A_NOP,[]) then
  1621. GetNextInstruction(p,p);
  1622. result:=assigned(p) and (p.typ=ait_instruction) and
  1623. ((taicpu(p).opcode = A_RET) or
  1624. ((taicpu(p).opcode=A_LEAVE) and
  1625. GetNextInstruction(p,hp2) and
  1626. MatchInstruction(hp2,A_RET,[S_NO])
  1627. ) or
  1628. (((taicpu(p).opcode=A_LEA) and
  1629. MatchOpType(taicpu(p),top_ref,top_reg) and
  1630. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1631. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1632. ) and
  1633. GetNextInstruction(p,hp2) and
  1634. MatchInstruction(hp2,A_RET,[S_NO])
  1635. ) or
  1636. ((((taicpu(p).opcode=A_MOV) and
  1637. MatchOpType(taicpu(p),top_reg,top_reg) and
  1638. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1639. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1640. ((taicpu(p).opcode=A_LEA) and
  1641. MatchOpType(taicpu(p),top_ref,top_reg) and
  1642. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1643. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1644. )
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1648. MatchOpType(taicpu(hp2),top_reg) and
  1649. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1650. GetNextInstruction(hp2,hp3) and
  1651. MatchInstruction(hp3,A_RET,[S_NO])
  1652. )
  1653. );
  1654. end;
  1655. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1656. begin
  1657. isFoldableArithOp := False;
  1658. case hp1.opcode of
  1659. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1660. isFoldableArithOp :=
  1661. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1662. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1663. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1664. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1665. (taicpu(hp1).oper[1]^.reg = reg);
  1666. A_INC,A_DEC,A_NEG,A_NOT:
  1667. isFoldableArithOp :=
  1668. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1669. (taicpu(hp1).oper[0]^.reg = reg);
  1670. else
  1671. ;
  1672. end;
  1673. end;
  1674. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1675. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1676. var
  1677. hp2: tai;
  1678. begin
  1679. hp2 := p;
  1680. repeat
  1681. hp2 := tai(hp2.previous);
  1682. if assigned(hp2) and
  1683. (hp2.typ = ait_regalloc) and
  1684. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1685. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1686. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1687. begin
  1688. RemoveInstruction(hp2);
  1689. break;
  1690. end;
  1691. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1692. end;
  1693. begin
  1694. case current_procinfo.procdef.returndef.typ of
  1695. arraydef,recorddef,pointerdef,
  1696. stringdef,enumdef,procdef,objectdef,errordef,
  1697. filedef,setdef,procvardef,
  1698. classrefdef,forwarddef:
  1699. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1700. orddef:
  1701. if current_procinfo.procdef.returndef.size <> 0 then
  1702. begin
  1703. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1704. { for int64/qword }
  1705. if current_procinfo.procdef.returndef.size = 8 then
  1706. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1707. end;
  1708. else
  1709. ;
  1710. end;
  1711. end;
  1712. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1713. var
  1714. hp1,hp2 : tai;
  1715. begin
  1716. result:=false;
  1717. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1718. begin
  1719. { vmova* reg1,reg1
  1720. =>
  1721. <nop> }
  1722. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1723. begin
  1724. RemoveCurrentP(p);
  1725. result:=true;
  1726. exit;
  1727. end
  1728. else if GetNextInstruction(p,hp1) then
  1729. begin
  1730. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1731. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1732. begin
  1733. { vmova* reg1,reg2
  1734. vmova* reg2,reg3
  1735. dealloc reg2
  1736. =>
  1737. vmova* reg1,reg3 }
  1738. TransferUsedRegs(TmpUsedRegs);
  1739. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1740. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1741. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1742. begin
  1743. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1744. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1745. RemoveInstruction(hp1);
  1746. result:=true;
  1747. exit;
  1748. end
  1749. { special case:
  1750. vmova* reg1,<op>
  1751. vmova* <op>,reg1
  1752. =>
  1753. vmova* reg1,<op> }
  1754. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1755. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1756. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1757. ) then
  1758. begin
  1759. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1760. RemoveInstruction(hp1);
  1761. result:=true;
  1762. exit;
  1763. end
  1764. end
  1765. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1766. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1767. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1768. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1769. ) and
  1770. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1771. begin
  1772. { vmova* reg1,reg2
  1773. vmovs* reg2,<op>
  1774. dealloc reg2
  1775. =>
  1776. vmovs* reg1,reg3 }
  1777. TransferUsedRegs(TmpUsedRegs);
  1778. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1779. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1780. begin
  1781. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1782. taicpu(p).opcode:=taicpu(hp1).opcode;
  1783. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1784. RemoveInstruction(hp1);
  1785. result:=true;
  1786. exit;
  1787. end
  1788. end;
  1789. end;
  1790. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1791. begin
  1792. if MatchInstruction(hp1,[A_VFMADDPD,
  1793. A_VFMADD132PD,
  1794. A_VFMADD132PS,
  1795. A_VFMADD132SD,
  1796. A_VFMADD132SS,
  1797. A_VFMADD213PD,
  1798. A_VFMADD213PS,
  1799. A_VFMADD213SD,
  1800. A_VFMADD213SS,
  1801. A_VFMADD231PD,
  1802. A_VFMADD231PS,
  1803. A_VFMADD231SD,
  1804. A_VFMADD231SS,
  1805. A_VFMADDSUB132PD,
  1806. A_VFMADDSUB132PS,
  1807. A_VFMADDSUB213PD,
  1808. A_VFMADDSUB213PS,
  1809. A_VFMADDSUB231PD,
  1810. A_VFMADDSUB231PS,
  1811. A_VFMSUB132PD,
  1812. A_VFMSUB132PS,
  1813. A_VFMSUB132SD,
  1814. A_VFMSUB132SS,
  1815. A_VFMSUB213PD,
  1816. A_VFMSUB213PS,
  1817. A_VFMSUB213SD,
  1818. A_VFMSUB213SS,
  1819. A_VFMSUB231PD,
  1820. A_VFMSUB231PS,
  1821. A_VFMSUB231SD,
  1822. A_VFMSUB231SS,
  1823. A_VFMSUBADD132PD,
  1824. A_VFMSUBADD132PS,
  1825. A_VFMSUBADD213PD,
  1826. A_VFMSUBADD213PS,
  1827. A_VFMSUBADD231PD,
  1828. A_VFMSUBADD231PS,
  1829. A_VFNMADD132PD,
  1830. A_VFNMADD132PS,
  1831. A_VFNMADD132SD,
  1832. A_VFNMADD132SS,
  1833. A_VFNMADD213PD,
  1834. A_VFNMADD213PS,
  1835. A_VFNMADD213SD,
  1836. A_VFNMADD213SS,
  1837. A_VFNMADD231PD,
  1838. A_VFNMADD231PS,
  1839. A_VFNMADD231SD,
  1840. A_VFNMADD231SS,
  1841. A_VFNMSUB132PD,
  1842. A_VFNMSUB132PS,
  1843. A_VFNMSUB132SD,
  1844. A_VFNMSUB132SS,
  1845. A_VFNMSUB213PD,
  1846. A_VFNMSUB213PS,
  1847. A_VFNMSUB213SD,
  1848. A_VFNMSUB213SS,
  1849. A_VFNMSUB231PD,
  1850. A_VFNMSUB231PS,
  1851. A_VFNMSUB231SD,
  1852. A_VFNMSUB231SS],[S_NO]) and
  1853. { we mix single and double opperations here because we assume that the compiler
  1854. generates vmovapd only after double operations and vmovaps only after single operations }
  1855. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1856. GetNextInstruction(hp1,hp2) and
  1857. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1858. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1859. begin
  1860. TransferUsedRegs(TmpUsedRegs);
  1861. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1862. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1863. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1864. begin
  1865. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1866. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1867. RemoveInstruction(hp2);
  1868. end;
  1869. end
  1870. else if (hp1.typ = ait_instruction) and
  1871. GetNextInstruction(hp1, hp2) and
  1872. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1873. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1874. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1875. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1876. (((taicpu(p).opcode=A_MOVAPS) and
  1877. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1878. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1879. ((taicpu(p).opcode=A_MOVAPD) and
  1880. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1881. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1882. ) then
  1883. { change
  1884. movapX reg,reg2
  1885. addsX/subsX/... reg3, reg2
  1886. movapX reg2,reg
  1887. to
  1888. addsX/subsX/... reg3,reg
  1889. }
  1890. begin
  1891. TransferUsedRegs(TmpUsedRegs);
  1892. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1893. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1894. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1895. begin
  1896. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1897. debug_op2str(taicpu(p).opcode)+' '+
  1898. debug_op2str(taicpu(hp1).opcode)+' '+
  1899. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1900. { we cannot eliminate the first move if
  1901. the operations uses the same register for source and dest }
  1902. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1903. RemoveCurrentP(p, nil);
  1904. p:=hp1;
  1905. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1906. RemoveInstruction(hp2);
  1907. result:=true;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1914. var
  1915. hp1 : tai;
  1916. begin
  1917. result:=false;
  1918. { replace
  1919. V<Op>X %mreg1,%mreg2,%mreg3
  1920. VMovX %mreg3,%mreg4
  1921. dealloc %mreg3
  1922. by
  1923. V<Op>X %mreg1,%mreg2,%mreg4
  1924. ?
  1925. }
  1926. if GetNextInstruction(p,hp1) and
  1927. { we mix single and double operations here because we assume that the compiler
  1928. generates vmovapd only after double operations and vmovaps only after single operations }
  1929. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1930. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1931. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1932. begin
  1933. TransferUsedRegs(TmpUsedRegs);
  1934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1935. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1936. begin
  1937. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1938. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1939. RemoveInstruction(hp1);
  1940. result:=true;
  1941. end;
  1942. end;
  1943. end;
  1944. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1945. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1946. begin
  1947. Result := False;
  1948. { For safety reasons, only check for exact register matches }
  1949. { Check base register }
  1950. if (ref.base = AOldReg) then
  1951. begin
  1952. ref.base := ANewReg;
  1953. Result := True;
  1954. end;
  1955. { Check index register }
  1956. if (ref.index = AOldReg) then
  1957. begin
  1958. ref.index := ANewReg;
  1959. Result := True;
  1960. end;
  1961. end;
  1962. { Replaces all references to AOldReg in an operand to ANewReg }
  1963. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1964. var
  1965. OldSupReg, NewSupReg: TSuperRegister;
  1966. OldSubReg, NewSubReg: TSubRegister;
  1967. OldRegType: TRegisterType;
  1968. ThisOper: POper;
  1969. begin
  1970. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1971. Result := False;
  1972. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1973. InternalError(2020011801);
  1974. OldSupReg := getsupreg(AOldReg);
  1975. OldSubReg := getsubreg(AOldReg);
  1976. OldRegType := getregtype(AOldReg);
  1977. NewSupReg := getsupreg(ANewReg);
  1978. NewSubReg := getsubreg(ANewReg);
  1979. if OldRegType <> getregtype(ANewReg) then
  1980. InternalError(2020011802);
  1981. if OldSubReg <> NewSubReg then
  1982. InternalError(2020011803);
  1983. case ThisOper^.typ of
  1984. top_reg:
  1985. if (
  1986. (ThisOper^.reg = AOldReg) or
  1987. (
  1988. (OldRegType = R_INTREGISTER) and
  1989. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1990. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1991. (
  1992. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1993. {$ifndef x86_64}
  1994. and (
  1995. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1996. don't have an 8-bit representation }
  1997. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1998. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1999. )
  2000. {$endif x86_64}
  2001. )
  2002. )
  2003. ) then
  2004. begin
  2005. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2006. Result := True;
  2007. end;
  2008. top_ref:
  2009. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2010. Result := True;
  2011. else
  2012. ;
  2013. end;
  2014. end;
  2015. { Replaces all references to AOldReg in an instruction to ANewReg }
  2016. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2017. const
  2018. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2019. var
  2020. OperIdx: Integer;
  2021. begin
  2022. Result := False;
  2023. for OperIdx := 0 to p.ops - 1 do
  2024. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2025. begin
  2026. { The shift and rotate instructions can only use CL }
  2027. if not (
  2028. (OperIdx = 0) and
  2029. { This second condition just helps to avoid unnecessarily
  2030. calling MatchInstruction for 10 different opcodes }
  2031. (p.oper[0]^.reg = NR_CL) and
  2032. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2033. ) then
  2034. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2035. end
  2036. else if p.oper[OperIdx]^.typ = top_ref then
  2037. { It's okay to replace registers in references that get written to }
  2038. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2039. end;
  2040. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2041. begin
  2042. with ref^ do
  2043. Result :=
  2044. (index = NR_NO) and
  2045. (
  2046. {$ifdef x86_64}
  2047. (
  2048. (base = NR_RIP) and
  2049. (refaddr in [addr_pic, addr_pic_no_got])
  2050. ) or
  2051. {$endif x86_64}
  2052. (base = NR_STACK_POINTER_REG) or
  2053. (base = current_procinfo.framepointer)
  2054. );
  2055. end;
  2056. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2057. var
  2058. l: asizeint;
  2059. begin
  2060. Result := False;
  2061. { Should have been checked previously }
  2062. if p.opcode <> A_LEA then
  2063. InternalError(2020072501);
  2064. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2065. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2066. not(cs_opt_size in current_settings.optimizerswitches) then
  2067. exit;
  2068. with p.oper[0]^.ref^ do
  2069. begin
  2070. if (base <> p.oper[1]^.reg) or
  2071. (index <> NR_NO) or
  2072. assigned(symbol) then
  2073. exit;
  2074. l:=offset;
  2075. if (l=1) and UseIncDec then
  2076. begin
  2077. p.opcode:=A_INC;
  2078. p.loadreg(0,p.oper[1]^.reg);
  2079. p.ops:=1;
  2080. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2081. end
  2082. else if (l=-1) and UseIncDec then
  2083. begin
  2084. p.opcode:=A_DEC;
  2085. p.loadreg(0,p.oper[1]^.reg);
  2086. p.ops:=1;
  2087. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2088. end
  2089. else
  2090. begin
  2091. if (l<0) and (l<>-2147483648) then
  2092. begin
  2093. p.opcode:=A_SUB;
  2094. p.loadConst(0,-l);
  2095. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2096. end
  2097. else
  2098. begin
  2099. p.opcode:=A_ADD;
  2100. p.loadConst(0,l);
  2101. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2102. end;
  2103. end;
  2104. end;
  2105. Result := True;
  2106. end;
  2107. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2108. var
  2109. CurrentReg, ReplaceReg: TRegister;
  2110. begin
  2111. Result := False;
  2112. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2113. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2114. case hp.opcode of
  2115. A_FSTSW, A_FNSTSW,
  2116. A_IN, A_INS, A_OUT, A_OUTS,
  2117. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2118. { These routines have explicit operands, but they are restricted in
  2119. what they can be (e.g. IN and OUT can only read from AL, AX or
  2120. EAX. }
  2121. Exit;
  2122. A_IMUL:
  2123. begin
  2124. { The 1-operand version writes to implicit registers
  2125. The 2-operand version reads from the first operator, and reads
  2126. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2127. the 3-operand version reads from a register that it doesn't write to
  2128. }
  2129. case hp.ops of
  2130. 1:
  2131. if (
  2132. (
  2133. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2134. ) or
  2135. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2136. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2137. begin
  2138. Result := True;
  2139. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2140. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2141. end;
  2142. 2:
  2143. { Only modify the first parameter }
  2144. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2145. begin
  2146. Result := True;
  2147. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2148. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2149. end;
  2150. 3:
  2151. { Only modify the second parameter }
  2152. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2153. begin
  2154. Result := True;
  2155. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2156. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2157. end;
  2158. else
  2159. InternalError(2020012901);
  2160. end;
  2161. end;
  2162. else
  2163. if (hp.ops > 0) and
  2164. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2165. begin
  2166. Result := True;
  2167. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2168. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2169. end;
  2170. end;
  2171. end;
  2172. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2173. var
  2174. hp1, hp2, hp3: tai;
  2175. DoOptimisation, TempBool: Boolean;
  2176. {$ifdef x86_64}
  2177. NewConst: TCGInt;
  2178. {$endif x86_64}
  2179. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2180. begin
  2181. if taicpu(hp1).opcode = signed_movop then
  2182. begin
  2183. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2184. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2185. end
  2186. else
  2187. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2188. end;
  2189. function TryConstMerge(var p1, p2: tai): Boolean;
  2190. var
  2191. ThisRef: TReference;
  2192. begin
  2193. Result := False;
  2194. ThisRef := taicpu(p2).oper[1]^.ref^;
  2195. { Only permit writes to the stack, since we can guarantee alignment with that }
  2196. if (ThisRef.index = NR_NO) and
  2197. (
  2198. (ThisRef.base = NR_STACK_POINTER_REG) or
  2199. (ThisRef.base = current_procinfo.framepointer)
  2200. ) then
  2201. begin
  2202. case taicpu(p).opsize of
  2203. S_B:
  2204. begin
  2205. { Word writes must be on a 2-byte boundary }
  2206. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2207. begin
  2208. { Reduce offset of second reference to see if it is sequential with the first }
  2209. Dec(ThisRef.offset, 1);
  2210. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2211. begin
  2212. { Make sure the constants aren't represented as a
  2213. negative number, as these won't merge properly }
  2214. taicpu(p1).opsize := S_W;
  2215. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2216. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2217. RemoveInstruction(p2);
  2218. Result := True;
  2219. end;
  2220. end;
  2221. end;
  2222. S_W:
  2223. begin
  2224. { Longword writes must be on a 4-byte boundary }
  2225. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2226. begin
  2227. { Reduce offset of second reference to see if it is sequential with the first }
  2228. Dec(ThisRef.offset, 2);
  2229. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2230. begin
  2231. { Make sure the constants aren't represented as a
  2232. negative number, as these won't merge properly }
  2233. taicpu(p1).opsize := S_L;
  2234. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2235. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2236. RemoveInstruction(p2);
  2237. Result := True;
  2238. end;
  2239. end;
  2240. end;
  2241. {$ifdef x86_64}
  2242. S_L:
  2243. begin
  2244. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2245. see if the constants can be encoded this way. }
  2246. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2247. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2248. { Quadword writes must be on an 8-byte boundary }
  2249. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2250. begin
  2251. { Reduce offset of second reference to see if it is sequential with the first }
  2252. Dec(ThisRef.offset, 4);
  2253. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2254. begin
  2255. { Make sure the constants aren't represented as a
  2256. negative number, as these won't merge properly }
  2257. taicpu(p1).opsize := S_Q;
  2258. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2259. taicpu(p1).oper[0]^.val := NewConst;
  2260. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2261. RemoveInstruction(p2);
  2262. Result := True;
  2263. end;
  2264. end;
  2265. end;
  2266. {$endif x86_64}
  2267. else
  2268. ;
  2269. end;
  2270. end;
  2271. end;
  2272. var
  2273. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2274. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2275. NewSize: topsize;
  2276. CurrentReg, ActiveReg: TRegister;
  2277. SourceRef, TargetRef: TReference;
  2278. MovAligned, MovUnaligned: TAsmOp;
  2279. begin
  2280. Result:=false;
  2281. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2282. { remove mov reg1,reg1? }
  2283. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2284. then
  2285. begin
  2286. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2287. { take care of the register (de)allocs following p }
  2288. RemoveCurrentP(p, hp1);
  2289. Result:=true;
  2290. exit;
  2291. end;
  2292. { All the next optimisations require a next instruction }
  2293. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2294. Exit;
  2295. { Look for:
  2296. mov %reg1,%reg2
  2297. ??? %reg2,r/m
  2298. Change to:
  2299. mov %reg1,%reg2
  2300. ??? %reg1,r/m
  2301. }
  2302. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2303. begin
  2304. CurrentReg := taicpu(p).oper[1]^.reg;
  2305. if RegReadByInstruction(CurrentReg, hp1) and
  2306. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2307. begin
  2308. { A change has occurred, just not in p }
  2309. Result := True;
  2310. TransferUsedRegs(TmpUsedRegs);
  2311. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2312. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2313. { Just in case something didn't get modified (e.g. an
  2314. implicit register) }
  2315. not RegReadByInstruction(CurrentReg, hp1) then
  2316. begin
  2317. { We can remove the original MOV }
  2318. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2319. RemoveCurrentp(p, hp1);
  2320. { UsedRegs got updated by RemoveCurrentp }
  2321. Result := True;
  2322. Exit;
  2323. end;
  2324. { If we know a MOV instruction has become a null operation, we might as well
  2325. get rid of it now to save time. }
  2326. if (taicpu(hp1).opcode = A_MOV) and
  2327. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2328. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2329. { Just being a register is enough to confirm it's a null operation }
  2330. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2331. begin
  2332. Result := True;
  2333. { Speed-up to reduce a pipeline stall... if we had something like...
  2334. movl %eax,%edx
  2335. movw %dx,%ax
  2336. ... the second instruction would change to movw %ax,%ax, but
  2337. given that it is now %ax that's active rather than %eax,
  2338. penalties might occur due to a partial register write, so instead,
  2339. change it to a MOVZX instruction when optimising for speed.
  2340. }
  2341. if not (cs_opt_size in current_settings.optimizerswitches) and
  2342. IsMOVZXAcceptable and
  2343. (taicpu(hp1).opsize < taicpu(p).opsize)
  2344. {$ifdef x86_64}
  2345. { operations already implicitly set the upper 64 bits to zero }
  2346. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2347. {$endif x86_64}
  2348. then
  2349. begin
  2350. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2351. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2352. case taicpu(p).opsize of
  2353. S_W:
  2354. if taicpu(hp1).opsize = S_B then
  2355. taicpu(hp1).opsize := S_BL
  2356. else
  2357. InternalError(2020012911);
  2358. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2359. case taicpu(hp1).opsize of
  2360. S_B:
  2361. taicpu(hp1).opsize := S_BL;
  2362. S_W:
  2363. taicpu(hp1).opsize := S_WL;
  2364. else
  2365. InternalError(2020012912);
  2366. end;
  2367. else
  2368. InternalError(2020012910);
  2369. end;
  2370. taicpu(hp1).opcode := A_MOVZX;
  2371. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2372. end
  2373. else
  2374. begin
  2375. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2376. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2377. RemoveInstruction(hp1);
  2378. { The instruction after what was hp1 is now the immediate next instruction,
  2379. so we can continue to make optimisations if it's present }
  2380. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2381. Exit;
  2382. hp1 := hp2;
  2383. end;
  2384. end;
  2385. end;
  2386. end;
  2387. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2388. overwrites the original destination register. e.g.
  2389. movl ###,%reg2d
  2390. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2391. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2392. }
  2393. if (taicpu(p).oper[1]^.typ = top_reg) and
  2394. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2395. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2396. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2397. begin
  2398. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2399. begin
  2400. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2401. case taicpu(p).oper[0]^.typ of
  2402. top_const:
  2403. { We have something like:
  2404. movb $x, %regb
  2405. movzbl %regb,%regd
  2406. Change to:
  2407. movl $x, %regd
  2408. }
  2409. begin
  2410. case taicpu(hp1).opsize of
  2411. S_BW:
  2412. begin
  2413. convert_mov_value(A_MOVSX, $FF);
  2414. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2415. taicpu(p).opsize := S_W;
  2416. end;
  2417. S_BL:
  2418. begin
  2419. convert_mov_value(A_MOVSX, $FF);
  2420. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2421. taicpu(p).opsize := S_L;
  2422. end;
  2423. S_WL:
  2424. begin
  2425. convert_mov_value(A_MOVSX, $FFFF);
  2426. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2427. taicpu(p).opsize := S_L;
  2428. end;
  2429. {$ifdef x86_64}
  2430. S_BQ:
  2431. begin
  2432. convert_mov_value(A_MOVSX, $FF);
  2433. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2434. taicpu(p).opsize := S_Q;
  2435. end;
  2436. S_WQ:
  2437. begin
  2438. convert_mov_value(A_MOVSX, $FFFF);
  2439. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2440. taicpu(p).opsize := S_Q;
  2441. end;
  2442. S_LQ:
  2443. begin
  2444. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2445. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2446. taicpu(p).opsize := S_Q;
  2447. end;
  2448. {$endif x86_64}
  2449. else
  2450. { If hp1 was a MOV instruction, it should have been
  2451. optimised already }
  2452. InternalError(2020021001);
  2453. end;
  2454. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2455. RemoveInstruction(hp1);
  2456. Result := True;
  2457. Exit;
  2458. end;
  2459. top_ref:
  2460. { We have something like:
  2461. movb mem, %regb
  2462. movzbl %regb,%regd
  2463. Change to:
  2464. movzbl mem, %regd
  2465. }
  2466. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2467. begin
  2468. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2469. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2470. RemoveCurrentP(p, hp1);
  2471. Result:=True;
  2472. Exit;
  2473. end;
  2474. else
  2475. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2476. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2477. Exit;
  2478. end;
  2479. end
  2480. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2481. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2482. optimised }
  2483. else
  2484. begin
  2485. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2486. RemoveCurrentP(p, hp1);
  2487. Result := True;
  2488. Exit;
  2489. end;
  2490. end;
  2491. if (taicpu(hp1).opcode = A_AND) and
  2492. (taicpu(p).oper[1]^.typ = top_reg) and
  2493. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2494. begin
  2495. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2496. begin
  2497. case taicpu(p).opsize of
  2498. S_L:
  2499. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2500. begin
  2501. { Optimize out:
  2502. mov x, %reg
  2503. and ffffffffh, %reg
  2504. }
  2505. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2506. RemoveInstruction(hp1);
  2507. Result:=true;
  2508. exit;
  2509. end;
  2510. S_Q: { TODO: Confirm if this is even possible }
  2511. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2512. begin
  2513. { Optimize out:
  2514. mov x, %reg
  2515. and ffffffffffffffffh, %reg
  2516. }
  2517. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2518. RemoveInstruction(hp1);
  2519. Result:=true;
  2520. exit;
  2521. end;
  2522. else
  2523. ;
  2524. end;
  2525. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2526. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2527. GetNextInstruction(hp1,hp2) and
  2528. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2529. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2530. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2531. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2532. GetNextInstruction(hp2,hp3) and
  2533. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2534. (taicpu(hp3).condition in [C_E,C_NE]) then
  2535. begin
  2536. TransferUsedRegs(TmpUsedRegs);
  2537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2538. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2539. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2540. begin
  2541. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2542. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2543. taicpu(hp1).opcode:=A_TEST;
  2544. RemoveInstruction(hp2);
  2545. RemoveCurrentP(p, hp1);
  2546. Result:=true;
  2547. exit;
  2548. end;
  2549. end;
  2550. end
  2551. else if IsMOVZXAcceptable and
  2552. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2553. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2554. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2555. then
  2556. begin
  2557. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2558. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2559. case taicpu(p).opsize of
  2560. S_B:
  2561. if (taicpu(hp1).oper[0]^.val = $ff) then
  2562. begin
  2563. { Convert:
  2564. movb x, %regl movb x, %regl
  2565. andw ffh, %regw andl ffh, %regd
  2566. To:
  2567. movzbw x, %regd movzbl x, %regd
  2568. (Identical registers, just different sizes)
  2569. }
  2570. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2571. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2572. case taicpu(hp1).opsize of
  2573. S_W: NewSize := S_BW;
  2574. S_L: NewSize := S_BL;
  2575. {$ifdef x86_64}
  2576. S_Q: NewSize := S_BQ;
  2577. {$endif x86_64}
  2578. else
  2579. InternalError(2018011510);
  2580. end;
  2581. end
  2582. else
  2583. NewSize := S_NO;
  2584. S_W:
  2585. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2586. begin
  2587. { Convert:
  2588. movw x, %regw
  2589. andl ffffh, %regd
  2590. To:
  2591. movzwl x, %regd
  2592. (Identical registers, just different sizes)
  2593. }
  2594. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2595. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2596. case taicpu(hp1).opsize of
  2597. S_L: NewSize := S_WL;
  2598. {$ifdef x86_64}
  2599. S_Q: NewSize := S_WQ;
  2600. {$endif x86_64}
  2601. else
  2602. InternalError(2018011511);
  2603. end;
  2604. end
  2605. else
  2606. NewSize := S_NO;
  2607. else
  2608. NewSize := S_NO;
  2609. end;
  2610. if NewSize <> S_NO then
  2611. begin
  2612. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2613. { The actual optimization }
  2614. taicpu(p).opcode := A_MOVZX;
  2615. taicpu(p).changeopsize(NewSize);
  2616. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2617. { Safeguard if "and" is followed by a conditional command }
  2618. TransferUsedRegs(TmpUsedRegs);
  2619. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2620. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2621. begin
  2622. { At this point, the "and" command is effectively equivalent to
  2623. "test %reg,%reg". This will be handled separately by the
  2624. Peephole Optimizer. [Kit] }
  2625. DebugMsg(SPeepholeOptimization + PreMessage +
  2626. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2627. end
  2628. else
  2629. begin
  2630. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2631. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2632. RemoveInstruction(hp1);
  2633. end;
  2634. Result := True;
  2635. Exit;
  2636. end;
  2637. end;
  2638. end;
  2639. if (taicpu(hp1).opcode = A_OR) and
  2640. (taicpu(p).oper[1]^.typ = top_reg) and
  2641. MatchOperand(taicpu(p).oper[0]^, 0) and
  2642. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2643. begin
  2644. { mov 0, %reg
  2645. or ###,%reg
  2646. Change to (only if the flags are not used):
  2647. mov ###,%reg
  2648. }
  2649. TransferUsedRegs(TmpUsedRegs);
  2650. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2651. DoOptimisation := True;
  2652. { Even if the flags are used, we might be able to do the optimisation
  2653. if the conditions are predictable }
  2654. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2655. begin
  2656. { Only perform if ### = %reg (the same register) or equal to 0,
  2657. so %reg is guaranteed to still have a value of zero }
  2658. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2659. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2660. begin
  2661. hp2 := hp1;
  2662. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2663. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2664. GetNextInstruction(hp2, hp3) do
  2665. begin
  2666. { Don't continue modifying if the flags state is getting changed }
  2667. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2668. Break;
  2669. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2670. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2671. begin
  2672. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2673. begin
  2674. { Condition is always true }
  2675. case taicpu(hp3).opcode of
  2676. A_Jcc:
  2677. begin
  2678. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2679. { Check for jump shortcuts before we destroy the condition }
  2680. DoJumpOptimizations(hp3, TempBool);
  2681. MakeUnconditional(taicpu(hp3));
  2682. Result := True;
  2683. end;
  2684. A_CMOVcc:
  2685. begin
  2686. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2687. taicpu(hp3).opcode := A_MOV;
  2688. taicpu(hp3).condition := C_None;
  2689. Result := True;
  2690. end;
  2691. A_SETcc:
  2692. begin
  2693. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2694. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2695. taicpu(hp3).opcode := A_MOV;
  2696. taicpu(hp3).ops := 2;
  2697. taicpu(hp3).condition := C_None;
  2698. taicpu(hp3).opsize := S_B;
  2699. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2700. taicpu(hp3).loadconst(0, 1);
  2701. Result := True;
  2702. end;
  2703. else
  2704. InternalError(2021090701);
  2705. end;
  2706. end
  2707. 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
  2708. begin
  2709. { Condition is always false }
  2710. case taicpu(hp3).opcode of
  2711. A_Jcc:
  2712. begin
  2713. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2714. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2715. RemoveInstruction(hp3);
  2716. Result := True;
  2717. { Since hp3 was deleted, hp2 must not be updated }
  2718. Continue;
  2719. end;
  2720. A_CMOVcc:
  2721. begin
  2722. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2723. RemoveInstruction(hp3);
  2724. Result := True;
  2725. { Since hp3 was deleted, hp2 must not be updated }
  2726. Continue;
  2727. end;
  2728. A_SETcc:
  2729. begin
  2730. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2731. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2732. taicpu(hp3).opcode := A_MOV;
  2733. taicpu(hp3).ops := 2;
  2734. taicpu(hp3).condition := C_None;
  2735. taicpu(hp3).opsize := S_B;
  2736. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2737. taicpu(hp3).loadconst(0, 0);
  2738. Result := True;
  2739. end;
  2740. else
  2741. InternalError(2021090702);
  2742. end;
  2743. end
  2744. else
  2745. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2746. DoOptimisation := False;
  2747. end;
  2748. hp2 := hp3;
  2749. end;
  2750. { Flags are still in use - don't optimise }
  2751. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2752. DoOptimisation := False;
  2753. end
  2754. else
  2755. DoOptimisation := False;
  2756. end;
  2757. if DoOptimisation then
  2758. begin
  2759. {$ifdef x86_64}
  2760. { OR only supports 32-bit sign-extended constants for 64-bit
  2761. instructions, so compensate for this if the constant is
  2762. encoded as a value greater than or equal to 2^31 }
  2763. if (taicpu(hp1).opsize = S_Q) and
  2764. (taicpu(hp1).oper[0]^.typ = top_const) and
  2765. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2766. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2767. {$endif x86_64}
  2768. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2769. taicpu(hp1).opcode := A_MOV;
  2770. RemoveCurrentP(p, hp1);
  2771. Result := True;
  2772. Exit;
  2773. end;
  2774. end;
  2775. { Next instruction is also a MOV ? }
  2776. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2777. begin
  2778. if MatchOpType(taicpu(p), top_const, top_ref) and
  2779. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2780. TryConstMerge(p, hp1) then
  2781. begin
  2782. Result := True;
  2783. { In case we have four byte writes in a row, check for 2 more
  2784. right now so we don't have to wait for another iteration of
  2785. pass 1
  2786. }
  2787. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2788. case taicpu(p).opsize of
  2789. S_W:
  2790. begin
  2791. if GetNextInstruction(p, hp1) and
  2792. MatchInstruction(hp1, A_MOV, [S_B]) and
  2793. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2794. GetNextInstruction(hp1, hp2) and
  2795. MatchInstruction(hp2, A_MOV, [S_B]) and
  2796. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2797. { Try to merge the two bytes }
  2798. TryConstMerge(hp1, hp2) then
  2799. { Now try to merge the two words (hp2 will get deleted) }
  2800. TryConstMerge(p, hp1);
  2801. end;
  2802. S_L:
  2803. begin
  2804. { Though this only really benefits x86_64 and not i386, it
  2805. gets a potential optimisation done faster and hence
  2806. reduces the number of times OptPass1MOV is entered }
  2807. if GetNextInstruction(p, hp1) and
  2808. MatchInstruction(hp1, A_MOV, [S_W]) and
  2809. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2810. GetNextInstruction(hp1, hp2) and
  2811. MatchInstruction(hp2, A_MOV, [S_W]) and
  2812. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2813. { Try to merge the two words }
  2814. TryConstMerge(hp1, hp2) then
  2815. { This will always fail on i386, so don't bother
  2816. calling it unless we're doing x86_64 }
  2817. {$ifdef x86_64}
  2818. { Now try to merge the two longwords (hp2 will get deleted) }
  2819. TryConstMerge(p, hp1)
  2820. {$endif x86_64}
  2821. ;
  2822. end;
  2823. else
  2824. ;
  2825. end;
  2826. Exit;
  2827. end;
  2828. if (taicpu(p).oper[1]^.typ = top_reg) and
  2829. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2830. begin
  2831. CurrentReg := taicpu(p).oper[1]^.reg;
  2832. TransferUsedRegs(TmpUsedRegs);
  2833. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2834. { we have
  2835. mov x, %treg
  2836. mov %treg, y
  2837. }
  2838. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2839. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2840. { we've got
  2841. mov x, %treg
  2842. mov %treg, y
  2843. with %treg is not used after }
  2844. case taicpu(p).oper[0]^.typ Of
  2845. { top_reg is covered by DeepMOVOpt }
  2846. top_const:
  2847. begin
  2848. { change
  2849. mov const, %treg
  2850. mov %treg, y
  2851. to
  2852. mov const, y
  2853. }
  2854. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2855. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2856. begin
  2857. if taicpu(hp1).oper[1]^.typ=top_reg then
  2858. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2859. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2860. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2861. RemoveInstruction(hp1);
  2862. Result:=true;
  2863. Exit;
  2864. end;
  2865. end;
  2866. top_ref:
  2867. case taicpu(hp1).oper[1]^.typ of
  2868. top_reg:
  2869. begin
  2870. { change
  2871. mov mem, %treg
  2872. mov %treg, %reg
  2873. to
  2874. mov mem, %reg"
  2875. }
  2876. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2877. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2878. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2879. RemoveInstruction(hp1);
  2880. Result:=true;
  2881. Exit;
  2882. end;
  2883. top_ref:
  2884. begin
  2885. {$ifdef x86_64}
  2886. { Look for the following to simplify:
  2887. mov x(mem1), %reg
  2888. mov %reg, y(mem2)
  2889. mov x+8(mem1), %reg
  2890. mov %reg, y+8(mem2)
  2891. Change to:
  2892. movdqu x(mem1), %xmmreg
  2893. movdqu %xmmreg, y(mem2)
  2894. }
  2895. SourceRef := taicpu(p).oper[0]^.ref^;
  2896. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2897. if (taicpu(p).opsize = S_Q) and
  2898. GetNextInstruction(hp1, hp2) and
  2899. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2900. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2901. begin
  2902. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2903. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2904. Inc(SourceRef.offset, 8);
  2905. if UseAVX then
  2906. begin
  2907. MovAligned := A_VMOVDQA;
  2908. MovUnaligned := A_VMOVDQU;
  2909. end
  2910. else
  2911. begin
  2912. MovAligned := A_MOVDQA;
  2913. MovUnaligned := A_MOVDQU;
  2914. end;
  2915. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2916. begin
  2917. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2918. Inc(TargetRef.offset, 8);
  2919. if GetNextInstruction(hp2, hp3) and
  2920. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2921. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2922. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2923. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2924. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2925. begin
  2926. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2927. if CurrentReg <> NR_NO then
  2928. begin
  2929. { Remember that the offsets are 8 ahead }
  2930. if ((SourceRef.offset mod 16) = 8) and
  2931. (
  2932. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2933. (SourceRef.base = current_procinfo.framepointer) or
  2934. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2935. ) then
  2936. taicpu(p).opcode := MovAligned
  2937. else
  2938. taicpu(p).opcode := MovUnaligned;
  2939. taicpu(p).opsize := S_XMM;
  2940. taicpu(p).oper[1]^.reg := CurrentReg;
  2941. if ((TargetRef.offset mod 16) = 8) and
  2942. (
  2943. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2944. (TargetRef.base = current_procinfo.framepointer) or
  2945. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2946. ) then
  2947. taicpu(hp1).opcode := MovAligned
  2948. else
  2949. taicpu(hp1).opcode := MovUnaligned;
  2950. taicpu(hp1).opsize := S_XMM;
  2951. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2952. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2953. RemoveInstruction(hp2);
  2954. RemoveInstruction(hp3);
  2955. Result := True;
  2956. Exit;
  2957. end;
  2958. end;
  2959. end
  2960. else
  2961. begin
  2962. { See if the next references are 8 less rather than 8 greater }
  2963. Dec(SourceRef.offset, 16); { -8 the other way }
  2964. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2965. begin
  2966. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2967. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2968. if GetNextInstruction(hp2, hp3) and
  2969. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2970. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2971. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2972. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2973. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2974. begin
  2975. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2976. if CurrentReg <> NR_NO then
  2977. begin
  2978. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2979. if ((SourceRef.offset mod 16) = 0) and
  2980. (
  2981. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2982. (SourceRef.base = current_procinfo.framepointer) or
  2983. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2984. ) then
  2985. taicpu(hp2).opcode := MovAligned
  2986. else
  2987. taicpu(hp2).opcode := MovUnaligned;
  2988. taicpu(hp2).opsize := S_XMM;
  2989. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2990. if ((TargetRef.offset mod 16) = 0) and
  2991. (
  2992. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2993. (TargetRef.base = current_procinfo.framepointer) or
  2994. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2995. ) then
  2996. taicpu(hp3).opcode := MovAligned
  2997. else
  2998. taicpu(hp3).opcode := MovUnaligned;
  2999. taicpu(hp3).opsize := S_XMM;
  3000. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3001. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3002. RemoveInstruction(hp1);
  3003. RemoveCurrentP(p, hp2);
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. end;
  3008. end;
  3009. end;
  3010. end;
  3011. {$endif x86_64}
  3012. end;
  3013. else
  3014. { The write target should be a reg or a ref }
  3015. InternalError(2021091601);
  3016. end;
  3017. else
  3018. ;
  3019. end
  3020. else
  3021. { %treg is used afterwards, but all eventualities
  3022. other than the first MOV instruction being a constant
  3023. are covered by DeepMOVOpt, so only check for that }
  3024. if (taicpu(p).oper[0]^.typ = top_const) and
  3025. (
  3026. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3027. not (cs_opt_size in current_settings.optimizerswitches) or
  3028. (taicpu(hp1).opsize = S_B)
  3029. ) and
  3030. (
  3031. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3032. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3033. ) then
  3034. begin
  3035. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3036. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3037. end;
  3038. end;
  3039. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3040. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3041. { mov reg1, mem1 or mov mem1, reg1
  3042. mov mem2, reg2 mov reg2, mem2}
  3043. begin
  3044. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3045. { mov reg1, mem1 or mov mem1, reg1
  3046. mov mem2, reg1 mov reg2, mem1}
  3047. begin
  3048. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3049. { Removes the second statement from
  3050. mov reg1, mem1/reg2
  3051. mov mem1/reg2, reg1 }
  3052. begin
  3053. if taicpu(p).oper[0]^.typ=top_reg then
  3054. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3055. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3056. RemoveInstruction(hp1);
  3057. Result:=true;
  3058. exit;
  3059. end
  3060. else
  3061. begin
  3062. TransferUsedRegs(TmpUsedRegs);
  3063. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3064. if (taicpu(p).oper[1]^.typ = top_ref) and
  3065. { mov reg1, mem1
  3066. mov mem2, reg1 }
  3067. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3068. GetNextInstruction(hp1, hp2) and
  3069. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3070. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3071. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3072. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3073. { change to
  3074. mov reg1, mem1 mov reg1, mem1
  3075. mov mem2, reg1 cmp reg1, mem2
  3076. cmp mem1, reg1
  3077. }
  3078. begin
  3079. RemoveInstruction(hp2);
  3080. taicpu(hp1).opcode := A_CMP;
  3081. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3082. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3083. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3084. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3085. end;
  3086. end;
  3087. end
  3088. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3089. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3090. begin
  3091. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3092. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3093. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3094. end
  3095. else
  3096. begin
  3097. TransferUsedRegs(TmpUsedRegs);
  3098. if GetNextInstruction(hp1, hp2) and
  3099. MatchOpType(taicpu(p),top_ref,top_reg) and
  3100. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3101. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3102. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3103. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3104. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3105. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3106. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3107. { mov mem1, %reg1
  3108. mov %reg1, mem2
  3109. mov mem2, reg2
  3110. to:
  3111. mov mem1, reg2
  3112. mov reg2, mem2}
  3113. begin
  3114. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3115. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3116. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3117. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3118. RemoveInstruction(hp2);
  3119. Result := True;
  3120. end
  3121. {$ifdef i386}
  3122. { this is enabled for i386 only, as the rules to create the reg sets below
  3123. are too complicated for x86-64, so this makes this code too error prone
  3124. on x86-64
  3125. }
  3126. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3127. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3128. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3129. { mov mem1, reg1 mov mem1, reg1
  3130. mov reg1, mem2 mov reg1, mem2
  3131. mov mem2, reg2 mov mem2, reg1
  3132. to: to:
  3133. mov mem1, reg1 mov mem1, reg1
  3134. mov mem1, reg2 mov reg1, mem2
  3135. mov reg1, mem2
  3136. or (if mem1 depends on reg1
  3137. and/or if mem2 depends on reg2)
  3138. to:
  3139. mov mem1, reg1
  3140. mov reg1, mem2
  3141. mov reg1, reg2
  3142. }
  3143. begin
  3144. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3145. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3146. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3147. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3148. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3149. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3150. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3151. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3152. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3153. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3154. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3155. end
  3156. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3157. begin
  3158. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3159. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3160. end
  3161. else
  3162. begin
  3163. RemoveInstruction(hp2);
  3164. end
  3165. {$endif i386}
  3166. ;
  3167. end;
  3168. end
  3169. { movl [mem1],reg1
  3170. movl [mem1],reg2
  3171. to
  3172. movl [mem1],reg1
  3173. movl reg1,reg2
  3174. }
  3175. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3176. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3177. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3178. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3179. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3180. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3181. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3182. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3183. begin
  3184. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3185. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3186. end;
  3187. { movl const1,[mem1]
  3188. movl [mem1],reg1
  3189. to
  3190. movl const1,reg1
  3191. movl reg1,[mem1]
  3192. }
  3193. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3194. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3195. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3196. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3197. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3198. begin
  3199. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3200. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3201. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3202. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3203. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3204. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3205. Result:=true;
  3206. exit;
  3207. end;
  3208. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3209. end;
  3210. { search further than the next instruction for a mov (as long as it's not a jump) }
  3211. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3212. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3213. (taicpu(p).oper[1]^.typ = top_reg) and
  3214. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3215. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3216. begin
  3217. { we work with hp2 here, so hp1 can be still used later on when
  3218. checking for GetNextInstruction_p }
  3219. hp3 := hp1;
  3220. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3221. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3222. { Saves on a large number of dereferences }
  3223. ActiveReg := taicpu(p).oper[1]^.reg;
  3224. TransferUsedRegs(TmpUsedRegs);
  3225. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3226. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3227. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3228. (hp2.typ=ait_instruction) do
  3229. begin
  3230. case taicpu(hp2).opcode of
  3231. A_POP:
  3232. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3233. begin
  3234. if not CrossJump and
  3235. not RegUsedBetween(ActiveReg, p, hp2) then
  3236. begin
  3237. { We can remove the original MOV since the register
  3238. wasn't used between it and its popping from the stack }
  3239. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3240. RemoveCurrentp(p, hp1);
  3241. Result := True;
  3242. Exit;
  3243. end;
  3244. { Can't go any further }
  3245. Break;
  3246. end;
  3247. A_MOV:
  3248. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3249. ((taicpu(p).oper[0]^.typ=top_const) or
  3250. ((taicpu(p).oper[0]^.typ=top_reg) and
  3251. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3252. )
  3253. ) then
  3254. begin
  3255. { we have
  3256. mov x, %treg
  3257. mov %treg, y
  3258. }
  3259. { We don't need to call UpdateUsedRegs for every instruction between
  3260. p and hp2 because the register we're concerned about will not
  3261. become deallocated (otherwise GetNextInstructionUsingReg would
  3262. have stopped at an earlier instruction). [Kit] }
  3263. TempRegUsed :=
  3264. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3265. RegReadByInstruction(ActiveReg, hp3) or
  3266. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3267. case taicpu(p).oper[0]^.typ Of
  3268. top_reg:
  3269. begin
  3270. { change
  3271. mov %reg, %treg
  3272. mov %treg, y
  3273. to
  3274. mov %reg, y
  3275. }
  3276. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3277. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3278. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3279. begin
  3280. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3281. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3282. if TempRegUsed then
  3283. begin
  3284. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3285. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3286. { Set the start of the next GetNextInstructionUsingRegCond search
  3287. to start at the entry right before hp2 (which is about to be removed) }
  3288. hp3 := tai(hp2.Previous);
  3289. RemoveInstruction(hp2);
  3290. { See if there's more we can optimise }
  3291. Continue;
  3292. end
  3293. else
  3294. begin
  3295. RemoveInstruction(hp2);
  3296. { We can remove the original MOV too }
  3297. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3298. RemoveCurrentP(p, hp1);
  3299. Result:=true;
  3300. Exit;
  3301. end;
  3302. end
  3303. else
  3304. begin
  3305. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3306. taicpu(hp2).loadReg(0, CurrentReg);
  3307. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3308. { Check to see if the register also appears in the reference }
  3309. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3310. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3311. { Don't remove the first instruction if the temporary register is in use }
  3312. if not TempRegUsed and
  3313. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3314. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3315. begin
  3316. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3317. RemoveCurrentP(p, hp1);
  3318. Result:=true;
  3319. Exit;
  3320. end;
  3321. { No need to set Result to True here. If there's another instruction later
  3322. on that can be optimised, it will be detected when the main Pass 1 loop
  3323. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3324. end;
  3325. end;
  3326. top_const:
  3327. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3328. begin
  3329. { change
  3330. mov const, %treg
  3331. mov %treg, y
  3332. to
  3333. mov const, y
  3334. }
  3335. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3336. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3337. begin
  3338. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3339. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3340. if TempRegUsed then
  3341. begin
  3342. { Don't remove the first instruction if the temporary register is in use }
  3343. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3344. { No need to set Result to True. If there's another instruction later on
  3345. that can be optimised, it will be detected when the main Pass 1 loop
  3346. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3347. end
  3348. else
  3349. begin
  3350. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3351. RemoveCurrentP(p, hp1);
  3352. Result:=true;
  3353. Exit;
  3354. end;
  3355. end;
  3356. end;
  3357. else
  3358. Internalerror(2019103001);
  3359. end;
  3360. end
  3361. else
  3362. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3363. begin
  3364. if not CrossJump and
  3365. not RegUsedBetween(ActiveReg, p, hp2) and
  3366. not RegReadByInstruction(ActiveReg, hp2) then
  3367. begin
  3368. { Register is not used before it is overwritten }
  3369. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3370. RemoveCurrentp(p, hp1);
  3371. Result := True;
  3372. Exit;
  3373. end;
  3374. if (taicpu(p).oper[0]^.typ = top_const) and
  3375. (taicpu(hp2).oper[0]^.typ = top_const) then
  3376. begin
  3377. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3378. begin
  3379. { Same value - register hasn't changed }
  3380. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3381. RemoveInstruction(hp2);
  3382. Result := True;
  3383. { See if there's more we can optimise }
  3384. Continue;
  3385. end;
  3386. end;
  3387. end;
  3388. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3389. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3390. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3391. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3392. begin
  3393. {
  3394. Change from:
  3395. mov ###, %reg
  3396. ...
  3397. movs/z %reg,%reg (Same register, just different sizes)
  3398. To:
  3399. movs/z ###, %reg (Longer version)
  3400. ...
  3401. (remove)
  3402. }
  3403. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3404. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3405. { Keep the first instruction as mov if ### is a constant }
  3406. if taicpu(p).oper[0]^.typ = top_const then
  3407. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3408. else
  3409. begin
  3410. taicpu(p).opcode := taicpu(hp2).opcode;
  3411. taicpu(p).opsize := taicpu(hp2).opsize;
  3412. end;
  3413. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3414. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3415. RemoveInstruction(hp2);
  3416. Result := True;
  3417. Exit;
  3418. end;
  3419. else
  3420. { Move down to the MatchOpType if-block below };
  3421. end;
  3422. { Also catches MOV/S/Z instructions that aren't modified }
  3423. if taicpu(p).oper[0]^.typ = top_reg then
  3424. begin
  3425. CurrentReg := taicpu(p).oper[0]^.reg;
  3426. if
  3427. not RegModifiedByInstruction(CurrentReg, hp3) and
  3428. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3429. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3430. begin
  3431. Result := True;
  3432. { Just in case something didn't get modified (e.g. an
  3433. implicit register). Also, if it does read from this
  3434. register, then there's no longer an advantage to
  3435. changing the register on subsequent instructions.}
  3436. if not RegReadByInstruction(ActiveReg, hp2) then
  3437. begin
  3438. { If a conditional jump was crossed, do not delete
  3439. the original MOV no matter what }
  3440. if not CrossJump and
  3441. { RegEndOfLife returns True if the register is
  3442. deallocated before the next instruction or has
  3443. been loaded with a new value }
  3444. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3445. begin
  3446. { We can remove the original MOV }
  3447. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3448. RemoveCurrentp(p, hp1);
  3449. Exit;
  3450. end;
  3451. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3452. begin
  3453. { See if there's more we can optimise }
  3454. hp3 := hp2;
  3455. Continue;
  3456. end;
  3457. end;
  3458. end;
  3459. end;
  3460. { Break out of the while loop under normal circumstances }
  3461. Break;
  3462. end;
  3463. end;
  3464. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3465. (taicpu(p).oper[1]^.typ = top_reg) and
  3466. (taicpu(p).opsize = S_L) and
  3467. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3468. (taicpu(hp2).opcode = A_AND) and
  3469. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3470. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3471. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3472. ) then
  3473. begin
  3474. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3475. begin
  3476. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3477. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3478. begin
  3479. { Optimize out:
  3480. mov x, %reg
  3481. and ffffffffh, %reg
  3482. }
  3483. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3484. RemoveInstruction(hp2);
  3485. Result:=true;
  3486. exit;
  3487. end;
  3488. end;
  3489. end;
  3490. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3491. x >= RetOffset) as it doesn't do anything (it writes either to a
  3492. parameter or to the temporary storage room for the function
  3493. result)
  3494. }
  3495. if IsExitCode(hp1) and
  3496. (taicpu(p).oper[1]^.typ = top_ref) and
  3497. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3498. (
  3499. (
  3500. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3501. not (
  3502. assigned(current_procinfo.procdef.funcretsym) and
  3503. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3504. )
  3505. ) or
  3506. { Also discard writes to the stack that are below the base pointer,
  3507. as this is temporary storage rather than a function result on the
  3508. stack, say. }
  3509. (
  3510. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3511. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3512. )
  3513. ) then
  3514. begin
  3515. RemoveCurrentp(p, hp1);
  3516. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3517. RemoveLastDeallocForFuncRes(p);
  3518. Result:=true;
  3519. exit;
  3520. end;
  3521. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3522. begin
  3523. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3524. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3525. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3526. begin
  3527. { change
  3528. mov reg1, mem1
  3529. test/cmp x, mem1
  3530. to
  3531. mov reg1, mem1
  3532. test/cmp x, reg1
  3533. }
  3534. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3535. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3536. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3537. Result := True;
  3538. Exit;
  3539. end;
  3540. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3541. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3542. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3543. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3544. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3545. (
  3546. (
  3547. (taicpu(hp1).opcode = A_TEST)
  3548. ) or (
  3549. (taicpu(hp1).opcode = A_CMP) and
  3550. { A sanity check more than anything }
  3551. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3552. )
  3553. ) then
  3554. begin
  3555. { change
  3556. mov mem, %reg
  3557. cmp/test x, %reg / test %reg,%reg
  3558. (reg deallocated)
  3559. to
  3560. cmp/test x, mem / cmp 0, mem
  3561. }
  3562. TransferUsedRegs(TmpUsedRegs);
  3563. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3564. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3565. begin
  3566. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3567. if (taicpu(hp1).opcode = A_TEST) and
  3568. (
  3569. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3570. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3571. ) then
  3572. begin
  3573. taicpu(hp1).opcode := A_CMP;
  3574. taicpu(hp1).loadconst(0, 0);
  3575. end;
  3576. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3577. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3578. RemoveCurrentP(p, hp1);
  3579. Result := True;
  3580. Exit;
  3581. end;
  3582. end;
  3583. end;
  3584. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3585. { If the flags register is in use, don't change the instruction to an
  3586. ADD otherwise this will scramble the flags. [Kit] }
  3587. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3588. begin
  3589. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3590. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3591. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3592. ) or
  3593. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3594. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3595. )
  3596. ) then
  3597. { mov reg1,ref
  3598. lea reg2,[reg1,reg2]
  3599. to
  3600. add reg2,ref}
  3601. begin
  3602. TransferUsedRegs(TmpUsedRegs);
  3603. { reg1 may not be used afterwards }
  3604. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3605. begin
  3606. Taicpu(hp1).opcode:=A_ADD;
  3607. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3608. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3609. RemoveCurrentp(p, hp1);
  3610. result:=true;
  3611. exit;
  3612. end;
  3613. end;
  3614. { If the LEA instruction can be converted into an arithmetic instruction,
  3615. it may be possible to then fold it in the next optimisation, otherwise
  3616. there's nothing more that can be optimised here. }
  3617. if not ConvertLEA(taicpu(hp1)) then
  3618. Exit;
  3619. end;
  3620. if (taicpu(p).oper[1]^.typ = top_reg) and
  3621. (hp1.typ = ait_instruction) and
  3622. GetNextInstruction(hp1, hp2) and
  3623. MatchInstruction(hp2,A_MOV,[]) and
  3624. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3625. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3626. (
  3627. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3628. {$ifdef x86_64}
  3629. or
  3630. (
  3631. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3632. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3633. )
  3634. {$endif x86_64}
  3635. ) then
  3636. begin
  3637. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3638. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3639. { change movsX/movzX reg/ref, reg2
  3640. add/sub/or/... reg3/$const, reg2
  3641. mov reg2 reg/ref
  3642. dealloc reg2
  3643. to
  3644. add/sub/or/... reg3/$const, reg/ref }
  3645. begin
  3646. TransferUsedRegs(TmpUsedRegs);
  3647. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3648. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3649. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3650. begin
  3651. { by example:
  3652. movswl %si,%eax movswl %si,%eax p
  3653. decl %eax addl %edx,%eax hp1
  3654. movw %ax,%si movw %ax,%si hp2
  3655. ->
  3656. movswl %si,%eax movswl %si,%eax p
  3657. decw %eax addw %edx,%eax hp1
  3658. movw %ax,%si movw %ax,%si hp2
  3659. }
  3660. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3661. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3662. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3663. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3664. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3665. {
  3666. ->
  3667. movswl %si,%eax movswl %si,%eax p
  3668. decw %si addw %dx,%si hp1
  3669. movw %ax,%si movw %ax,%si hp2
  3670. }
  3671. case taicpu(hp1).ops of
  3672. 1:
  3673. begin
  3674. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3675. if taicpu(hp1).oper[0]^.typ=top_reg then
  3676. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3677. end;
  3678. 2:
  3679. begin
  3680. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3681. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3682. (taicpu(hp1).opcode<>A_SHL) and
  3683. (taicpu(hp1).opcode<>A_SHR) and
  3684. (taicpu(hp1).opcode<>A_SAR) then
  3685. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3686. end;
  3687. else
  3688. internalerror(2008042701);
  3689. end;
  3690. {
  3691. ->
  3692. decw %si addw %dx,%si p
  3693. }
  3694. RemoveInstruction(hp2);
  3695. RemoveCurrentP(p, hp1);
  3696. Result:=True;
  3697. Exit;
  3698. end;
  3699. end;
  3700. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3701. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3702. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3703. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3704. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3705. )
  3706. {$ifdef i386}
  3707. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3708. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3709. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3710. {$endif i386}
  3711. then
  3712. { change movsX/movzX reg/ref, reg2
  3713. add/sub/or/... regX/$const, reg2
  3714. mov reg2, reg3
  3715. dealloc reg2
  3716. to
  3717. movsX/movzX reg/ref, reg3
  3718. add/sub/or/... reg3/$const, reg3
  3719. }
  3720. begin
  3721. TransferUsedRegs(TmpUsedRegs);
  3722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3723. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3724. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3725. begin
  3726. { by example:
  3727. movswl %si,%eax movswl %si,%eax p
  3728. decl %eax addl %edx,%eax hp1
  3729. movw %ax,%si movw %ax,%si hp2
  3730. ->
  3731. movswl %si,%eax movswl %si,%eax p
  3732. decw %eax addw %edx,%eax hp1
  3733. movw %ax,%si movw %ax,%si hp2
  3734. }
  3735. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3736. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3737. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3738. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3739. { limit size of constants as well to avoid assembler errors, but
  3740. check opsize to avoid overflow when left shifting the 1 }
  3741. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3742. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3743. {$ifdef x86_64}
  3744. { Be careful of, for example:
  3745. movl %reg1,%reg2
  3746. addl %reg3,%reg2
  3747. movq %reg2,%reg4
  3748. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3749. }
  3750. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3751. begin
  3752. taicpu(hp2).changeopsize(S_L);
  3753. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3754. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3755. end;
  3756. {$endif x86_64}
  3757. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3758. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3759. if taicpu(p).oper[0]^.typ=top_reg then
  3760. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3761. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3762. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3763. {
  3764. ->
  3765. movswl %si,%eax movswl %si,%eax p
  3766. decw %si addw %dx,%si hp1
  3767. movw %ax,%si movw %ax,%si hp2
  3768. }
  3769. case taicpu(hp1).ops of
  3770. 1:
  3771. begin
  3772. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3773. if taicpu(hp1).oper[0]^.typ=top_reg then
  3774. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3775. end;
  3776. 2:
  3777. begin
  3778. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3779. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3780. (taicpu(hp1).opcode<>A_SHL) and
  3781. (taicpu(hp1).opcode<>A_SHR) and
  3782. (taicpu(hp1).opcode<>A_SAR) then
  3783. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3784. end;
  3785. else
  3786. internalerror(2018111801);
  3787. end;
  3788. {
  3789. ->
  3790. decw %si addw %dx,%si p
  3791. }
  3792. RemoveInstruction(hp2);
  3793. end;
  3794. end;
  3795. end;
  3796. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3797. GetNextInstruction(hp1, hp2) and
  3798. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3799. MatchOperand(Taicpu(p).oper[0]^,0) and
  3800. (Taicpu(p).oper[1]^.typ = top_reg) and
  3801. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3802. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3803. { mov reg1,0
  3804. bts reg1,operand1 --> mov reg1,operand2
  3805. or reg1,operand2 bts reg1,operand1}
  3806. begin
  3807. Taicpu(hp2).opcode:=A_MOV;
  3808. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3809. asml.remove(hp1);
  3810. insertllitem(hp2,hp2.next,hp1);
  3811. RemoveCurrentp(p, hp1);
  3812. Result:=true;
  3813. exit;
  3814. end;
  3815. {
  3816. mov ref,reg0
  3817. <op> reg0,reg1
  3818. dealloc reg0
  3819. to
  3820. <op> ref,reg1
  3821. }
  3822. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3823. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3824. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3825. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3826. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3827. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3828. begin
  3829. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3830. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3831. RemoveCurrentp(p, hp1);
  3832. Result:=true;
  3833. exit;
  3834. end;
  3835. {$ifdef x86_64}
  3836. { Convert:
  3837. movq x(ref),%reg64
  3838. shrq y,%reg64
  3839. To:
  3840. movq x+4(ref),%reg32
  3841. shrq y-32,%reg32 (Remove if y = 32)
  3842. }
  3843. if (taicpu(p).opsize = S_Q) and
  3844. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3845. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3846. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3847. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3848. (taicpu(hp1).oper[0]^.val >= 32) and
  3849. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3850. begin
  3851. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3852. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3853. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3854. { Convert to 32-bit }
  3855. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3856. taicpu(p).opsize := S_L;
  3857. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3858. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3859. if (taicpu(hp1).oper[0]^.val = 32) then
  3860. begin
  3861. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3862. RemoveInstruction(hp1);
  3863. end
  3864. else
  3865. begin
  3866. { This will potentially open up more arithmetic operations since
  3867. the peephole optimizer now has a big hint that only the lower
  3868. 32 bits are currently in use (and opcodes are smaller in size) }
  3869. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3870. taicpu(hp1).opsize := S_L;
  3871. Dec(taicpu(hp1).oper[0]^.val, 32);
  3872. DebugMsg(SPeepholeOptimization + PreMessage +
  3873. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3874. end;
  3875. Result := True;
  3876. Exit;
  3877. end;
  3878. {$endif x86_64}
  3879. end;
  3880. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3881. var
  3882. hp1 : tai;
  3883. begin
  3884. Result:=false;
  3885. if taicpu(p).ops <> 2 then
  3886. exit;
  3887. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3888. GetNextInstruction(p,hp1) then
  3889. begin
  3890. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3891. (taicpu(hp1).ops = 2) then
  3892. begin
  3893. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3894. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3895. { movXX reg1, mem1 or movXX mem1, reg1
  3896. movXX mem2, reg2 movXX reg2, mem2}
  3897. begin
  3898. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3899. { movXX reg1, mem1 or movXX mem1, reg1
  3900. movXX mem2, reg1 movXX reg2, mem1}
  3901. begin
  3902. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3903. begin
  3904. { Removes the second statement from
  3905. movXX reg1, mem1/reg2
  3906. movXX mem1/reg2, reg1
  3907. }
  3908. if taicpu(p).oper[0]^.typ=top_reg then
  3909. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3910. { Removes the second statement from
  3911. movXX mem1/reg1, reg2
  3912. movXX reg2, mem1/reg1
  3913. }
  3914. if (taicpu(p).oper[1]^.typ=top_reg) and
  3915. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3916. begin
  3917. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3918. RemoveInstruction(hp1);
  3919. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3920. Result:=true;
  3921. exit;
  3922. end
  3923. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3924. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3925. begin
  3926. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3927. RemoveInstruction(hp1);
  3928. Result:=true;
  3929. exit;
  3930. end;
  3931. end
  3932. end;
  3933. end;
  3934. end;
  3935. end;
  3936. end;
  3937. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3938. var
  3939. hp1 : tai;
  3940. begin
  3941. result:=false;
  3942. { replace
  3943. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3944. MovX %mreg2,%mreg1
  3945. dealloc %mreg2
  3946. by
  3947. <Op>X %mreg2,%mreg1
  3948. ?
  3949. }
  3950. if GetNextInstruction(p,hp1) and
  3951. { we mix single and double opperations here because we assume that the compiler
  3952. generates vmovapd only after double operations and vmovaps only after single operations }
  3953. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3954. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3955. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3956. (taicpu(p).oper[0]^.typ=top_reg) then
  3957. begin
  3958. TransferUsedRegs(TmpUsedRegs);
  3959. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3960. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3961. begin
  3962. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3963. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3964. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3965. RemoveInstruction(hp1);
  3966. result:=true;
  3967. end;
  3968. end;
  3969. end;
  3970. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3971. var
  3972. hp1, p_label, p_dist, hp1_dist: tai;
  3973. JumpLabel, JumpLabel_dist: TAsmLabel;
  3974. FirstValue, SecondValue: TCGInt;
  3975. begin
  3976. Result := False;
  3977. if (taicpu(p).oper[0]^.typ = top_const) and
  3978. (taicpu(p).oper[0]^.val <> -1) then
  3979. begin
  3980. { Convert unsigned maximum constants to -1 to aid optimisation }
  3981. case taicpu(p).opsize of
  3982. S_B:
  3983. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  3984. begin
  3985. taicpu(p).oper[0]^.val := -1;
  3986. Result := True;
  3987. Exit;
  3988. end;
  3989. S_W:
  3990. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  3991. begin
  3992. taicpu(p).oper[0]^.val := -1;
  3993. Result := True;
  3994. Exit;
  3995. end;
  3996. S_L:
  3997. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  3998. begin
  3999. taicpu(p).oper[0]^.val := -1;
  4000. Result := True;
  4001. Exit;
  4002. end;
  4003. {$ifdef x86_64}
  4004. S_Q:
  4005. { Storing anything greater than $7FFFFFFF is not possible so do
  4006. nothing };
  4007. {$endif x86_64}
  4008. else
  4009. InternalError(2021121001);
  4010. end;
  4011. end;
  4012. if GetNextInstruction(p, hp1) and
  4013. TrySwapMovCmp(p, hp1) then
  4014. begin
  4015. Result := True;
  4016. Exit;
  4017. end;
  4018. { Search for:
  4019. test $x,(reg/ref)
  4020. jne @lbl1
  4021. test $y,(reg/ref) (same register or reference)
  4022. jne @lbl1
  4023. Change to:
  4024. test $(x or y),(reg/ref)
  4025. jne @lbl1
  4026. (Note, this doesn't work with je instead of jne)
  4027. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4028. Also search for:
  4029. test $x,(reg/ref)
  4030. je @lbl1
  4031. test $y,(reg/ref)
  4032. je/jne @lbl2
  4033. If (x or y) = x, then the second jump is deterministic
  4034. }
  4035. if (
  4036. (
  4037. (taicpu(p).oper[0]^.typ = top_const) or
  4038. (
  4039. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4040. (taicpu(p).oper[0]^.typ = top_reg) and
  4041. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4042. )
  4043. ) and
  4044. MatchInstruction(hp1, A_JCC, [])
  4045. ) then
  4046. begin
  4047. if (taicpu(p).oper[0]^.typ = top_reg) and
  4048. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4049. FirstValue := -1
  4050. else
  4051. FirstValue := taicpu(p).oper[0]^.val;
  4052. { If we have several test/jne's in a row, it might be the case that
  4053. the second label doesn't go to the same location, but the one
  4054. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4055. so accommodate for this with a while loop.
  4056. }
  4057. hp1_dist := hp1;
  4058. if GetNextInstruction(hp1, p_dist) and
  4059. (p_dist.typ = ait_instruction) and
  4060. (
  4061. (
  4062. (taicpu(p_dist).opcode = A_TEST) and
  4063. (
  4064. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4065. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4066. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4067. )
  4068. ) or
  4069. (
  4070. { cmp 0,%reg = test %reg,%reg }
  4071. (taicpu(p_dist).opcode = A_CMP) and
  4072. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4073. )
  4074. ) and
  4075. { Make sure the destination operands are actually the same }
  4076. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4077. GetNextInstruction(p_dist, hp1_dist) and
  4078. MatchInstruction(hp1_dist, A_JCC, []) then
  4079. begin
  4080. if
  4081. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4082. (
  4083. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4084. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4085. ) then
  4086. SecondValue := -1
  4087. else
  4088. SecondValue := taicpu(p_dist).oper[0]^.val;
  4089. { If both of the TEST constants are identical, delete the second
  4090. TEST that is unnecessary. }
  4091. if (FirstValue = SecondValue) then
  4092. begin
  4093. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4094. RemoveInstruction(p_dist);
  4095. { Don't let the flags register become deallocated and reallocated between the jumps }
  4096. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4097. Result := True;
  4098. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4099. begin
  4100. { Since the second jump's condition is a subset of the first, we
  4101. know it will never branch because the first jump dominates it.
  4102. Get it out of the way now rather than wait for the jump
  4103. optimisations for a speed boost. }
  4104. if IsJumpToLabel(taicpu(hp1_dist)) then
  4105. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4106. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4107. RemoveInstruction(hp1_dist);
  4108. end
  4109. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4110. begin
  4111. { If the inverse of the first condition is a subset of the second,
  4112. the second one will definitely branch if the first one doesn't }
  4113. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4114. MakeUnconditional(taicpu(hp1_dist));
  4115. RemoveDeadCodeAfterJump(hp1_dist);
  4116. end;
  4117. Exit;
  4118. end;
  4119. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4120. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4121. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4122. then the second jump will never branch, so it can also be
  4123. removed regardless of where it goes }
  4124. (
  4125. (FirstValue = -1) or
  4126. (SecondValue = -1) or
  4127. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4128. ) then
  4129. begin
  4130. { Same jump location... can be a register since nothing's changed }
  4131. { If any of the entries are equivalent to test %reg,%reg, then the
  4132. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4133. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4134. if IsJumpToLabel(taicpu(hp1_dist)) then
  4135. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4136. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4137. RemoveInstruction(hp1_dist);
  4138. { Only remove the second test if no jumps or other conditional instructions follow }
  4139. TransferUsedRegs(TmpUsedRegs);
  4140. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4141. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4142. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4143. RemoveInstruction(p_dist);
  4144. Result := True;
  4145. Exit;
  4146. end;
  4147. end;
  4148. end;
  4149. { Search for:
  4150. test %reg,%reg
  4151. j(c1) @lbl1
  4152. ...
  4153. @lbl:
  4154. test %reg,%reg (same register)
  4155. j(c2) @lbl2
  4156. If c2 is a subset of c1, change to:
  4157. test %reg,%reg
  4158. j(c1) @lbl2
  4159. (@lbl1 may become a dead label as a result)
  4160. }
  4161. if (taicpu(p).oper[1]^.typ = top_reg) and
  4162. (taicpu(p).oper[0]^.typ = top_reg) and
  4163. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4164. MatchInstruction(hp1, A_JCC, []) and
  4165. IsJumpToLabel(taicpu(hp1)) then
  4166. begin
  4167. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4168. p_label := nil;
  4169. if Assigned(JumpLabel) then
  4170. p_label := getlabelwithsym(JumpLabel);
  4171. if Assigned(p_label) and
  4172. GetNextInstruction(p_label, p_dist) and
  4173. MatchInstruction(p_dist, A_TEST, []) and
  4174. { It's fine if the second test uses smaller sub-registers }
  4175. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4176. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4177. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4178. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4179. GetNextInstruction(p_dist, hp1_dist) and
  4180. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4181. begin
  4182. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4183. if JumpLabel = JumpLabel_dist then
  4184. { This is an infinite loop }
  4185. Exit;
  4186. { Best optimisation when the first condition is a subset (or equal) of the second }
  4187. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4188. begin
  4189. { Any registers used here will already be allocated }
  4190. if Assigned(JumpLabel_dist) then
  4191. JumpLabel_dist.IncRefs;
  4192. if Assigned(JumpLabel) then
  4193. JumpLabel.DecRefs;
  4194. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4195. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4196. Result := True;
  4197. Exit;
  4198. end;
  4199. end;
  4200. end;
  4201. end;
  4202. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4203. var
  4204. hp1, hp2: tai;
  4205. ActiveReg: TRegister;
  4206. OldOffset: asizeint;
  4207. ThisConst: TCGInt;
  4208. function RegDeallocated: Boolean;
  4209. begin
  4210. TransferUsedRegs(TmpUsedRegs);
  4211. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4212. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4213. end;
  4214. begin
  4215. result:=false;
  4216. hp1 := nil;
  4217. { replace
  4218. addX const,%reg1
  4219. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4220. dealloc %reg1
  4221. by
  4222. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4223. }
  4224. if MatchOpType(taicpu(p),top_const,top_reg) then
  4225. begin
  4226. ActiveReg := taicpu(p).oper[1]^.reg;
  4227. { Ensures the entire register was updated }
  4228. if (taicpu(p).opsize >= S_L) and
  4229. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4230. MatchInstruction(hp1,A_LEA,[]) and
  4231. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4232. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4233. (
  4234. { Cover the case where the register in the reference is also the destination register }
  4235. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4236. (
  4237. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4238. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4239. RegDeallocated
  4240. )
  4241. ) then
  4242. begin
  4243. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4244. {$push}
  4245. {$R-}{$Q-}
  4246. { Explicitly disable overflow checking for these offset calculation
  4247. as those do not matter for the final result }
  4248. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4249. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4250. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4251. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4252. {$pop}
  4253. {$ifdef x86_64}
  4254. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4255. begin
  4256. { Overflow; abort }
  4257. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4258. end
  4259. else
  4260. {$endif x86_64}
  4261. begin
  4262. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4263. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4264. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4265. RemoveCurrentP(p, hp1)
  4266. else
  4267. RemoveCurrentP(p);
  4268. result:=true;
  4269. Exit;
  4270. end;
  4271. end;
  4272. if (
  4273. { Save calling GetNextInstructionUsingReg again }
  4274. Assigned(hp1) or
  4275. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4276. ) and
  4277. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4278. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4279. begin
  4280. if taicpu(hp1).oper[0]^.typ = top_const then
  4281. begin
  4282. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4283. if taicpu(hp1).opcode = A_ADD then
  4284. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4285. else
  4286. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4287. Result := True;
  4288. { Handle any overflows }
  4289. case taicpu(p).opsize of
  4290. S_B:
  4291. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4292. S_W:
  4293. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4294. S_L:
  4295. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4296. {$ifdef x86_64}
  4297. S_Q:
  4298. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4299. { Overflow; abort }
  4300. Result := False
  4301. else
  4302. taicpu(p).oper[0]^.val := ThisConst;
  4303. {$endif x86_64}
  4304. else
  4305. InternalError(2021102610);
  4306. end;
  4307. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4308. if Result then
  4309. begin
  4310. if (taicpu(p).oper[0]^.val < 0) and
  4311. (
  4312. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4313. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4314. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4315. ) then
  4316. begin
  4317. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4318. taicpu(p).opcode := A_SUB;
  4319. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4320. end
  4321. else
  4322. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4323. RemoveInstruction(hp1);
  4324. end;
  4325. end
  4326. else
  4327. begin
  4328. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4329. TransferUsedRegs(TmpUsedRegs);
  4330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4331. hp2 := p;
  4332. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4333. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4334. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4335. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4336. begin
  4337. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4338. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4339. Asml.Remove(p);
  4340. Asml.InsertAfter(p, hp1);
  4341. p := hp1;
  4342. Result := True;
  4343. end;
  4344. end;
  4345. end;
  4346. end;
  4347. end;
  4348. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4349. var
  4350. hp1: tai;
  4351. ref: Integer;
  4352. saveref: treference;
  4353. TempReg: TRegister;
  4354. Multiple: TCGInt;
  4355. begin
  4356. Result:=false;
  4357. { removes seg register prefixes from LEA operations, as they
  4358. don't do anything}
  4359. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4360. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4361. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4362. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4363. (
  4364. { do not mess with leas accessing the stack pointer
  4365. unless it's a null operation }
  4366. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4367. (
  4368. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4369. (taicpu(p).oper[0]^.ref^.offset = 0)
  4370. )
  4371. ) and
  4372. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4373. begin
  4374. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4375. begin
  4376. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4377. begin
  4378. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4379. taicpu(p).oper[1]^.reg);
  4380. InsertLLItem(p.previous,p.next, hp1);
  4381. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4382. p.free;
  4383. p:=hp1;
  4384. end
  4385. else
  4386. begin
  4387. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4388. RemoveCurrentP(p);
  4389. end;
  4390. Result:=true;
  4391. exit;
  4392. end
  4393. else if (
  4394. { continue to use lea to adjust the stack pointer,
  4395. it is the recommended way, but only if not optimizing for size }
  4396. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4397. (cs_opt_size in current_settings.optimizerswitches)
  4398. ) and
  4399. { If the flags register is in use, don't change the instruction
  4400. to an ADD otherwise this will scramble the flags. [Kit] }
  4401. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4402. ConvertLEA(taicpu(p)) then
  4403. begin
  4404. Result:=true;
  4405. exit;
  4406. end;
  4407. end;
  4408. if GetNextInstruction(p,hp1) and
  4409. (hp1.typ=ait_instruction) then
  4410. begin
  4411. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4412. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4413. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4414. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4415. begin
  4416. TransferUsedRegs(TmpUsedRegs);
  4417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4418. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4419. begin
  4420. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4421. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4422. RemoveInstruction(hp1);
  4423. result:=true;
  4424. exit;
  4425. end;
  4426. end;
  4427. { changes
  4428. lea <ref1>, reg1
  4429. <op> ...,<ref. with reg1>,...
  4430. to
  4431. <op> ...,<ref1>,... }
  4432. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4433. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4434. not(MatchInstruction(hp1,A_LEA,[])) then
  4435. begin
  4436. { find a reference which uses reg1 }
  4437. 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
  4438. ref:=0
  4439. 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
  4440. ref:=1
  4441. else
  4442. ref:=-1;
  4443. if (ref<>-1) and
  4444. { reg1 must be either the base or the index }
  4445. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4446. begin
  4447. { reg1 can be removed from the reference }
  4448. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4449. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4450. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4451. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4452. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4453. else
  4454. Internalerror(2019111201);
  4455. { check if the can insert all data of the lea into the second instruction }
  4456. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4457. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4458. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4459. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4460. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4461. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4462. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4463. {$ifdef x86_64}
  4464. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4465. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4466. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4467. )
  4468. {$endif x86_64}
  4469. then
  4470. begin
  4471. { reg1 might not used by the second instruction after it is remove from the reference }
  4472. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4473. begin
  4474. TransferUsedRegs(TmpUsedRegs);
  4475. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4476. { reg1 is not updated so it might not be used afterwards }
  4477. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4478. begin
  4479. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4480. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4481. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4482. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4483. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4484. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4485. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4486. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4487. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4488. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4489. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4490. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4491. RemoveCurrentP(p, hp1);
  4492. result:=true;
  4493. exit;
  4494. end
  4495. end;
  4496. end;
  4497. { recover }
  4498. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4499. end;
  4500. end;
  4501. end;
  4502. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4503. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4504. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4505. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4506. begin
  4507. { Check common LEA/LEA conditions }
  4508. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4509. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4510. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4511. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4512. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4513. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4514. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4515. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4516. (
  4517. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4518. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4519. ) and (
  4520. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4521. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4522. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4523. ) then
  4524. begin
  4525. { changes
  4526. lea (regX,scale), reg1
  4527. lea offset(reg1,reg1), reg1
  4528. to
  4529. lea offset(regX,scale*2), reg1
  4530. and
  4531. lea (regX,scale1), reg1
  4532. lea offset(reg1,scale2), reg1
  4533. to
  4534. lea offset(regX,scale1*scale2), reg1
  4535. ... so long as the final scale does not exceed 8
  4536. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4537. }
  4538. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4539. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4540. (
  4541. (
  4542. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4543. ) or (
  4544. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4545. (
  4546. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4547. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4548. )
  4549. )
  4550. ) and (
  4551. (
  4552. { lea (reg1,scale2), reg1 variant }
  4553. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4554. (
  4555. (
  4556. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4557. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4558. ) or (
  4559. { lea (regX,regX), reg1 variant }
  4560. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4561. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4562. )
  4563. )
  4564. ) or (
  4565. { lea (reg1,reg1), reg1 variant }
  4566. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4567. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4568. )
  4569. ) then
  4570. begin
  4571. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4572. { Make everything homogeneous to make calculations easier }
  4573. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4574. begin
  4575. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4576. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4577. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4578. else
  4579. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4580. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4581. end;
  4582. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4583. begin
  4584. { Just to prevent miscalculations }
  4585. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4586. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4587. else
  4588. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4589. end
  4590. else
  4591. begin
  4592. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4593. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4594. end;
  4595. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4596. RemoveCurrentP(p);
  4597. result:=true;
  4598. exit;
  4599. end
  4600. { changes
  4601. lea offset1(regX), reg1
  4602. lea offset2(reg1), reg1
  4603. to
  4604. lea offset1+offset2(regX), reg1 }
  4605. else if
  4606. (
  4607. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4608. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4609. ) or (
  4610. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4611. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4612. (
  4613. (
  4614. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4615. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4616. ) or (
  4617. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4618. (
  4619. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4620. (
  4621. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4622. (
  4623. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4624. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4625. )
  4626. )
  4627. )
  4628. )
  4629. )
  4630. ) then
  4631. begin
  4632. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4633. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4634. begin
  4635. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4636. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4637. { if the register is used as index and base, we have to increase for base as well
  4638. and adapt base }
  4639. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4640. begin
  4641. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4642. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4643. end;
  4644. end
  4645. else
  4646. begin
  4647. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4648. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4649. end;
  4650. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4651. begin
  4652. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4653. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4654. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4655. end;
  4656. RemoveCurrentP(p);
  4657. result:=true;
  4658. exit;
  4659. end;
  4660. end;
  4661. { Change:
  4662. leal/q $x(%reg1),%reg2
  4663. ...
  4664. shll/q $y,%reg2
  4665. To:
  4666. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4667. }
  4668. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4669. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4670. (taicpu(hp1).oper[0]^.val <= 3) then
  4671. begin
  4672. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4673. TransferUsedRegs(TmpUsedRegs);
  4674. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4675. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4676. if
  4677. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4678. (this works even if scalefactor is zero) }
  4679. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4680. { Ensure offset doesn't go out of bounds }
  4681. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4682. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4683. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4684. (
  4685. (
  4686. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4687. (
  4688. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4689. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4690. (
  4691. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4692. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4693. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4694. )
  4695. )
  4696. ) or (
  4697. (
  4698. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4699. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4700. ) and
  4701. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4702. )
  4703. ) then
  4704. begin
  4705. repeat
  4706. with taicpu(p).oper[0]^.ref^ do
  4707. begin
  4708. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4709. if index = base then
  4710. begin
  4711. if Multiple > 4 then
  4712. { Optimisation will no longer work because resultant
  4713. scale factor will exceed 8 }
  4714. Break;
  4715. base := NR_NO;
  4716. scalefactor := 2;
  4717. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4718. end
  4719. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4720. begin
  4721. { Scale factor only works on the index register }
  4722. index := base;
  4723. base := NR_NO;
  4724. end;
  4725. { For safety }
  4726. if scalefactor <= 1 then
  4727. begin
  4728. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4729. scalefactor := Multiple;
  4730. end
  4731. else
  4732. begin
  4733. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4734. scalefactor := scalefactor * Multiple;
  4735. end;
  4736. offset := offset * Multiple;
  4737. end;
  4738. RemoveInstruction(hp1);
  4739. Result := True;
  4740. Exit;
  4741. { This repeat..until loop exists for the benefit of Break }
  4742. until True;
  4743. end;
  4744. end;
  4745. end;
  4746. end;
  4747. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4748. var
  4749. hp1 : tai;
  4750. begin
  4751. DoSubAddOpt := False;
  4752. if taicpu(p).oper[0]^.typ <> top_const then
  4753. { Should have been confirmed before calling }
  4754. InternalError(2021102601);
  4755. if GetLastInstruction(p, hp1) and
  4756. (hp1.typ = ait_instruction) and
  4757. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4758. case taicpu(hp1).opcode Of
  4759. A_DEC:
  4760. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4761. begin
  4762. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4763. RemoveInstruction(hp1);
  4764. end;
  4765. A_SUB:
  4766. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4767. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4768. begin
  4769. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4770. RemoveInstruction(hp1);
  4771. end;
  4772. A_ADD:
  4773. begin
  4774. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4775. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4776. begin
  4777. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4778. RemoveInstruction(hp1);
  4779. if (taicpu(p).oper[0]^.val = 0) then
  4780. begin
  4781. hp1 := tai(p.next);
  4782. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4783. if not GetLastInstruction(hp1, p) then
  4784. p := hp1;
  4785. DoSubAddOpt := True;
  4786. end
  4787. end;
  4788. end;
  4789. else
  4790. ;
  4791. end;
  4792. end;
  4793. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4794. var
  4795. hp1, hp2: tai;
  4796. ActiveReg: TRegister;
  4797. OldOffset: asizeint;
  4798. ThisConst: TCGInt;
  4799. function RegDeallocated: Boolean;
  4800. begin
  4801. TransferUsedRegs(TmpUsedRegs);
  4802. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4803. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4804. end;
  4805. begin
  4806. Result:=false;
  4807. hp1 := nil;
  4808. { replace
  4809. subX const,%reg1
  4810. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4811. dealloc %reg1
  4812. by
  4813. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4814. }
  4815. if MatchOpType(taicpu(p),top_const,top_reg) then
  4816. begin
  4817. ActiveReg := taicpu(p).oper[1]^.reg;
  4818. { Ensures the entire register was updated }
  4819. if (taicpu(p).opsize >= S_L) and
  4820. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4821. MatchInstruction(hp1,A_LEA,[]) and
  4822. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4823. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4824. (
  4825. { Cover the case where the register in the reference is also the destination register }
  4826. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4827. (
  4828. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4829. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4830. RegDeallocated
  4831. )
  4832. ) then
  4833. begin
  4834. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4835. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4836. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4837. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4838. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4839. {$ifdef x86_64}
  4840. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4841. begin
  4842. { Overflow; abort }
  4843. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4844. end
  4845. else
  4846. {$endif x86_64}
  4847. begin
  4848. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4849. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4850. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4851. RemoveCurrentP(p, hp1)
  4852. else
  4853. RemoveCurrentP(p);
  4854. result:=true;
  4855. Exit;
  4856. end;
  4857. end;
  4858. if (
  4859. { Save calling GetNextInstructionUsingReg again }
  4860. Assigned(hp1) or
  4861. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4862. ) and
  4863. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4864. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4865. begin
  4866. if taicpu(hp1).oper[0]^.typ = top_const then
  4867. begin
  4868. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4869. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4870. Result := True;
  4871. { Handle any overflows }
  4872. case taicpu(p).opsize of
  4873. S_B:
  4874. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4875. S_W:
  4876. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4877. S_L:
  4878. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4879. {$ifdef x86_64}
  4880. S_Q:
  4881. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4882. { Overflow; abort }
  4883. Result := False
  4884. else
  4885. taicpu(p).oper[0]^.val := ThisConst;
  4886. {$endif x86_64}
  4887. else
  4888. InternalError(2021102610);
  4889. end;
  4890. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4891. if Result then
  4892. begin
  4893. if (taicpu(p).oper[0]^.val < 0) and
  4894. (
  4895. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4896. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4897. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4898. ) then
  4899. begin
  4900. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4901. taicpu(p).opcode := A_SUB;
  4902. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4903. end
  4904. else
  4905. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4906. RemoveInstruction(hp1);
  4907. end;
  4908. end
  4909. else
  4910. begin
  4911. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4912. TransferUsedRegs(TmpUsedRegs);
  4913. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4914. hp2 := p;
  4915. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4916. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4917. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4918. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4919. begin
  4920. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4921. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4922. Asml.Remove(p);
  4923. Asml.InsertAfter(p, hp1);
  4924. p := hp1;
  4925. Result := True;
  4926. Exit;
  4927. end;
  4928. end;
  4929. end;
  4930. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4931. { * change "sub/add const1, reg" or "dec reg" followed by
  4932. "sub const2, reg" to one "sub ..., reg" }
  4933. {$ifdef i386}
  4934. if (taicpu(p).oper[0]^.val = 2) and
  4935. (ActiveReg = NR_ESP) and
  4936. { Don't do the sub/push optimization if the sub }
  4937. { comes from setting up the stack frame (JM) }
  4938. (not(GetLastInstruction(p,hp1)) or
  4939. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4940. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4941. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4942. begin
  4943. hp1 := tai(p.next);
  4944. while Assigned(hp1) and
  4945. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4946. not RegReadByInstruction(NR_ESP,hp1) and
  4947. not RegModifiedByInstruction(NR_ESP,hp1) do
  4948. hp1 := tai(hp1.next);
  4949. if Assigned(hp1) and
  4950. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4951. begin
  4952. taicpu(hp1).changeopsize(S_L);
  4953. if taicpu(hp1).oper[0]^.typ=top_reg then
  4954. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4955. hp1 := tai(p.next);
  4956. RemoveCurrentp(p, hp1);
  4957. Result:=true;
  4958. exit;
  4959. end;
  4960. end;
  4961. {$endif i386}
  4962. if DoSubAddOpt(p) then
  4963. Result:=true;
  4964. end;
  4965. end;
  4966. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4967. var
  4968. TmpBool1,TmpBool2 : Boolean;
  4969. tmpref : treference;
  4970. hp1,hp2: tai;
  4971. mask: tcgint;
  4972. begin
  4973. Result:=false;
  4974. { All these optimisations work on "shl/sal const,%reg" }
  4975. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4976. Exit;
  4977. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4978. (taicpu(p).oper[0]^.val <= 3) then
  4979. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4980. begin
  4981. { should we check the next instruction? }
  4982. TmpBool1 := True;
  4983. { have we found an add/sub which could be
  4984. integrated in the lea? }
  4985. TmpBool2 := False;
  4986. reference_reset(tmpref,2,[]);
  4987. TmpRef.index := taicpu(p).oper[1]^.reg;
  4988. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4989. while TmpBool1 and
  4990. GetNextInstruction(p, hp1) and
  4991. (tai(hp1).typ = ait_instruction) and
  4992. ((((taicpu(hp1).opcode = A_ADD) or
  4993. (taicpu(hp1).opcode = A_SUB)) and
  4994. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4995. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4996. (((taicpu(hp1).opcode = A_INC) or
  4997. (taicpu(hp1).opcode = A_DEC)) and
  4998. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4999. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5000. ((taicpu(hp1).opcode = A_LEA) and
  5001. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5002. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5003. (not GetNextInstruction(hp1,hp2) or
  5004. not instrReadsFlags(hp2)) Do
  5005. begin
  5006. TmpBool1 := False;
  5007. if taicpu(hp1).opcode=A_LEA then
  5008. begin
  5009. if (TmpRef.base = NR_NO) and
  5010. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5011. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5012. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5013. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5014. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5015. begin
  5016. TmpBool1 := True;
  5017. TmpBool2 := True;
  5018. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5019. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5020. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5021. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5022. RemoveInstruction(hp1);
  5023. end
  5024. end
  5025. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5026. begin
  5027. TmpBool1 := True;
  5028. TmpBool2 := True;
  5029. case taicpu(hp1).opcode of
  5030. A_ADD:
  5031. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5032. A_SUB:
  5033. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5034. else
  5035. internalerror(2019050536);
  5036. end;
  5037. RemoveInstruction(hp1);
  5038. end
  5039. else
  5040. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5041. (((taicpu(hp1).opcode = A_ADD) and
  5042. (TmpRef.base = NR_NO)) or
  5043. (taicpu(hp1).opcode = A_INC) or
  5044. (taicpu(hp1).opcode = A_DEC)) then
  5045. begin
  5046. TmpBool1 := True;
  5047. TmpBool2 := True;
  5048. case taicpu(hp1).opcode of
  5049. A_ADD:
  5050. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5051. A_INC:
  5052. inc(TmpRef.offset);
  5053. A_DEC:
  5054. dec(TmpRef.offset);
  5055. else
  5056. internalerror(2019050535);
  5057. end;
  5058. RemoveInstruction(hp1);
  5059. end;
  5060. end;
  5061. if TmpBool2
  5062. {$ifndef x86_64}
  5063. or
  5064. ((current_settings.optimizecputype < cpu_Pentium2) and
  5065. (taicpu(p).oper[0]^.val <= 3) and
  5066. not(cs_opt_size in current_settings.optimizerswitches))
  5067. {$endif x86_64}
  5068. then
  5069. begin
  5070. if not(TmpBool2) and
  5071. (taicpu(p).oper[0]^.val=1) then
  5072. begin
  5073. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5074. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5075. end
  5076. else
  5077. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5078. taicpu(p).oper[1]^.reg);
  5079. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5080. InsertLLItem(p.previous, p.next, hp1);
  5081. p.free;
  5082. p := hp1;
  5083. end;
  5084. end
  5085. {$ifndef x86_64}
  5086. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5087. begin
  5088. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5089. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5090. (unlike shl, which is only Tairable in the U pipe) }
  5091. if taicpu(p).oper[0]^.val=1 then
  5092. begin
  5093. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5094. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5095. InsertLLItem(p.previous, p.next, hp1);
  5096. p.free;
  5097. p := hp1;
  5098. end
  5099. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5100. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5101. else if (taicpu(p).opsize = S_L) and
  5102. (taicpu(p).oper[0]^.val<= 3) then
  5103. begin
  5104. reference_reset(tmpref,2,[]);
  5105. TmpRef.index := taicpu(p).oper[1]^.reg;
  5106. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5107. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5108. InsertLLItem(p.previous, p.next, hp1);
  5109. p.free;
  5110. p := hp1;
  5111. end;
  5112. end
  5113. {$endif x86_64}
  5114. else if
  5115. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5116. (
  5117. (
  5118. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5119. SetAndTest(hp1, hp2)
  5120. {$ifdef x86_64}
  5121. ) or
  5122. (
  5123. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5124. GetNextInstruction(hp1, hp2) and
  5125. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5126. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5127. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5128. {$endif x86_64}
  5129. )
  5130. ) and
  5131. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5132. begin
  5133. { Change:
  5134. shl x, %reg1
  5135. mov -(1<<x), %reg2
  5136. and %reg2, %reg1
  5137. Or:
  5138. shl x, %reg1
  5139. and -(1<<x), %reg1
  5140. To just:
  5141. shl x, %reg1
  5142. Since the and operation only zeroes bits that are already zero from the shl operation
  5143. }
  5144. case taicpu(p).oper[0]^.val of
  5145. 8:
  5146. mask:=$FFFFFFFFFFFFFF00;
  5147. 16:
  5148. mask:=$FFFFFFFFFFFF0000;
  5149. 32:
  5150. mask:=$FFFFFFFF00000000;
  5151. 63:
  5152. { Constant pre-calculated to prevent overflow errors with Int64 }
  5153. mask:=$8000000000000000;
  5154. else
  5155. begin
  5156. if taicpu(p).oper[0]^.val >= 64 then
  5157. { Shouldn't happen realistically, since the register
  5158. is guaranteed to be set to zero at this point }
  5159. mask := 0
  5160. else
  5161. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5162. end;
  5163. end;
  5164. if taicpu(hp1).oper[0]^.val = mask then
  5165. begin
  5166. { Everything checks out, perform the optimisation, as long as
  5167. the FLAGS register isn't being used}
  5168. TransferUsedRegs(TmpUsedRegs);
  5169. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5170. {$ifdef x86_64}
  5171. if (hp1 <> hp2) then
  5172. begin
  5173. { "shl/mov/and" version }
  5174. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5175. { Don't do the optimisation if the FLAGS register is in use }
  5176. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5177. begin
  5178. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5179. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5180. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5181. begin
  5182. RemoveInstruction(hp1);
  5183. Result := True;
  5184. end;
  5185. { Only set Result to True if the 'mov' instruction was removed }
  5186. RemoveInstruction(hp2);
  5187. end;
  5188. end
  5189. else
  5190. {$endif x86_64}
  5191. begin
  5192. { "shl/and" version }
  5193. { Don't do the optimisation if the FLAGS register is in use }
  5194. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5195. begin
  5196. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5197. RemoveInstruction(hp1);
  5198. Result := True;
  5199. end;
  5200. end;
  5201. Exit;
  5202. end
  5203. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5204. begin
  5205. { Even if the mask doesn't allow for its removal, we might be
  5206. able to optimise the mask for the "shl/and" version, which
  5207. may permit other peephole optimisations }
  5208. {$ifdef DEBUG_AOPTCPU}
  5209. mask := taicpu(hp1).oper[0]^.val and mask;
  5210. if taicpu(hp1).oper[0]^.val <> mask then
  5211. begin
  5212. DebugMsg(
  5213. SPeepholeOptimization +
  5214. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5215. ' to $' + debug_tostr(mask) +
  5216. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5217. taicpu(hp1).oper[0]^.val := mask;
  5218. end;
  5219. {$else DEBUG_AOPTCPU}
  5220. { If debugging is off, just set the operand even if it's the same }
  5221. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5222. {$endif DEBUG_AOPTCPU}
  5223. end;
  5224. end;
  5225. {
  5226. change
  5227. shl/sal const,reg
  5228. <op> ...(...,reg,1),...
  5229. into
  5230. <op> ...(...,reg,1 shl const),...
  5231. if const in 1..3
  5232. }
  5233. if MatchOpType(taicpu(p), top_const, top_reg) and
  5234. (taicpu(p).oper[0]^.val in [1..3]) and
  5235. GetNextInstruction(p, hp1) and
  5236. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5237. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5238. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5239. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5240. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5241. begin
  5242. TransferUsedRegs(TmpUsedRegs);
  5243. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5244. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5245. begin
  5246. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5247. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5248. RemoveCurrentP(p);
  5249. Result:=true;
  5250. end;
  5251. end;
  5252. end;
  5253. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5254. var
  5255. CurrentRef: TReference;
  5256. FullReg: TRegister;
  5257. hp1, hp2: tai;
  5258. begin
  5259. Result := False;
  5260. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5261. Exit;
  5262. { We assume you've checked if the operand is actually a reference by
  5263. this point. If it isn't, you'll most likely get an access violation }
  5264. CurrentRef := first_mov.oper[1]^.ref^;
  5265. { Memory must be aligned }
  5266. if (CurrentRef.offset mod 4) <> 0 then
  5267. Exit;
  5268. Inc(CurrentRef.offset);
  5269. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5270. if MatchOperand(second_mov.oper[0]^, 0) and
  5271. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5272. GetNextInstruction(second_mov, hp1) and
  5273. (hp1.typ = ait_instruction) and
  5274. (taicpu(hp1).opcode = A_MOV) and
  5275. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5276. (taicpu(hp1).oper[0]^.val = 0) then
  5277. begin
  5278. Inc(CurrentRef.offset);
  5279. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5280. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5281. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5282. begin
  5283. case taicpu(hp1).opsize of
  5284. S_B:
  5285. if GetNextInstruction(hp1, hp2) and
  5286. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5287. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5288. (taicpu(hp2).oper[0]^.val = 0) then
  5289. begin
  5290. Inc(CurrentRef.offset);
  5291. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5292. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5293. (taicpu(hp2).opsize = S_B) then
  5294. begin
  5295. RemoveInstruction(hp1);
  5296. RemoveInstruction(hp2);
  5297. first_mov.opsize := S_L;
  5298. if first_mov.oper[0]^.typ = top_reg then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5301. { Reuse second_mov as a MOVZX instruction }
  5302. second_mov.opcode := A_MOVZX;
  5303. second_mov.opsize := S_BL;
  5304. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5305. second_mov.loadreg(1, FullReg);
  5306. first_mov.oper[0]^.reg := FullReg;
  5307. asml.Remove(second_mov);
  5308. asml.InsertBefore(second_mov, first_mov);
  5309. end
  5310. else
  5311. { It's a value }
  5312. begin
  5313. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5314. RemoveInstruction(second_mov);
  5315. end;
  5316. Result := True;
  5317. Exit;
  5318. end;
  5319. end;
  5320. S_W:
  5321. begin
  5322. RemoveInstruction(hp1);
  5323. first_mov.opsize := S_L;
  5324. if first_mov.oper[0]^.typ = top_reg then
  5325. begin
  5326. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5327. { Reuse second_mov as a MOVZX instruction }
  5328. second_mov.opcode := A_MOVZX;
  5329. second_mov.opsize := S_BL;
  5330. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5331. second_mov.loadreg(1, FullReg);
  5332. first_mov.oper[0]^.reg := FullReg;
  5333. asml.Remove(second_mov);
  5334. asml.InsertBefore(second_mov, first_mov);
  5335. end
  5336. else
  5337. { It's a value }
  5338. begin
  5339. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5340. RemoveInstruction(second_mov);
  5341. end;
  5342. Result := True;
  5343. Exit;
  5344. end;
  5345. else
  5346. ;
  5347. end;
  5348. end;
  5349. end;
  5350. end;
  5351. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5352. { returns true if a "continue" should be done after this optimization }
  5353. var
  5354. hp1, hp2: tai;
  5355. begin
  5356. Result := false;
  5357. if MatchOpType(taicpu(p),top_ref) and
  5358. GetNextInstruction(p, hp1) and
  5359. (hp1.typ = ait_instruction) and
  5360. (((taicpu(hp1).opcode = A_FLD) and
  5361. (taicpu(p).opcode = A_FSTP)) or
  5362. ((taicpu(p).opcode = A_FISTP) and
  5363. (taicpu(hp1).opcode = A_FILD))) and
  5364. MatchOpType(taicpu(hp1),top_ref) and
  5365. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5366. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5367. begin
  5368. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5369. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5370. GetNextInstruction(hp1, hp2) and
  5371. (hp2.typ = ait_instruction) and
  5372. IsExitCode(hp2) and
  5373. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5374. not(assigned(current_procinfo.procdef.funcretsym) and
  5375. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5376. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5377. begin
  5378. RemoveInstruction(hp1);
  5379. RemoveCurrentP(p, hp2);
  5380. RemoveLastDeallocForFuncRes(p);
  5381. Result := true;
  5382. end
  5383. else
  5384. { we can do this only in fast math mode as fstp is rounding ...
  5385. ... still disabled as it breaks the compiler and/or rtl }
  5386. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5387. { ... or if another fstp equal to the first one follows }
  5388. (GetNextInstruction(hp1,hp2) and
  5389. (hp2.typ = ait_instruction) and
  5390. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5391. (taicpu(p).opsize=taicpu(hp2).opsize))
  5392. ) and
  5393. { fst can't store an extended/comp value }
  5394. (taicpu(p).opsize <> S_FX) and
  5395. (taicpu(p).opsize <> S_IQ) then
  5396. begin
  5397. if (taicpu(p).opcode = A_FSTP) then
  5398. taicpu(p).opcode := A_FST
  5399. else
  5400. taicpu(p).opcode := A_FIST;
  5401. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5402. RemoveInstruction(hp1);
  5403. end;
  5404. end;
  5405. end;
  5406. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5407. var
  5408. hp1, hp2: tai;
  5409. begin
  5410. result:=false;
  5411. if MatchOpType(taicpu(p),top_reg) and
  5412. GetNextInstruction(p, hp1) and
  5413. (hp1.typ = Ait_Instruction) and
  5414. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5415. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5416. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5417. { change to
  5418. fld reg fxxx reg,st
  5419. fxxxp st, st1 (hp1)
  5420. Remark: non commutative operations must be reversed!
  5421. }
  5422. begin
  5423. case taicpu(hp1).opcode Of
  5424. A_FMULP,A_FADDP,
  5425. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5426. begin
  5427. case taicpu(hp1).opcode Of
  5428. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5429. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5430. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5431. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5432. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5433. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5434. else
  5435. internalerror(2019050534);
  5436. end;
  5437. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5438. taicpu(hp1).oper[1]^.reg := NR_ST;
  5439. RemoveCurrentP(p, hp1);
  5440. Result:=true;
  5441. exit;
  5442. end;
  5443. else
  5444. ;
  5445. end;
  5446. end
  5447. else
  5448. if MatchOpType(taicpu(p),top_ref) and
  5449. GetNextInstruction(p, hp2) and
  5450. (hp2.typ = Ait_Instruction) and
  5451. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5452. (taicpu(p).opsize in [S_FS, S_FL]) and
  5453. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5454. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5455. if GetLastInstruction(p, hp1) and
  5456. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5457. MatchOpType(taicpu(hp1),top_ref) and
  5458. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5459. if ((taicpu(hp2).opcode = A_FMULP) or
  5460. (taicpu(hp2).opcode = A_FADDP)) then
  5461. { change to
  5462. fld/fst mem1 (hp1) fld/fst mem1
  5463. fld mem1 (p) fadd/
  5464. faddp/ fmul st, st
  5465. fmulp st, st1 (hp2) }
  5466. begin
  5467. RemoveCurrentP(p, hp1);
  5468. if (taicpu(hp2).opcode = A_FADDP) then
  5469. taicpu(hp2).opcode := A_FADD
  5470. else
  5471. taicpu(hp2).opcode := A_FMUL;
  5472. taicpu(hp2).oper[1]^.reg := NR_ST;
  5473. end
  5474. else
  5475. { change to
  5476. fld/fst mem1 (hp1) fld/fst mem1
  5477. fld mem1 (p) fld st}
  5478. begin
  5479. taicpu(p).changeopsize(S_FL);
  5480. taicpu(p).loadreg(0,NR_ST);
  5481. end
  5482. else
  5483. begin
  5484. case taicpu(hp2).opcode Of
  5485. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5486. { change to
  5487. fld/fst mem1 (hp1) fld/fst mem1
  5488. fld mem2 (p) fxxx mem2
  5489. fxxxp st, st1 (hp2) }
  5490. begin
  5491. case taicpu(hp2).opcode Of
  5492. A_FADDP: taicpu(p).opcode := A_FADD;
  5493. A_FMULP: taicpu(p).opcode := A_FMUL;
  5494. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5495. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5496. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5497. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5498. else
  5499. internalerror(2019050533);
  5500. end;
  5501. RemoveInstruction(hp2);
  5502. end
  5503. else
  5504. ;
  5505. end
  5506. end
  5507. end;
  5508. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5509. begin
  5510. Result := condition_in(cond1, cond2) or
  5511. { Not strictly subsets due to the actual flags checked, but because we're
  5512. comparing integers, E is a subset of AE and GE and their aliases }
  5513. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5514. end;
  5515. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5516. var
  5517. v: TCGInt;
  5518. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5519. FirstMatch: Boolean;
  5520. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5521. begin
  5522. Result:=false;
  5523. { All these optimisations need a next instruction }
  5524. if not GetNextInstruction(p, hp1) then
  5525. Exit;
  5526. { Search for:
  5527. cmp ###,###
  5528. j(c1) @lbl1
  5529. ...
  5530. @lbl:
  5531. cmp ###.### (same comparison as above)
  5532. j(c2) @lbl2
  5533. If c1 is a subset of c2, change to:
  5534. cmp ###,###
  5535. j(c2) @lbl2
  5536. (@lbl1 may become a dead label as a result)
  5537. }
  5538. { Also handle cases where there are multiple jumps in a row }
  5539. p_jump := hp1;
  5540. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5541. begin
  5542. if IsJumpToLabel(taicpu(p_jump)) then
  5543. begin
  5544. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5545. p_label := nil;
  5546. if Assigned(JumpLabel) then
  5547. p_label := getlabelwithsym(JumpLabel);
  5548. if Assigned(p_label) and
  5549. GetNextInstruction(p_label, p_dist) and
  5550. MatchInstruction(p_dist, A_CMP, []) and
  5551. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5552. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5553. GetNextInstruction(p_dist, hp1_dist) and
  5554. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5555. begin
  5556. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5557. if JumpLabel = JumpLabel_dist then
  5558. { This is an infinite loop }
  5559. Exit;
  5560. { Best optimisation when the first condition is a subset (or equal) of the second }
  5561. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5562. begin
  5563. { Any registers used here will already be allocated }
  5564. if Assigned(JumpLabel_dist) then
  5565. JumpLabel_dist.IncRefs;
  5566. if Assigned(JumpLabel) then
  5567. JumpLabel.DecRefs;
  5568. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5569. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5570. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5571. Result := True;
  5572. { Don't exit yet. Since p and p_jump haven't actually been
  5573. removed, we can check for more on this iteration }
  5574. end
  5575. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5576. GetNextInstruction(hp1_dist, hp1_label) and
  5577. SkipAligns(hp1_label, hp1_label) and
  5578. (hp1_label.typ = ait_label) then
  5579. begin
  5580. JumpLabel_far := tai_label(hp1_label).labsym;
  5581. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5582. { This is an infinite loop }
  5583. Exit;
  5584. if Assigned(JumpLabel_far) then
  5585. begin
  5586. { In this situation, if the first jump branches, the second one will never,
  5587. branch so change the destination label to after the second jump }
  5588. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5589. if Assigned(JumpLabel) then
  5590. JumpLabel.DecRefs;
  5591. JumpLabel_far.IncRefs;
  5592. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5593. Result := True;
  5594. { Don't exit yet. Since p and p_jump haven't actually been
  5595. removed, we can check for more on this iteration }
  5596. Continue;
  5597. end;
  5598. end;
  5599. end;
  5600. end;
  5601. { Search for:
  5602. cmp ###,###
  5603. j(c1) @lbl1
  5604. cmp ###,### (same as first)
  5605. Remove second cmp
  5606. }
  5607. if GetNextInstruction(p_jump, hp2) and
  5608. (
  5609. (
  5610. MatchInstruction(hp2, A_CMP, []) and
  5611. (
  5612. (
  5613. MatchOpType(taicpu(p), top_const, top_reg) and
  5614. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5615. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5616. ) or (
  5617. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5618. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5619. )
  5620. )
  5621. ) or (
  5622. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5623. MatchOperand(taicpu(p).oper[0]^, 0) and
  5624. (taicpu(p).oper[1]^.typ = top_reg) and
  5625. MatchInstruction(hp2, A_TEST, []) and
  5626. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5627. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5628. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5629. )
  5630. ) then
  5631. begin
  5632. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5633. RemoveInstruction(hp2);
  5634. Result := True;
  5635. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5636. end;
  5637. GetNextInstruction(p_jump, p_jump);
  5638. end;
  5639. if taicpu(p).oper[0]^.typ = top_const then
  5640. begin
  5641. if (taicpu(p).oper[0]^.val = 0) and
  5642. (taicpu(p).oper[1]^.typ = top_reg) and
  5643. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5644. begin
  5645. hp2 := p;
  5646. FirstMatch := True;
  5647. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5648. anything meaningful once it's converted to "test %reg,%reg";
  5649. additionally, some jumps will always (or never) branch, so
  5650. evaluate every jump immediately following the
  5651. comparison, optimising the conditions if possible.
  5652. Similarly with SETcc... those that are always set to 0 or 1
  5653. are changed to MOV instructions }
  5654. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5655. (
  5656. GetNextInstruction(hp2, hp1) and
  5657. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5658. ) do
  5659. begin
  5660. FirstMatch := False;
  5661. case taicpu(hp1).condition of
  5662. C_B, C_C, C_NAE, C_O:
  5663. { For B/NAE:
  5664. Will never branch since an unsigned integer can never be below zero
  5665. For C/O:
  5666. Result cannot overflow because 0 is being subtracted
  5667. }
  5668. begin
  5669. if taicpu(hp1).opcode = A_Jcc then
  5670. begin
  5671. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5672. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5673. RemoveInstruction(hp1);
  5674. { Since hp1 was deleted, hp2 must not be updated }
  5675. Continue;
  5676. end
  5677. else
  5678. begin
  5679. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5680. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5681. taicpu(hp1).opcode := A_MOV;
  5682. taicpu(hp1).ops := 2;
  5683. taicpu(hp1).condition := C_None;
  5684. taicpu(hp1).opsize := S_B;
  5685. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5686. taicpu(hp1).loadconst(0, 0);
  5687. end;
  5688. end;
  5689. C_BE, C_NA:
  5690. begin
  5691. { Will only branch if equal to zero }
  5692. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5693. taicpu(hp1).condition := C_E;
  5694. end;
  5695. C_A, C_NBE:
  5696. begin
  5697. { Will only branch if not equal to zero }
  5698. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5699. taicpu(hp1).condition := C_NE;
  5700. end;
  5701. C_AE, C_NB, C_NC, C_NO:
  5702. begin
  5703. { Will always branch }
  5704. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5705. if taicpu(hp1).opcode = A_Jcc then
  5706. begin
  5707. MakeUnconditional(taicpu(hp1));
  5708. { Any jumps/set that follow will now be dead code }
  5709. RemoveDeadCodeAfterJump(taicpu(hp1));
  5710. Break;
  5711. end
  5712. else
  5713. begin
  5714. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5715. taicpu(hp1).opcode := A_MOV;
  5716. taicpu(hp1).ops := 2;
  5717. taicpu(hp1).condition := C_None;
  5718. taicpu(hp1).opsize := S_B;
  5719. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5720. taicpu(hp1).loadconst(0, 1);
  5721. end;
  5722. end;
  5723. C_None:
  5724. InternalError(2020012201);
  5725. C_P, C_PE, C_NP, C_PO:
  5726. { We can't handle parity checks and they should never be generated
  5727. after a general-purpose CMP (it's used in some floating-point
  5728. comparisons that don't use CMP) }
  5729. InternalError(2020012202);
  5730. else
  5731. { Zero/Equality, Sign, their complements and all of the
  5732. signed comparisons do not need to be converted };
  5733. end;
  5734. hp2 := hp1;
  5735. end;
  5736. { Convert the instruction to a TEST }
  5737. taicpu(p).opcode := A_TEST;
  5738. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5739. Result := True;
  5740. Exit;
  5741. end
  5742. else if (taicpu(p).oper[0]^.val = 1) and
  5743. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5744. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5745. begin
  5746. { Convert; To:
  5747. cmp $1,r/m cmp $0,r/m
  5748. jl @lbl jle @lbl
  5749. }
  5750. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5751. taicpu(p).oper[0]^.val := 0;
  5752. taicpu(hp1).condition := C_LE;
  5753. { If the instruction is now "cmp $0,%reg", convert it to a
  5754. TEST (and effectively do the work of the "cmp $0,%reg" in
  5755. the block above)
  5756. If it's a reference, we can get away with not setting
  5757. Result to True because he haven't evaluated the jump
  5758. in this pass yet.
  5759. }
  5760. if (taicpu(p).oper[1]^.typ = top_reg) then
  5761. begin
  5762. taicpu(p).opcode := A_TEST;
  5763. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5764. Result := True;
  5765. end;
  5766. Exit;
  5767. end
  5768. else if (taicpu(p).oper[1]^.typ = top_reg)
  5769. {$ifdef x86_64}
  5770. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5771. {$endif x86_64}
  5772. then
  5773. begin
  5774. { cmp register,$8000 neg register
  5775. je target --> jo target
  5776. .... only if register is deallocated before jump.}
  5777. case Taicpu(p).opsize of
  5778. S_B: v:=$80;
  5779. S_W: v:=$8000;
  5780. S_L: v:=qword($80000000);
  5781. else
  5782. internalerror(2013112905);
  5783. end;
  5784. if (taicpu(p).oper[0]^.val=v) and
  5785. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5786. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5787. begin
  5788. TransferUsedRegs(TmpUsedRegs);
  5789. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5790. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5791. begin
  5792. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5793. Taicpu(p).opcode:=A_NEG;
  5794. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5795. Taicpu(p).clearop(1);
  5796. Taicpu(p).ops:=1;
  5797. if Taicpu(hp1).condition=C_E then
  5798. Taicpu(hp1).condition:=C_O
  5799. else
  5800. Taicpu(hp1).condition:=C_NO;
  5801. Result:=true;
  5802. exit;
  5803. end;
  5804. end;
  5805. end;
  5806. end;
  5807. if TrySwapMovCmp(p, hp1) then
  5808. begin
  5809. Result := True;
  5810. Exit;
  5811. end;
  5812. end;
  5813. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5814. var
  5815. hp1: tai;
  5816. begin
  5817. {
  5818. remove the second (v)pxor from
  5819. pxor reg,reg
  5820. ...
  5821. pxor reg,reg
  5822. }
  5823. Result:=false;
  5824. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5825. MatchOpType(taicpu(p),top_reg,top_reg) and
  5826. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5827. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5828. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5829. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5830. begin
  5831. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5832. RemoveInstruction(hp1);
  5833. Result:=true;
  5834. Exit;
  5835. end
  5836. {
  5837. replace
  5838. pxor reg1,reg1
  5839. movapd/s reg1,reg2
  5840. dealloc reg1
  5841. by
  5842. pxor reg2,reg2
  5843. }
  5844. else if GetNextInstruction(p,hp1) and
  5845. { we mix single and double opperations here because we assume that the compiler
  5846. generates vmovapd only after double operations and vmovaps only after single operations }
  5847. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5848. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5849. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5850. (taicpu(p).oper[0]^.typ=top_reg) then
  5851. begin
  5852. TransferUsedRegs(TmpUsedRegs);
  5853. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5854. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5855. begin
  5856. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5857. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5858. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5859. RemoveInstruction(hp1);
  5860. result:=true;
  5861. end;
  5862. end;
  5863. end;
  5864. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5865. var
  5866. hp1: tai;
  5867. begin
  5868. {
  5869. remove the second (v)pxor from
  5870. (v)pxor reg,reg
  5871. ...
  5872. (v)pxor reg,reg
  5873. }
  5874. Result:=false;
  5875. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5876. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5877. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5878. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5879. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5880. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5881. begin
  5882. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5883. RemoveInstruction(hp1);
  5884. Result:=true;
  5885. Exit;
  5886. end
  5887. else
  5888. Result:=OptPass1VOP(p);
  5889. end;
  5890. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5891. var
  5892. hp1 : tai;
  5893. begin
  5894. result:=false;
  5895. { replace
  5896. IMul const,%mreg1,%mreg2
  5897. Mov %reg2,%mreg3
  5898. dealloc %mreg3
  5899. by
  5900. Imul const,%mreg1,%mreg23
  5901. }
  5902. if (taicpu(p).ops=3) and
  5903. GetNextInstruction(p,hp1) and
  5904. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5905. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5906. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5907. begin
  5908. TransferUsedRegs(TmpUsedRegs);
  5909. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5910. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5911. begin
  5912. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5913. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5914. RemoveInstruction(hp1);
  5915. result:=true;
  5916. end;
  5917. end;
  5918. end;
  5919. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5920. var
  5921. hp1 : tai;
  5922. begin
  5923. result:=false;
  5924. { replace
  5925. IMul %reg0,%reg1,%reg2
  5926. Mov %reg2,%reg3
  5927. dealloc %reg2
  5928. by
  5929. Imul %reg0,%reg1,%reg3
  5930. }
  5931. if GetNextInstruction(p,hp1) and
  5932. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5933. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5934. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5935. begin
  5936. TransferUsedRegs(TmpUsedRegs);
  5937. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5938. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5939. begin
  5940. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5941. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5942. RemoveInstruction(hp1);
  5943. result:=true;
  5944. end;
  5945. end;
  5946. end;
  5947. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  5948. var
  5949. hp1: tai;
  5950. begin
  5951. Result:=false;
  5952. { get rid of
  5953. (v)cvtss2sd reg0,<reg1,>reg2
  5954. (v)cvtss2sd reg2,<reg2,>reg0
  5955. }
  5956. if GetNextInstruction(p,hp1) and
  5957. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  5958. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  5959. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  5960. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5961. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  5962. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5963. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5964. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  5965. )
  5966. ) then
  5967. begin
  5968. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  5969. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  5970. begin
  5971. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  5972. RemoveCurrentP(p);
  5973. RemoveInstruction(hp1);
  5974. end
  5975. else
  5976. begin
  5977. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  5978. if taicpu(hp1).opcode=A_CVTSD2SS then
  5979. begin
  5980. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  5981. taicpu(p).opcode:=A_MOVAPS;
  5982. end
  5983. else
  5984. begin
  5985. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  5986. taicpu(p).opcode:=A_VMOVAPS;
  5987. end;
  5988. taicpu(p).ops:=2;
  5989. RemoveInstruction(hp1);
  5990. end;
  5991. Result:=true;
  5992. Exit;
  5993. end;
  5994. end;
  5995. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5996. var
  5997. hp1, hp2, hp3, hp4, hp5: tai;
  5998. ThisReg: TRegister;
  5999. begin
  6000. Result := False;
  6001. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6002. Exit;
  6003. {
  6004. convert
  6005. j<c> .L1
  6006. mov 1,reg
  6007. jmp .L2
  6008. .L1
  6009. mov 0,reg
  6010. .L2
  6011. into
  6012. mov 0,reg
  6013. set<not(c)> reg
  6014. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6015. would destroy the flag contents
  6016. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6017. executed at the same time as a previous comparison.
  6018. set<not(c)> reg
  6019. movzx reg, reg
  6020. }
  6021. if MatchInstruction(hp1,A_MOV,[]) and
  6022. (taicpu(hp1).oper[0]^.typ = top_const) and
  6023. (
  6024. (
  6025. (taicpu(hp1).oper[1]^.typ = top_reg)
  6026. {$ifdef i386}
  6027. { Under i386, ESI, EDI, EBP and ESP
  6028. don't have an 8-bit representation }
  6029. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6030. {$endif i386}
  6031. ) or (
  6032. {$ifdef i386}
  6033. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6034. {$endif i386}
  6035. (taicpu(hp1).opsize = S_B)
  6036. )
  6037. ) and
  6038. GetNextInstruction(hp1,hp2) and
  6039. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6040. GetNextInstruction(hp2,hp3) and
  6041. SkipAligns(hp3, hp3) and
  6042. (hp3.typ=ait_label) and
  6043. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6044. GetNextInstruction(hp3,hp4) and
  6045. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6046. (taicpu(hp4).oper[0]^.typ = top_const) and
  6047. (
  6048. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6049. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6050. ) and
  6051. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6052. GetNextInstruction(hp4,hp5) and
  6053. SkipAligns(hp5, hp5) and
  6054. (hp5.typ=ait_label) and
  6055. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6056. begin
  6057. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6058. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6059. tai_label(hp3).labsym.DecRefs;
  6060. { If this isn't the only reference to the middle label, we can
  6061. still make a saving - only that the first jump and everything
  6062. that follows will remain. }
  6063. if (tai_label(hp3).labsym.getrefs = 0) then
  6064. begin
  6065. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6066. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6067. else
  6068. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6069. { remove jump, first label and second MOV (also catching any aligns) }
  6070. repeat
  6071. if not GetNextInstruction(hp2, hp3) then
  6072. InternalError(2021040810);
  6073. RemoveInstruction(hp2);
  6074. hp2 := hp3;
  6075. until hp2 = hp5;
  6076. { Don't decrement reference count before the removal loop
  6077. above, otherwise GetNextInstruction won't stop on the
  6078. the label }
  6079. tai_label(hp5).labsym.DecRefs;
  6080. end
  6081. else
  6082. begin
  6083. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6084. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6085. else
  6086. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6087. end;
  6088. taicpu(p).opcode:=A_SETcc;
  6089. taicpu(p).opsize:=S_B;
  6090. taicpu(p).is_jmp:=False;
  6091. if taicpu(hp1).opsize=S_B then
  6092. begin
  6093. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6094. if taicpu(hp1).oper[1]^.typ = top_reg then
  6095. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6096. RemoveInstruction(hp1);
  6097. end
  6098. else
  6099. begin
  6100. { Will be a register because the size can't be S_B otherwise }
  6101. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6102. taicpu(p).loadreg(0, ThisReg);
  6103. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6104. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6105. begin
  6106. case taicpu(hp1).opsize of
  6107. S_W:
  6108. taicpu(hp1).opsize := S_BW;
  6109. S_L:
  6110. taicpu(hp1).opsize := S_BL;
  6111. {$ifdef x86_64}
  6112. S_Q:
  6113. begin
  6114. taicpu(hp1).opsize := S_BL;
  6115. { Change the destination register to 32-bit }
  6116. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6117. end;
  6118. {$endif x86_64}
  6119. else
  6120. InternalError(2021040820);
  6121. end;
  6122. taicpu(hp1).opcode := A_MOVZX;
  6123. taicpu(hp1).loadreg(0, ThisReg);
  6124. end
  6125. else
  6126. begin
  6127. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6128. { hp1 is already a MOV instruction with the correct register }
  6129. taicpu(hp1).loadconst(0, 0);
  6130. { Inserting it right before p will guarantee that the flags are also tracked }
  6131. asml.Remove(hp1);
  6132. asml.InsertBefore(hp1, p);
  6133. end;
  6134. end;
  6135. Result:=true;
  6136. exit;
  6137. end
  6138. end;
  6139. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6140. var
  6141. hp1, hp2, hp3: tai;
  6142. SourceRef, TargetRef: TReference;
  6143. CurrentReg: TRegister;
  6144. begin
  6145. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6146. if not UseAVX then
  6147. InternalError(2021100501);
  6148. Result := False;
  6149. { Look for the following to simplify:
  6150. vmovdqa/u x(mem1), %xmmreg
  6151. vmovdqa/u %xmmreg, y(mem2)
  6152. vmovdqa/u x+16(mem1), %xmmreg
  6153. vmovdqa/u %xmmreg, y+16(mem2)
  6154. Change to:
  6155. vmovdqa/u x(mem1), %ymmreg
  6156. vmovdqa/u %ymmreg, y(mem2)
  6157. vpxor %ymmreg, %ymmreg, %ymmreg
  6158. ( The VPXOR instruction is to zero the upper half, thus removing the
  6159. need to call the potentially expensive VZEROUPPER instruction. Other
  6160. peephole optimisations can remove VPXOR if it's unnecessary )
  6161. }
  6162. TransferUsedRegs(TmpUsedRegs);
  6163. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6164. { NOTE: In the optimisations below, if the references dictate that an
  6165. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6166. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6167. if (taicpu(p).opsize = S_XMM) and
  6168. MatchOpType(taicpu(p), top_ref, top_reg) and
  6169. GetNextInstruction(p, hp1) and
  6170. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6171. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6172. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6173. begin
  6174. SourceRef := taicpu(p).oper[0]^.ref^;
  6175. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6176. if GetNextInstruction(hp1, hp2) and
  6177. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6178. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6179. begin
  6180. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6181. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6182. Inc(SourceRef.offset, 16);
  6183. { Reuse the register in the first block move }
  6184. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6185. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6186. begin
  6187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6188. Inc(TargetRef.offset, 16);
  6189. if GetNextInstruction(hp2, hp3) and
  6190. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6191. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6192. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6193. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6194. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6195. begin
  6196. { Update the register tracking to the new size }
  6197. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6198. { Remember that the offsets are 16 ahead }
  6199. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6200. if not (
  6201. ((SourceRef.offset mod 32) = 16) and
  6202. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6203. ) then
  6204. taicpu(p).opcode := A_VMOVDQU;
  6205. taicpu(p).opsize := S_YMM;
  6206. taicpu(p).oper[1]^.reg := CurrentReg;
  6207. if not (
  6208. ((TargetRef.offset mod 32) = 16) and
  6209. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6210. ) then
  6211. taicpu(hp1).opcode := A_VMOVDQU;
  6212. taicpu(hp1).opsize := S_YMM;
  6213. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6214. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6215. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6216. if (pi_uses_ymm in current_procinfo.flags) then
  6217. RemoveInstruction(hp2)
  6218. else
  6219. begin
  6220. taicpu(hp2).opcode := A_VPXOR;
  6221. taicpu(hp2).opsize := S_YMM;
  6222. taicpu(hp2).loadreg(0, CurrentReg);
  6223. taicpu(hp2).loadreg(1, CurrentReg);
  6224. taicpu(hp2).loadreg(2, CurrentReg);
  6225. taicpu(hp2).ops := 3;
  6226. end;
  6227. RemoveInstruction(hp3);
  6228. Result := True;
  6229. Exit;
  6230. end;
  6231. end
  6232. else
  6233. begin
  6234. { See if the next references are 16 less rather than 16 greater }
  6235. Dec(SourceRef.offset, 32); { -16 the other way }
  6236. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6237. begin
  6238. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6239. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6240. if GetNextInstruction(hp2, hp3) and
  6241. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6242. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6243. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6244. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6245. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6246. begin
  6247. { Update the register tracking to the new size }
  6248. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6249. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6250. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6251. if not(
  6252. ((SourceRef.offset mod 32) = 0) and
  6253. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6254. ) then
  6255. taicpu(hp2).opcode := A_VMOVDQU;
  6256. taicpu(hp2).opsize := S_YMM;
  6257. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6258. if not (
  6259. ((TargetRef.offset mod 32) = 0) and
  6260. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6261. ) then
  6262. taicpu(hp3).opcode := A_VMOVDQU;
  6263. taicpu(hp3).opsize := S_YMM;
  6264. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6265. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6266. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6267. if (pi_uses_ymm in current_procinfo.flags) then
  6268. RemoveInstruction(hp1)
  6269. else
  6270. begin
  6271. taicpu(hp1).opcode := A_VPXOR;
  6272. taicpu(hp1).opsize := S_YMM;
  6273. taicpu(hp1).loadreg(0, CurrentReg);
  6274. taicpu(hp1).loadreg(1, CurrentReg);
  6275. taicpu(hp1).loadreg(2, CurrentReg);
  6276. taicpu(hp1).ops := 3;
  6277. Asml.Remove(hp1);
  6278. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6279. end;
  6280. RemoveCurrentP(p, hp2);
  6281. Result := True;
  6282. Exit;
  6283. end;
  6284. end;
  6285. end;
  6286. end;
  6287. end;
  6288. end;
  6289. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6290. var
  6291. hp2, hp3, first_assignment: tai;
  6292. IncCount, OperIdx: Integer;
  6293. OrigLabel: TAsmLabel;
  6294. begin
  6295. Count := 0;
  6296. Result := False;
  6297. first_assignment := nil;
  6298. if (LoopCount >= 20) then
  6299. begin
  6300. { Guard against infinite loops }
  6301. Exit;
  6302. end;
  6303. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6304. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6305. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6306. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6307. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6308. Exit;
  6309. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6310. {
  6311. change
  6312. jmp .L1
  6313. ...
  6314. .L1:
  6315. mov ##, ## ( multiple movs possible )
  6316. jmp/ret
  6317. into
  6318. mov ##, ##
  6319. jmp/ret
  6320. }
  6321. if not Assigned(hp1) then
  6322. begin
  6323. hp1 := GetLabelWithSym(OrigLabel);
  6324. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6325. Exit;
  6326. end;
  6327. hp2 := hp1;
  6328. while Assigned(hp2) do
  6329. begin
  6330. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6331. SkipLabels(hp2,hp2);
  6332. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6333. Break;
  6334. case taicpu(hp2).opcode of
  6335. A_MOVSS:
  6336. begin
  6337. if taicpu(hp2).ops = 0 then
  6338. { Wrong MOVSS }
  6339. Break;
  6340. Inc(Count);
  6341. if Count >= 5 then
  6342. { Too many to be worthwhile }
  6343. Break;
  6344. GetNextInstruction(hp2, hp2);
  6345. Continue;
  6346. end;
  6347. A_MOV,
  6348. A_MOVD,
  6349. A_MOVQ,
  6350. A_MOVSX,
  6351. {$ifdef x86_64}
  6352. A_MOVSXD,
  6353. {$endif x86_64}
  6354. A_MOVZX,
  6355. A_MOVAPS,
  6356. A_MOVUPS,
  6357. A_MOVSD,
  6358. A_MOVAPD,
  6359. A_MOVUPD,
  6360. A_MOVDQA,
  6361. A_MOVDQU,
  6362. A_VMOVSS,
  6363. A_VMOVAPS,
  6364. A_VMOVUPS,
  6365. A_VMOVSD,
  6366. A_VMOVAPD,
  6367. A_VMOVUPD,
  6368. A_VMOVDQA,
  6369. A_VMOVDQU:
  6370. begin
  6371. Inc(Count);
  6372. if Count >= 5 then
  6373. { Too many to be worthwhile }
  6374. Break;
  6375. GetNextInstruction(hp2, hp2);
  6376. Continue;
  6377. end;
  6378. A_JMP:
  6379. begin
  6380. { Guard against infinite loops }
  6381. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6382. Exit;
  6383. { Analyse this jump first in case it also duplicates assignments }
  6384. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6385. begin
  6386. { Something did change! }
  6387. Result := True;
  6388. Inc(Count, IncCount);
  6389. if Count >= 5 then
  6390. begin
  6391. { Too many to be worthwhile }
  6392. Exit;
  6393. end;
  6394. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6395. Break;
  6396. end;
  6397. Result := True;
  6398. Break;
  6399. end;
  6400. A_RET:
  6401. begin
  6402. Result := True;
  6403. Break;
  6404. end;
  6405. else
  6406. Break;
  6407. end;
  6408. end;
  6409. if Result then
  6410. begin
  6411. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6412. if Count = 0 then
  6413. begin
  6414. Result := False;
  6415. Exit;
  6416. end;
  6417. hp3 := p;
  6418. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6419. while True do
  6420. begin
  6421. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6422. SkipLabels(hp1,hp1);
  6423. if (hp1.typ <> ait_instruction) then
  6424. InternalError(2021040720);
  6425. case taicpu(hp1).opcode of
  6426. A_JMP:
  6427. begin
  6428. { Change the original jump to the new destination }
  6429. OrigLabel.decrefs;
  6430. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6431. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6432. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6433. if not Assigned(first_assignment) then
  6434. InternalError(2021040810)
  6435. else
  6436. p := first_assignment;
  6437. Exit;
  6438. end;
  6439. A_RET:
  6440. begin
  6441. { Now change the jump into a RET instruction }
  6442. ConvertJumpToRET(p, hp1);
  6443. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6444. if not Assigned(first_assignment) then
  6445. InternalError(2021040811)
  6446. else
  6447. p := first_assignment;
  6448. Exit;
  6449. end;
  6450. else
  6451. begin
  6452. { Duplicate the MOV instruction }
  6453. hp3:=tai(hp1.getcopy);
  6454. if first_assignment = nil then
  6455. first_assignment := hp3;
  6456. asml.InsertBefore(hp3, p);
  6457. { Make sure the compiler knows about any final registers written here }
  6458. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6459. with taicpu(hp3).oper[OperIdx]^ do
  6460. begin
  6461. case typ of
  6462. top_ref:
  6463. begin
  6464. if (ref^.base <> NR_NO) and
  6465. (getsupreg(ref^.base) <> RS_ESP) and
  6466. (getsupreg(ref^.base) <> RS_EBP)
  6467. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6468. then
  6469. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6470. if (ref^.index <> NR_NO) and
  6471. (getsupreg(ref^.index) <> RS_ESP) and
  6472. (getsupreg(ref^.index) <> RS_EBP)
  6473. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6474. (ref^.index <> ref^.base) then
  6475. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6476. end;
  6477. top_reg:
  6478. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6479. else
  6480. ;
  6481. end;
  6482. end;
  6483. end;
  6484. end;
  6485. if not GetNextInstruction(hp1, hp1) then
  6486. { Should have dropped out earlier }
  6487. InternalError(2021040710);
  6488. end;
  6489. end;
  6490. end;
  6491. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6492. var
  6493. hp2: tai;
  6494. X: Integer;
  6495. const
  6496. WriteOp: array[0..3] of set of TInsChange = (
  6497. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6498. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6499. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6500. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6501. RegWriteFlags: array[0..7] of set of TInsChange = (
  6502. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6503. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6504. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6505. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6506. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6507. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6508. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6509. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6510. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6511. begin
  6512. { If we have something like:
  6513. cmp ###,%reg1
  6514. mov 0,%reg2
  6515. And no modified registers are shared, move the instruction to before
  6516. the comparison as this means it can be optimised without worrying
  6517. about the FLAGS register. (CMP/MOV is generated by
  6518. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6519. As long as the second instruction doesn't use the flags or one of the
  6520. registers used by CMP or TEST (also check any references that use the
  6521. registers), then it can be moved prior to the comparison.
  6522. }
  6523. Result := False;
  6524. if (hp1.typ <> ait_instruction) or
  6525. taicpu(hp1).is_jmp or
  6526. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6527. Exit;
  6528. { NOP is a pipeline fence, likely marking the beginning of the function
  6529. epilogue, so drop out. Similarly, drop out if POP or RET are
  6530. encountered }
  6531. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6532. Exit;
  6533. if (taicpu(hp1).opcode = A_MOVSS) and
  6534. (taicpu(hp1).ops = 0) then
  6535. { Wrong MOVSS }
  6536. Exit;
  6537. { Check for writes to specific registers first }
  6538. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6539. for X := 0 to 7 do
  6540. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6541. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6542. Exit;
  6543. for X := 0 to taicpu(hp1).ops - 1 do
  6544. begin
  6545. { Check to see if this operand writes to something }
  6546. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6547. { And matches something in the CMP/TEST instruction }
  6548. (
  6549. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6550. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6551. (
  6552. { If it's a register, make sure the register written to doesn't
  6553. appear in the cmp instruction as part of a reference }
  6554. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6555. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6556. )
  6557. ) then
  6558. Exit;
  6559. end;
  6560. { The instruction can be safely moved }
  6561. asml.Remove(hp1);
  6562. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6563. if not GetLastInstruction(p, hp2) then
  6564. asml.InsertBefore(hp1, p)
  6565. else
  6566. asml.InsertAfter(hp1, hp2);
  6567. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6568. for X := 0 to taicpu(hp1).ops - 1 do
  6569. case taicpu(hp1).oper[X]^.typ of
  6570. top_reg:
  6571. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6572. top_ref:
  6573. begin
  6574. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6575. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6576. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6577. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6578. end;
  6579. else
  6580. ;
  6581. end;
  6582. if taicpu(hp1).opcode = A_LEA then
  6583. { The flags will be overwritten by the CMP/TEST instruction }
  6584. ConvertLEA(taicpu(hp1));
  6585. Result := True;
  6586. end;
  6587. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6588. function IsXCHGAcceptable: Boolean; inline;
  6589. begin
  6590. { Always accept if optimising for size }
  6591. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6592. (
  6593. {$ifdef x86_64}
  6594. { XCHG takes 3 cycles on AMD Athlon64 }
  6595. (current_settings.optimizecputype >= cpu_core_i)
  6596. {$else x86_64}
  6597. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6598. than 3, so it becomes a saving compared to three MOVs with two of
  6599. them able to execute simultaneously. [Kit] }
  6600. (current_settings.optimizecputype >= cpu_PentiumM)
  6601. {$endif x86_64}
  6602. );
  6603. end;
  6604. var
  6605. NewRef: TReference;
  6606. hp1, hp2, hp3, hp4: Tai;
  6607. {$ifndef x86_64}
  6608. OperIdx: Integer;
  6609. {$endif x86_64}
  6610. NewInstr : Taicpu;
  6611. NewAligh : Tai_align;
  6612. DestLabel: TAsmLabel;
  6613. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6614. var
  6615. NextInstr: tai;
  6616. begin
  6617. Result := False;
  6618. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6619. if not GetNextInstruction(InputInstr, NextInstr) or
  6620. (
  6621. { The FLAGS register isn't always tracked properly, so do not
  6622. perform this optimisation if a conditional statement follows }
  6623. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6624. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6625. ) then
  6626. begin
  6627. reference_reset(NewRef, 1, []);
  6628. NewRef.base := taicpu(p).oper[0]^.reg;
  6629. NewRef.scalefactor := 1;
  6630. if taicpu(InputInstr).opcode = A_ADD then
  6631. begin
  6632. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6633. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6634. end
  6635. else
  6636. begin
  6637. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6638. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6639. end;
  6640. taicpu(p).opcode := A_LEA;
  6641. taicpu(p).loadref(0, NewRef);
  6642. RemoveInstruction(InputInstr);
  6643. Result := True;
  6644. end;
  6645. end;
  6646. begin
  6647. Result:=false;
  6648. { This optimisation adds an instruction, so only do it for speed }
  6649. if not (cs_opt_size in current_settings.optimizerswitches) and
  6650. MatchOpType(taicpu(p), top_const, top_reg) and
  6651. (taicpu(p).oper[0]^.val = 0) then
  6652. begin
  6653. { To avoid compiler warning }
  6654. DestLabel := nil;
  6655. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6656. InternalError(2021040750);
  6657. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6658. Exit;
  6659. case hp1.typ of
  6660. ait_label:
  6661. begin
  6662. { Change:
  6663. mov $0,%reg mov $0,%reg
  6664. @Lbl1: @Lbl1:
  6665. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6666. je @Lbl2 jne @Lbl2
  6667. To: To:
  6668. mov $0,%reg mov $0,%reg
  6669. jmp @Lbl2 jmp @Lbl3
  6670. (align) (align)
  6671. @Lbl1: @Lbl1:
  6672. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6673. je @Lbl2 je @Lbl2
  6674. @Lbl3: <-- Only if label exists
  6675. (Not if it's optimised for size)
  6676. }
  6677. if not GetNextInstruction(hp1, hp2) then
  6678. Exit;
  6679. if not (cs_opt_size in current_settings.optimizerswitches) and
  6680. (hp2.typ = ait_instruction) and
  6681. (
  6682. { Register sizes must exactly match }
  6683. (
  6684. (taicpu(hp2).opcode = A_CMP) and
  6685. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6686. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6687. ) or (
  6688. (taicpu(hp2).opcode = A_TEST) and
  6689. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6690. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6691. )
  6692. ) and GetNextInstruction(hp2, hp3) and
  6693. (hp3.typ = ait_instruction) and
  6694. (taicpu(hp3).opcode = A_JCC) and
  6695. (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
  6696. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6697. begin
  6698. { Check condition of jump }
  6699. { Always true? }
  6700. if condition_in(C_E, taicpu(hp3).condition) then
  6701. begin
  6702. { Copy label symbol and obtain matching label entry for the
  6703. conditional jump, as this will be our destination}
  6704. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6705. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6706. Result := True;
  6707. end
  6708. { Always false? }
  6709. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6710. begin
  6711. { This is only worth it if there's a jump to take }
  6712. case hp2.typ of
  6713. ait_instruction:
  6714. begin
  6715. if taicpu(hp2).opcode = A_JMP then
  6716. begin
  6717. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6718. { An unconditional jump follows the conditional jump which will always be false,
  6719. so use this jump's destination for the new jump }
  6720. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6721. Result := True;
  6722. end
  6723. else if taicpu(hp2).opcode = A_JCC then
  6724. begin
  6725. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6726. if condition_in(C_E, taicpu(hp2).condition) then
  6727. begin
  6728. { A second conditional jump follows the conditional jump which will always be false,
  6729. while the second jump is always True, so use this jump's destination for the new jump }
  6730. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6731. Result := True;
  6732. end;
  6733. { Don't risk it if the jump isn't always true (Result remains False) }
  6734. end;
  6735. end;
  6736. else
  6737. { If anything else don't optimise };
  6738. end;
  6739. end;
  6740. if Result then
  6741. begin
  6742. { Just so we have something to insert as a paremeter}
  6743. reference_reset(NewRef, 1, []);
  6744. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6745. { Now actually load the correct parameter }
  6746. NewInstr.loadsymbol(0, DestLabel, 0);
  6747. { Get instruction before original label (may not be p under -O3) }
  6748. if not GetLastInstruction(hp1, hp2) then
  6749. { Shouldn't fail here }
  6750. InternalError(2021040701);
  6751. DestLabel.increfs;
  6752. AsmL.InsertAfter(NewInstr, hp2);
  6753. { Add new alignment field }
  6754. (* AsmL.InsertAfter(
  6755. cai_align.create_max(
  6756. current_settings.alignment.jumpalign,
  6757. current_settings.alignment.jumpalignskipmax
  6758. ),
  6759. NewInstr
  6760. ); *)
  6761. end;
  6762. Exit;
  6763. end;
  6764. end;
  6765. else
  6766. ;
  6767. end;
  6768. end;
  6769. if not GetNextInstruction(p, hp1) then
  6770. Exit;
  6771. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6772. begin
  6773. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6774. further, but we can't just put this jump optimisation in pass 1
  6775. because it tends to perform worse when conditional jumps are
  6776. nearby (e.g. when converting CMOV instructions). [Kit] }
  6777. if OptPass2JMP(hp1) then
  6778. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6779. Result := OptPass1MOV(p)
  6780. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6781. returned True and the instruction is still a MOV, thus checking
  6782. the optimisations below }
  6783. { If OptPass2JMP returned False, no optimisations were done to
  6784. the jump and there are no further optimisations that can be done
  6785. to the MOV instruction on this pass }
  6786. end
  6787. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6788. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6789. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6790. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6791. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6792. begin
  6793. { Change:
  6794. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6795. addl/q $x,%reg2 subl/q $x,%reg2
  6796. To:
  6797. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6798. }
  6799. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6800. { be lazy, checking separately for sub would be slightly better }
  6801. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6802. begin
  6803. TransferUsedRegs(TmpUsedRegs);
  6804. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6805. if TryMovArith2Lea(hp1) then
  6806. begin
  6807. Result := True;
  6808. Exit;
  6809. end
  6810. end
  6811. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6812. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6813. { Same as above, but also adds or subtracts to %reg2 in between.
  6814. It's still valid as long as the flags aren't in use }
  6815. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6816. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6817. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6818. { be lazy, checking separately for sub would be slightly better }
  6819. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6820. begin
  6821. TransferUsedRegs(TmpUsedRegs);
  6822. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6823. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6824. if TryMovArith2Lea(hp2) then
  6825. begin
  6826. Result := True;
  6827. Exit;
  6828. end;
  6829. end;
  6830. end
  6831. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6832. {$ifdef x86_64}
  6833. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6834. {$else x86_64}
  6835. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6836. {$endif x86_64}
  6837. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6838. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6839. { mov reg1, reg2 mov reg1, reg2
  6840. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6841. begin
  6842. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6843. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6844. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6845. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6846. TransferUsedRegs(TmpUsedRegs);
  6847. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6848. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6849. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6850. then
  6851. begin
  6852. RemoveCurrentP(p, hp1);
  6853. Result:=true;
  6854. end;
  6855. exit;
  6856. end
  6857. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6858. IsXCHGAcceptable and
  6859. { XCHG doesn't support 8-byte registers }
  6860. (taicpu(p).opsize <> S_B) and
  6861. MatchInstruction(hp1, A_MOV, []) and
  6862. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6863. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6864. GetNextInstruction(hp1, hp2) and
  6865. MatchInstruction(hp2, A_MOV, []) and
  6866. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6867. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6868. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6869. begin
  6870. { mov %reg1,%reg2
  6871. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6872. mov %reg2,%reg3
  6873. (%reg2 not used afterwards)
  6874. Note that xchg takes 3 cycles to execute, and generally mov's take
  6875. only one cycle apiece, but the first two mov's can be executed in
  6876. parallel, only taking 2 cycles overall. Older processors should
  6877. therefore only optimise for size. [Kit]
  6878. }
  6879. TransferUsedRegs(TmpUsedRegs);
  6880. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6881. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6882. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6883. begin
  6884. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6885. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6886. taicpu(hp1).opcode := A_XCHG;
  6887. RemoveCurrentP(p, hp1);
  6888. RemoveInstruction(hp2);
  6889. Result := True;
  6890. Exit;
  6891. end;
  6892. end
  6893. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6894. MatchInstruction(hp1, A_SAR, []) then
  6895. begin
  6896. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6897. begin
  6898. { the use of %edx also covers the opsize being S_L }
  6899. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6900. begin
  6901. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6902. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6903. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6904. begin
  6905. { Change:
  6906. movl %eax,%edx
  6907. sarl $31,%edx
  6908. To:
  6909. cltd
  6910. }
  6911. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6912. RemoveInstruction(hp1);
  6913. taicpu(p).opcode := A_CDQ;
  6914. taicpu(p).opsize := S_NO;
  6915. taicpu(p).clearop(1);
  6916. taicpu(p).clearop(0);
  6917. taicpu(p).ops:=0;
  6918. Result := True;
  6919. end
  6920. else if (cs_opt_size in current_settings.optimizerswitches) and
  6921. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6922. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6923. begin
  6924. { Change:
  6925. movl %edx,%eax
  6926. sarl $31,%edx
  6927. To:
  6928. movl %edx,%eax
  6929. cltd
  6930. Note that this creates a dependency between the two instructions,
  6931. so only perform if optimising for size.
  6932. }
  6933. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6934. taicpu(hp1).opcode := A_CDQ;
  6935. taicpu(hp1).opsize := S_NO;
  6936. taicpu(hp1).clearop(1);
  6937. taicpu(hp1).clearop(0);
  6938. taicpu(hp1).ops:=0;
  6939. end;
  6940. {$ifndef x86_64}
  6941. end
  6942. { Don't bother if CMOV is supported, because a more optimal
  6943. sequence would have been generated for the Abs() intrinsic }
  6944. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6945. { the use of %eax also covers the opsize being S_L }
  6946. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6947. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6948. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6949. GetNextInstruction(hp1, hp2) and
  6950. MatchInstruction(hp2, A_XOR, [S_L]) and
  6951. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6952. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6953. GetNextInstruction(hp2, hp3) and
  6954. MatchInstruction(hp3, A_SUB, [S_L]) and
  6955. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6956. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6957. begin
  6958. { Change:
  6959. movl %eax,%edx
  6960. sarl $31,%eax
  6961. xorl %eax,%edx
  6962. subl %eax,%edx
  6963. (Instruction that uses %edx)
  6964. (%eax deallocated)
  6965. (%edx deallocated)
  6966. To:
  6967. cltd
  6968. xorl %edx,%eax <-- Note the registers have swapped
  6969. subl %edx,%eax
  6970. (Instruction that uses %eax) <-- %eax rather than %edx
  6971. }
  6972. TransferUsedRegs(TmpUsedRegs);
  6973. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6974. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6976. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6977. begin
  6978. if GetNextInstruction(hp3, hp4) and
  6979. not RegModifiedByInstruction(NR_EDX, hp4) and
  6980. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6981. begin
  6982. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6983. taicpu(p).opcode := A_CDQ;
  6984. taicpu(p).clearop(1);
  6985. taicpu(p).clearop(0);
  6986. taicpu(p).ops:=0;
  6987. RemoveInstruction(hp1);
  6988. taicpu(hp2).loadreg(0, NR_EDX);
  6989. taicpu(hp2).loadreg(1, NR_EAX);
  6990. taicpu(hp3).loadreg(0, NR_EDX);
  6991. taicpu(hp3).loadreg(1, NR_EAX);
  6992. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6993. { Convert references in the following instruction (hp4) from %edx to %eax }
  6994. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6995. with taicpu(hp4).oper[OperIdx]^ do
  6996. case typ of
  6997. top_reg:
  6998. if getsupreg(reg) = RS_EDX then
  6999. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7000. top_ref:
  7001. begin
  7002. if getsupreg(reg) = RS_EDX then
  7003. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7004. if getsupreg(reg) = RS_EDX then
  7005. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7006. end;
  7007. else
  7008. ;
  7009. end;
  7010. end;
  7011. end;
  7012. {$else x86_64}
  7013. end;
  7014. end
  7015. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7016. { the use of %rdx also covers the opsize being S_Q }
  7017. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7018. begin
  7019. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7020. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7021. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7022. begin
  7023. { Change:
  7024. movq %rax,%rdx
  7025. sarq $63,%rdx
  7026. To:
  7027. cqto
  7028. }
  7029. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7030. RemoveInstruction(hp1);
  7031. taicpu(p).opcode := A_CQO;
  7032. taicpu(p).opsize := S_NO;
  7033. taicpu(p).clearop(1);
  7034. taicpu(p).clearop(0);
  7035. taicpu(p).ops:=0;
  7036. Result := True;
  7037. end
  7038. else if (cs_opt_size in current_settings.optimizerswitches) and
  7039. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7040. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7041. begin
  7042. { Change:
  7043. movq %rdx,%rax
  7044. sarq $63,%rdx
  7045. To:
  7046. movq %rdx,%rax
  7047. cqto
  7048. Note that this creates a dependency between the two instructions,
  7049. so only perform if optimising for size.
  7050. }
  7051. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7052. taicpu(hp1).opcode := A_CQO;
  7053. taicpu(hp1).opsize := S_NO;
  7054. taicpu(hp1).clearop(1);
  7055. taicpu(hp1).clearop(0);
  7056. taicpu(hp1).ops:=0;
  7057. {$endif x86_64}
  7058. end;
  7059. end;
  7060. end
  7061. else if MatchInstruction(hp1, A_MOV, []) and
  7062. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7063. { Though "GetNextInstruction" could be factored out, along with
  7064. the instructions that depend on hp2, it is an expensive call that
  7065. should be delayed for as long as possible, hence we do cheaper
  7066. checks first that are likely to be False. [Kit] }
  7067. begin
  7068. if (
  7069. (
  7070. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7071. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7072. (
  7073. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7074. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7075. )
  7076. ) or
  7077. (
  7078. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7079. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7080. (
  7081. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7082. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7083. )
  7084. )
  7085. ) and
  7086. GetNextInstruction(hp1, hp2) and
  7087. MatchInstruction(hp2, A_SAR, []) and
  7088. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7089. begin
  7090. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7091. begin
  7092. { Change:
  7093. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7094. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7095. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7096. To:
  7097. movl r/m,%eax <- Note the change in register
  7098. cltd
  7099. }
  7100. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7101. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7102. taicpu(p).loadreg(1, NR_EAX);
  7103. taicpu(hp1).opcode := A_CDQ;
  7104. taicpu(hp1).clearop(1);
  7105. taicpu(hp1).clearop(0);
  7106. taicpu(hp1).ops:=0;
  7107. RemoveInstruction(hp2);
  7108. (*
  7109. {$ifdef x86_64}
  7110. end
  7111. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7112. { This code sequence does not get generated - however it might become useful
  7113. if and when 128-bit signed integer types make an appearance, so the code
  7114. is kept here for when it is eventually needed. [Kit] }
  7115. (
  7116. (
  7117. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7118. (
  7119. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7120. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7121. )
  7122. ) or
  7123. (
  7124. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7125. (
  7126. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7127. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7128. )
  7129. )
  7130. ) and
  7131. GetNextInstruction(hp1, hp2) and
  7132. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7133. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7134. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7135. begin
  7136. { Change:
  7137. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7138. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7139. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7140. To:
  7141. movq r/m,%rax <- Note the change in register
  7142. cqto
  7143. }
  7144. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7145. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7146. taicpu(p).loadreg(1, NR_RAX);
  7147. taicpu(hp1).opcode := A_CQO;
  7148. taicpu(hp1).clearop(1);
  7149. taicpu(hp1).clearop(0);
  7150. taicpu(hp1).ops:=0;
  7151. RemoveInstruction(hp2);
  7152. {$endif x86_64}
  7153. *)
  7154. end;
  7155. end;
  7156. {$ifdef x86_64}
  7157. end
  7158. else if (taicpu(p).opsize = S_L) and
  7159. (taicpu(p).oper[1]^.typ = top_reg) and
  7160. (
  7161. MatchInstruction(hp1, A_MOV,[]) and
  7162. (taicpu(hp1).opsize = S_L) and
  7163. (taicpu(hp1).oper[1]^.typ = top_reg)
  7164. ) and (
  7165. GetNextInstruction(hp1, hp2) and
  7166. (tai(hp2).typ=ait_instruction) and
  7167. (taicpu(hp2).opsize = S_Q) and
  7168. (
  7169. (
  7170. MatchInstruction(hp2, A_ADD,[]) and
  7171. (taicpu(hp2).opsize = S_Q) and
  7172. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7173. (
  7174. (
  7175. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7176. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7177. ) or (
  7178. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7179. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7180. )
  7181. )
  7182. ) or (
  7183. MatchInstruction(hp2, A_LEA,[]) and
  7184. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7185. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7186. (
  7187. (
  7188. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7189. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7190. ) or (
  7191. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7192. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7193. )
  7194. ) and (
  7195. (
  7196. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7197. ) or (
  7198. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7199. )
  7200. )
  7201. )
  7202. )
  7203. ) and (
  7204. GetNextInstruction(hp2, hp3) and
  7205. MatchInstruction(hp3, A_SHR,[]) and
  7206. (taicpu(hp3).opsize = S_Q) and
  7207. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7208. (taicpu(hp3).oper[0]^.val = 1) and
  7209. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7210. ) then
  7211. begin
  7212. { Change movl x, reg1d movl x, reg1d
  7213. movl y, reg2d movl y, reg2d
  7214. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7215. shrq $1, reg1q shrq $1, reg1q
  7216. ( reg1d and reg2d can be switched around in the first two instructions )
  7217. To movl x, reg1d
  7218. addl y, reg1d
  7219. rcrl $1, reg1d
  7220. This corresponds to the common expression (x + y) shr 1, where
  7221. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7222. smaller code, but won't account for x + y causing an overflow). [Kit]
  7223. }
  7224. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7225. { Change first MOV command to have the same register as the final output }
  7226. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7227. else
  7228. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7229. { Change second MOV command to an ADD command. This is easier than
  7230. converting the existing command because it means we don't have to
  7231. touch 'y', which might be a complicated reference, and also the
  7232. fact that the third command might either be ADD or LEA. [Kit] }
  7233. taicpu(hp1).opcode := A_ADD;
  7234. { Delete old ADD/LEA instruction }
  7235. RemoveInstruction(hp2);
  7236. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7237. taicpu(hp3).opcode := A_RCR;
  7238. taicpu(hp3).changeopsize(S_L);
  7239. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7240. {$endif x86_64}
  7241. end;
  7242. end;
  7243. {$push}
  7244. {$q-}{$r-}
  7245. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7246. label
  7247. { This label permits the case block for MOVSX/D to pass into the MOVZX block }
  7248. movzx_cascade;
  7249. var
  7250. ThisReg: TRegister;
  7251. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7252. TargetSubReg: TSubRegister;
  7253. hp1, hp2: tai;
  7254. RegInUse, RegChanged, p_removed: Boolean;
  7255. { Store list of found instructions so we don't have to call
  7256. GetNextInstructionUsingReg multiple times }
  7257. InstrList: array of taicpu;
  7258. InstrMax, Index: Integer;
  7259. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7260. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7261. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7262. WorkingValue: TCgInt;
  7263. PreMessage: string;
  7264. { Data flow analysis }
  7265. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7266. BitwiseOnly, OrXorUsed,
  7267. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7268. function CheckOverflowConditions: Boolean;
  7269. begin
  7270. Result := True;
  7271. if (TestValSignedMax > SignedUpperLimit) or (TestValSignedMax < SignedUpperLimitBottom) then
  7272. UpperSignedOverflow := True;
  7273. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7274. LowerSignedOverflow := True;
  7275. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7276. LowerUnsignedOverflow := True;
  7277. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7278. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax > SignedUpperLimit) then
  7279. begin
  7280. { Absolute overflow }
  7281. Result := False;
  7282. Exit;
  7283. end;
  7284. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7285. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7286. ShiftDownOverflow := True;
  7287. if (TestValMin < 0) or (TestValMax < 0) then
  7288. begin
  7289. LowerUnsignedOverflow := True;
  7290. UpperUnsignedOverflow := True;
  7291. end;
  7292. end;
  7293. procedure AdjustFinalLoad;
  7294. begin
  7295. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7296. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7297. begin
  7298. { Convert the output MOVZX to a MOV }
  7299. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7300. begin
  7301. { Or remove it completely! }
  7302. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7303. { Be careful; if p = hp1 and p was also removed, p
  7304. will become a dangling pointer }
  7305. if p = hp1 then
  7306. begin
  7307. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7308. p_removed := True;
  7309. end
  7310. else
  7311. RemoveInstruction(hp1);
  7312. end
  7313. else
  7314. begin
  7315. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7316. taicpu(hp1).opcode := A_MOV;
  7317. taicpu(hp1).oper[0]^.reg := ThisReg;
  7318. taicpu(hp1).opsize := TargetSize;
  7319. end;
  7320. end
  7321. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7322. begin
  7323. { Need to change the size of the output }
  7324. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7325. taicpu(hp1).oper[0]^.reg := ThisReg;
  7326. taicpu(hp1).opsize := S_BL;
  7327. end;
  7328. end;
  7329. begin
  7330. Result := False;
  7331. p_removed := False;
  7332. ThisReg := taicpu(p).oper[1]^.reg;
  7333. { Check for:
  7334. movs/z ###,%ecx (or %cx or %rcx)
  7335. ...
  7336. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7337. (dealloc %ecx)
  7338. Change to:
  7339. mov ###,%cl (if ### = %cl, then remove completely)
  7340. ...
  7341. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7342. }
  7343. if (getsupreg(ThisReg) = RS_ECX) and
  7344. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7345. (hp1.typ = ait_instruction) and
  7346. (
  7347. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7348. instruction that doesn't actually contain ECX }
  7349. (cs_opt_level3 in current_settings.optimizerswitches) or
  7350. RegInInstruction(NR_ECX, hp1) or
  7351. (
  7352. { It's common for the shift/rotate's read/write register to be
  7353. initialised in between, so under -O2 and under, search ahead
  7354. one more instruction
  7355. }
  7356. GetNextInstruction(hp1, hp1) and
  7357. (hp1.typ = ait_instruction) and
  7358. RegInInstruction(NR_ECX, hp1)
  7359. )
  7360. ) and
  7361. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7362. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7363. begin
  7364. TransferUsedRegs(TmpUsedRegs);
  7365. hp2 := p;
  7366. repeat
  7367. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7368. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7369. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7370. begin
  7371. case taicpu(p).opsize of
  7372. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7373. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7374. begin
  7375. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7376. RemoveCurrentP(p);
  7377. end
  7378. else
  7379. begin
  7380. taicpu(p).opcode := A_MOV;
  7381. taicpu(p).opsize := S_B;
  7382. taicpu(p).oper[1]^.reg := NR_CL;
  7383. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7384. end;
  7385. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7386. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7387. begin
  7388. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7389. RemoveCurrentP(p);
  7390. end
  7391. else
  7392. begin
  7393. taicpu(p).opcode := A_MOV;
  7394. taicpu(p).opsize := S_W;
  7395. taicpu(p).oper[1]^.reg := NR_CX;
  7396. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7397. end;
  7398. {$ifdef x86_64}
  7399. S_LQ:
  7400. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7401. begin
  7402. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7403. RemoveCurrentP(p);
  7404. end
  7405. else
  7406. begin
  7407. taicpu(p).opcode := A_MOV;
  7408. taicpu(p).opsize := S_L;
  7409. taicpu(p).oper[1]^.reg := NR_ECX;
  7410. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7411. end;
  7412. {$endif x86_64}
  7413. else
  7414. InternalError(2021120401);
  7415. end;
  7416. Result := True;
  7417. Exit;
  7418. end;
  7419. end;
  7420. { This is anything but quick! }
  7421. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7422. Exit;
  7423. SetLength(InstrList, 0);
  7424. InstrMax := -1;
  7425. case taicpu(p).opsize of
  7426. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7427. begin
  7428. {$if defined(i386) or defined(i8086)}
  7429. { If the target size is 8-bit, make sure we can actually encode it }
  7430. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7431. Exit;
  7432. {$endif i386 or i8086}
  7433. LowerLimit := $FF;
  7434. SignedLowerLimit := $7F;
  7435. SignedLowerLimitBottom := -128;
  7436. MinSize := S_B;
  7437. if taicpu(p).opsize = S_BW then
  7438. begin
  7439. MaxSize := S_W;
  7440. UpperLimit := $FFFF;
  7441. SignedUpperLimit := $7FFF;
  7442. SignedUpperLimitBottom := -32768;
  7443. end
  7444. else
  7445. begin
  7446. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7447. MaxSize := S_L;
  7448. UpperLimit := $FFFFFFFF;
  7449. SignedUpperLimit := $7FFFFFFF;
  7450. SignedUpperLimitBottom := -2147483648;
  7451. end;
  7452. end;
  7453. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7454. begin
  7455. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7456. LowerLimit := $FFFF;
  7457. SignedLowerLimit := $7FFF;
  7458. SignedLowerLimitBottom := -32768;
  7459. UpperLimit := $FFFFFFFF;
  7460. SignedUpperLimit := $7FFFFFFF;
  7461. SignedUpperLimitBottom := -2147483648;
  7462. MinSize := S_W;
  7463. MaxSize := S_L;
  7464. end;
  7465. {$ifdef x86_64}
  7466. S_LQ:
  7467. begin
  7468. { Both the lower and upper limits are set to 32-bit. If a limit
  7469. is breached, then optimisation is impossible }
  7470. LowerLimit := $FFFFFFFF;
  7471. SignedLowerLimit := $7FFFFFFF;
  7472. SignedLowerLimitBottom := -2147483648;
  7473. UpperLimit := $FFFFFFFF;
  7474. SignedUpperLimit := $7FFFFFFF;
  7475. SignedUpperLimitBottom := -2147483648;
  7476. MinSize := S_L;
  7477. MaxSize := S_L;
  7478. end;
  7479. {$endif x86_64}
  7480. else
  7481. InternalError(2020112301);
  7482. end;
  7483. TestValMin := 0;
  7484. TestValMax := LowerLimit;
  7485. TestValSignedMax := SignedLowerLimit;
  7486. TryShiftDownLimit := LowerLimit;
  7487. TryShiftDown := S_NO;
  7488. ShiftDownOverflow := False;
  7489. RegChanged := False;
  7490. BitwiseOnly := True;
  7491. OrXorUsed := False;
  7492. UpperSignedOverflow := False;
  7493. LowerSignedOverflow := False;
  7494. UpperUnsignedOverflow := False;
  7495. LowerUnsignedOverflow := False;
  7496. hp1 := p;
  7497. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7498. (hp1.typ = ait_instruction) and
  7499. (
  7500. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7501. instruction that doesn't actually contain ThisReg }
  7502. (cs_opt_level3 in current_settings.optimizerswitches) or
  7503. RegInInstruction(ThisReg, hp1)
  7504. ) do
  7505. begin
  7506. case taicpu(hp1).opcode of
  7507. A_INC,A_DEC:
  7508. begin
  7509. { Has to be an exact match on the register }
  7510. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7511. Break;
  7512. if taicpu(hp1).opcode = A_INC then
  7513. begin
  7514. Inc(TestValMin);
  7515. Inc(TestValMax);
  7516. Inc(TestValSignedMax);
  7517. end
  7518. else
  7519. begin
  7520. Dec(TestValMin);
  7521. Dec(TestValMax);
  7522. Dec(TestValSignedMax);
  7523. end;
  7524. end;
  7525. A_TEST, A_CMP:
  7526. begin
  7527. if (
  7528. { Too high a risk of non-linear behaviour that breaks DFA
  7529. here, unless it's cmp $0,%reg, which is equivalent to
  7530. test %reg,%reg }
  7531. OrXorUsed and
  7532. (taicpu(hp1).opcode = A_CMP) and
  7533. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7534. ) or
  7535. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7536. { Has to be an exact match on the register }
  7537. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7538. (
  7539. { Permit "test %reg,%reg" }
  7540. (taicpu(hp1).opcode = A_TEST) and
  7541. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7542. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7543. ) or
  7544. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7545. { Make sure the comparison value is not smaller than the
  7546. smallest allowed signed value for the minimum size (e.g.
  7547. -128 for 8-bit) }
  7548. not (
  7549. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7550. { Is it in the negative range? }
  7551. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  7552. ) then
  7553. Break;
  7554. { ANDing can't increase the value past the limit or decrease
  7555. it below 0, so we can skip the checks, plus the test value
  7556. won't change afterwards }
  7557. if (taicpu(hp1).opcode = A_CMP) and
  7558. { cmp $0,$reg is equivalent to test %reg,%reg, plus the
  7559. test values aren't being modified anyway }
  7560. (taicpu(hp1).oper[0]^.val <> 0) then
  7561. begin
  7562. WorkingValue := taicpu(hp1).oper[0]^.val;
  7563. case MinSize of
  7564. S_B:
  7565. if (WorkingValue and $ff)<>WorkingValue then
  7566. break;
  7567. S_W:
  7568. if (WorkingValue and $ffff)<>WorkingValue then
  7569. break;
  7570. else
  7571. ;
  7572. end;
  7573. TestValMin := TestValMin - WorkingValue;
  7574. TestValMax := TestValMax - WorkingValue;
  7575. TestValSignedMax := TestValSignedMax - WorkingValue;
  7576. if not CheckOverflowConditions then
  7577. Break;
  7578. { Because the register isn't actually adjusted, we can
  7579. restore the test values to what they were previously }
  7580. TestValMin := TestValMin + WorkingValue;
  7581. TestValMax := TestValMax + WorkingValue;
  7582. TestValSignedMax := TestValSignedMax + WorkingValue;
  7583. end;
  7584. { Check to see if the active register is used afterwards }
  7585. TransferUsedRegs(TmpUsedRegs);
  7586. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7587. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7588. begin
  7589. case MinSize of
  7590. S_B:
  7591. TargetSubReg := R_SUBL;
  7592. S_W:
  7593. TargetSubReg := R_SUBW;
  7594. else
  7595. InternalError(2021051002);
  7596. end;
  7597. { Update the register to its new size }
  7598. setsubreg(ThisReg, TargetSubReg);
  7599. taicpu(hp1).oper[1]^.reg := ThisReg;
  7600. taicpu(hp1).opsize := MinSize;
  7601. { Convert the input MOVZX to a MOV }
  7602. if (taicpu(p).oper[0]^.typ = top_reg) and
  7603. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7604. begin
  7605. { Or remove it completely! }
  7606. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7607. RemoveCurrentP(p);
  7608. p_removed := True;
  7609. end
  7610. else
  7611. begin
  7612. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7613. taicpu(p).opcode := A_MOV;
  7614. taicpu(p).oper[1]^.reg := ThisReg;
  7615. taicpu(p).opsize := MinSize;
  7616. end;
  7617. if (InstrMax >= 0) then
  7618. begin
  7619. for Index := 0 to InstrMax do
  7620. begin
  7621. { If p_removed is true, then the original MOV/Z was removed
  7622. and removing the AND instruction may not be safe if it
  7623. appears first }
  7624. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7625. InternalError(2020112311);
  7626. if InstrList[Index].oper[0]^.typ = top_reg then
  7627. InstrList[Index].oper[0]^.reg := ThisReg;
  7628. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7629. InstrList[Index].opsize := MinSize;
  7630. end;
  7631. end;
  7632. Result := True;
  7633. Exit;
  7634. end;
  7635. end;
  7636. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  7637. begin
  7638. if
  7639. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7640. { Has to be an exact match on the register }
  7641. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  7642. (
  7643. (
  7644. (taicpu(hp1).oper[0]^.typ = top_const) and
  7645. (
  7646. (
  7647. (taicpu(hp1).opcode = A_SHL) and
  7648. (
  7649. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  7650. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  7651. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  7652. )
  7653. ) or (
  7654. (taicpu(hp1).opcode <> A_SHL) and
  7655. (
  7656. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7657. { Is it in the negative range? }
  7658. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7659. )
  7660. )
  7661. )
  7662. ) or (
  7663. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  7664. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  7665. )
  7666. ) then
  7667. Break;
  7668. { Only process OR and XOR if there are only bitwise operations,
  7669. since otherwise they can too easily fool the data flow
  7670. analysis (they can cause non-linear behaviour) }
  7671. case taicpu(hp1).opcode of
  7672. A_ADD:
  7673. begin
  7674. if OrXorUsed then
  7675. { Too high a risk of non-linear behaviour that breaks DFA here }
  7676. Break
  7677. else
  7678. BitwiseOnly := False;
  7679. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7680. begin
  7681. TestValMin := TestValMin * 2;
  7682. TestValMax := TestValMax * 2;
  7683. TestValSignedMax := TestValSignedMax * 2;
  7684. end
  7685. else
  7686. begin
  7687. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  7688. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  7689. TestValSignedMax := TestValSignedMax + taicpu(hp1).oper[0]^.val;
  7690. end;
  7691. end;
  7692. A_SUB:
  7693. begin
  7694. if OrXorUsed then
  7695. { Too high a risk of non-linear behaviour that breaks DFA here }
  7696. Break
  7697. else
  7698. BitwiseOnly := False;
  7699. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7700. begin
  7701. TestValMin := 0;
  7702. TestValMax := 0;
  7703. TestValSignedMax := 0;
  7704. end
  7705. else
  7706. begin
  7707. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  7708. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  7709. TestValSignedMax := TestValSignedMax - taicpu(hp1).oper[0]^.val;
  7710. end;
  7711. end;
  7712. A_AND:
  7713. if (taicpu(hp1).oper[0]^.typ = top_const) then
  7714. begin
  7715. { we might be able to go smaller if AND appears first }
  7716. if InstrMax = -1 then
  7717. case MinSize of
  7718. S_B:
  7719. ;
  7720. S_W:
  7721. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7722. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7723. begin
  7724. TryShiftDown := S_B;
  7725. TryShiftDownLimit := $FF;
  7726. end;
  7727. S_L:
  7728. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  7729. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  7730. begin
  7731. TryShiftDown := S_B;
  7732. TryShiftDownLimit := $FF;
  7733. end
  7734. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  7735. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  7736. begin
  7737. TryShiftDown := S_W;
  7738. TryShiftDownLimit := $FFFF;
  7739. end;
  7740. else
  7741. InternalError(2020112320);
  7742. end;
  7743. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  7744. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  7745. TestValSignedMax := TestValSignedMax and taicpu(hp1).oper[0]^.val;
  7746. end;
  7747. A_OR:
  7748. begin
  7749. if not BitwiseOnly then
  7750. Break;
  7751. OrXorUsed := True;
  7752. TestValMin := TestValMin or taicpu(hp1).oper[0]^.val;
  7753. TestValMax := TestValMax or taicpu(hp1).oper[0]^.val;
  7754. TestValSignedMax := TestValSignedMax or taicpu(hp1).oper[0]^.val;
  7755. end;
  7756. A_XOR:
  7757. begin
  7758. if not BitwiseOnly then
  7759. Break;
  7760. OrXorUsed := True;
  7761. TestValMin := TestValMin xor taicpu(hp1).oper[0]^.val;
  7762. TestValMax := TestValMax xor taicpu(hp1).oper[0]^.val;
  7763. TestValSignedMax := TestValSignedMax xor taicpu(hp1).oper[0]^.val;
  7764. end;
  7765. A_SHL:
  7766. begin
  7767. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  7768. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  7769. TestValSignedMax := TestValSignedMax shl taicpu(hp1).oper[0]^.val;
  7770. end;
  7771. A_SHR,
  7772. { The first instruction was MOVZX, so the value won't be negative }
  7773. A_SAR:
  7774. begin
  7775. { we might be able to go smaller if SHR appears first }
  7776. if InstrMax = -1 then
  7777. case MinSize of
  7778. S_B:
  7779. ;
  7780. S_W:
  7781. if (taicpu(hp1).oper[0]^.val >= 8) then
  7782. begin
  7783. TryShiftDown := S_B;
  7784. TryShiftDownLimit := $FF;
  7785. TryShiftDownSignedLimit := $7F;
  7786. TryShiftDownSignedLimitLower := -128;
  7787. end;
  7788. S_L:
  7789. if (taicpu(hp1).oper[0]^.val >= 24) then
  7790. begin
  7791. TryShiftDown := S_B;
  7792. TryShiftDownLimit := $FF;
  7793. TryShiftDownSignedLimit := $7F;
  7794. TryShiftDownSignedLimitLower := -128;
  7795. end
  7796. else if (taicpu(hp1).oper[0]^.val >= 16) then
  7797. begin
  7798. TryShiftDown := S_W;
  7799. TryShiftDownLimit := $FFFF;
  7800. TryShiftDownSignedLimit := $7FFF;
  7801. TryShiftDownSignedLimitLower := -32768;
  7802. end;
  7803. else
  7804. InternalError(2020112321);
  7805. end;
  7806. if taicpu(hp1).opcode = A_SAR then
  7807. begin
  7808. TestValMin := SarInt64(TestValMin, taicpu(hp1).oper[0]^.val);
  7809. TestValMax := SarInt64(TestValMax, taicpu(hp1).oper[0]^.val);
  7810. TestValSignedMax := SarInt64(TestValSignedMax, taicpu(hp1).oper[0]^.val);
  7811. end
  7812. else
  7813. begin
  7814. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  7815. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  7816. TestValSignedMax := TestValSignedMax shr taicpu(hp1).oper[0]^.val;
  7817. end;
  7818. end;
  7819. else
  7820. InternalError(2020112303);
  7821. end;
  7822. end;
  7823. (*
  7824. A_IMUL:
  7825. case taicpu(hp1).ops of
  7826. 2:
  7827. begin
  7828. if not MatchOpType(hp1, top_reg, top_reg) or
  7829. { Has to be an exact match on the register }
  7830. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  7831. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  7832. Break;
  7833. TestValMin := TestValMin * TestValMin;
  7834. TestValMax := TestValMax * TestValMax;
  7835. TestValSignedMax := TestValSignedMax * TestValMax;
  7836. end;
  7837. 3:
  7838. begin
  7839. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7840. { Has to be an exact match on the register }
  7841. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7842. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7843. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7844. { Is it in the negative range? }
  7845. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7846. Break;
  7847. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  7848. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  7849. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  7850. end;
  7851. else
  7852. Break;
  7853. end;
  7854. A_IDIV:
  7855. case taicpu(hp1).ops of
  7856. 3:
  7857. begin
  7858. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  7859. { Has to be an exact match on the register }
  7860. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7861. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  7862. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7863. { Is it in the negative range? }
  7864. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  7865. Break;
  7866. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  7867. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  7868. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  7869. end;
  7870. else
  7871. Break;
  7872. end;
  7873. *)
  7874. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  7875. begin
  7876. { If there are no instructions in between, then we might be able to make a saving }
  7877. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  7878. Break;
  7879. { We have something like:
  7880. movzbw %dl,%dx
  7881. ...
  7882. movswl %dx,%edx
  7883. Change the latter to a zero-extension then enter the
  7884. A_MOVZX case branch.
  7885. }
  7886. {$ifdef x86_64}
  7887. if (taicpu(hp1).opcode = A_MOVSXD) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7888. begin
  7889. { this becomes a zero extension from 32-bit to 64-bit, but
  7890. the upper 32 bits are already zero, so just delete the
  7891. instruction }
  7892. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  7893. RemoveInstruction(hp1);
  7894. Result := True;
  7895. Exit;
  7896. end
  7897. else
  7898. {$endif x86_64}
  7899. begin
  7900. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  7901. taicpu(hp1).opcode := A_MOVZX;
  7902. {$ifdef x86_64}
  7903. case taicpu(hp1).opsize of
  7904. S_BQ:
  7905. begin
  7906. taicpu(hp1).opsize := S_BL;
  7907. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  7908. end;
  7909. S_WQ:
  7910. begin
  7911. taicpu(hp1).opsize := S_WL;
  7912. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  7913. end;
  7914. S_LQ:
  7915. begin
  7916. taicpu(hp1).opcode := A_MOV;
  7917. taicpu(hp1).opsize := S_L;
  7918. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  7919. { In this instance, we need to break out because the
  7920. instruction is no longer MOVZX or MOVSXD }
  7921. Result := True;
  7922. Exit;
  7923. end;
  7924. else
  7925. ;
  7926. end;
  7927. {$endif x86_64}
  7928. Result := True;
  7929. { Enter the A_MOVZX block below }
  7930. goto movzx_cascade;
  7931. end;
  7932. end;
  7933. A_MOVZX:
  7934. begin
  7935. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  7936. Break;
  7937. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  7938. begin
  7939. { Because hp1 was obtained via GetNextInstructionUsingReg
  7940. and ThisReg doesn't appear in the first operand, it
  7941. must appear in the second operand and hence gets
  7942. overwritten }
  7943. if (InstrMax = -1) and
  7944. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7945. begin
  7946. { The two MOVZX instructions are adjacent, so remove the first one }
  7947. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  7948. RemoveCurrentP(p);
  7949. Result := True;
  7950. Exit;
  7951. end;
  7952. Break;
  7953. end;
  7954. movzx_cascade:
  7955. { The objective here is to try to find a combination that
  7956. removes one of the MOV/Z instructions. }
  7957. if (
  7958. (taicpu(p).oper[0]^.typ <> top_reg) or
  7959. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7960. ) and
  7961. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7962. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7963. begin
  7964. { Make a preference to remove the second MOVZX instruction }
  7965. case taicpu(hp1).opsize of
  7966. S_BL, S_WL:
  7967. begin
  7968. TargetSize := S_L;
  7969. TargetSubReg := R_SUBD;
  7970. end;
  7971. S_BW:
  7972. begin
  7973. TargetSize := S_W;
  7974. TargetSubReg := R_SUBW;
  7975. end;
  7976. else
  7977. InternalError(2020112302);
  7978. end;
  7979. end
  7980. else
  7981. begin
  7982. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7983. begin
  7984. { Exceeded lower bound but not upper bound }
  7985. TargetSize := MaxSize;
  7986. end
  7987. else if not LowerUnsignedOverflow then
  7988. begin
  7989. { Size didn't exceed lower bound }
  7990. TargetSize := MinSize;
  7991. end
  7992. else
  7993. Break;
  7994. end;
  7995. case TargetSize of
  7996. S_B:
  7997. TargetSubReg := R_SUBL;
  7998. S_W:
  7999. TargetSubReg := R_SUBW;
  8000. S_L:
  8001. TargetSubReg := R_SUBD;
  8002. else
  8003. InternalError(2020112350);
  8004. end;
  8005. { Update the register to its new size }
  8006. setsubreg(ThisReg, TargetSubReg);
  8007. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8008. begin
  8009. { Check to see if the active register is used afterwards;
  8010. if not, we can change it and make a saving. }
  8011. RegInUse := False;
  8012. TransferUsedRegs(TmpUsedRegs);
  8013. { The target register may be marked as in use to cross
  8014. a jump to a distant label, so exclude it }
  8015. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8016. hp2 := p;
  8017. repeat
  8018. { Explicitly check for the excluded register (don't include the first
  8019. instruction as it may be reading from here }
  8020. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8021. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8022. begin
  8023. RegInUse := True;
  8024. Break;
  8025. end;
  8026. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8027. if not GetNextInstruction(hp2, hp2) then
  8028. InternalError(2020112340);
  8029. until (hp2 = hp1);
  8030. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8031. { We might still be able to get away with this }
  8032. RegInUse := not
  8033. (
  8034. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8035. (hp2.typ = ait_instruction) and
  8036. (
  8037. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8038. instruction that doesn't actually contain ThisReg }
  8039. (cs_opt_level3 in current_settings.optimizerswitches) or
  8040. RegInInstruction(ThisReg, hp2)
  8041. ) and
  8042. RegLoadedWithNewValue(ThisReg, hp2)
  8043. );
  8044. if not RegInUse then
  8045. begin
  8046. { Force the register size to the same as this instruction so it can be removed}
  8047. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8048. begin
  8049. TargetSize := S_L;
  8050. TargetSubReg := R_SUBD;
  8051. end
  8052. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8053. begin
  8054. TargetSize := S_W;
  8055. TargetSubReg := R_SUBW;
  8056. end;
  8057. ThisReg := taicpu(hp1).oper[1]^.reg;
  8058. setsubreg(ThisReg, TargetSubReg);
  8059. RegChanged := True;
  8060. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8061. TransferUsedRegs(TmpUsedRegs);
  8062. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8063. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8064. if p = hp1 then
  8065. begin
  8066. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8067. p_removed := True;
  8068. end
  8069. else
  8070. RemoveInstruction(hp1);
  8071. { Instruction will become "mov %reg,%reg" }
  8072. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8073. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8074. begin
  8075. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8076. RemoveCurrentP(p);
  8077. p_removed := True;
  8078. end
  8079. else
  8080. taicpu(p).oper[1]^.reg := ThisReg;
  8081. Result := True;
  8082. end
  8083. else
  8084. begin
  8085. if TargetSize <> MaxSize then
  8086. begin
  8087. { Since the register is in use, we have to force it to
  8088. MaxSize otherwise part of it may become undefined later on }
  8089. TargetSize := MaxSize;
  8090. case TargetSize of
  8091. S_B:
  8092. TargetSubReg := R_SUBL;
  8093. S_W:
  8094. TargetSubReg := R_SUBW;
  8095. S_L:
  8096. TargetSubReg := R_SUBD;
  8097. else
  8098. InternalError(2020112351);
  8099. end;
  8100. setsubreg(ThisReg, TargetSubReg);
  8101. end;
  8102. AdjustFinalLoad;
  8103. end;
  8104. end
  8105. else
  8106. AdjustFinalLoad;
  8107. if not p_removed then
  8108. begin
  8109. if TargetSize = MinSize then
  8110. begin
  8111. { Convert the input MOVZX to a MOV }
  8112. if (taicpu(p).oper[0]^.typ = top_reg) and
  8113. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8114. begin
  8115. { Or remove it completely! }
  8116. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8117. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  8118. RemoveCurrentP(p);
  8119. p_removed := True;
  8120. end
  8121. else
  8122. begin
  8123. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8124. taicpu(p).opcode := A_MOV;
  8125. taicpu(p).oper[1]^.reg := ThisReg;
  8126. taicpu(p).opsize := TargetSize;
  8127. end;
  8128. Result := True;
  8129. end
  8130. else if TargetSize <> MaxSize then
  8131. begin
  8132. case MaxSize of
  8133. S_L:
  8134. if TargetSize = S_W then
  8135. begin
  8136. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8137. taicpu(p).opsize := S_BW;
  8138. taicpu(p).oper[1]^.reg := ThisReg;
  8139. Result := True;
  8140. end
  8141. else
  8142. InternalError(2020112341);
  8143. S_W:
  8144. if TargetSize = S_L then
  8145. begin
  8146. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8147. taicpu(p).opsize := S_BL;
  8148. taicpu(p).oper[1]^.reg := ThisReg;
  8149. Result := True;
  8150. end
  8151. else
  8152. InternalError(2020112342);
  8153. else
  8154. ;
  8155. end;
  8156. end;
  8157. end;
  8158. { Now go through every instruction we found and change the
  8159. size. If TargetSize = MaxSize, then almost no changes are
  8160. needed and Result can remain False if it hasn't been set
  8161. yet.
  8162. If RegChanged is True, then the register requires changing
  8163. and so the point about TargetSize = MaxSize doesn't apply. }
  8164. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8165. begin
  8166. for Index := 0 to InstrMax do
  8167. begin
  8168. { If p_removed is true, then the original MOV/Z was removed
  8169. and removing the AND instruction may not be safe if it
  8170. appears first }
  8171. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8172. InternalError(2020112310);
  8173. if InstrList[Index].oper[0]^.typ = top_reg then
  8174. InstrList[Index].oper[0]^.reg := ThisReg;
  8175. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8176. InstrList[Index].opsize := TargetSize;
  8177. end;
  8178. Result := True;
  8179. end;
  8180. Exit;
  8181. end;
  8182. else
  8183. { This includes ADC, SBB, IDIV and SAR }
  8184. Break;
  8185. end;
  8186. if not CheckOverflowConditions then
  8187. Break;
  8188. { Contains highest index (so instruction count - 1) }
  8189. Inc(InstrMax);
  8190. if InstrMax > High(InstrList) then
  8191. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8192. InstrList[InstrMax] := taicpu(hp1);
  8193. end;
  8194. end;
  8195. {$pop}
  8196. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8197. var
  8198. hp1 : tai;
  8199. begin
  8200. Result:=false;
  8201. if (taicpu(p).ops >= 2) and
  8202. ((taicpu(p).oper[0]^.typ = top_const) or
  8203. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8204. (taicpu(p).oper[1]^.typ = top_reg) and
  8205. ((taicpu(p).ops = 2) or
  8206. ((taicpu(p).oper[2]^.typ = top_reg) and
  8207. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8208. GetLastInstruction(p,hp1) and
  8209. MatchInstruction(hp1,A_MOV,[]) and
  8210. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8211. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8212. begin
  8213. TransferUsedRegs(TmpUsedRegs);
  8214. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8215. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8216. { change
  8217. mov reg1,reg2
  8218. imul y,reg2 to imul y,reg1,reg2 }
  8219. begin
  8220. taicpu(p).ops := 3;
  8221. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8222. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8223. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8224. RemoveInstruction(hp1);
  8225. result:=true;
  8226. end;
  8227. end;
  8228. end;
  8229. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8230. var
  8231. ThisLabel: TAsmLabel;
  8232. begin
  8233. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8234. ThisLabel.decrefs;
  8235. taicpu(p).opcode := A_RET;
  8236. taicpu(p).is_jmp := false;
  8237. taicpu(p).ops := taicpu(ret_p).ops;
  8238. case taicpu(ret_p).ops of
  8239. 0:
  8240. taicpu(p).clearop(0);
  8241. 1:
  8242. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8243. else
  8244. internalerror(2016041301);
  8245. end;
  8246. { If the original label is now dead, it might turn out that the label
  8247. immediately follows p. As a result, everything beyond it, which will
  8248. be just some final register configuration and a RET instruction, is
  8249. now dead code. [Kit] }
  8250. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8251. running RemoveDeadCodeAfterJump for each RET instruction, because
  8252. this optimisation rarely happens and most RETs appear at the end of
  8253. routines where there is nothing that can be stripped. [Kit] }
  8254. if not ThisLabel.is_used then
  8255. RemoveDeadCodeAfterJump(p);
  8256. end;
  8257. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8258. var
  8259. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8260. Unconditional, PotentialModified: Boolean;
  8261. OperPtr: POper;
  8262. NewRef: TReference;
  8263. InstrList: array of taicpu;
  8264. InstrMax, Index: Integer;
  8265. const
  8266. {$ifdef DEBUG_AOPTCPU}
  8267. SNoFlags: shortstring = ' so the flags aren''t modified';
  8268. {$else DEBUG_AOPTCPU}
  8269. SNoFlags = '';
  8270. {$endif DEBUG_AOPTCPU}
  8271. begin
  8272. Result:=false;
  8273. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8274. begin
  8275. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8276. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8277. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8278. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8279. GetNextInstruction(hp1, hp2) and
  8280. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8281. { Change from: To:
  8282. set(C) %reg j(~C) label
  8283. test %reg,%reg/cmp $0,%reg
  8284. je label
  8285. set(C) %reg j(C) label
  8286. test %reg,%reg/cmp $0,%reg
  8287. jne label
  8288. (Also do something similar with sete/setne instead of je/jne)
  8289. }
  8290. begin
  8291. { Before we do anything else, we need to check the instructions
  8292. in between SETcc and TEST to make sure they don't modify the
  8293. FLAGS register - if -O2 or under, there won't be any
  8294. instructions between SET and TEST }
  8295. TransferUsedRegs(TmpUsedRegs);
  8296. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8297. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8298. begin
  8299. next := p;
  8300. SetLength(InstrList, 0);
  8301. InstrMax := -1;
  8302. PotentialModified := False;
  8303. { Make a note of every instruction that modifies the FLAGS
  8304. register }
  8305. while GetNextInstruction(next, next) and (next <> hp1) do
  8306. begin
  8307. if next.typ <> ait_instruction then
  8308. { GetNextInstructionUsingReg should have returned False }
  8309. InternalError(2021051701);
  8310. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8311. begin
  8312. case taicpu(next).opcode of
  8313. A_SETcc,
  8314. A_CMOVcc,
  8315. A_Jcc:
  8316. begin
  8317. if PotentialModified then
  8318. { Not safe because the flags were modified earlier }
  8319. Exit
  8320. else
  8321. { Condition is the same as the initial SETcc, so this is safe
  8322. (don't add to instruction list though) }
  8323. Continue;
  8324. end;
  8325. A_ADD:
  8326. begin
  8327. if (taicpu(next).opsize = S_B) or
  8328. { LEA doesn't support 8-bit operands }
  8329. (taicpu(next).oper[1]^.typ <> top_reg) or
  8330. { Must write to a register }
  8331. (taicpu(next).oper[0]^.typ = top_ref) then
  8332. { Require a constant or a register }
  8333. Exit;
  8334. PotentialModified := True;
  8335. end;
  8336. A_SUB:
  8337. begin
  8338. if (taicpu(next).opsize = S_B) or
  8339. { LEA doesn't support 8-bit operands }
  8340. (taicpu(next).oper[1]^.typ <> top_reg) or
  8341. { Must write to a register }
  8342. (taicpu(next).oper[0]^.typ <> top_const) or
  8343. (taicpu(next).oper[0]^.val = $80000000) then
  8344. { Can't subtract a register with LEA - also
  8345. check that the value isn't -2^31, as this
  8346. can't be negated }
  8347. Exit;
  8348. PotentialModified := True;
  8349. end;
  8350. A_SAL,
  8351. A_SHL:
  8352. begin
  8353. if (taicpu(next).opsize = S_B) or
  8354. { LEA doesn't support 8-bit operands }
  8355. (taicpu(next).oper[1]^.typ <> top_reg) or
  8356. { Must write to a register }
  8357. (taicpu(next).oper[0]^.typ <> top_const) or
  8358. (taicpu(next).oper[0]^.val < 0) or
  8359. (taicpu(next).oper[0]^.val > 3) then
  8360. Exit;
  8361. PotentialModified := True;
  8362. end;
  8363. A_IMUL:
  8364. begin
  8365. if (taicpu(next).ops <> 3) or
  8366. (taicpu(next).oper[1]^.typ <> top_reg) or
  8367. { Must write to a register }
  8368. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8369. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8370. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8371. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8372. Exit
  8373. else
  8374. PotentialModified := True;
  8375. end;
  8376. else
  8377. { Don't know how to change this, so abort }
  8378. Exit;
  8379. end;
  8380. { Contains highest index (so instruction count - 1) }
  8381. Inc(InstrMax);
  8382. if InstrMax > High(InstrList) then
  8383. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8384. InstrList[InstrMax] := taicpu(next);
  8385. end;
  8386. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8387. end;
  8388. if not Assigned(next) or (next <> hp1) then
  8389. { It should be equal to hp1 }
  8390. InternalError(2021051702);
  8391. { Cycle through each instruction and check to see if we can
  8392. change them to versions that don't modify the flags }
  8393. if (InstrMax >= 0) then
  8394. begin
  8395. for Index := 0 to InstrMax do
  8396. case InstrList[Index].opcode of
  8397. A_ADD:
  8398. begin
  8399. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8400. InstrList[Index].opcode := A_LEA;
  8401. reference_reset(NewRef, 1, []);
  8402. NewRef.base := InstrList[Index].oper[1]^.reg;
  8403. if InstrList[Index].oper[0]^.typ = top_reg then
  8404. begin
  8405. NewRef.index := InstrList[Index].oper[0]^.reg;
  8406. NewRef.scalefactor := 1;
  8407. end
  8408. else
  8409. NewRef.offset := InstrList[Index].oper[0]^.val;
  8410. InstrList[Index].loadref(0, NewRef);
  8411. end;
  8412. A_SUB:
  8413. begin
  8414. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8415. InstrList[Index].opcode := A_LEA;
  8416. reference_reset(NewRef, 1, []);
  8417. NewRef.base := InstrList[Index].oper[1]^.reg;
  8418. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8419. InstrList[Index].loadref(0, NewRef);
  8420. end;
  8421. A_SHL,
  8422. A_SAL:
  8423. begin
  8424. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8425. InstrList[Index].opcode := A_LEA;
  8426. reference_reset(NewRef, 1, []);
  8427. NewRef.index := InstrList[Index].oper[1]^.reg;
  8428. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8429. InstrList[Index].loadref(0, NewRef);
  8430. end;
  8431. A_IMUL:
  8432. begin
  8433. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8434. InstrList[Index].opcode := A_LEA;
  8435. reference_reset(NewRef, 1, []);
  8436. NewRef.index := InstrList[Index].oper[1]^.reg;
  8437. case InstrList[Index].oper[0]^.val of
  8438. 2, 4, 8:
  8439. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8440. else {3, 5 and 9}
  8441. begin
  8442. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8443. NewRef.base := InstrList[Index].oper[1]^.reg;
  8444. end;
  8445. end;
  8446. InstrList[Index].loadref(0, NewRef);
  8447. end;
  8448. else
  8449. InternalError(2021051710);
  8450. end;
  8451. end;
  8452. { Mark the FLAGS register as used across this whole block }
  8453. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8454. end;
  8455. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8456. JumpC := taicpu(hp2).condition;
  8457. Unconditional := False;
  8458. if conditions_equal(JumpC, C_E) then
  8459. SetC := inverse_cond(taicpu(p).condition)
  8460. else if conditions_equal(JumpC, C_NE) then
  8461. SetC := taicpu(p).condition
  8462. else
  8463. { We've got something weird here (and inefficent) }
  8464. begin
  8465. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8466. SetC := C_NONE;
  8467. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8468. if condition_in(C_AE, JumpC) then
  8469. Unconditional := True
  8470. else
  8471. { Not sure what to do with this jump - drop out }
  8472. Exit;
  8473. end;
  8474. RemoveInstruction(hp1);
  8475. if Unconditional then
  8476. MakeUnconditional(taicpu(hp2))
  8477. else
  8478. begin
  8479. if SetC = C_NONE then
  8480. InternalError(2018061402);
  8481. taicpu(hp2).SetCondition(SetC);
  8482. end;
  8483. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8484. TmpUsedRegs }
  8485. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8486. begin
  8487. RemoveCurrentp(p, hp2);
  8488. if taicpu(hp2).opcode = A_SETcc then
  8489. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8490. else
  8491. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8492. end
  8493. else
  8494. if taicpu(hp2).opcode = A_SETcc then
  8495. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8496. else
  8497. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8498. Result := True;
  8499. end
  8500. else if
  8501. { Make sure the instructions are adjacent }
  8502. (
  8503. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8504. GetNextInstruction(p, hp1)
  8505. ) and
  8506. MatchInstruction(hp1, A_MOV, [S_B]) and
  8507. { Writing to memory is allowed }
  8508. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8509. begin
  8510. {
  8511. Watch out for sequences such as:
  8512. set(c)b %regb
  8513. movb %regb,(ref)
  8514. movb $0,1(ref)
  8515. movb $0,2(ref)
  8516. movb $0,3(ref)
  8517. Much more efficient to turn it into:
  8518. movl $0,%regl
  8519. set(c)b %regb
  8520. movl %regl,(ref)
  8521. Or:
  8522. set(c)b %regb
  8523. movzbl %regb,%regl
  8524. movl %regl,(ref)
  8525. }
  8526. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8527. GetNextInstruction(hp1, hp2) and
  8528. MatchInstruction(hp2, A_MOV, [S_B]) and
  8529. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8530. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8531. begin
  8532. { Don't do anything else except set Result to True }
  8533. end
  8534. else
  8535. begin
  8536. if taicpu(p).oper[0]^.typ = top_reg then
  8537. begin
  8538. TransferUsedRegs(TmpUsedRegs);
  8539. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8540. end;
  8541. { If it's not a register, it's a memory address }
  8542. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8543. begin
  8544. { Even if the register is still in use, we can minimise the
  8545. pipeline stall by changing the MOV into another SETcc. }
  8546. taicpu(hp1).opcode := A_SETcc;
  8547. taicpu(hp1).condition := taicpu(p).condition;
  8548. if taicpu(hp1).oper[1]^.typ = top_ref then
  8549. begin
  8550. { Swapping the operand pointers like this is probably a
  8551. bit naughty, but it is far faster than using loadoper
  8552. to transfer the reference from oper[1] to oper[0] if
  8553. you take into account the extra procedure calls and
  8554. the memory allocation and deallocation required }
  8555. OperPtr := taicpu(hp1).oper[1];
  8556. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8557. taicpu(hp1).oper[0] := OperPtr;
  8558. end
  8559. else
  8560. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8561. taicpu(hp1).clearop(1);
  8562. taicpu(hp1).ops := 1;
  8563. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8564. end
  8565. else
  8566. begin
  8567. if taicpu(hp1).oper[1]^.typ = top_reg then
  8568. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8569. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8570. RemoveInstruction(hp1);
  8571. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8572. end
  8573. end;
  8574. Result := True;
  8575. end;
  8576. end;
  8577. end;
  8578. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8579. var
  8580. hp1: tai;
  8581. Count: Integer;
  8582. OrigLabel: TAsmLabel;
  8583. begin
  8584. result := False;
  8585. { Sometimes, the optimisations below can permit this }
  8586. RemoveDeadCodeAfterJump(p);
  8587. 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
  8588. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8589. begin
  8590. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8591. { Also a side-effect of optimisations }
  8592. if CollapseZeroDistJump(p, OrigLabel) then
  8593. begin
  8594. Result := True;
  8595. Exit;
  8596. end;
  8597. hp1 := GetLabelWithSym(OrigLabel);
  8598. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8599. begin
  8600. case taicpu(hp1).opcode of
  8601. A_RET:
  8602. {
  8603. change
  8604. jmp .L1
  8605. ...
  8606. .L1:
  8607. ret
  8608. into
  8609. ret
  8610. }
  8611. begin
  8612. ConvertJumpToRET(p, hp1);
  8613. result:=true;
  8614. end;
  8615. { Check any kind of direct assignment instruction }
  8616. A_MOV,
  8617. A_MOVD,
  8618. A_MOVQ,
  8619. A_MOVSX,
  8620. {$ifdef x86_64}
  8621. A_MOVSXD,
  8622. {$endif x86_64}
  8623. A_MOVZX,
  8624. A_MOVAPS,
  8625. A_MOVUPS,
  8626. A_MOVSD,
  8627. A_MOVAPD,
  8628. A_MOVUPD,
  8629. A_MOVDQA,
  8630. A_MOVDQU,
  8631. A_VMOVSS,
  8632. A_VMOVAPS,
  8633. A_VMOVUPS,
  8634. A_VMOVSD,
  8635. A_VMOVAPD,
  8636. A_VMOVUPD,
  8637. A_VMOVDQA,
  8638. A_VMOVDQU:
  8639. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8640. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8641. begin
  8642. Result := True;
  8643. Exit;
  8644. end;
  8645. else
  8646. ;
  8647. end;
  8648. end;
  8649. end;
  8650. end;
  8651. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8652. begin
  8653. CanBeCMOV:=assigned(p) and
  8654. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8655. { we can't use cmov ref,reg because
  8656. ref could be nil and cmov still throws an exception
  8657. if ref=nil but the mov isn't done (FK)
  8658. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8659. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8660. }
  8661. (taicpu(p).oper[1]^.typ = top_reg) and
  8662. (
  8663. (taicpu(p).oper[0]^.typ = top_reg) or
  8664. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8665. it is not expected that this can cause a seg. violation }
  8666. (
  8667. (taicpu(p).oper[0]^.typ = top_ref) and
  8668. IsRefSafe(taicpu(p).oper[0]^.ref)
  8669. )
  8670. );
  8671. end;
  8672. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8673. var
  8674. hp1,hp2: tai;
  8675. {$ifndef i8086}
  8676. hp3,hp4,hpmov2, hp5: tai;
  8677. l : Longint;
  8678. condition : TAsmCond;
  8679. {$endif i8086}
  8680. carryadd_opcode : TAsmOp;
  8681. symbol: TAsmSymbol;
  8682. reg: tsuperregister;
  8683. increg, tmpreg: TRegister;
  8684. begin
  8685. result:=false;
  8686. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8687. begin
  8688. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8689. if (
  8690. (
  8691. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8692. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8693. (Taicpu(hp1).oper[0]^.val=1)
  8694. ) or
  8695. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8696. ) and
  8697. GetNextInstruction(hp1,hp2) and
  8698. SkipAligns(hp2, hp2) and
  8699. (hp2.typ = ait_label) and
  8700. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8701. { jb @@1 cmc
  8702. inc/dec operand --> adc/sbb operand,0
  8703. @@1:
  8704. ... and ...
  8705. jnb @@1
  8706. inc/dec operand --> adc/sbb operand,0
  8707. @@1: }
  8708. begin
  8709. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8710. begin
  8711. case taicpu(hp1).opcode of
  8712. A_INC,
  8713. A_ADD:
  8714. carryadd_opcode:=A_ADC;
  8715. A_DEC,
  8716. A_SUB:
  8717. carryadd_opcode:=A_SBB;
  8718. else
  8719. InternalError(2021011001);
  8720. end;
  8721. Taicpu(p).clearop(0);
  8722. Taicpu(p).ops:=0;
  8723. Taicpu(p).is_jmp:=false;
  8724. Taicpu(p).opcode:=A_CMC;
  8725. Taicpu(p).condition:=C_NONE;
  8726. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8727. Taicpu(hp1).ops:=2;
  8728. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8729. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8730. else
  8731. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8732. Taicpu(hp1).loadconst(0,0);
  8733. Taicpu(hp1).opcode:=carryadd_opcode;
  8734. result:=true;
  8735. exit;
  8736. end
  8737. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8738. begin
  8739. case taicpu(hp1).opcode of
  8740. A_INC,
  8741. A_ADD:
  8742. carryadd_opcode:=A_ADC;
  8743. A_DEC,
  8744. A_SUB:
  8745. carryadd_opcode:=A_SBB;
  8746. else
  8747. InternalError(2021011002);
  8748. end;
  8749. Taicpu(hp1).ops:=2;
  8750. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8751. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8752. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8753. else
  8754. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8755. Taicpu(hp1).loadconst(0,0);
  8756. Taicpu(hp1).opcode:=carryadd_opcode;
  8757. RemoveCurrentP(p, hp1);
  8758. result:=true;
  8759. exit;
  8760. end
  8761. {
  8762. jcc @@1 setcc tmpreg
  8763. inc/dec/add/sub operand -> (movzx tmpreg)
  8764. @@1: add/sub tmpreg,operand
  8765. While this increases code size slightly, it makes the code much faster if the
  8766. jump is unpredictable
  8767. }
  8768. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8769. begin
  8770. { search for an available register which is volatile }
  8771. for reg in tcpuregisterset do
  8772. begin
  8773. if
  8774. {$if defined(i386) or defined(i8086)}
  8775. { Only use registers whose lowest 8-bits can Be accessed }
  8776. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8777. {$endif i386 or i8086}
  8778. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8779. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8780. { We don't need to check if tmpreg is in hp1 or not, because
  8781. it will be marked as in use at p (if not, this is
  8782. indictive of a compiler bug). }
  8783. then
  8784. begin
  8785. TAsmLabel(symbol).decrefs;
  8786. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8787. Taicpu(p).clearop(0);
  8788. Taicpu(p).ops:=1;
  8789. Taicpu(p).is_jmp:=false;
  8790. Taicpu(p).opcode:=A_SETcc;
  8791. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8792. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8793. Taicpu(p).loadreg(0,increg);
  8794. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8795. begin
  8796. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8797. R_SUBW:
  8798. begin
  8799. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8800. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8801. end;
  8802. R_SUBD:
  8803. begin
  8804. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8805. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8806. end;
  8807. {$ifdef x86_64}
  8808. R_SUBQ:
  8809. begin
  8810. { MOVZX doesn't have a 64-bit variant, because
  8811. the 32-bit version implicitly zeroes the
  8812. upper 32-bits of the destination register }
  8813. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8814. newreg(R_INTREGISTER,reg,R_SUBD));
  8815. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8816. end;
  8817. {$endif x86_64}
  8818. else
  8819. Internalerror(2020030601);
  8820. end;
  8821. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8822. asml.InsertAfter(hp2,p);
  8823. end
  8824. else
  8825. tmpreg := increg;
  8826. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8827. begin
  8828. Taicpu(hp1).ops:=2;
  8829. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  8830. end;
  8831. Taicpu(hp1).loadreg(0,tmpreg);
  8832. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  8833. Result := True;
  8834. { p is no longer a Jcc instruction, so exit }
  8835. Exit;
  8836. end;
  8837. end;
  8838. end;
  8839. end;
  8840. { Detect the following:
  8841. jmp<cond> @Lbl1
  8842. jmp @Lbl2
  8843. ...
  8844. @Lbl1:
  8845. ret
  8846. Change to:
  8847. jmp<inv_cond> @Lbl2
  8848. ret
  8849. }
  8850. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8851. begin
  8852. hp2:=getlabelwithsym(TAsmLabel(symbol));
  8853. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  8854. MatchInstruction(hp2,A_RET,[S_NO]) then
  8855. begin
  8856. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8857. { Change label address to that of the unconditional jump }
  8858. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  8859. TAsmLabel(symbol).DecRefs;
  8860. taicpu(hp1).opcode := A_RET;
  8861. taicpu(hp1).is_jmp := false;
  8862. taicpu(hp1).ops := taicpu(hp2).ops;
  8863. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  8864. case taicpu(hp2).ops of
  8865. 0:
  8866. taicpu(hp1).clearop(0);
  8867. 1:
  8868. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  8869. else
  8870. internalerror(2016041302);
  8871. end;
  8872. end;
  8873. {$ifndef i8086}
  8874. end
  8875. {
  8876. convert
  8877. j<c> .L1
  8878. mov 1,reg
  8879. jmp .L2
  8880. .L1
  8881. mov 0,reg
  8882. .L2
  8883. into
  8884. mov 0,reg
  8885. set<not(c)> reg
  8886. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8887. would destroy the flag contents
  8888. }
  8889. else if MatchInstruction(hp1,A_MOV,[]) and
  8890. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8891. {$ifdef i386}
  8892. (
  8893. { Under i386, ESI, EDI, EBP and ESP
  8894. don't have an 8-bit representation }
  8895. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8896. ) and
  8897. {$endif i386}
  8898. (taicpu(hp1).oper[0]^.val=1) and
  8899. GetNextInstruction(hp1,hp2) and
  8900. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8901. GetNextInstruction(hp2,hp3) and
  8902. { skip align }
  8903. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  8904. (hp3.typ=ait_label) and
  8905. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8906. (tai_label(hp3).labsym.getrefs=1) and
  8907. GetNextInstruction(hp3,hp4) and
  8908. MatchInstruction(hp4,A_MOV,[]) and
  8909. MatchOpType(taicpu(hp4),top_const,top_reg) and
  8910. (taicpu(hp4).oper[0]^.val=0) and
  8911. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8912. GetNextInstruction(hp4,hp5) and
  8913. (hp5.typ=ait_label) and
  8914. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  8915. (tai_label(hp5).labsym.getrefs=1) then
  8916. begin
  8917. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  8918. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  8919. { remove last label }
  8920. RemoveInstruction(hp5);
  8921. { remove second label }
  8922. RemoveInstruction(hp3);
  8923. { if align is present remove it }
  8924. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  8925. RemoveInstruction(hp3);
  8926. { remove jmp }
  8927. RemoveInstruction(hp2);
  8928. if taicpu(hp1).opsize=S_B then
  8929. RemoveInstruction(hp1)
  8930. else
  8931. taicpu(hp1).loadconst(0,0);
  8932. taicpu(hp4).opcode:=A_SETcc;
  8933. taicpu(hp4).opsize:=S_B;
  8934. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  8935. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  8936. taicpu(hp4).opercnt:=1;
  8937. taicpu(hp4).ops:=1;
  8938. taicpu(hp4).freeop(1);
  8939. RemoveCurrentP(p);
  8940. Result:=true;
  8941. exit;
  8942. end
  8943. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  8944. begin
  8945. { check for
  8946. jCC xxx
  8947. <several movs>
  8948. xxx:
  8949. }
  8950. l:=0;
  8951. while assigned(hp1) and
  8952. CanBeCMOV(hp1) and
  8953. { stop on labels }
  8954. not(hp1.typ=ait_label) do
  8955. begin
  8956. inc(l);
  8957. GetNextInstruction(hp1,hp1);
  8958. end;
  8959. if assigned(hp1) then
  8960. begin
  8961. if FindLabel(tasmlabel(symbol),hp1) then
  8962. begin
  8963. if (l<=4) and (l>0) then
  8964. begin
  8965. condition:=inverse_cond(taicpu(p).condition);
  8966. UpdateUsedRegs(tai(p.next));
  8967. GetNextInstruction(p,hp1);
  8968. repeat
  8969. if not Assigned(hp1) then
  8970. InternalError(2018062900);
  8971. taicpu(hp1).opcode:=A_CMOVcc;
  8972. taicpu(hp1).condition:=condition;
  8973. UpdateUsedRegs(tai(hp1.next));
  8974. GetNextInstruction(hp1,hp1);
  8975. until not(CanBeCMOV(hp1));
  8976. { Remember what hp1 is in case there's multiple aligns to get rid of }
  8977. hp2 := hp1;
  8978. repeat
  8979. if not Assigned(hp2) then
  8980. InternalError(2018062910);
  8981. case hp2.typ of
  8982. ait_label:
  8983. { What we expected - break out of the loop (it won't be a dead label at the top of
  8984. a cluster because that was optimised at an earlier stage) }
  8985. Break;
  8986. ait_align:
  8987. { Go to the next entry until a label is found (may be multiple aligns before it) }
  8988. begin
  8989. hp2 := tai(hp2.Next);
  8990. Continue;
  8991. end;
  8992. else
  8993. begin
  8994. { Might be a comment or temporary allocation entry }
  8995. if not (hp2.typ in SkipInstr) then
  8996. InternalError(2018062911);
  8997. hp2 := tai(hp2.Next);
  8998. Continue;
  8999. end;
  9000. end;
  9001. until False;
  9002. { Now we can safely decrement the reference count }
  9003. tasmlabel(symbol).decrefs;
  9004. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9005. { Remove the original jump }
  9006. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9007. UpdateUsedRegs(tai(hp2.next));
  9008. GetNextInstruction(hp2, p); { Instruction after the label }
  9009. { Remove the label if this is its final reference }
  9010. if (tasmlabel(symbol).getrefs=0) then
  9011. StripLabelFast(hp1);
  9012. if Assigned(p) then
  9013. result:=true;
  9014. exit;
  9015. end;
  9016. end
  9017. else
  9018. begin
  9019. { check further for
  9020. jCC xxx
  9021. <several movs 1>
  9022. jmp yyy
  9023. xxx:
  9024. <several movs 2>
  9025. yyy:
  9026. }
  9027. { hp2 points to jmp yyy }
  9028. hp2:=hp1;
  9029. { skip hp1 to xxx (or an align right before it) }
  9030. GetNextInstruction(hp1, hp1);
  9031. if assigned(hp2) and
  9032. assigned(hp1) and
  9033. (l<=3) and
  9034. (hp2.typ=ait_instruction) and
  9035. (taicpu(hp2).is_jmp) and
  9036. (taicpu(hp2).condition=C_None) and
  9037. { real label and jump, no further references to the
  9038. label are allowed }
  9039. (tasmlabel(symbol).getrefs=1) and
  9040. FindLabel(tasmlabel(symbol),hp1) then
  9041. begin
  9042. l:=0;
  9043. { skip hp1 to <several moves 2> }
  9044. if (hp1.typ = ait_align) then
  9045. GetNextInstruction(hp1, hp1);
  9046. GetNextInstruction(hp1, hpmov2);
  9047. hp1 := hpmov2;
  9048. while assigned(hp1) and
  9049. CanBeCMOV(hp1) do
  9050. begin
  9051. inc(l);
  9052. GetNextInstruction(hp1, hp1);
  9053. end;
  9054. { hp1 points to yyy (or an align right before it) }
  9055. hp3 := hp1;
  9056. if assigned(hp1) and
  9057. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9058. begin
  9059. condition:=inverse_cond(taicpu(p).condition);
  9060. UpdateUsedRegs(tai(p.next));
  9061. GetNextInstruction(p,hp1);
  9062. repeat
  9063. taicpu(hp1).opcode:=A_CMOVcc;
  9064. taicpu(hp1).condition:=condition;
  9065. UpdateUsedRegs(tai(hp1.next));
  9066. GetNextInstruction(hp1,hp1);
  9067. until not(assigned(hp1)) or
  9068. not(CanBeCMOV(hp1));
  9069. condition:=inverse_cond(condition);
  9070. if GetLastInstruction(hpmov2,hp1) then
  9071. UpdateUsedRegs(tai(hp1.next));
  9072. hp1 := hpmov2;
  9073. { hp1 is now at <several movs 2> }
  9074. while Assigned(hp1) and CanBeCMOV(hp1) do
  9075. begin
  9076. taicpu(hp1).opcode:=A_CMOVcc;
  9077. taicpu(hp1).condition:=condition;
  9078. UpdateUsedRegs(tai(hp1.next));
  9079. GetNextInstruction(hp1,hp1);
  9080. end;
  9081. hp1 := p;
  9082. { Get first instruction after label }
  9083. UpdateUsedRegs(tai(hp3.next));
  9084. GetNextInstruction(hp3, p);
  9085. if assigned(p) and (hp3.typ = ait_align) then
  9086. GetNextInstruction(p, p);
  9087. { Don't dereference yet, as doing so will cause
  9088. GetNextInstruction to skip the label and
  9089. optional align marker. [Kit] }
  9090. GetNextInstruction(hp2, hp4);
  9091. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9092. { remove jCC }
  9093. RemoveInstruction(hp1);
  9094. { Now we can safely decrement it }
  9095. tasmlabel(symbol).decrefs;
  9096. { Remove label xxx (it will have a ref of zero due to the initial check }
  9097. StripLabelFast(hp4);
  9098. { remove jmp }
  9099. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9100. RemoveInstruction(hp2);
  9101. { As before, now we can safely decrement it }
  9102. tasmlabel(symbol).decrefs;
  9103. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9104. if tasmlabel(symbol).getrefs = 0 then
  9105. StripLabelFast(hp3);
  9106. if Assigned(p) then
  9107. result:=true;
  9108. exit;
  9109. end;
  9110. end;
  9111. end;
  9112. end;
  9113. {$endif i8086}
  9114. end;
  9115. end;
  9116. end;
  9117. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9118. var
  9119. hp1,hp2,hp3: tai;
  9120. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9121. NewSize: TOpSize;
  9122. NewRegSize: TSubRegister;
  9123. Limit: TCgInt;
  9124. SwapOper: POper;
  9125. begin
  9126. result:=false;
  9127. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9128. GetNextInstruction(p,hp1) and
  9129. (hp1.typ = ait_instruction);
  9130. if reg_and_hp1_is_instr and
  9131. (
  9132. (taicpu(hp1).opcode <> A_LEA) or
  9133. { If the LEA instruction can be converted into an arithmetic instruction,
  9134. it may be possible to then fold it. }
  9135. (
  9136. { If the flags register is in use, don't change the instruction
  9137. to an ADD otherwise this will scramble the flags. [Kit] }
  9138. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9139. ConvertLEA(taicpu(hp1))
  9140. )
  9141. ) and
  9142. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9143. GetNextInstruction(hp1,hp2) and
  9144. MatchInstruction(hp2,A_MOV,[]) and
  9145. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9146. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9147. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9148. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9149. {$ifdef i386}
  9150. { not all registers have byte size sub registers on i386 }
  9151. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9152. {$endif i386}
  9153. (((taicpu(hp1).ops=2) and
  9154. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9155. ((taicpu(hp1).ops=1) and
  9156. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9157. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9158. begin
  9159. { change movsX/movzX reg/ref, reg2
  9160. add/sub/or/... reg3/$const, reg2
  9161. mov reg2 reg/ref
  9162. to add/sub/or/... reg3/$const, reg/ref }
  9163. { by example:
  9164. movswl %si,%eax movswl %si,%eax p
  9165. decl %eax addl %edx,%eax hp1
  9166. movw %ax,%si movw %ax,%si hp2
  9167. ->
  9168. movswl %si,%eax movswl %si,%eax p
  9169. decw %eax addw %edx,%eax hp1
  9170. movw %ax,%si movw %ax,%si hp2
  9171. }
  9172. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9173. {
  9174. ->
  9175. movswl %si,%eax movswl %si,%eax p
  9176. decw %si addw %dx,%si hp1
  9177. movw %ax,%si movw %ax,%si hp2
  9178. }
  9179. case taicpu(hp1).ops of
  9180. 1:
  9181. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9182. 2:
  9183. begin
  9184. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9185. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9186. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9187. end;
  9188. else
  9189. internalerror(2008042702);
  9190. end;
  9191. {
  9192. ->
  9193. decw %si addw %dx,%si p
  9194. }
  9195. DebugMsg(SPeepholeOptimization + 'var3',p);
  9196. RemoveCurrentP(p, hp1);
  9197. RemoveInstruction(hp2);
  9198. Result := True;
  9199. Exit;
  9200. end;
  9201. if reg_and_hp1_is_instr and
  9202. (taicpu(hp1).opcode = A_MOV) and
  9203. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9204. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9205. {$ifdef x86_64}
  9206. { check for implicit extension to 64 bit }
  9207. or
  9208. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9209. (taicpu(hp1).opsize=S_Q) and
  9210. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9211. )
  9212. {$endif x86_64}
  9213. )
  9214. then
  9215. begin
  9216. { change
  9217. movx %reg1,%reg2
  9218. mov %reg2,%reg3
  9219. dealloc %reg2
  9220. into
  9221. movx %reg,%reg3
  9222. }
  9223. TransferUsedRegs(TmpUsedRegs);
  9224. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9225. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9226. begin
  9227. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9228. {$ifdef x86_64}
  9229. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9230. (taicpu(hp1).opsize=S_Q) then
  9231. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9232. else
  9233. {$endif x86_64}
  9234. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9235. RemoveInstruction(hp1);
  9236. Result := True;
  9237. Exit;
  9238. end;
  9239. end;
  9240. if reg_and_hp1_is_instr and
  9241. ((taicpu(hp1).opcode=A_MOV) or
  9242. (taicpu(hp1).opcode=A_ADD) or
  9243. (taicpu(hp1).opcode=A_SUB) or
  9244. (taicpu(hp1).opcode=A_CMP) or
  9245. (taicpu(hp1).opcode=A_OR) or
  9246. (taicpu(hp1).opcode=A_XOR) or
  9247. (taicpu(hp1).opcode=A_AND)
  9248. ) and
  9249. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9250. begin
  9251. AndTest := (taicpu(hp1).opcode=A_AND) and
  9252. GetNextInstruction(hp1, hp2) and
  9253. (hp2.typ = ait_instruction) and
  9254. (
  9255. (
  9256. (taicpu(hp2).opcode=A_TEST) and
  9257. (
  9258. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9259. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9260. (
  9261. { If the AND and TEST instructions share a constant, this is also valid }
  9262. (taicpu(hp1).oper[0]^.typ = top_const) and
  9263. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9264. )
  9265. ) and
  9266. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9267. ) or
  9268. (
  9269. (taicpu(hp2).opcode=A_CMP) and
  9270. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9271. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9272. )
  9273. );
  9274. { change
  9275. movx (oper),%reg2
  9276. and $x,%reg2
  9277. test %reg2,%reg2
  9278. dealloc %reg2
  9279. into
  9280. op %reg1,%reg3
  9281. if the second op accesses only the bits stored in reg1
  9282. }
  9283. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9284. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9285. (taicpu(hp1).oper[0]^.typ = top_const) and
  9286. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9287. AndTest then
  9288. begin
  9289. { Check if the AND constant is in range }
  9290. case taicpu(p).opsize of
  9291. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9292. begin
  9293. NewSize := S_B;
  9294. Limit := $FF;
  9295. end;
  9296. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9297. begin
  9298. NewSize := S_W;
  9299. Limit := $FFFF;
  9300. end;
  9301. {$ifdef x86_64}
  9302. S_LQ:
  9303. begin
  9304. NewSize := S_L;
  9305. Limit := $FFFFFFFF;
  9306. end;
  9307. {$endif x86_64}
  9308. else
  9309. InternalError(2021120303);
  9310. end;
  9311. if (
  9312. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9313. { Check for negative operands }
  9314. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9315. ) and
  9316. GetNextInstruction(hp2,hp3) and
  9317. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9318. (taicpu(hp3).condition in [C_E,C_NE]) then
  9319. begin
  9320. TransferUsedRegs(TmpUsedRegs);
  9321. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9322. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9323. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9324. begin
  9325. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9326. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9327. taicpu(hp1).opcode := A_TEST;
  9328. taicpu(hp1).opsize := NewSize;
  9329. RemoveInstruction(hp2);
  9330. RemoveCurrentP(p, hp1);
  9331. Result:=true;
  9332. exit;
  9333. end;
  9334. end;
  9335. end;
  9336. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9337. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9338. (taicpu(hp1).opsize=S_B)) or
  9339. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9340. (taicpu(hp1).opsize=S_W))
  9341. {$ifdef x86_64}
  9342. or ((taicpu(p).opsize=S_LQ) and
  9343. (taicpu(hp1).opsize=S_L))
  9344. {$endif x86_64}
  9345. ) and
  9346. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9347. begin
  9348. { change
  9349. movx %reg1,%reg2
  9350. op %reg2,%reg3
  9351. dealloc %reg2
  9352. into
  9353. op %reg1,%reg3
  9354. if the second op accesses only the bits stored in reg1
  9355. }
  9356. TransferUsedRegs(TmpUsedRegs);
  9357. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9358. if AndTest then
  9359. begin
  9360. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9361. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9362. end
  9363. else
  9364. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9365. if not RegUsed then
  9366. begin
  9367. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9368. if taicpu(p).oper[0]^.typ=top_reg then
  9369. begin
  9370. case taicpu(hp1).opsize of
  9371. S_B:
  9372. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9373. S_W:
  9374. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9375. S_L:
  9376. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9377. else
  9378. Internalerror(2020102301);
  9379. end;
  9380. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9381. end
  9382. else
  9383. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9384. RemoveCurrentP(p);
  9385. if AndTest then
  9386. RemoveInstruction(hp2);
  9387. result:=true;
  9388. exit;
  9389. end;
  9390. end
  9391. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9392. (
  9393. { Bitwise operations only }
  9394. (taicpu(hp1).opcode=A_AND) or
  9395. (taicpu(hp1).opcode=A_TEST) or
  9396. (
  9397. (taicpu(hp1).oper[0]^.typ = top_const) and
  9398. (
  9399. (taicpu(hp1).opcode=A_OR) or
  9400. (taicpu(hp1).opcode=A_XOR)
  9401. )
  9402. )
  9403. ) and
  9404. (
  9405. (taicpu(hp1).oper[0]^.typ = top_const) or
  9406. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9407. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9408. ) then
  9409. begin
  9410. { change
  9411. movx %reg2,%reg2
  9412. op const,%reg2
  9413. into
  9414. op const,%reg2 (smaller version)
  9415. movx %reg2,%reg2
  9416. also change
  9417. movx %reg1,%reg2
  9418. and/test (oper),%reg2
  9419. dealloc %reg2
  9420. into
  9421. and/test (oper),%reg1
  9422. }
  9423. case taicpu(p).opsize of
  9424. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9425. begin
  9426. NewSize := S_B;
  9427. NewRegSize := R_SUBL;
  9428. Limit := $FF;
  9429. end;
  9430. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9431. begin
  9432. NewSize := S_W;
  9433. NewRegSize := R_SUBW;
  9434. Limit := $FFFF;
  9435. end;
  9436. {$ifdef x86_64}
  9437. S_LQ:
  9438. begin
  9439. NewSize := S_L;
  9440. NewRegSize := R_SUBD;
  9441. Limit := $FFFFFFFF;
  9442. end;
  9443. {$endif x86_64}
  9444. else
  9445. Internalerror(2021120302);
  9446. end;
  9447. TransferUsedRegs(TmpUsedRegs);
  9448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9449. if AndTest then
  9450. begin
  9451. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9452. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9453. end
  9454. else
  9455. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9456. if
  9457. (
  9458. (taicpu(p).opcode = A_MOVZX) and
  9459. (
  9460. (taicpu(hp1).opcode=A_AND) or
  9461. (taicpu(hp1).opcode=A_TEST)
  9462. ) and
  9463. not (
  9464. { If both are references, then the final instruction will have
  9465. both operands as references, which is not allowed }
  9466. (taicpu(p).oper[0]^.typ = top_ref) and
  9467. (taicpu(hp1).oper[0]^.typ = top_ref)
  9468. ) and
  9469. not RegUsed
  9470. ) or
  9471. (
  9472. (
  9473. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9474. not RegUsed
  9475. ) and
  9476. (taicpu(p).oper[0]^.typ = top_reg) and
  9477. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9478. (taicpu(hp1).oper[0]^.typ = top_const) and
  9479. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9480. ) then
  9481. begin
  9482. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9483. if AndTest and not RegUsed then
  9484. taicpu(hp1).opcode := A_TEST;
  9485. taicpu(hp1).opsize := NewSize;
  9486. case taicpu(hp1).oper[0]^.typ of
  9487. top_reg:
  9488. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9489. top_const:
  9490. { For the AND/TEST case }
  9491. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9492. else
  9493. ;
  9494. end;
  9495. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9496. if (taicpu(hp1).opcode = A_TEST) and (taicpu(hp1).oper[0]^.typ = top_ref) then
  9497. begin
  9498. { For TEST, make sure the reference is the second operand }
  9499. SwapOper := taicpu(hp1).oper[0];
  9500. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9501. taicpu(hp1).oper[1] := SwapOper;
  9502. end;
  9503. if AndTest then
  9504. RemoveInstruction(hp2);
  9505. if RegUsed then
  9506. begin
  9507. AsmL.Remove(p);
  9508. AsmL.InsertAfter(p, hp1);
  9509. p := hp1;
  9510. end
  9511. else
  9512. RemoveCurrentP(p, hp1);
  9513. result:=true;
  9514. exit;
  9515. end;
  9516. end;
  9517. end;
  9518. if reg_and_hp1_is_instr and
  9519. (taicpu(p).oper[0]^.typ = top_reg) and
  9520. (
  9521. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9522. ) and
  9523. (taicpu(hp1).oper[0]^.typ = top_const) and
  9524. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9525. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9526. { Minimum shift value allowed is the bit difference between the sizes }
  9527. (taicpu(hp1).oper[0]^.val >=
  9528. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9529. 8 * (
  9530. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9531. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9532. )
  9533. ) then
  9534. begin
  9535. { For:
  9536. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9537. shl/sal ##, %reg1
  9538. Remove the movsx/movzx instruction if the shift overwrites the
  9539. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9540. }
  9541. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9542. RemoveCurrentP(p, hp1);
  9543. Result := True;
  9544. Exit;
  9545. end
  9546. else if reg_and_hp1_is_instr and
  9547. (taicpu(p).oper[0]^.typ = top_reg) and
  9548. (
  9549. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9550. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9551. ) and
  9552. (taicpu(hp1).oper[0]^.typ = top_const) and
  9553. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9554. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9555. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9556. (taicpu(hp1).oper[0]^.val <
  9557. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9558. 8 * (
  9559. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9560. )
  9561. ) then
  9562. begin
  9563. { For:
  9564. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9565. sar ##, %reg1 shr ##, %reg1
  9566. Move the shift to before the movx instruction if the shift value
  9567. is not too large.
  9568. }
  9569. asml.Remove(hp1);
  9570. asml.InsertBefore(hp1, p);
  9571. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9572. case taicpu(p).opsize of
  9573. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9574. taicpu(hp1).opsize := S_B;
  9575. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9576. taicpu(hp1).opsize := S_W;
  9577. {$ifdef x86_64}
  9578. S_LQ:
  9579. taicpu(hp1).opsize := S_L;
  9580. {$endif}
  9581. else
  9582. InternalError(2020112401);
  9583. end;
  9584. if (taicpu(hp1).opcode = A_SHR) then
  9585. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9586. else
  9587. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9588. Result := True;
  9589. end;
  9590. if reg_and_hp1_is_instr and
  9591. (taicpu(p).oper[0]^.typ = top_reg) and
  9592. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9593. (
  9594. (taicpu(hp1).opcode = taicpu(p).opcode)
  9595. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9596. {$ifdef x86_64}
  9597. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9598. {$endif x86_64}
  9599. ) then
  9600. begin
  9601. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9602. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9603. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9604. begin
  9605. {
  9606. For example:
  9607. movzbw %al,%ax
  9608. movzwl %ax,%eax
  9609. Compress into:
  9610. movzbl %al,%eax
  9611. }
  9612. RegUsed := False;
  9613. case taicpu(p).opsize of
  9614. S_BW:
  9615. case taicpu(hp1).opsize of
  9616. S_WL:
  9617. begin
  9618. taicpu(p).opsize := S_BL;
  9619. RegUsed := True;
  9620. end;
  9621. {$ifdef x86_64}
  9622. S_WQ:
  9623. begin
  9624. if taicpu(p).opcode = A_MOVZX then
  9625. taicpu(p).opsize := S_BL
  9626. else
  9627. taicpu(p).opsize := S_BQ;
  9628. RegUsed := True;
  9629. end;
  9630. {$endif x86_64}
  9631. else
  9632. ;
  9633. end;
  9634. {$ifdef x86_64}
  9635. S_BL:
  9636. case taicpu(hp1).opsize of
  9637. S_LQ:
  9638. begin
  9639. if taicpu(p).opcode = A_MOVZX then
  9640. taicpu(p).opsize := S_BL
  9641. else
  9642. taicpu(p).opsize := S_BQ;
  9643. RegUsed := True;
  9644. end;
  9645. else
  9646. ;
  9647. end;
  9648. S_WL:
  9649. case taicpu(hp1).opsize of
  9650. S_LQ:
  9651. begin
  9652. if taicpu(p).opcode = A_MOVZX then
  9653. taicpu(p).opsize := S_WL
  9654. else
  9655. taicpu(p).opsize := S_WQ;
  9656. RegUsed := True;
  9657. end;
  9658. else
  9659. ;
  9660. end;
  9661. {$endif x86_64}
  9662. else
  9663. ;
  9664. end;
  9665. if RegUsed then
  9666. begin
  9667. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9668. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9669. RemoveInstruction(hp1);
  9670. Result := True;
  9671. Exit;
  9672. end;
  9673. end;
  9674. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9675. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9676. GetNextInstruction(hp1, hp2) and
  9677. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9678. (
  9679. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9680. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9681. {$ifdef x86_64}
  9682. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9683. {$endif x86_64}
  9684. ) and
  9685. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9686. (
  9687. (
  9688. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9689. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9690. ) or
  9691. (
  9692. { Only allow the operands in reverse order for TEST instructions }
  9693. (taicpu(hp2).opcode = A_TEST) and
  9694. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9695. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9696. )
  9697. ) then
  9698. begin
  9699. {
  9700. For example:
  9701. movzbl %al,%eax
  9702. movzbl (ref),%edx
  9703. andl %edx,%eax
  9704. (%edx deallocated)
  9705. Change to:
  9706. andb (ref),%al
  9707. movzbl %al,%eax
  9708. Rules are:
  9709. - First two instructions have the same opcode and opsize
  9710. - First instruction's operands are the same super-register
  9711. - Second instruction operates on a different register
  9712. - Third instruction is AND, OR, XOR or TEST
  9713. - Third instruction's operands are the destination registers of the first two instructions
  9714. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9715. - Second instruction's destination register is deallocated afterwards
  9716. }
  9717. TransferUsedRegs(TmpUsedRegs);
  9718. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9719. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9720. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9721. begin
  9722. case taicpu(p).opsize of
  9723. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9724. NewSize := S_B;
  9725. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9726. NewSize := S_W;
  9727. {$ifdef x86_64}
  9728. S_LQ:
  9729. NewSize := S_L;
  9730. {$endif x86_64}
  9731. else
  9732. InternalError(2021120301);
  9733. end;
  9734. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9735. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9736. taicpu(hp2).opsize := NewSize;
  9737. RemoveInstruction(hp1);
  9738. { With TEST, it's best to keep the MOVX instruction at the top }
  9739. if (taicpu(hp2).opcode <> A_TEST) then
  9740. begin
  9741. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9742. asml.Remove(p);
  9743. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9744. asml.InsertAfter(p, hp2);
  9745. p := hp2;
  9746. end
  9747. else
  9748. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  9749. Result := True;
  9750. Exit;
  9751. end;
  9752. end;
  9753. end;
  9754. if taicpu(p).opcode=A_MOVZX then
  9755. begin
  9756. { removes superfluous And's after movzx's }
  9757. if reg_and_hp1_is_instr and
  9758. (taicpu(hp1).opcode = A_AND) and
  9759. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9760. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9761. {$ifdef x86_64}
  9762. { check for implicit extension to 64 bit }
  9763. or
  9764. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9765. (taicpu(hp1).opsize=S_Q) and
  9766. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  9767. )
  9768. {$endif x86_64}
  9769. )
  9770. then
  9771. begin
  9772. case taicpu(p).opsize Of
  9773. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9774. if (taicpu(hp1).oper[0]^.val = $ff) then
  9775. begin
  9776. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  9777. RemoveInstruction(hp1);
  9778. Result:=true;
  9779. exit;
  9780. end;
  9781. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9782. if (taicpu(hp1).oper[0]^.val = $ffff) then
  9783. begin
  9784. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  9785. RemoveInstruction(hp1);
  9786. Result:=true;
  9787. exit;
  9788. end;
  9789. {$ifdef x86_64}
  9790. S_LQ:
  9791. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  9792. begin
  9793. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  9794. RemoveInstruction(hp1);
  9795. Result:=true;
  9796. exit;
  9797. end;
  9798. {$endif x86_64}
  9799. else
  9800. ;
  9801. end;
  9802. { we cannot get rid of the and, but can we get rid of the movz ?}
  9803. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  9804. begin
  9805. case taicpu(p).opsize Of
  9806. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9807. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  9808. begin
  9809. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  9810. RemoveCurrentP(p,hp1);
  9811. Result:=true;
  9812. exit;
  9813. end;
  9814. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9815. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  9816. begin
  9817. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  9818. RemoveCurrentP(p,hp1);
  9819. Result:=true;
  9820. exit;
  9821. end;
  9822. {$ifdef x86_64}
  9823. S_LQ:
  9824. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  9825. begin
  9826. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  9827. RemoveCurrentP(p,hp1);
  9828. Result:=true;
  9829. exit;
  9830. end;
  9831. {$endif x86_64}
  9832. else
  9833. ;
  9834. end;
  9835. end;
  9836. end;
  9837. { changes some movzx constructs to faster synonyms (all examples
  9838. are given with eax/ax, but are also valid for other registers)}
  9839. if MatchOpType(taicpu(p),top_reg,top_reg) then
  9840. begin
  9841. case taicpu(p).opsize of
  9842. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  9843. (the machine code is equivalent to movzbl %al,%eax), but the
  9844. code generator still generates that assembler instruction and
  9845. it is silently converted. This should probably be checked.
  9846. [Kit] }
  9847. S_BW:
  9848. begin
  9849. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  9850. (
  9851. not IsMOVZXAcceptable
  9852. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  9853. or (
  9854. (cs_opt_size in current_settings.optimizerswitches) and
  9855. (taicpu(p).oper[1]^.reg = NR_AX)
  9856. )
  9857. ) then
  9858. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  9859. begin
  9860. DebugMsg(SPeepholeOptimization + 'var7',p);
  9861. taicpu(p).opcode := A_AND;
  9862. taicpu(p).changeopsize(S_W);
  9863. taicpu(p).loadConst(0,$ff);
  9864. Result := True;
  9865. end
  9866. else if not IsMOVZXAcceptable and
  9867. GetNextInstruction(p, hp1) and
  9868. (tai(hp1).typ = ait_instruction) and
  9869. (taicpu(hp1).opcode = A_AND) and
  9870. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9871. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9872. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  9873. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  9874. begin
  9875. DebugMsg(SPeepholeOptimization + 'var8',p);
  9876. taicpu(p).opcode := A_MOV;
  9877. taicpu(p).changeopsize(S_W);
  9878. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  9879. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  9880. Result := True;
  9881. end;
  9882. end;
  9883. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  9884. S_BL:
  9885. begin
  9886. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  9887. (
  9888. not IsMOVZXAcceptable
  9889. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  9890. or (
  9891. (cs_opt_size in current_settings.optimizerswitches) and
  9892. (taicpu(p).oper[1]^.reg = NR_EAX)
  9893. )
  9894. ) then
  9895. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  9896. begin
  9897. DebugMsg(SPeepholeOptimization + 'var9',p);
  9898. taicpu(p).opcode := A_AND;
  9899. taicpu(p).changeopsize(S_L);
  9900. taicpu(p).loadConst(0,$ff);
  9901. Result := True;
  9902. end
  9903. else if not IsMOVZXAcceptable and
  9904. GetNextInstruction(p, hp1) and
  9905. (tai(hp1).typ = ait_instruction) and
  9906. (taicpu(hp1).opcode = A_AND) and
  9907. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9908. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9909. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  9910. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  9911. begin
  9912. DebugMsg(SPeepholeOptimization + 'var10',p);
  9913. taicpu(p).opcode := A_MOV;
  9914. taicpu(p).changeopsize(S_L);
  9915. { do not use R_SUBWHOLE
  9916. as movl %rdx,%eax
  9917. is invalid in assembler PM }
  9918. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9919. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  9920. Result := True;
  9921. end;
  9922. end;
  9923. {$endif i8086}
  9924. S_WL:
  9925. if not IsMOVZXAcceptable then
  9926. begin
  9927. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  9928. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  9929. begin
  9930. DebugMsg(SPeepholeOptimization + 'var11',p);
  9931. taicpu(p).opcode := A_AND;
  9932. taicpu(p).changeopsize(S_L);
  9933. taicpu(p).loadConst(0,$ffff);
  9934. Result := True;
  9935. end
  9936. else if GetNextInstruction(p, hp1) and
  9937. (tai(hp1).typ = ait_instruction) and
  9938. (taicpu(hp1).opcode = A_AND) and
  9939. (taicpu(hp1).oper[0]^.typ = top_const) and
  9940. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9941. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9942. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  9943. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  9944. begin
  9945. DebugMsg(SPeepholeOptimization + 'var12',p);
  9946. taicpu(p).opcode := A_MOV;
  9947. taicpu(p).changeopsize(S_L);
  9948. { do not use R_SUBWHOLE
  9949. as movl %rdx,%eax
  9950. is invalid in assembler PM }
  9951. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9952. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  9953. Result := True;
  9954. end;
  9955. end;
  9956. else
  9957. InternalError(2017050705);
  9958. end;
  9959. end
  9960. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  9961. begin
  9962. if GetNextInstruction(p, hp1) and
  9963. (tai(hp1).typ = ait_instruction) and
  9964. (taicpu(hp1).opcode = A_AND) and
  9965. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9966. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9967. begin
  9968. //taicpu(p).opcode := A_MOV;
  9969. case taicpu(p).opsize Of
  9970. S_BL:
  9971. begin
  9972. DebugMsg(SPeepholeOptimization + 'var13',p);
  9973. taicpu(hp1).changeopsize(S_L);
  9974. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  9975. end;
  9976. S_WL:
  9977. begin
  9978. DebugMsg(SPeepholeOptimization + 'var14',p);
  9979. taicpu(hp1).changeopsize(S_L);
  9980. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  9981. end;
  9982. S_BW:
  9983. begin
  9984. DebugMsg(SPeepholeOptimization + 'var15',p);
  9985. taicpu(hp1).changeopsize(S_W);
  9986. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  9987. end;
  9988. else
  9989. Internalerror(2017050704)
  9990. end;
  9991. Result := True;
  9992. end;
  9993. end;
  9994. end;
  9995. end;
  9996. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  9997. var
  9998. hp1, hp2 : tai;
  9999. MaskLength : Cardinal;
  10000. MaskedBits : TCgInt;
  10001. ActiveReg : TRegister;
  10002. begin
  10003. Result:=false;
  10004. { There are no optimisations for reference targets }
  10005. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10006. Exit;
  10007. while GetNextInstruction(p, hp1) and
  10008. (hp1.typ = ait_instruction) do
  10009. begin
  10010. if (taicpu(p).oper[0]^.typ = top_const) then
  10011. begin
  10012. case taicpu(hp1).opcode of
  10013. A_AND:
  10014. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10015. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10016. { the second register must contain the first one, so compare their subreg types }
  10017. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10018. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10019. { change
  10020. and const1, reg
  10021. and const2, reg
  10022. to
  10023. and (const1 and const2), reg
  10024. }
  10025. begin
  10026. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10027. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10028. RemoveCurrentP(p, hp1);
  10029. Result:=true;
  10030. exit;
  10031. end;
  10032. A_CMP:
  10033. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10034. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10035. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10036. { Just check that the condition on the next instruction is compatible }
  10037. GetNextInstruction(hp1, hp2) and
  10038. (hp2.typ = ait_instruction) and
  10039. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10040. then
  10041. { change
  10042. and 2^n, reg
  10043. cmp 2^n, reg
  10044. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10045. to
  10046. and 2^n, reg
  10047. test reg, reg
  10048. j(~c) / set(~c) / cmov(~c)
  10049. }
  10050. begin
  10051. { Keep TEST instruction in, rather than remove it, because
  10052. it may trigger other optimisations such as MovAndTest2Test }
  10053. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10054. taicpu(hp1).opcode := A_TEST;
  10055. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10056. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10057. Result := True;
  10058. Exit;
  10059. end;
  10060. A_MOVZX:
  10061. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10062. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10063. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10064. (
  10065. (
  10066. (taicpu(p).opsize=S_W) and
  10067. (taicpu(hp1).opsize=S_BW)
  10068. ) or
  10069. (
  10070. (taicpu(p).opsize=S_L) and
  10071. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10072. )
  10073. {$ifdef x86_64}
  10074. or
  10075. (
  10076. (taicpu(p).opsize=S_Q) and
  10077. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10078. )
  10079. {$endif x86_64}
  10080. ) then
  10081. begin
  10082. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10083. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10084. ) or
  10085. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10086. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10087. then
  10088. begin
  10089. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10090. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10091. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10092. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10093. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10094. }
  10095. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10096. RemoveInstruction(hp1);
  10097. { See if there are other optimisations possible }
  10098. Continue;
  10099. end;
  10100. end;
  10101. A_SHL:
  10102. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10103. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10104. begin
  10105. {$ifopt R+}
  10106. {$define RANGE_WAS_ON}
  10107. {$R-}
  10108. {$endif}
  10109. { get length of potential and mask }
  10110. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10111. { really a mask? }
  10112. {$ifdef RANGE_WAS_ON}
  10113. {$R+}
  10114. {$endif}
  10115. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10116. { unmasked part shifted out? }
  10117. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10118. begin
  10119. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10120. RemoveCurrentP(p, hp1);
  10121. Result:=true;
  10122. exit;
  10123. end;
  10124. end;
  10125. A_SHR:
  10126. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10127. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10128. (taicpu(hp1).oper[0]^.val <= 63) then
  10129. begin
  10130. { Does SHR combined with the AND cover all the bits?
  10131. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10132. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10133. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10134. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10135. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10136. begin
  10137. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10138. RemoveCurrentP(p, hp1);
  10139. Result := True;
  10140. Exit;
  10141. end;
  10142. end;
  10143. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10144. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10145. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10146. begin
  10147. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10148. (
  10149. (
  10150. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10151. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10152. ) or (
  10153. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10154. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10155. {$ifdef x86_64}
  10156. ) or (
  10157. (taicpu(hp1).opsize = S_LQ) and
  10158. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10159. {$endif x86_64}
  10160. )
  10161. ) then
  10162. begin
  10163. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10164. begin
  10165. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10166. RemoveInstruction(hp1);
  10167. { See if there are other optimisations possible }
  10168. Continue;
  10169. end;
  10170. { The super-registers are the same though.
  10171. Note that this change by itself doesn't improve
  10172. code speed, but it opens up other optimisations. }
  10173. {$ifdef x86_64}
  10174. { Convert 64-bit register to 32-bit }
  10175. case taicpu(hp1).opsize of
  10176. S_BQ:
  10177. begin
  10178. taicpu(hp1).opsize := S_BL;
  10179. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10180. end;
  10181. S_WQ:
  10182. begin
  10183. taicpu(hp1).opsize := S_WL;
  10184. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10185. end
  10186. else
  10187. ;
  10188. end;
  10189. {$endif x86_64}
  10190. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10191. taicpu(hp1).opcode := A_MOVZX;
  10192. { See if there are other optimisations possible }
  10193. Continue;
  10194. end;
  10195. end;
  10196. else
  10197. ;
  10198. end;
  10199. end
  10200. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10201. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10202. begin
  10203. {$ifdef x86_64}
  10204. if (taicpu(p).opsize = S_Q) then
  10205. begin
  10206. { Never necessary }
  10207. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10208. RemoveCurrentP(p, hp1);
  10209. Result := True;
  10210. Exit;
  10211. end;
  10212. {$endif x86_64}
  10213. { Forward check to determine necessity of and %reg,%reg }
  10214. TransferUsedRegs(TmpUsedRegs);
  10215. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10216. { Saves on a bunch of dereferences }
  10217. ActiveReg := taicpu(p).oper[1]^.reg;
  10218. case taicpu(hp1).opcode of
  10219. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10220. if (
  10221. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10222. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10223. ) and
  10224. (
  10225. (taicpu(hp1).opcode <> A_MOV) or
  10226. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10227. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10228. ) and
  10229. not (
  10230. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10231. (taicpu(hp1).opcode = A_MOV) and
  10232. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10233. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10234. ) and
  10235. (
  10236. (
  10237. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10238. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10239. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10240. ) or
  10241. (
  10242. {$ifdef x86_64}
  10243. (
  10244. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10245. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10246. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10247. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10248. ) and
  10249. {$endif x86_64}
  10250. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10251. )
  10252. ) then
  10253. begin
  10254. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10255. RemoveCurrentP(p, hp1);
  10256. Result := True;
  10257. Exit;
  10258. end;
  10259. A_ADD,
  10260. A_AND,
  10261. A_BSF,
  10262. A_BSR,
  10263. A_BTC,
  10264. A_BTR,
  10265. A_BTS,
  10266. A_OR,
  10267. A_SUB,
  10268. A_XOR:
  10269. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10270. if (
  10271. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10272. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10273. ) and
  10274. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10275. begin
  10276. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10277. RemoveCurrentP(p, hp1);
  10278. Result := True;
  10279. Exit;
  10280. end;
  10281. A_CMP,
  10282. A_TEST:
  10283. if (
  10284. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10285. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10286. ) and
  10287. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10288. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10289. begin
  10290. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10291. RemoveCurrentP(p, hp1);
  10292. Result := True;
  10293. Exit;
  10294. end;
  10295. A_BSWAP,
  10296. A_NEG,
  10297. A_NOT:
  10298. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10299. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10300. begin
  10301. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10302. RemoveCurrentP(p, hp1);
  10303. Result := True;
  10304. Exit;
  10305. end;
  10306. else
  10307. ;
  10308. end;
  10309. end;
  10310. if (taicpu(hp1).is_jmp) and
  10311. (taicpu(hp1).opcode<>A_JMP) and
  10312. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10313. begin
  10314. { change
  10315. and x, reg
  10316. jxx
  10317. to
  10318. test x, reg
  10319. jxx
  10320. if reg is deallocated before the
  10321. jump, but only if it's a conditional jump (PFV)
  10322. }
  10323. taicpu(p).opcode := A_TEST;
  10324. Exit;
  10325. end;
  10326. Break;
  10327. end;
  10328. { Lone AND tests }
  10329. if (taicpu(p).oper[0]^.typ = top_const) then
  10330. begin
  10331. {
  10332. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10333. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10334. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10335. }
  10336. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10337. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10338. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10339. begin
  10340. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10341. if taicpu(p).opsize = S_L then
  10342. begin
  10343. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10344. Result := True;
  10345. end;
  10346. end;
  10347. end;
  10348. { Backward check to determine necessity of and %reg,%reg }
  10349. if (taicpu(p).oper[0]^.typ = top_reg) and
  10350. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10351. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10352. GetLastInstruction(p, hp2) and
  10353. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10354. { Check size of adjacent instruction to determine if the AND is
  10355. effectively a null operation }
  10356. (
  10357. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10358. { Note: Don't include S_Q }
  10359. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10360. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10361. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10362. ) then
  10363. begin
  10364. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10365. { If GetNextInstruction returned False, hp1 will be nil }
  10366. RemoveCurrentP(p, hp1);
  10367. Result := True;
  10368. Exit;
  10369. end;
  10370. end;
  10371. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10372. var
  10373. hp1: tai; NewRef: TReference;
  10374. { This entire nested function is used in an if-statement below, but we
  10375. want to avoid all the used reg transfers and GetNextInstruction calls
  10376. until we really have to check }
  10377. function MemRegisterNotUsedLater: Boolean; inline;
  10378. var
  10379. hp2: tai;
  10380. begin
  10381. TransferUsedRegs(TmpUsedRegs);
  10382. hp2 := p;
  10383. repeat
  10384. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10385. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10386. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10387. end;
  10388. begin
  10389. Result := False;
  10390. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10391. Exit;
  10392. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10393. begin
  10394. { Change:
  10395. add %reg2,%reg1
  10396. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10397. To:
  10398. mov/s/z #(%reg1,%reg2),%reg1
  10399. }
  10400. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10401. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10402. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10403. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10404. (
  10405. (
  10406. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10407. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10408. { r/esp cannot be an index }
  10409. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10410. ) or (
  10411. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10412. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10413. )
  10414. ) and (
  10415. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10416. (
  10417. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10418. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10419. MemRegisterNotUsedLater
  10420. )
  10421. ) then
  10422. begin
  10423. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10424. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10425. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10426. RemoveCurrentp(p, hp1);
  10427. Result := True;
  10428. Exit;
  10429. end;
  10430. { Change:
  10431. addl/q $x,%reg1
  10432. movl/q %reg1,%reg2
  10433. To:
  10434. leal/q $x(%reg1),%reg2
  10435. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10436. Breaks the dependency chain.
  10437. }
  10438. if MatchOpType(taicpu(p),top_const,top_reg) and
  10439. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10440. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10441. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10442. (
  10443. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10444. not (cs_opt_size in current_settings.optimizerswitches) or
  10445. (
  10446. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10447. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10448. )
  10449. ) then
  10450. begin
  10451. { Change the MOV instruction to a LEA instruction, and update the
  10452. first operand }
  10453. reference_reset(NewRef, 1, []);
  10454. NewRef.base := taicpu(p).oper[1]^.reg;
  10455. NewRef.scalefactor := 1;
  10456. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10457. taicpu(hp1).opcode := A_LEA;
  10458. taicpu(hp1).loadref(0, NewRef);
  10459. TransferUsedRegs(TmpUsedRegs);
  10460. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10461. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10462. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10463. begin
  10464. { Move what is now the LEA instruction to before the SUB instruction }
  10465. Asml.Remove(hp1);
  10466. Asml.InsertBefore(hp1, p);
  10467. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10468. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10469. p := hp1;
  10470. end
  10471. else
  10472. begin
  10473. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10474. RemoveCurrentP(p, hp1);
  10475. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10476. end;
  10477. Result := True;
  10478. end;
  10479. end;
  10480. end;
  10481. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10482. var
  10483. SubReg: TSubRegister;
  10484. begin
  10485. Result:=false;
  10486. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10487. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10488. with taicpu(p).oper[0]^.ref^ do
  10489. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10490. begin
  10491. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10492. begin
  10493. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10494. taicpu(p).opcode := A_ADD;
  10495. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10496. Result := True;
  10497. end
  10498. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10499. begin
  10500. if (base <> NR_NO) then
  10501. begin
  10502. if (scalefactor <= 1) then
  10503. begin
  10504. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10505. taicpu(p).opcode := A_ADD;
  10506. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10507. Result := True;
  10508. end;
  10509. end
  10510. else
  10511. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10512. if (scalefactor in [2, 4, 8]) then
  10513. begin
  10514. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10515. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10516. taicpu(p).opcode := A_SHL;
  10517. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10518. Result := True;
  10519. end;
  10520. end;
  10521. end;
  10522. end;
  10523. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10524. var
  10525. hp1: tai; NewRef: TReference;
  10526. begin
  10527. { Change:
  10528. subl/q $x,%reg1
  10529. movl/q %reg1,%reg2
  10530. To:
  10531. leal/q $-x(%reg1),%reg2
  10532. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10533. Breaks the dependency chain and potentially permits the removal of
  10534. a CMP instruction if one follows.
  10535. }
  10536. Result := False;
  10537. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10538. MatchOpType(taicpu(p),top_const,top_reg) and
  10539. GetNextInstruction(p, hp1) and
  10540. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10541. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10542. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10543. (
  10544. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10545. not (cs_opt_size in current_settings.optimizerswitches) or
  10546. (
  10547. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10548. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10549. )
  10550. ) then
  10551. begin
  10552. { Change the MOV instruction to a LEA instruction, and update the
  10553. first operand }
  10554. reference_reset(NewRef, 1, []);
  10555. NewRef.base := taicpu(p).oper[1]^.reg;
  10556. NewRef.scalefactor := 1;
  10557. NewRef.offset := -taicpu(p).oper[0]^.val;
  10558. taicpu(hp1).opcode := A_LEA;
  10559. taicpu(hp1).loadref(0, NewRef);
  10560. TransferUsedRegs(TmpUsedRegs);
  10561. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10562. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10563. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10564. begin
  10565. { Move what is now the LEA instruction to before the SUB instruction }
  10566. Asml.Remove(hp1);
  10567. Asml.InsertBefore(hp1, p);
  10568. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10569. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10570. p := hp1;
  10571. end
  10572. else
  10573. begin
  10574. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10575. RemoveCurrentP(p, hp1);
  10576. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10577. end;
  10578. Result := True;
  10579. end;
  10580. end;
  10581. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10582. begin
  10583. { we can skip all instructions not messing with the stack pointer }
  10584. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10585. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10586. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10587. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10588. ({(taicpu(hp1).ops=0) or }
  10589. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10590. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10591. ) and }
  10592. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10593. )
  10594. ) do
  10595. GetNextInstruction(hp1,hp1);
  10596. Result:=assigned(hp1);
  10597. end;
  10598. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10599. var
  10600. hp1, hp2, hp3, hp4, hp5: tai;
  10601. begin
  10602. Result:=false;
  10603. hp5:=nil;
  10604. { replace
  10605. leal(q) x(<stackpointer>),<stackpointer>
  10606. call procname
  10607. leal(q) -x(<stackpointer>),<stackpointer>
  10608. ret
  10609. by
  10610. jmp procname
  10611. but do it only on level 4 because it destroys stack back traces
  10612. }
  10613. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10614. MatchOpType(taicpu(p),top_ref,top_reg) and
  10615. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10616. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10617. { the -8 or -24 are not required, but bail out early if possible,
  10618. higher values are unlikely }
  10619. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10620. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10621. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10622. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10623. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10624. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10625. GetNextInstruction(p, hp1) and
  10626. { Take a copy of hp1 }
  10627. SetAndTest(hp1, hp4) and
  10628. { trick to skip label }
  10629. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10630. SkipSimpleInstructions(hp1) and
  10631. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10632. GetNextInstruction(hp1, hp2) and
  10633. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10634. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10635. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10636. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10637. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10638. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10639. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10640. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10641. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10642. GetNextInstruction(hp2, hp3) and
  10643. { trick to skip label }
  10644. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10645. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10646. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10647. SetAndTest(hp3,hp5) and
  10648. GetNextInstruction(hp3,hp3) and
  10649. MatchInstruction(hp3,A_RET,[S_NO])
  10650. )
  10651. ) and
  10652. (taicpu(hp3).ops=0) then
  10653. begin
  10654. taicpu(hp1).opcode := A_JMP;
  10655. taicpu(hp1).is_jmp := true;
  10656. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10657. RemoveCurrentP(p, hp4);
  10658. RemoveInstruction(hp2);
  10659. RemoveInstruction(hp3);
  10660. if Assigned(hp5) then
  10661. begin
  10662. AsmL.Remove(hp5);
  10663. ASmL.InsertBefore(hp5,hp1)
  10664. end;
  10665. Result:=true;
  10666. end;
  10667. end;
  10668. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10669. {$ifdef x86_64}
  10670. var
  10671. hp1, hp2, hp3, hp4, hp5: tai;
  10672. {$endif x86_64}
  10673. begin
  10674. Result:=false;
  10675. {$ifdef x86_64}
  10676. hp5:=nil;
  10677. { replace
  10678. push %rax
  10679. call procname
  10680. pop %rcx
  10681. ret
  10682. by
  10683. jmp procname
  10684. but do it only on level 4 because it destroys stack back traces
  10685. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10686. for all supported calling conventions
  10687. }
  10688. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10689. MatchOpType(taicpu(p),top_reg) and
  10690. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10691. GetNextInstruction(p, hp1) and
  10692. { Take a copy of hp1 }
  10693. SetAndTest(hp1, hp4) and
  10694. { trick to skip label }
  10695. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10696. SkipSimpleInstructions(hp1) and
  10697. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10698. GetNextInstruction(hp1, hp2) and
  10699. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10700. MatchOpType(taicpu(hp2),top_reg) and
  10701. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10702. GetNextInstruction(hp2, hp3) and
  10703. { trick to skip label }
  10704. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10705. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10706. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10707. SetAndTest(hp3,hp5) and
  10708. GetNextInstruction(hp3,hp3) and
  10709. MatchInstruction(hp3,A_RET,[S_NO])
  10710. )
  10711. ) and
  10712. (taicpu(hp3).ops=0) then
  10713. begin
  10714. taicpu(hp1).opcode := A_JMP;
  10715. taicpu(hp1).is_jmp := true;
  10716. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10717. RemoveCurrentP(p, hp4);
  10718. RemoveInstruction(hp2);
  10719. RemoveInstruction(hp3);
  10720. if Assigned(hp5) then
  10721. begin
  10722. AsmL.Remove(hp5);
  10723. ASmL.InsertBefore(hp5,hp1)
  10724. end;
  10725. Result:=true;
  10726. end;
  10727. {$endif x86_64}
  10728. end;
  10729. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10730. var
  10731. Value, RegName: string;
  10732. begin
  10733. Result:=false;
  10734. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10735. begin
  10736. case taicpu(p).oper[0]^.val of
  10737. 0:
  10738. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10739. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10740. begin
  10741. { change "mov $0,%reg" into "xor %reg,%reg" }
  10742. taicpu(p).opcode := A_XOR;
  10743. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10744. Result := True;
  10745. {$ifdef x86_64}
  10746. end
  10747. else if (taicpu(p).opsize = S_Q) then
  10748. begin
  10749. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10750. { The actual optimization }
  10751. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10752. taicpu(p).changeopsize(S_L);
  10753. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10754. Result := True;
  10755. end;
  10756. $1..$FFFFFFFF:
  10757. begin
  10758. { Code size reduction by J. Gareth "Kit" Moreton }
  10759. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  10760. case taicpu(p).opsize of
  10761. S_Q:
  10762. begin
  10763. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10764. Value := debug_tostr(taicpu(p).oper[0]^.val);
  10765. { The actual optimization }
  10766. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10767. taicpu(p).changeopsize(S_L);
  10768. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10769. Result := True;
  10770. end;
  10771. else
  10772. { Do nothing };
  10773. end;
  10774. {$endif x86_64}
  10775. end;
  10776. -1:
  10777. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  10778. if (cs_opt_size in current_settings.optimizerswitches) and
  10779. (taicpu(p).opsize <> S_B) and
  10780. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10781. begin
  10782. { change "mov $-1,%reg" into "or $-1,%reg" }
  10783. { NOTES:
  10784. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  10785. - This operation creates a false dependency on the register, so only do it when optimising for size
  10786. - 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
  10787. }
  10788. taicpu(p).opcode := A_OR;
  10789. Result := True;
  10790. end;
  10791. else
  10792. { Do nothing };
  10793. end;
  10794. end;
  10795. end;
  10796. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  10797. var
  10798. hp1: tai;
  10799. begin
  10800. { Detect:
  10801. andw x, %ax (0 <= x < $8000)
  10802. ...
  10803. movzwl %ax,%eax
  10804. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10805. }
  10806. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  10807. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10808. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  10809. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  10810. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  10811. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  10812. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  10813. begin
  10814. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  10815. taicpu(hp1).opcode := A_CWDE;
  10816. taicpu(hp1).clearop(0);
  10817. taicpu(hp1).clearop(1);
  10818. taicpu(hp1).ops := 0;
  10819. { A change was made, but not with p, so move forward 1 }
  10820. p := tai(p.Next);
  10821. Result := True;
  10822. end;
  10823. end;
  10824. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  10825. begin
  10826. Result := False;
  10827. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  10828. Exit;
  10829. { Convert:
  10830. movswl %ax,%eax -> cwtl
  10831. movslq %eax,%rax -> cdqe
  10832. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  10833. refer to the same opcode and depends only on the assembler's
  10834. current operand-size attribute. [Kit]
  10835. }
  10836. with taicpu(p) do
  10837. case opsize of
  10838. S_WL:
  10839. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  10840. begin
  10841. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  10842. opcode := A_CWDE;
  10843. clearop(0);
  10844. clearop(1);
  10845. ops := 0;
  10846. Result := True;
  10847. end;
  10848. {$ifdef x86_64}
  10849. S_LQ:
  10850. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  10851. begin
  10852. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  10853. opcode := A_CDQE;
  10854. clearop(0);
  10855. clearop(1);
  10856. ops := 0;
  10857. Result := True;
  10858. end;
  10859. {$endif x86_64}
  10860. else
  10861. ;
  10862. end;
  10863. end;
  10864. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  10865. var
  10866. hp1: tai;
  10867. begin
  10868. { Detect:
  10869. shr x, %ax (x > 0)
  10870. ...
  10871. movzwl %ax,%eax
  10872. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10873. }
  10874. Result := False;
  10875. if MatchOpType(taicpu(p), top_const, top_reg) and
  10876. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10877. (taicpu(p).oper[0]^.val > 0) and
  10878. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  10879. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  10880. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  10881. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  10882. begin
  10883. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  10884. taicpu(hp1).opcode := A_CWDE;
  10885. taicpu(hp1).clearop(0);
  10886. taicpu(hp1).clearop(1);
  10887. taicpu(hp1).ops := 0;
  10888. { A change was made, but not with p, so move forward 1 }
  10889. p := tai(p.Next);
  10890. Result := True;
  10891. end;
  10892. end;
  10893. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  10894. var
  10895. hp1, hp2: tai;
  10896. Opposite, SecondOpposite: TAsmOp;
  10897. NewCond: TAsmCond;
  10898. begin
  10899. Result := False;
  10900. { Change:
  10901. add/sub 128,(dest)
  10902. To:
  10903. sub/add -128,(dest)
  10904. This generaally takes fewer bytes to encode because -128 can be stored
  10905. in a signed byte, whereas +128 cannot.
  10906. }
  10907. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  10908. begin
  10909. if taicpu(p).opcode = A_ADD then
  10910. Opposite := A_SUB
  10911. else
  10912. Opposite := A_ADD;
  10913. { Be careful if the flags are in use, because the CF flag inverts
  10914. when changing from ADD to SUB and vice versa }
  10915. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10916. GetNextInstruction(p, hp1) then
  10917. begin
  10918. TransferUsedRegs(TmpUsedRegs);
  10919. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  10920. hp2 := hp1;
  10921. { Scan ahead to check if everything's safe }
  10922. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  10923. begin
  10924. if (hp1.typ <> ait_instruction) then
  10925. { Probably unsafe since the flags are still in use }
  10926. Exit;
  10927. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  10928. { Stop searching at an unconditional jump }
  10929. Break;
  10930. if not
  10931. (
  10932. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  10933. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  10934. ) and
  10935. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  10936. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  10937. Exit;
  10938. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10939. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  10940. { Move to the next instruction }
  10941. GetNextInstruction(hp1, hp1);
  10942. end;
  10943. while Assigned(hp2) and (hp2 <> hp1) do
  10944. begin
  10945. NewCond := C_None;
  10946. case taicpu(hp2).condition of
  10947. C_A, C_NBE:
  10948. NewCond := C_BE;
  10949. C_B, C_C, C_NAE:
  10950. NewCond := C_AE;
  10951. C_AE, C_NB, C_NC:
  10952. NewCond := C_B;
  10953. C_BE, C_NA:
  10954. NewCond := C_A;
  10955. else
  10956. { No change needed };
  10957. end;
  10958. if NewCond <> C_None then
  10959. begin
  10960. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  10961. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  10962. taicpu(hp2).condition := NewCond;
  10963. end
  10964. else
  10965. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  10966. begin
  10967. { Because of the flipping of the carry bit, to ensure
  10968. the operation remains equivalent, ADC becomes SBB
  10969. and vice versa, and the constant is not-inverted.
  10970. If multiple ADCs or SBBs appear in a row, each one
  10971. changed causes the carry bit to invert, so they all
  10972. need to be flipped }
  10973. if taicpu(hp2).opcode = A_ADC then
  10974. SecondOpposite := A_SBB
  10975. else
  10976. SecondOpposite := A_ADC;
  10977. if taicpu(hp2).oper[0]^.typ <> top_const then
  10978. { Should have broken out of this optimisation already }
  10979. InternalError(2021112901);
  10980. 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]^) + ' -> ' +
  10981. 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);
  10982. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  10983. taicpu(hp2).opcode := SecondOpposite;
  10984. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  10985. end;
  10986. { Move to the next instruction }
  10987. GetNextInstruction(hp2, hp2);
  10988. end;
  10989. if (hp2 <> hp1) then
  10990. InternalError(2021111501);
  10991. end;
  10992. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  10993. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  10994. taicpu(p).opcode := Opposite;
  10995. taicpu(p).oper[0]^.val := -128;
  10996. { No further optimisations can be made on this instruction, so move
  10997. onto the next one to save time }
  10998. p := tai(p.Next);
  10999. UpdateUsedRegs(p);
  11000. Result := True;
  11001. Exit;
  11002. end;
  11003. { Detect:
  11004. add/sub %reg2,(dest)
  11005. add/sub x, (dest)
  11006. (dest can be a register or a reference)
  11007. Swap the instructions to minimise a pipeline stall. This reverses the
  11008. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11009. optimisations could be made.
  11010. }
  11011. if (taicpu(p).oper[0]^.typ = top_reg) and
  11012. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11013. (
  11014. (
  11015. (taicpu(p).oper[1]^.typ = top_reg) and
  11016. { We can try searching further ahead if we're writing to a register }
  11017. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11018. ) or
  11019. (
  11020. (taicpu(p).oper[1]^.typ = top_ref) and
  11021. GetNextInstruction(p, hp1)
  11022. )
  11023. ) and
  11024. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11025. (taicpu(hp1).oper[0]^.typ = top_const) and
  11026. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11027. begin
  11028. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11029. TransferUsedRegs(TmpUsedRegs);
  11030. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11031. hp2 := p;
  11032. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11033. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11034. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11035. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11036. begin
  11037. asml.remove(hp1);
  11038. asml.InsertBefore(hp1, p);
  11039. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11040. Result := True;
  11041. end;
  11042. end;
  11043. end;
  11044. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11045. begin
  11046. Result:=false;
  11047. { change "cmp $0, %reg" to "test %reg, %reg" }
  11048. if MatchOpType(taicpu(p),top_const,top_reg) and
  11049. (taicpu(p).oper[0]^.val = 0) then
  11050. begin
  11051. taicpu(p).opcode := A_TEST;
  11052. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11053. Result:=true;
  11054. end;
  11055. end;
  11056. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11057. var
  11058. IsTestConstX : Boolean;
  11059. hp1,hp2 : tai;
  11060. begin
  11061. Result:=false;
  11062. { removes the line marked with (x) from the sequence
  11063. and/or/xor/add/sub/... $x, %y
  11064. test/or %y, %y | test $-1, %y (x)
  11065. j(n)z _Label
  11066. as the first instruction already adjusts the ZF
  11067. %y operand may also be a reference }
  11068. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11069. MatchOperand(taicpu(p).oper[0]^,-1);
  11070. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11071. GetLastInstruction(p, hp1) and
  11072. (tai(hp1).typ = ait_instruction) and
  11073. GetNextInstruction(p,hp2) and
  11074. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11075. case taicpu(hp1).opcode Of
  11076. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  11077. begin
  11078. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11079. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11080. { and in case of carry for A(E)/B(E)/C/NC }
  11081. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11082. ((taicpu(hp1).opcode <> A_ADD) and
  11083. (taicpu(hp1).opcode <> A_SUB))) then
  11084. begin
  11085. RemoveCurrentP(p, hp2);
  11086. Result:=true;
  11087. Exit;
  11088. end;
  11089. end;
  11090. A_SHL, A_SAL, A_SHR, A_SAR:
  11091. begin
  11092. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11093. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11094. { therefore, it's only safe to do this optimization for }
  11095. { shifts by a (nonzero) constant }
  11096. (taicpu(hp1).oper[0]^.typ = top_const) and
  11097. (taicpu(hp1).oper[0]^.val <> 0) and
  11098. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11099. { and in case of carry for A(E)/B(E)/C/NC }
  11100. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11101. begin
  11102. RemoveCurrentP(p, hp2);
  11103. Result:=true;
  11104. Exit;
  11105. end;
  11106. end;
  11107. A_DEC, A_INC, A_NEG:
  11108. begin
  11109. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11110. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11111. { and in case of carry for A(E)/B(E)/C/NC }
  11112. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11113. begin
  11114. RemoveCurrentP(p, hp2);
  11115. Result:=true;
  11116. Exit;
  11117. end;
  11118. end
  11119. else
  11120. ;
  11121. end; { case }
  11122. { change "test $-1,%reg" into "test %reg,%reg" }
  11123. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11124. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11125. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11126. if MatchInstruction(p, A_OR, []) and
  11127. { Can only match if they're both registers }
  11128. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11129. begin
  11130. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11131. taicpu(p).opcode := A_TEST;
  11132. { No need to set Result to True, as we've done all the optimisations we can }
  11133. end;
  11134. end;
  11135. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11136. var
  11137. hp1,hp3 : tai;
  11138. {$ifndef x86_64}
  11139. hp2 : taicpu;
  11140. {$endif x86_64}
  11141. begin
  11142. Result:=false;
  11143. hp3:=nil;
  11144. {$ifndef x86_64}
  11145. { don't do this on modern CPUs, this really hurts them due to
  11146. broken call/ret pairing }
  11147. if (current_settings.optimizecputype < cpu_Pentium2) and
  11148. not(cs_create_pic in current_settings.moduleswitches) and
  11149. GetNextInstruction(p, hp1) and
  11150. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11151. MatchOpType(taicpu(hp1),top_ref) and
  11152. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11153. begin
  11154. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11155. InsertLLItem(p.previous, p, hp2);
  11156. taicpu(p).opcode := A_JMP;
  11157. taicpu(p).is_jmp := true;
  11158. RemoveInstruction(hp1);
  11159. Result:=true;
  11160. end
  11161. else
  11162. {$endif x86_64}
  11163. { replace
  11164. call procname
  11165. ret
  11166. by
  11167. jmp procname
  11168. but do it only on level 4 because it destroys stack back traces
  11169. else if the subroutine is marked as no return, remove the ret
  11170. }
  11171. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11172. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11173. GetNextInstruction(p, hp1) and
  11174. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11175. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11176. SetAndTest(hp1,hp3) and
  11177. GetNextInstruction(hp1,hp1) and
  11178. MatchInstruction(hp1,A_RET,[S_NO])
  11179. )
  11180. ) and
  11181. (taicpu(hp1).ops=0) then
  11182. begin
  11183. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11184. { we might destroy stack alignment here if we do not do a call }
  11185. (target_info.stackalign<=sizeof(SizeUInt)) then
  11186. begin
  11187. taicpu(p).opcode := A_JMP;
  11188. taicpu(p).is_jmp := true;
  11189. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11190. end
  11191. else
  11192. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11193. RemoveInstruction(hp1);
  11194. if Assigned(hp3) then
  11195. begin
  11196. AsmL.Remove(hp3);
  11197. AsmL.InsertBefore(hp3,p)
  11198. end;
  11199. Result:=true;
  11200. end;
  11201. end;
  11202. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11203. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11204. begin
  11205. case OpSize of
  11206. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11207. Result := (Val <= $FF) and (Val >= -128);
  11208. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11209. Result := (Val <= $FFFF) and (Val >= -32768);
  11210. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11211. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11212. else
  11213. Result := True;
  11214. end;
  11215. end;
  11216. var
  11217. hp1, hp2 : tai;
  11218. SizeChange: Boolean;
  11219. PreMessage: string;
  11220. begin
  11221. Result := False;
  11222. if (taicpu(p).oper[0]^.typ = top_reg) and
  11223. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11224. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11225. begin
  11226. { Change (using movzbl %al,%eax as an example):
  11227. movzbl %al, %eax movzbl %al, %eax
  11228. cmpl x, %eax testl %eax,%eax
  11229. To:
  11230. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11231. movzbl %al, %eax movzbl %al, %eax
  11232. Smaller instruction and minimises pipeline stall as the CPU
  11233. doesn't have to wait for the register to get zero-extended. [Kit]
  11234. Also allow if the smaller of the two registers is being checked,
  11235. as this still removes the false dependency.
  11236. }
  11237. if
  11238. (
  11239. (
  11240. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11241. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11242. ) or (
  11243. { If MatchOperand returns True, they must both be registers }
  11244. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11245. )
  11246. ) and
  11247. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11248. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11249. begin
  11250. 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);
  11251. asml.Remove(hp1);
  11252. asml.InsertBefore(hp1, p);
  11253. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11254. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11255. begin
  11256. taicpu(hp1).opcode := A_TEST;
  11257. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11258. end;
  11259. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11260. case taicpu(p).opsize of
  11261. S_BW, S_BL:
  11262. begin
  11263. SizeChange := taicpu(hp1).opsize <> S_B;
  11264. taicpu(hp1).changeopsize(S_B);
  11265. end;
  11266. S_WL:
  11267. begin
  11268. SizeChange := taicpu(hp1).opsize <> S_W;
  11269. taicpu(hp1).changeopsize(S_W);
  11270. end
  11271. else
  11272. InternalError(2020112701);
  11273. end;
  11274. UpdateUsedRegs(tai(p.Next));
  11275. { Check if the register is used aferwards - if not, we can
  11276. remove the movzx instruction completely }
  11277. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11278. begin
  11279. { Hp1 is a better position than p for debugging purposes }
  11280. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11281. RemoveCurrentp(p, hp1);
  11282. Result := True;
  11283. end;
  11284. if SizeChange then
  11285. DebugMsg(SPeepholeOptimization + PreMessage +
  11286. 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)
  11287. else
  11288. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11289. Exit;
  11290. end;
  11291. { Change (using movzwl %ax,%eax as an example):
  11292. movzwl %ax, %eax
  11293. movb %al, (dest) (Register is smaller than read register in movz)
  11294. To:
  11295. movb %al, (dest) (Move one back to avoid a false dependency)
  11296. movzwl %ax, %eax
  11297. }
  11298. if (taicpu(hp1).opcode = A_MOV) and
  11299. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11300. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11301. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11302. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11303. begin
  11304. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11305. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11306. asml.Remove(hp1);
  11307. asml.InsertBefore(hp1, p);
  11308. if taicpu(hp1).oper[1]^.typ = top_reg then
  11309. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11310. { Check if the register is used aferwards - if not, we can
  11311. remove the movzx instruction completely }
  11312. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11313. begin
  11314. { Hp1 is a better position than p for debugging purposes }
  11315. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11316. RemoveCurrentp(p, hp1);
  11317. Result := True;
  11318. end;
  11319. Exit;
  11320. end;
  11321. end;
  11322. end;
  11323. {$ifdef x86_64}
  11324. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11325. var
  11326. PreMessage, RegName: string;
  11327. begin
  11328. { Code size reduction by J. Gareth "Kit" Moreton }
  11329. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11330. as this removes the REX prefix }
  11331. Result := False;
  11332. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11333. Exit;
  11334. if taicpu(p).oper[0]^.typ <> top_reg then
  11335. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11336. InternalError(2018011500);
  11337. case taicpu(p).opsize of
  11338. S_Q:
  11339. begin
  11340. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11341. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11342. { The actual optimization }
  11343. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11344. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11345. taicpu(p).changeopsize(S_L);
  11346. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11347. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11348. end;
  11349. else
  11350. ;
  11351. end;
  11352. end;
  11353. {$endif}
  11354. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11355. var
  11356. XReg: TRegister;
  11357. begin
  11358. Result := False;
  11359. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11360. Smaller encoding and slightly faster on some platforms (also works for
  11361. ZMM-sized registers) }
  11362. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11363. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11364. begin
  11365. XReg := taicpu(p).oper[0]^.reg;
  11366. if (taicpu(p).oper[1]^.reg = XReg) then
  11367. begin
  11368. taicpu(p).changeopsize(S_XMM);
  11369. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11370. if (cs_opt_size in current_settings.optimizerswitches) then
  11371. begin
  11372. { Change input registers to %xmm0 to reduce size. Note that
  11373. there's a risk of a false dependency doing this, so only
  11374. optimise for size here }
  11375. XReg := NR_XMM0;
  11376. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11377. end
  11378. else
  11379. begin
  11380. setsubreg(XReg, R_SUBMMX);
  11381. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11382. end;
  11383. taicpu(p).oper[0]^.reg := XReg;
  11384. taicpu(p).oper[1]^.reg := XReg;
  11385. Result := True;
  11386. end;
  11387. end;
  11388. end;
  11389. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11390. var
  11391. OperIdx: Integer;
  11392. begin
  11393. for OperIdx := 0 to p.ops - 1 do
  11394. if p.oper[OperIdx]^.typ = top_ref then
  11395. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11396. end;
  11397. end.