aoptx86.pas 444 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { Attempts to allocate a volatile integer register for use between p and hp,
  68. using AUsedRegs for the current register usage information. Returns NR_NO
  69. if no free register could be found }
  70. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  71. { Attempts to allocate a volatile MM register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  76. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  77. { checks whether reading the value in reg1 depends on the value of reg2. This
  78. is very similar to SuperRegisterEquals, except it takes into account that
  79. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  80. depend on the value in AH). }
  81. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  82. { Replaces all references to AOldReg in a memory reference to ANewReg }
  83. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  84. { Replaces all references to AOldReg in an operand to ANewReg }
  85. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  86. { Replaces all references to AOldReg in an instruction to ANewReg,
  87. except where the register is being written }
  88. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  89. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  90. or writes to a global symbol }
  91. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  92. { Returns true if the given MOV instruction can be safely converted to CMOV }
  93. class function CanBeCMOV(p : tai) : boolean; static;
  94. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  95. conversion was successful }
  96. function ConvertLEA(const p : taicpu): Boolean;
  97. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  98. procedure DebugMsg(const s : string; p : tai);inline;
  99. class function IsExitCode(p : tai) : boolean; static;
  100. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  101. procedure RemoveLastDeallocForFuncRes(p : tai);
  102. function DoSubAddOpt(var p : tai) : Boolean;
  103. function PrePeepholeOptSxx(var p : tai) : boolean;
  104. function PrePeepholeOptIMUL(var p : tai) : boolean;
  105. function PrePeepholeOptAND(var p : tai) : boolean;
  106. function OptPass1Test(var p: tai): boolean;
  107. function OptPass1Add(var p: tai): boolean;
  108. function OptPass1AND(var p : tai) : boolean;
  109. function OptPass1_V_MOVAP(var p : tai) : boolean;
  110. function OptPass1VOP(var p : tai) : boolean;
  111. function OptPass1MOV(var p : tai) : boolean;
  112. function OptPass1Movx(var p : tai) : boolean;
  113. function OptPass1MOVXX(var p : tai) : boolean;
  114. function OptPass1OP(var p : tai) : boolean;
  115. function OptPass1LEA(var p : tai) : boolean;
  116. function OptPass1Sub(var p : tai) : boolean;
  117. function OptPass1SHLSAL(var p : tai) : boolean;
  118. function OptPass1FSTP(var p : tai) : boolean;
  119. function OptPass1FLD(var p : tai) : boolean;
  120. function OptPass1Cmp(var p : tai) : boolean;
  121. function OptPass1PXor(var p : tai) : boolean;
  122. function OptPass1VPXor(var p: tai): boolean;
  123. function OptPass1Imul(var p : tai) : boolean;
  124. function OptPass1Jcc(var p : tai) : boolean;
  125. function OptPass1SHXX(var p: tai): boolean;
  126. function OptPass2Movx(var p : tai): Boolean;
  127. function OptPass2MOV(var p : tai) : boolean;
  128. function OptPass2Imul(var p : tai) : boolean;
  129. function OptPass2Jmp(var p : tai) : boolean;
  130. function OptPass2Jcc(var p : tai) : boolean;
  131. function OptPass2Lea(var p: tai): Boolean;
  132. function OptPass2SUB(var p: tai): Boolean;
  133. function OptPass2ADD(var p : tai): Boolean;
  134. function OptPass2SETcc(var p : tai) : boolean;
  135. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  136. function PostPeepholeOptMov(var p : tai) : Boolean;
  137. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  138. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  139. function PostPeepholeOptXor(var p : tai) : Boolean;
  140. {$endif}
  141. function PostPeepholeOptAnd(var p : tai) : boolean;
  142. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  143. function PostPeepholeOptCmp(var p : tai) : Boolean;
  144. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  145. function PostPeepholeOptCall(var p : tai) : Boolean;
  146. function PostPeepholeOptLea(var p : tai) : Boolean;
  147. function PostPeepholeOptPush(var p: tai): Boolean;
  148. function PostPeepholeOptShr(var p : tai) : boolean;
  149. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  150. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  151. procedure SwapMovCmp(var p, hp1: tai);
  152. { Processor-dependent reference optimisation }
  153. class procedure OptimizeRefs(var p: taicpu); static;
  154. end;
  155. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  156. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  157. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  158. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  159. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  160. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  161. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  162. {$if max_operands>2}
  163. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  164. {$endif max_operands>2}
  165. function RefsEqual(const r1, r2: treference): boolean;
  166. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  167. { returns true, if ref is a reference using only the registers passed as base and index
  168. and having an offset }
  169. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  170. implementation
  171. uses
  172. cutils,verbose,
  173. systems,
  174. globals,
  175. cpuinfo,
  176. procinfo,
  177. paramgr,
  178. aasmbase,
  179. aoptbase,aoptutils,
  180. symconst,symsym,
  181. cgx86,
  182. itcpugas;
  183. {$ifdef DEBUG_AOPTCPU}
  184. const
  185. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  186. {$else DEBUG_AOPTCPU}
  187. { Empty strings help the optimizer to remove string concatenations that won't
  188. ever appear to the user on release builds. [Kit] }
  189. const
  190. SPeepholeOptimization = '';
  191. {$endif DEBUG_AOPTCPU}
  192. LIST_STEP_SIZE = 4;
  193. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  194. begin
  195. result :=
  196. (instr.typ = ait_instruction) and
  197. (taicpu(instr).opcode = op) and
  198. ((opsize = []) or (taicpu(instr).opsize in opsize));
  199. end;
  200. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. ((taicpu(instr).opcode = op1) or
  205. (taicpu(instr).opcode = op2)
  206. ) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2) or
  215. (taicpu(instr).opcode = op3)
  216. ) and
  217. ((opsize = []) or (taicpu(instr).opsize in opsize));
  218. end;
  219. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  220. const opsize : topsizes) : boolean;
  221. var
  222. op : TAsmOp;
  223. begin
  224. result:=false;
  225. if (instr.typ <> ait_instruction) or
  226. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  227. exit;
  228. for op in ops do
  229. begin
  230. if taicpu(instr).opcode = op then
  231. begin
  232. result:=true;
  233. exit;
  234. end;
  235. end;
  236. end;
  237. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  238. begin
  239. result := (oper.typ = top_reg) and (oper.reg = reg);
  240. end;
  241. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  242. begin
  243. result := (oper.typ = top_const) and (oper.val = a);
  244. end;
  245. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  246. begin
  247. result := oper1.typ = oper2.typ;
  248. if result then
  249. case oper1.typ of
  250. top_const:
  251. Result:=oper1.val = oper2.val;
  252. top_reg:
  253. Result:=oper1.reg = oper2.reg;
  254. top_ref:
  255. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  256. else
  257. internalerror(2013102801);
  258. end
  259. end;
  260. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  261. begin
  262. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  263. if result then
  264. case oper1.typ of
  265. top_const:
  266. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  267. top_reg:
  268. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  269. top_ref:
  270. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  271. else
  272. internalerror(2020052401);
  273. end
  274. end;
  275. function RefsEqual(const r1, r2: treference): boolean;
  276. begin
  277. RefsEqual :=
  278. (r1.offset = r2.offset) and
  279. (r1.segment = r2.segment) and (r1.base = r2.base) and
  280. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  281. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  282. (r1.relsymbol = r2.relsymbol) and
  283. (r1.volatility=[]) and
  284. (r2.volatility=[]);
  285. end;
  286. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  287. begin
  288. Result:=(ref.offset=0) and
  289. (ref.scalefactor in [0,1]) and
  290. (ref.segment=NR_NO) and
  291. (ref.symbol=nil) and
  292. (ref.relsymbol=nil) and
  293. ((base=NR_INVALID) or
  294. (ref.base=base)) and
  295. ((index=NR_INVALID) or
  296. (ref.index=index)) and
  297. (ref.volatility=[]);
  298. end;
  299. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  300. begin
  301. Result:=(ref.scalefactor in [0,1]) and
  302. (ref.segment=NR_NO) and
  303. (ref.symbol=nil) and
  304. (ref.relsymbol=nil) and
  305. ((base=NR_INVALID) or
  306. (ref.base=base)) and
  307. ((index=NR_INVALID) or
  308. (ref.index=index)) and
  309. (ref.volatility=[]);
  310. end;
  311. function InstrReadsFlags(p: tai): boolean;
  312. begin
  313. InstrReadsFlags := true;
  314. case p.typ of
  315. ait_instruction:
  316. if InsProp[taicpu(p).opcode].Ch*
  317. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  318. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  319. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  320. exit;
  321. ait_label:
  322. exit;
  323. else
  324. ;
  325. end;
  326. InstrReadsFlags := false;
  327. end;
  328. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  329. begin
  330. Next:=Current;
  331. repeat
  332. Result:=GetNextInstruction(Next,Next);
  333. until not (Result) or
  334. not(cs_opt_level3 in current_settings.optimizerswitches) or
  335. (Next.typ<>ait_instruction) or
  336. RegInInstruction(reg,Next) or
  337. is_calljmp(taicpu(Next).opcode);
  338. end;
  339. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  340. begin
  341. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  342. Next := Current;
  343. repeat
  344. Result := GetNextInstruction(Next,Next);
  345. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  346. if is_calljmpuncondret(taicpu(Next).opcode) then
  347. begin
  348. Result := False;
  349. Exit;
  350. end
  351. else
  352. CrossJump := True;
  353. until not Result or
  354. not (cs_opt_level3 in current_settings.optimizerswitches) or
  355. (Next.typ <> ait_instruction) or
  356. RegInInstruction(reg,Next);
  357. end;
  358. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  359. begin
  360. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  361. begin
  362. Result:=GetNextInstruction(Current,Next);
  363. exit;
  364. end;
  365. Next:=tai(Current.Next);
  366. Result:=false;
  367. while assigned(Next) do
  368. begin
  369. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  370. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  371. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  372. exit
  373. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  374. begin
  375. Result:=true;
  376. exit;
  377. end;
  378. Next:=tai(Next.Next);
  379. end;
  380. end;
  381. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  382. begin
  383. Result:=RegReadByInstruction(reg,hp);
  384. end;
  385. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  386. var
  387. p: taicpu;
  388. opcount: longint;
  389. begin
  390. RegReadByInstruction := false;
  391. if hp.typ <> ait_instruction then
  392. exit;
  393. p := taicpu(hp);
  394. case p.opcode of
  395. A_CALL:
  396. regreadbyinstruction := true;
  397. A_IMUL:
  398. case p.ops of
  399. 1:
  400. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  401. (
  402. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  403. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  404. );
  405. 2,3:
  406. regReadByInstruction :=
  407. reginop(reg,p.oper[0]^) or
  408. reginop(reg,p.oper[1]^);
  409. else
  410. InternalError(2019112801);
  411. end;
  412. A_MUL:
  413. begin
  414. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  415. (
  416. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  417. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  418. );
  419. end;
  420. A_IDIV,A_DIV:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. (getregtype(reg)=R_INTREGISTER) and
  425. (
  426. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  427. )
  428. );
  429. end;
  430. else
  431. begin
  432. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  433. begin
  434. RegReadByInstruction := false;
  435. exit;
  436. end;
  437. for opcount := 0 to p.ops-1 do
  438. if (p.oper[opCount]^.typ = top_ref) and
  439. RegInRef(reg,p.oper[opcount]^.ref^) then
  440. begin
  441. RegReadByInstruction := true;
  442. exit
  443. end;
  444. { special handling for SSE MOVSD }
  445. if (p.opcode=A_MOVSD) and (p.ops>0) then
  446. begin
  447. if p.ops<>2 then
  448. internalerror(2017042702);
  449. regReadByInstruction := reginop(reg,p.oper[0]^) or
  450. (
  451. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  452. );
  453. exit;
  454. end;
  455. with insprop[p.opcode] do
  456. begin
  457. if getregtype(reg)=R_INTREGISTER then
  458. begin
  459. case getsupreg(reg) of
  460. RS_EAX:
  461. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  462. begin
  463. RegReadByInstruction := true;
  464. exit
  465. end;
  466. RS_ECX:
  467. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  468. begin
  469. RegReadByInstruction := true;
  470. exit
  471. end;
  472. RS_EDX:
  473. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  474. begin
  475. RegReadByInstruction := true;
  476. exit
  477. end;
  478. RS_EBX:
  479. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  480. begin
  481. RegReadByInstruction := true;
  482. exit
  483. end;
  484. RS_ESP:
  485. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  486. begin
  487. RegReadByInstruction := true;
  488. exit
  489. end;
  490. RS_EBP:
  491. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  492. begin
  493. RegReadByInstruction := true;
  494. exit
  495. end;
  496. RS_ESI:
  497. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  498. begin
  499. RegReadByInstruction := true;
  500. exit
  501. end;
  502. RS_EDI:
  503. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  504. begin
  505. RegReadByInstruction := true;
  506. exit
  507. end;
  508. end;
  509. end;
  510. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  511. begin
  512. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  513. begin
  514. case p.condition of
  515. C_A,C_NBE, { CF=0 and ZF=0 }
  516. C_BE,C_NA: { CF=1 or ZF=1 }
  517. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  518. C_AE,C_NB,C_NC, { CF=0 }
  519. C_B,C_NAE,C_C: { CF=1 }
  520. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  521. C_NE,C_NZ, { ZF=0 }
  522. C_E,C_Z: { ZF=1 }
  523. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  524. C_G,C_NLE, { ZF=0 and SF=OF }
  525. C_LE,C_NG: { ZF=1 or SF<>OF }
  526. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  527. C_GE,C_NL, { SF=OF }
  528. C_L,C_NGE: { SF<>OF }
  529. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  530. C_NO, { OF=0 }
  531. C_O: { OF=1 }
  532. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  533. C_NP,C_PO, { PF=0 }
  534. C_P,C_PE: { PF=1 }
  535. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  536. C_NS, { SF=0 }
  537. C_S: { SF=1 }
  538. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  539. else
  540. internalerror(2017042701);
  541. end;
  542. if RegReadByInstruction then
  543. exit;
  544. end;
  545. case getsubreg(reg) of
  546. R_SUBW,R_SUBD,R_SUBQ:
  547. RegReadByInstruction :=
  548. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  549. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  550. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  551. R_SUBFLAGCARRY:
  552. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  553. R_SUBFLAGPARITY:
  554. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  555. R_SUBFLAGAUXILIARY:
  556. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  557. R_SUBFLAGZERO:
  558. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  559. R_SUBFLAGSIGN:
  560. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  561. R_SUBFLAGOVERFLOW:
  562. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  563. R_SUBFLAGINTERRUPT:
  564. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  565. R_SUBFLAGDIRECTION:
  566. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  567. else
  568. internalerror(2017042601);
  569. end;
  570. exit;
  571. end;
  572. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  573. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  574. (p.oper[0]^.reg=p.oper[1]^.reg) then
  575. exit;
  576. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  577. begin
  578. RegReadByInstruction := true;
  579. exit
  580. end;
  581. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  582. begin
  583. RegReadByInstruction := true;
  584. exit
  585. end;
  586. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  587. begin
  588. RegReadByInstruction := true;
  589. exit
  590. end;
  591. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  592. begin
  593. RegReadByInstruction := true;
  594. exit
  595. end;
  596. end;
  597. end;
  598. end;
  599. end;
  600. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  601. begin
  602. result:=false;
  603. if p1.typ<>ait_instruction then
  604. exit;
  605. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  606. exit(true);
  607. if (getregtype(reg)=R_INTREGISTER) and
  608. { change information for xmm movsd are not correct }
  609. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  610. begin
  611. case getsupreg(reg) of
  612. { RS_EAX = RS_RAX on x86-64 }
  613. RS_EAX:
  614. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  615. RS_ECX:
  616. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  617. RS_EDX:
  618. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  619. RS_EBX:
  620. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  621. RS_ESP:
  622. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  623. RS_EBP:
  624. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  625. RS_ESI:
  626. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  627. RS_EDI:
  628. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  629. else
  630. ;
  631. end;
  632. if result then
  633. exit;
  634. end
  635. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  636. begin
  637. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  638. exit(true);
  639. case getsubreg(reg) of
  640. R_SUBFLAGCARRY:
  641. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. R_SUBFLAGPARITY:
  643. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. R_SUBFLAGAUXILIARY:
  645. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. R_SUBFLAGZERO:
  647. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. R_SUBFLAGSIGN:
  649. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. R_SUBFLAGOVERFLOW:
  651. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. R_SUBFLAGINTERRUPT:
  653. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  654. R_SUBFLAGDIRECTION:
  655. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  656. else
  657. ;
  658. end;
  659. if result then
  660. exit;
  661. end
  662. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  663. exit(true);
  664. Result:=inherited RegInInstruction(Reg, p1);
  665. end;
  666. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  667. begin
  668. Result := False;
  669. if p1.typ <> ait_instruction then
  670. exit;
  671. with insprop[taicpu(p1).opcode] do
  672. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  673. begin
  674. case getsubreg(reg) of
  675. R_SUBW,R_SUBD,R_SUBQ:
  676. Result :=
  677. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  678. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  679. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  680. R_SUBFLAGCARRY:
  681. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  682. R_SUBFLAGPARITY:
  683. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  684. R_SUBFLAGAUXILIARY:
  685. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  686. R_SUBFLAGZERO:
  687. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  688. R_SUBFLAGSIGN:
  689. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  690. R_SUBFLAGOVERFLOW:
  691. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  692. R_SUBFLAGINTERRUPT:
  693. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  694. R_SUBFLAGDIRECTION:
  695. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  696. else
  697. internalerror(2017042602);
  698. end;
  699. exit;
  700. end;
  701. case taicpu(p1).opcode of
  702. A_CALL:
  703. { We could potentially set Result to False if the register in
  704. question is non-volatile for the subroutine's calling convention,
  705. but this would require detecting the calling convention in use and
  706. also assuming that the routine doesn't contain malformed assembly
  707. language, for example... so it could only be done under -O4 as it
  708. would be considered a side-effect. [Kit] }
  709. Result := True;
  710. A_MOVSD:
  711. { special handling for SSE MOVSD }
  712. if (taicpu(p1).ops>0) then
  713. begin
  714. if taicpu(p1).ops<>2 then
  715. internalerror(2017042703);
  716. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  717. end;
  718. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  719. so fix it here (FK)
  720. }
  721. A_VMOVSS,
  722. A_VMOVSD:
  723. begin
  724. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  725. exit;
  726. end;
  727. A_IMUL:
  728. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  729. else
  730. ;
  731. end;
  732. if Result then
  733. exit;
  734. with insprop[taicpu(p1).opcode] do
  735. begin
  736. if getregtype(reg)=R_INTREGISTER then
  737. begin
  738. case getsupreg(reg) of
  739. RS_EAX:
  740. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  741. begin
  742. Result := True;
  743. exit
  744. end;
  745. RS_ECX:
  746. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  747. begin
  748. Result := True;
  749. exit
  750. end;
  751. RS_EDX:
  752. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  753. begin
  754. Result := True;
  755. exit
  756. end;
  757. RS_EBX:
  758. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  759. begin
  760. Result := True;
  761. exit
  762. end;
  763. RS_ESP:
  764. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  765. begin
  766. Result := True;
  767. exit
  768. end;
  769. RS_EBP:
  770. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  771. begin
  772. Result := True;
  773. exit
  774. end;
  775. RS_ESI:
  776. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  777. begin
  778. Result := True;
  779. exit
  780. end;
  781. RS_EDI:
  782. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  783. begin
  784. Result := True;
  785. exit
  786. end;
  787. end;
  788. end;
  789. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  790. begin
  791. Result := true;
  792. exit
  793. end;
  794. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  795. begin
  796. Result := true;
  797. exit
  798. end;
  799. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  800. begin
  801. Result := true;
  802. exit
  803. end;
  804. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  805. begin
  806. Result := true;
  807. exit
  808. end;
  809. end;
  810. end;
  811. {$ifdef DEBUG_AOPTCPU}
  812. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  813. begin
  814. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  815. end;
  816. function debug_tostr(i: tcgint): string; inline;
  817. begin
  818. Result := tostr(i);
  819. end;
  820. function debug_regname(r: TRegister): string; inline;
  821. begin
  822. Result := '%' + std_regname(r);
  823. end;
  824. { Debug output function - creates a string representation of an operator }
  825. function debug_operstr(oper: TOper): string;
  826. begin
  827. case oper.typ of
  828. top_const:
  829. Result := '$' + debug_tostr(oper.val);
  830. top_reg:
  831. Result := debug_regname(oper.reg);
  832. top_ref:
  833. begin
  834. if oper.ref^.offset <> 0 then
  835. Result := debug_tostr(oper.ref^.offset) + '('
  836. else
  837. Result := '(';
  838. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  839. begin
  840. Result := Result + debug_regname(oper.ref^.base);
  841. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  842. Result := Result + ',' + debug_regname(oper.ref^.index);
  843. end
  844. else
  845. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  846. Result := Result + debug_regname(oper.ref^.index);
  847. if (oper.ref^.scalefactor > 1) then
  848. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  849. else
  850. Result := Result + ')';
  851. end;
  852. else
  853. Result := '[UNKNOWN]';
  854. end;
  855. end;
  856. function debug_op2str(opcode: tasmop): string; inline;
  857. begin
  858. Result := std_op2str[opcode];
  859. end;
  860. function debug_opsize2str(opsize: topsize): string; inline;
  861. begin
  862. Result := gas_opsize2str[opsize];
  863. end;
  864. {$else DEBUG_AOPTCPU}
  865. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  866. begin
  867. end;
  868. function debug_tostr(i: tcgint): string; inline;
  869. begin
  870. Result := '';
  871. end;
  872. function debug_regname(r: TRegister): string; inline;
  873. begin
  874. Result := '';
  875. end;
  876. function debug_operstr(oper: TOper): string; inline;
  877. begin
  878. Result := '';
  879. end;
  880. function debug_op2str(opcode: tasmop): string; inline;
  881. begin
  882. Result := '';
  883. end;
  884. function debug_opsize2str(opsize: topsize): string; inline;
  885. begin
  886. Result := '';
  887. end;
  888. {$endif DEBUG_AOPTCPU}
  889. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  890. begin
  891. {$ifdef x86_64}
  892. { Always fine on x86-64 }
  893. Result := True;
  894. {$else x86_64}
  895. Result :=
  896. {$ifdef i8086}
  897. (current_settings.cputype >= cpu_386) and
  898. {$endif i8086}
  899. (
  900. { Always accept if optimising for size }
  901. (cs_opt_size in current_settings.optimizerswitches) or
  902. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  903. (current_settings.optimizecputype >= cpu_Pentium2)
  904. );
  905. {$endif x86_64}
  906. end;
  907. { Attempts to allocate a volatile integer register for use between p and hp,
  908. using AUsedRegs for the current register usage information. Returns NR_NO
  909. if no free register could be found }
  910. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  911. var
  912. RegSet: TCPURegisterSet;
  913. CurrentSuperReg: Integer;
  914. CurrentReg: TRegister;
  915. Currentp: tai;
  916. Breakout: Boolean;
  917. begin
  918. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  919. Result := NR_NO;
  920. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  921. for CurrentSuperReg in RegSet do
  922. begin
  923. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  924. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  925. begin
  926. Currentp := p;
  927. Breakout := False;
  928. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  929. begin
  930. case Currentp.typ of
  931. ait_instruction:
  932. begin
  933. if RegInInstruction(CurrentReg, Currentp) then
  934. begin
  935. Breakout := True;
  936. Break;
  937. end;
  938. { Cannot allocate across an unconditional jump }
  939. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  940. Exit;
  941. end;
  942. ait_marker:
  943. { Don't try anything more if a marker is hit }
  944. Exit;
  945. ait_regalloc:
  946. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  947. begin
  948. Breakout := True;
  949. Break;
  950. end;
  951. else
  952. ;
  953. end;
  954. end;
  955. if Breakout then
  956. { Try the next register }
  957. Continue;
  958. { We have a free register available }
  959. Result := CurrentReg;
  960. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  961. Exit;
  962. end;
  963. end;
  964. end;
  965. { Attempts to allocate a volatile MM register for use between p and hp,
  966. using AUsedRegs for the current register usage information. Returns NR_NO
  967. if no free register could be found }
  968. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  969. var
  970. RegSet: TCPURegisterSet;
  971. CurrentSuperReg: Integer;
  972. CurrentReg: TRegister;
  973. Currentp: tai;
  974. Breakout: Boolean;
  975. begin
  976. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  977. Result := NR_NO;
  978. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  979. for CurrentSuperReg in RegSet do
  980. begin
  981. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  982. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  983. begin
  984. Currentp := p;
  985. Breakout := False;
  986. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  987. begin
  988. case Currentp.typ of
  989. ait_instruction:
  990. begin
  991. if RegInInstruction(CurrentReg, Currentp) then
  992. begin
  993. Breakout := True;
  994. Break;
  995. end;
  996. { Cannot allocate across an unconditional jump }
  997. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  998. Exit;
  999. end;
  1000. ait_marker:
  1001. { Don't try anything more if a marker is hit }
  1002. Exit;
  1003. ait_regalloc:
  1004. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1005. begin
  1006. Breakout := True;
  1007. Break;
  1008. end;
  1009. else
  1010. ;
  1011. end;
  1012. end;
  1013. if Breakout then
  1014. { Try the next register }
  1015. Continue;
  1016. { We have a free register available }
  1017. Result := CurrentReg;
  1018. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1019. Exit;
  1020. end;
  1021. end;
  1022. end;
  1023. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1024. begin
  1025. if not SuperRegistersEqual(reg1,reg2) then
  1026. exit(false);
  1027. if getregtype(reg1)<>R_INTREGISTER then
  1028. exit(true); {because SuperRegisterEqual is true}
  1029. case getsubreg(reg1) of
  1030. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1031. higher, it preserves the high bits, so the new value depends on
  1032. reg2's previous value. In other words, it is equivalent to doing:
  1033. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1034. R_SUBL:
  1035. exit(getsubreg(reg2)=R_SUBL);
  1036. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1037. higher, it actually does a:
  1038. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1039. R_SUBH:
  1040. exit(getsubreg(reg2)=R_SUBH);
  1041. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1042. bits of reg2:
  1043. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1044. R_SUBW:
  1045. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1046. { a write to R_SUBD always overwrites every other subregister,
  1047. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1048. R_SUBD,
  1049. R_SUBQ:
  1050. exit(true);
  1051. else
  1052. internalerror(2017042801);
  1053. end;
  1054. end;
  1055. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1056. begin
  1057. if not SuperRegistersEqual(reg1,reg2) then
  1058. exit(false);
  1059. if getregtype(reg1)<>R_INTREGISTER then
  1060. exit(true); {because SuperRegisterEqual is true}
  1061. case getsubreg(reg1) of
  1062. R_SUBL:
  1063. exit(getsubreg(reg2)<>R_SUBH);
  1064. R_SUBH:
  1065. exit(getsubreg(reg2)<>R_SUBL);
  1066. R_SUBW,
  1067. R_SUBD,
  1068. R_SUBQ:
  1069. exit(true);
  1070. else
  1071. internalerror(2017042802);
  1072. end;
  1073. end;
  1074. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1075. var
  1076. hp1 : tai;
  1077. l : TCGInt;
  1078. begin
  1079. result:=false;
  1080. { changes the code sequence
  1081. shr/sar const1, x
  1082. shl const2, x
  1083. to
  1084. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1085. if GetNextInstruction(p, hp1) and
  1086. MatchInstruction(hp1,A_SHL,[]) and
  1087. (taicpu(p).oper[0]^.typ = top_const) and
  1088. (taicpu(hp1).oper[0]^.typ = top_const) and
  1089. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1090. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1091. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1092. begin
  1093. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1094. not(cs_opt_size in current_settings.optimizerswitches) then
  1095. begin
  1096. { shr/sar const1, %reg
  1097. shl const2, %reg
  1098. with const1 > const2 }
  1099. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1100. taicpu(hp1).opcode := A_AND;
  1101. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1102. case taicpu(p).opsize Of
  1103. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1104. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1105. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1106. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1107. else
  1108. Internalerror(2017050703)
  1109. end;
  1110. end
  1111. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1112. not(cs_opt_size in current_settings.optimizerswitches) then
  1113. begin
  1114. { shr/sar const1, %reg
  1115. shl const2, %reg
  1116. with const1 < const2 }
  1117. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1118. taicpu(p).opcode := A_AND;
  1119. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1120. case taicpu(p).opsize Of
  1121. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1122. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1123. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1124. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1125. else
  1126. Internalerror(2017050702)
  1127. end;
  1128. end
  1129. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1130. begin
  1131. { shr/sar const1, %reg
  1132. shl const2, %reg
  1133. with const1 = const2 }
  1134. taicpu(p).opcode := A_AND;
  1135. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1136. case taicpu(p).opsize Of
  1137. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1138. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1139. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1140. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1141. else
  1142. Internalerror(2017050701)
  1143. end;
  1144. RemoveInstruction(hp1);
  1145. end;
  1146. end;
  1147. end;
  1148. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1149. var
  1150. opsize : topsize;
  1151. hp1 : tai;
  1152. tmpref : treference;
  1153. ShiftValue : Cardinal;
  1154. BaseValue : TCGInt;
  1155. begin
  1156. result:=false;
  1157. opsize:=taicpu(p).opsize;
  1158. { changes certain "imul const, %reg"'s to lea sequences }
  1159. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1160. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1161. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1162. if (taicpu(p).oper[0]^.val = 1) then
  1163. if (taicpu(p).ops = 2) then
  1164. { remove "imul $1, reg" }
  1165. begin
  1166. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1167. Result := RemoveCurrentP(p);
  1168. end
  1169. else
  1170. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1171. begin
  1172. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1173. InsertLLItem(p.previous, p.next, hp1);
  1174. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1175. p.free;
  1176. p := hp1;
  1177. end
  1178. else if ((taicpu(p).ops <= 2) or
  1179. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1180. not(cs_opt_size in current_settings.optimizerswitches) and
  1181. (not(GetNextInstruction(p, hp1)) or
  1182. not((tai(hp1).typ = ait_instruction) and
  1183. ((taicpu(hp1).opcode=A_Jcc) and
  1184. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1185. begin
  1186. {
  1187. imul X, reg1, reg2 to
  1188. lea (reg1,reg1,Y), reg2
  1189. shl ZZ,reg2
  1190. imul XX, reg1 to
  1191. lea (reg1,reg1,YY), reg1
  1192. shl ZZ,reg2
  1193. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1194. it does not exist as a separate optimization target in FPC though.
  1195. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1196. at most two zeros
  1197. }
  1198. reference_reset(tmpref,1,[]);
  1199. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1200. begin
  1201. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1202. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1203. TmpRef.base := taicpu(p).oper[1]^.reg;
  1204. TmpRef.index := taicpu(p).oper[1]^.reg;
  1205. if not(BaseValue in [3,5,9]) then
  1206. Internalerror(2018110101);
  1207. TmpRef.ScaleFactor := BaseValue-1;
  1208. if (taicpu(p).ops = 2) then
  1209. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1210. else
  1211. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1212. AsmL.InsertAfter(hp1,p);
  1213. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1214. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1215. RemoveCurrentP(p, hp1);
  1216. if ShiftValue>0 then
  1217. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1218. end;
  1219. end;
  1220. end;
  1221. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1222. begin
  1223. Result := False;
  1224. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1225. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1226. begin
  1227. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1228. taicpu(p).opcode := A_MOV;
  1229. Result := True;
  1230. end;
  1231. end;
  1232. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1233. var
  1234. p: taicpu absolute hp;
  1235. i: Integer;
  1236. begin
  1237. Result := False;
  1238. if not assigned(hp) or
  1239. (hp.typ <> ait_instruction) then
  1240. Exit;
  1241. // p := taicpu(hp);
  1242. Prefetch(insprop[p.opcode]);
  1243. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1244. with insprop[p.opcode] do
  1245. begin
  1246. case getsubreg(reg) of
  1247. R_SUBW,R_SUBD,R_SUBQ:
  1248. Result:=
  1249. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1250. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1251. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1252. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1253. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1254. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1255. R_SUBFLAGCARRY:
  1256. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1257. R_SUBFLAGPARITY:
  1258. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1259. R_SUBFLAGAUXILIARY:
  1260. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1261. R_SUBFLAGZERO:
  1262. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1263. R_SUBFLAGSIGN:
  1264. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1265. R_SUBFLAGOVERFLOW:
  1266. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1267. R_SUBFLAGINTERRUPT:
  1268. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1269. R_SUBFLAGDIRECTION:
  1270. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1271. else
  1272. begin
  1273. writeln(getsubreg(reg));
  1274. internalerror(2017050501);
  1275. end;
  1276. end;
  1277. exit;
  1278. end;
  1279. { Handle special cases first }
  1280. case p.opcode of
  1281. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1282. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1283. begin
  1284. Result :=
  1285. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1286. (p.oper[1]^.typ = top_reg) and
  1287. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1288. (
  1289. (p.oper[0]^.typ = top_const) or
  1290. (
  1291. (p.oper[0]^.typ = top_reg) and
  1292. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1293. ) or (
  1294. (p.oper[0]^.typ = top_ref) and
  1295. not RegInRef(reg,p.oper[0]^.ref^)
  1296. )
  1297. );
  1298. end;
  1299. A_MUL, A_IMUL:
  1300. Result :=
  1301. (
  1302. (p.ops=3) and { IMUL only }
  1303. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1304. (
  1305. (
  1306. (p.oper[1]^.typ=top_reg) and
  1307. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1308. ) or (
  1309. (p.oper[1]^.typ=top_ref) and
  1310. not RegInRef(reg,p.oper[1]^.ref^)
  1311. )
  1312. )
  1313. ) or (
  1314. (
  1315. (p.ops=1) and
  1316. (
  1317. (
  1318. (
  1319. (p.oper[0]^.typ=top_reg) and
  1320. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1321. )
  1322. ) or (
  1323. (p.oper[0]^.typ=top_ref) and
  1324. not RegInRef(reg,p.oper[0]^.ref^)
  1325. )
  1326. ) and (
  1327. (
  1328. (p.opsize=S_B) and
  1329. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1330. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1331. ) or (
  1332. (p.opsize=S_W) and
  1333. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1334. ) or (
  1335. (p.opsize=S_L) and
  1336. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1337. {$ifdef x86_64}
  1338. ) or (
  1339. (p.opsize=S_Q) and
  1340. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1341. {$endif x86_64}
  1342. )
  1343. )
  1344. )
  1345. );
  1346. A_CBW:
  1347. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1348. {$ifndef x86_64}
  1349. A_LDS:
  1350. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1351. A_LES:
  1352. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1353. {$endif not x86_64}
  1354. A_LFS:
  1355. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1356. A_LGS:
  1357. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1358. A_LSS:
  1359. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1360. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1361. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1362. A_LODSB:
  1363. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1364. A_LODSW:
  1365. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1366. {$ifdef x86_64}
  1367. A_LODSQ:
  1368. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1369. {$endif x86_64}
  1370. A_LODSD:
  1371. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1372. A_FSTSW, A_FNSTSW:
  1373. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1374. else
  1375. begin
  1376. with insprop[p.opcode] do
  1377. begin
  1378. if (
  1379. { xor %reg,%reg etc. is classed as a new value }
  1380. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1381. MatchOpType(p, top_reg, top_reg) and
  1382. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1383. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1384. ) then
  1385. begin
  1386. Result := True;
  1387. Exit;
  1388. end;
  1389. { Make sure the entire register is overwritten }
  1390. if (getregtype(reg) = R_INTREGISTER) then
  1391. begin
  1392. if (p.ops > 0) then
  1393. begin
  1394. if RegInOp(reg, p.oper[0]^) then
  1395. begin
  1396. if (p.oper[0]^.typ = top_ref) then
  1397. begin
  1398. if RegInRef(reg, p.oper[0]^.ref^) then
  1399. begin
  1400. Result := False;
  1401. Exit;
  1402. end;
  1403. end
  1404. else if (p.oper[0]^.typ = top_reg) then
  1405. begin
  1406. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1407. begin
  1408. Result := False;
  1409. Exit;
  1410. end
  1411. else if ([Ch_WOp1]*Ch<>[]) then
  1412. begin
  1413. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1414. Result := True
  1415. else
  1416. begin
  1417. Result := False;
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. end;
  1423. if (p.ops > 1) then
  1424. begin
  1425. if RegInOp(reg, p.oper[1]^) then
  1426. begin
  1427. if (p.oper[1]^.typ = top_ref) then
  1428. begin
  1429. if RegInRef(reg, p.oper[1]^.ref^) then
  1430. begin
  1431. Result := False;
  1432. Exit;
  1433. end;
  1434. end
  1435. else if (p.oper[1]^.typ = top_reg) then
  1436. begin
  1437. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1438. begin
  1439. Result := False;
  1440. Exit;
  1441. end
  1442. else if ([Ch_WOp2]*Ch<>[]) then
  1443. begin
  1444. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1445. Result := True
  1446. else
  1447. begin
  1448. Result := False;
  1449. Exit;
  1450. end;
  1451. end;
  1452. end;
  1453. end;
  1454. if (p.ops > 2) then
  1455. begin
  1456. if RegInOp(reg, p.oper[2]^) then
  1457. begin
  1458. if (p.oper[2]^.typ = top_ref) then
  1459. begin
  1460. if RegInRef(reg, p.oper[2]^.ref^) then
  1461. begin
  1462. Result := False;
  1463. Exit;
  1464. end;
  1465. end
  1466. else if (p.oper[2]^.typ = top_reg) then
  1467. begin
  1468. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1469. begin
  1470. Result := False;
  1471. Exit;
  1472. end
  1473. else if ([Ch_WOp3]*Ch<>[]) then
  1474. begin
  1475. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1476. Result := True
  1477. else
  1478. begin
  1479. Result := False;
  1480. Exit;
  1481. end;
  1482. end;
  1483. end;
  1484. end;
  1485. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1486. begin
  1487. if (p.oper[3]^.typ = top_ref) then
  1488. begin
  1489. if RegInRef(reg, p.oper[3]^.ref^) then
  1490. begin
  1491. Result := False;
  1492. Exit;
  1493. end;
  1494. end
  1495. else if (p.oper[3]^.typ = top_reg) then
  1496. begin
  1497. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1498. begin
  1499. Result := False;
  1500. Exit;
  1501. end
  1502. else if ([Ch_WOp4]*Ch<>[]) then
  1503. begin
  1504. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1505. Result := True
  1506. else
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end;
  1511. end;
  1512. end;
  1513. end;
  1514. end;
  1515. end;
  1516. end;
  1517. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1518. case getsupreg(reg) of
  1519. RS_EAX:
  1520. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1521. begin
  1522. Result := True;
  1523. Exit;
  1524. end;
  1525. RS_ECX:
  1526. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1527. begin
  1528. Result := True;
  1529. Exit;
  1530. end;
  1531. RS_EDX:
  1532. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1533. begin
  1534. Result := True;
  1535. Exit;
  1536. end;
  1537. RS_EBX:
  1538. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1539. begin
  1540. Result := True;
  1541. Exit;
  1542. end;
  1543. RS_ESP:
  1544. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1545. begin
  1546. Result := True;
  1547. Exit;
  1548. end;
  1549. RS_EBP:
  1550. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1551. begin
  1552. Result := True;
  1553. Exit;
  1554. end;
  1555. RS_ESI:
  1556. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1557. begin
  1558. Result := True;
  1559. Exit;
  1560. end;
  1561. RS_EDI:
  1562. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1563. begin
  1564. Result := True;
  1565. Exit;
  1566. end;
  1567. else
  1568. ;
  1569. end;
  1570. end;
  1571. end;
  1572. end;
  1573. end;
  1574. end;
  1575. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1576. var
  1577. hp2,hp3 : tai;
  1578. begin
  1579. { some x86-64 issue a NOP before the real exit code }
  1580. if MatchInstruction(p,A_NOP,[]) then
  1581. GetNextInstruction(p,p);
  1582. result:=assigned(p) and (p.typ=ait_instruction) and
  1583. ((taicpu(p).opcode = A_RET) or
  1584. ((taicpu(p).opcode=A_LEAVE) and
  1585. GetNextInstruction(p,hp2) and
  1586. MatchInstruction(hp2,A_RET,[S_NO])
  1587. ) or
  1588. (((taicpu(p).opcode=A_LEA) and
  1589. MatchOpType(taicpu(p),top_ref,top_reg) and
  1590. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1591. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1592. ) and
  1593. GetNextInstruction(p,hp2) and
  1594. MatchInstruction(hp2,A_RET,[S_NO])
  1595. ) or
  1596. ((((taicpu(p).opcode=A_MOV) and
  1597. MatchOpType(taicpu(p),top_reg,top_reg) and
  1598. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1599. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1600. ((taicpu(p).opcode=A_LEA) and
  1601. MatchOpType(taicpu(p),top_ref,top_reg) and
  1602. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1603. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1604. )
  1605. ) and
  1606. GetNextInstruction(p,hp2) and
  1607. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1608. MatchOpType(taicpu(hp2),top_reg) and
  1609. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1610. GetNextInstruction(hp2,hp3) and
  1611. MatchInstruction(hp3,A_RET,[S_NO])
  1612. )
  1613. );
  1614. end;
  1615. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1616. begin
  1617. isFoldableArithOp := False;
  1618. case hp1.opcode of
  1619. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1620. isFoldableArithOp :=
  1621. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1622. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1623. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1624. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1625. (taicpu(hp1).oper[1]^.reg = reg);
  1626. A_INC,A_DEC,A_NEG,A_NOT:
  1627. isFoldableArithOp :=
  1628. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1629. (taicpu(hp1).oper[0]^.reg = reg);
  1630. else
  1631. ;
  1632. end;
  1633. end;
  1634. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1635. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1636. var
  1637. hp2: tai;
  1638. begin
  1639. hp2 := p;
  1640. repeat
  1641. hp2 := tai(hp2.previous);
  1642. if assigned(hp2) and
  1643. (hp2.typ = ait_regalloc) and
  1644. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1645. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1646. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1647. begin
  1648. RemoveInstruction(hp2);
  1649. break;
  1650. end;
  1651. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1652. end;
  1653. begin
  1654. case current_procinfo.procdef.returndef.typ of
  1655. arraydef,recorddef,pointerdef,
  1656. stringdef,enumdef,procdef,objectdef,errordef,
  1657. filedef,setdef,procvardef,
  1658. classrefdef,forwarddef:
  1659. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1660. orddef:
  1661. if current_procinfo.procdef.returndef.size <> 0 then
  1662. begin
  1663. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1664. { for int64/qword }
  1665. if current_procinfo.procdef.returndef.size = 8 then
  1666. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1667. end;
  1668. else
  1669. ;
  1670. end;
  1671. end;
  1672. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1673. var
  1674. hp1,hp2 : tai;
  1675. begin
  1676. result:=false;
  1677. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1678. begin
  1679. { vmova* reg1,reg1
  1680. =>
  1681. <nop> }
  1682. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1683. begin
  1684. RemoveCurrentP(p);
  1685. result:=true;
  1686. exit;
  1687. end
  1688. else if GetNextInstruction(p,hp1) then
  1689. begin
  1690. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1691. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1692. begin
  1693. { vmova* reg1,reg2
  1694. vmova* reg2,reg3
  1695. dealloc reg2
  1696. =>
  1697. vmova* reg1,reg3 }
  1698. TransferUsedRegs(TmpUsedRegs);
  1699. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1700. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1701. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1702. begin
  1703. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1704. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1705. RemoveInstruction(hp1);
  1706. result:=true;
  1707. exit;
  1708. end
  1709. { special case:
  1710. vmova* reg1,<op>
  1711. vmova* <op>,reg1
  1712. =>
  1713. vmova* reg1,<op> }
  1714. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1715. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1716. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1717. ) then
  1718. begin
  1719. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1720. RemoveInstruction(hp1);
  1721. result:=true;
  1722. exit;
  1723. end
  1724. end
  1725. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1726. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1727. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1728. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1729. ) and
  1730. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1731. begin
  1732. { vmova* reg1,reg2
  1733. vmovs* reg2,<op>
  1734. dealloc reg2
  1735. =>
  1736. vmovs* reg1,reg3 }
  1737. TransferUsedRegs(TmpUsedRegs);
  1738. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1739. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1740. begin
  1741. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1742. taicpu(p).opcode:=taicpu(hp1).opcode;
  1743. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1744. RemoveInstruction(hp1);
  1745. result:=true;
  1746. exit;
  1747. end
  1748. end;
  1749. end;
  1750. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1751. begin
  1752. if MatchInstruction(hp1,[A_VFMADDPD,
  1753. A_VFMADD132PD,
  1754. A_VFMADD132PS,
  1755. A_VFMADD132SD,
  1756. A_VFMADD132SS,
  1757. A_VFMADD213PD,
  1758. A_VFMADD213PS,
  1759. A_VFMADD213SD,
  1760. A_VFMADD213SS,
  1761. A_VFMADD231PD,
  1762. A_VFMADD231PS,
  1763. A_VFMADD231SD,
  1764. A_VFMADD231SS,
  1765. A_VFMADDSUB132PD,
  1766. A_VFMADDSUB132PS,
  1767. A_VFMADDSUB213PD,
  1768. A_VFMADDSUB213PS,
  1769. A_VFMADDSUB231PD,
  1770. A_VFMADDSUB231PS,
  1771. A_VFMSUB132PD,
  1772. A_VFMSUB132PS,
  1773. A_VFMSUB132SD,
  1774. A_VFMSUB132SS,
  1775. A_VFMSUB213PD,
  1776. A_VFMSUB213PS,
  1777. A_VFMSUB213SD,
  1778. A_VFMSUB213SS,
  1779. A_VFMSUB231PD,
  1780. A_VFMSUB231PS,
  1781. A_VFMSUB231SD,
  1782. A_VFMSUB231SS,
  1783. A_VFMSUBADD132PD,
  1784. A_VFMSUBADD132PS,
  1785. A_VFMSUBADD213PD,
  1786. A_VFMSUBADD213PS,
  1787. A_VFMSUBADD231PD,
  1788. A_VFMSUBADD231PS,
  1789. A_VFNMADD132PD,
  1790. A_VFNMADD132PS,
  1791. A_VFNMADD132SD,
  1792. A_VFNMADD132SS,
  1793. A_VFNMADD213PD,
  1794. A_VFNMADD213PS,
  1795. A_VFNMADD213SD,
  1796. A_VFNMADD213SS,
  1797. A_VFNMADD231PD,
  1798. A_VFNMADD231PS,
  1799. A_VFNMADD231SD,
  1800. A_VFNMADD231SS,
  1801. A_VFNMSUB132PD,
  1802. A_VFNMSUB132PS,
  1803. A_VFNMSUB132SD,
  1804. A_VFNMSUB132SS,
  1805. A_VFNMSUB213PD,
  1806. A_VFNMSUB213PS,
  1807. A_VFNMSUB213SD,
  1808. A_VFNMSUB213SS,
  1809. A_VFNMSUB231PD,
  1810. A_VFNMSUB231PS,
  1811. A_VFNMSUB231SD,
  1812. A_VFNMSUB231SS],[S_NO]) and
  1813. { we mix single and double opperations here because we assume that the compiler
  1814. generates vmovapd only after double operations and vmovaps only after single operations }
  1815. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1816. GetNextInstruction(hp1,hp2) and
  1817. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1818. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1819. begin
  1820. TransferUsedRegs(TmpUsedRegs);
  1821. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1822. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1823. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1824. begin
  1825. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1826. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1827. RemoveInstruction(hp2);
  1828. end;
  1829. end
  1830. else if (hp1.typ = ait_instruction) and
  1831. GetNextInstruction(hp1, hp2) and
  1832. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1833. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1834. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1835. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1836. (((taicpu(p).opcode=A_MOVAPS) and
  1837. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1838. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1839. ((taicpu(p).opcode=A_MOVAPD) and
  1840. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1841. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1842. ) then
  1843. { change
  1844. movapX reg,reg2
  1845. addsX/subsX/... reg3, reg2
  1846. movapX reg2,reg
  1847. to
  1848. addsX/subsX/... reg3,reg
  1849. }
  1850. begin
  1851. TransferUsedRegs(TmpUsedRegs);
  1852. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1853. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1854. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1855. begin
  1856. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1857. debug_op2str(taicpu(p).opcode)+' '+
  1858. debug_op2str(taicpu(hp1).opcode)+' '+
  1859. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1860. { we cannot eliminate the first move if
  1861. the operations uses the same register for source and dest }
  1862. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1863. RemoveCurrentP(p, nil);
  1864. p:=hp1;
  1865. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1866. RemoveInstruction(hp2);
  1867. result:=true;
  1868. end;
  1869. end;
  1870. end;
  1871. end;
  1872. end;
  1873. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1874. var
  1875. hp1 : tai;
  1876. begin
  1877. result:=false;
  1878. { replace
  1879. V<Op>X %mreg1,%mreg2,%mreg3
  1880. VMovX %mreg3,%mreg4
  1881. dealloc %mreg3
  1882. by
  1883. V<Op>X %mreg1,%mreg2,%mreg4
  1884. ?
  1885. }
  1886. if GetNextInstruction(p,hp1) and
  1887. { we mix single and double operations here because we assume that the compiler
  1888. generates vmovapd only after double operations and vmovaps only after single operations }
  1889. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1890. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1891. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1892. begin
  1893. TransferUsedRegs(TmpUsedRegs);
  1894. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1895. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1896. begin
  1897. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1898. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1899. RemoveInstruction(hp1);
  1900. result:=true;
  1901. end;
  1902. end;
  1903. end;
  1904. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1905. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1906. begin
  1907. Result := False;
  1908. { For safety reasons, only check for exact register matches }
  1909. { Check base register }
  1910. if (ref.base = AOldReg) then
  1911. begin
  1912. ref.base := ANewReg;
  1913. Result := True;
  1914. end;
  1915. { Check index register }
  1916. if (ref.index = AOldReg) then
  1917. begin
  1918. ref.index := ANewReg;
  1919. Result := True;
  1920. end;
  1921. end;
  1922. { Replaces all references to AOldReg in an operand to ANewReg }
  1923. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1924. var
  1925. OldSupReg, NewSupReg: TSuperRegister;
  1926. OldSubReg, NewSubReg: TSubRegister;
  1927. OldRegType: TRegisterType;
  1928. ThisOper: POper;
  1929. begin
  1930. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1931. Result := False;
  1932. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1933. InternalError(2020011801);
  1934. OldSupReg := getsupreg(AOldReg);
  1935. OldSubReg := getsubreg(AOldReg);
  1936. OldRegType := getregtype(AOldReg);
  1937. NewSupReg := getsupreg(ANewReg);
  1938. NewSubReg := getsubreg(ANewReg);
  1939. if OldRegType <> getregtype(ANewReg) then
  1940. InternalError(2020011802);
  1941. if OldSubReg <> NewSubReg then
  1942. InternalError(2020011803);
  1943. case ThisOper^.typ of
  1944. top_reg:
  1945. if (
  1946. (ThisOper^.reg = AOldReg) or
  1947. (
  1948. (OldRegType = R_INTREGISTER) and
  1949. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1950. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1951. (
  1952. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1953. {$ifndef x86_64}
  1954. and (
  1955. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1956. don't have an 8-bit representation }
  1957. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1958. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1959. )
  1960. {$endif x86_64}
  1961. )
  1962. )
  1963. ) then
  1964. begin
  1965. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1966. Result := True;
  1967. end;
  1968. top_ref:
  1969. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1970. Result := True;
  1971. else
  1972. ;
  1973. end;
  1974. end;
  1975. { Replaces all references to AOldReg in an instruction to ANewReg }
  1976. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1977. const
  1978. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1979. var
  1980. OperIdx: Integer;
  1981. begin
  1982. Result := False;
  1983. for OperIdx := 0 to p.ops - 1 do
  1984. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1985. { The shift and rotate instructions can only use CL }
  1986. not (
  1987. (OperIdx = 0) and
  1988. { This second condition just helps to avoid unnecessarily
  1989. calling MatchInstruction for 10 different opcodes }
  1990. (p.oper[0]^.reg = NR_CL) and
  1991. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1992. ) then
  1993. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1994. end;
  1995. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1996. begin
  1997. Result :=
  1998. (ref^.index = NR_NO) and
  1999. (
  2000. {$ifdef x86_64}
  2001. (
  2002. (ref^.base = NR_RIP) and
  2003. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2004. ) or
  2005. {$endif x86_64}
  2006. (ref^.base = NR_STACK_POINTER_REG) or
  2007. (ref^.base = current_procinfo.framepointer)
  2008. );
  2009. end;
  2010. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2011. var
  2012. l: asizeint;
  2013. begin
  2014. Result := False;
  2015. { Should have been checked previously }
  2016. if p.opcode <> A_LEA then
  2017. InternalError(2020072501);
  2018. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2019. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2020. not(cs_opt_size in current_settings.optimizerswitches) then
  2021. exit;
  2022. with p.oper[0]^.ref^ do
  2023. begin
  2024. if (base <> p.oper[1]^.reg) or
  2025. (index <> NR_NO) or
  2026. assigned(symbol) then
  2027. exit;
  2028. l:=offset;
  2029. if (l=1) and UseIncDec then
  2030. begin
  2031. p.opcode:=A_INC;
  2032. p.loadreg(0,p.oper[1]^.reg);
  2033. p.ops:=1;
  2034. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2035. end
  2036. else if (l=-1) and UseIncDec then
  2037. begin
  2038. p.opcode:=A_DEC;
  2039. p.loadreg(0,p.oper[1]^.reg);
  2040. p.ops:=1;
  2041. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2042. end
  2043. else
  2044. begin
  2045. if (l<0) and (l<>-2147483648) then
  2046. begin
  2047. p.opcode:=A_SUB;
  2048. p.loadConst(0,-l);
  2049. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2050. end
  2051. else
  2052. begin
  2053. p.opcode:=A_ADD;
  2054. p.loadConst(0,l);
  2055. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2056. end;
  2057. end;
  2058. end;
  2059. Result := True;
  2060. end;
  2061. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2062. var
  2063. CurrentReg, ReplaceReg: TRegister;
  2064. begin
  2065. Result := False;
  2066. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2067. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2068. case hp.opcode of
  2069. A_FSTSW, A_FNSTSW,
  2070. A_IN, A_INS, A_OUT, A_OUTS,
  2071. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2072. { These routines have explicit operands, but they are restricted in
  2073. what they can be (e.g. IN and OUT can only read from AL, AX or
  2074. EAX. }
  2075. Exit;
  2076. A_IMUL:
  2077. begin
  2078. { The 1-operand version writes to implicit registers
  2079. The 2-operand version reads from the first operator, and reads
  2080. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2081. the 3-operand version reads from a register that it doesn't write to
  2082. }
  2083. case hp.ops of
  2084. 1:
  2085. if (
  2086. (
  2087. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2088. ) or
  2089. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2090. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2091. begin
  2092. Result := True;
  2093. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2094. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2095. end;
  2096. 2:
  2097. { Only modify the first parameter }
  2098. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2099. begin
  2100. Result := True;
  2101. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2102. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2103. end;
  2104. 3:
  2105. { Only modify the second parameter }
  2106. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2107. begin
  2108. Result := True;
  2109. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2110. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2111. end;
  2112. else
  2113. InternalError(2020012901);
  2114. end;
  2115. end;
  2116. else
  2117. if (hp.ops > 0) and
  2118. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2119. begin
  2120. Result := True;
  2121. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2122. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2123. end;
  2124. end;
  2125. end;
  2126. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2127. var
  2128. hp1, hp2, hp3: tai;
  2129. DoOptimisation, TempBool: Boolean;
  2130. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2131. begin
  2132. if taicpu(hp1).opcode = signed_movop then
  2133. begin
  2134. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2135. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2136. end
  2137. else
  2138. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2139. end;
  2140. var
  2141. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2142. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2143. NewSize: topsize;
  2144. CurrentReg, ActiveReg: TRegister;
  2145. SourceRef, TargetRef: TReference;
  2146. MovAligned, MovUnaligned: TAsmOp;
  2147. begin
  2148. Result:=false;
  2149. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2150. { remove mov reg1,reg1? }
  2151. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2152. then
  2153. begin
  2154. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2155. { take care of the register (de)allocs following p }
  2156. RemoveCurrentP(p, hp1);
  2157. Result:=true;
  2158. exit;
  2159. end;
  2160. { All the next optimisations require a next instruction }
  2161. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2162. Exit;
  2163. { Look for:
  2164. mov %reg1,%reg2
  2165. ??? %reg2,r/m
  2166. Change to:
  2167. mov %reg1,%reg2
  2168. ??? %reg1,r/m
  2169. }
  2170. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2171. begin
  2172. CurrentReg := taicpu(p).oper[1]^.reg;
  2173. if RegReadByInstruction(CurrentReg, hp1) and
  2174. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2175. begin
  2176. TransferUsedRegs(TmpUsedRegs);
  2177. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2178. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2179. { Just in case something didn't get modified (e.g. an
  2180. implicit register) }
  2181. not RegReadByInstruction(CurrentReg, hp1) then
  2182. begin
  2183. { We can remove the original MOV }
  2184. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2185. RemoveCurrentp(p, hp1);
  2186. { UsedRegs got updated by RemoveCurrentp }
  2187. Result := True;
  2188. Exit;
  2189. end;
  2190. { If we know a MOV instruction has become a null operation, we might as well
  2191. get rid of it now to save time. }
  2192. if (taicpu(hp1).opcode = A_MOV) and
  2193. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2194. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2195. { Just being a register is enough to confirm it's a null operation }
  2196. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2197. begin
  2198. Result := True;
  2199. { Speed-up to reduce a pipeline stall... if we had something like...
  2200. movl %eax,%edx
  2201. movw %dx,%ax
  2202. ... the second instruction would change to movw %ax,%ax, but
  2203. given that it is now %ax that's active rather than %eax,
  2204. penalties might occur due to a partial register write, so instead,
  2205. change it to a MOVZX instruction when optimising for speed.
  2206. }
  2207. if not (cs_opt_size in current_settings.optimizerswitches) and
  2208. IsMOVZXAcceptable and
  2209. (taicpu(hp1).opsize < taicpu(p).opsize)
  2210. {$ifdef x86_64}
  2211. { operations already implicitly set the upper 64 bits to zero }
  2212. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2213. {$endif x86_64}
  2214. then
  2215. begin
  2216. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2217. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2218. case taicpu(p).opsize of
  2219. S_W:
  2220. if taicpu(hp1).opsize = S_B then
  2221. taicpu(hp1).opsize := S_BL
  2222. else
  2223. InternalError(2020012911);
  2224. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2225. case taicpu(hp1).opsize of
  2226. S_B:
  2227. taicpu(hp1).opsize := S_BL;
  2228. S_W:
  2229. taicpu(hp1).opsize := S_WL;
  2230. else
  2231. InternalError(2020012912);
  2232. end;
  2233. else
  2234. InternalError(2020012910);
  2235. end;
  2236. taicpu(hp1).opcode := A_MOVZX;
  2237. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2238. end
  2239. else
  2240. begin
  2241. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2242. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2243. RemoveInstruction(hp1);
  2244. { The instruction after what was hp1 is now the immediate next instruction,
  2245. so we can continue to make optimisations if it's present }
  2246. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2247. Exit;
  2248. hp1 := hp2;
  2249. end;
  2250. end;
  2251. end;
  2252. end;
  2253. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2254. overwrites the original destination register. e.g.
  2255. movl ###,%reg2d
  2256. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2257. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2258. }
  2259. if (taicpu(p).oper[1]^.typ = top_reg) and
  2260. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2261. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2262. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2263. begin
  2264. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2265. begin
  2266. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2267. case taicpu(p).oper[0]^.typ of
  2268. top_const:
  2269. { We have something like:
  2270. movb $x, %regb
  2271. movzbl %regb,%regd
  2272. Change to:
  2273. movl $x, %regd
  2274. }
  2275. begin
  2276. case taicpu(hp1).opsize of
  2277. S_BW:
  2278. begin
  2279. convert_mov_value(A_MOVSX, $FF);
  2280. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2281. taicpu(p).opsize := S_W;
  2282. end;
  2283. S_BL:
  2284. begin
  2285. convert_mov_value(A_MOVSX, $FF);
  2286. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2287. taicpu(p).opsize := S_L;
  2288. end;
  2289. S_WL:
  2290. begin
  2291. convert_mov_value(A_MOVSX, $FFFF);
  2292. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2293. taicpu(p).opsize := S_L;
  2294. end;
  2295. {$ifdef x86_64}
  2296. S_BQ:
  2297. begin
  2298. convert_mov_value(A_MOVSX, $FF);
  2299. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2300. taicpu(p).opsize := S_Q;
  2301. end;
  2302. S_WQ:
  2303. begin
  2304. convert_mov_value(A_MOVSX, $FFFF);
  2305. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2306. taicpu(p).opsize := S_Q;
  2307. end;
  2308. S_LQ:
  2309. begin
  2310. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2311. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2312. taicpu(p).opsize := S_Q;
  2313. end;
  2314. {$endif x86_64}
  2315. else
  2316. { If hp1 was a MOV instruction, it should have been
  2317. optimised already }
  2318. InternalError(2020021001);
  2319. end;
  2320. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2321. RemoveInstruction(hp1);
  2322. Result := True;
  2323. Exit;
  2324. end;
  2325. top_ref:
  2326. { We have something like:
  2327. movb mem, %regb
  2328. movzbl %regb,%regd
  2329. Change to:
  2330. movzbl mem, %regd
  2331. }
  2332. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2333. begin
  2334. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2335. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2336. RemoveCurrentP(p, hp1);
  2337. Result:=True;
  2338. Exit;
  2339. end;
  2340. else
  2341. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2342. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2343. Exit;
  2344. end;
  2345. end
  2346. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2347. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2348. optimised }
  2349. else
  2350. begin
  2351. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2352. RemoveCurrentP(p, hp1);
  2353. Result := True;
  2354. Exit;
  2355. end;
  2356. end;
  2357. if (taicpu(hp1).opcode = A_AND) and
  2358. (taicpu(p).oper[1]^.typ = top_reg) and
  2359. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2360. begin
  2361. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2362. begin
  2363. case taicpu(p).opsize of
  2364. S_L:
  2365. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2366. begin
  2367. { Optimize out:
  2368. mov x, %reg
  2369. and ffffffffh, %reg
  2370. }
  2371. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2372. RemoveInstruction(hp1);
  2373. Result:=true;
  2374. exit;
  2375. end;
  2376. S_Q: { TODO: Confirm if this is even possible }
  2377. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2378. begin
  2379. { Optimize out:
  2380. mov x, %reg
  2381. and ffffffffffffffffh, %reg
  2382. }
  2383. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2384. RemoveInstruction(hp1);
  2385. Result:=true;
  2386. exit;
  2387. end;
  2388. else
  2389. ;
  2390. end;
  2391. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2392. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2393. GetNextInstruction(hp1,hp2) and
  2394. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2395. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2396. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2397. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2398. GetNextInstruction(hp2,hp3) and
  2399. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2400. (taicpu(hp3).condition in [C_E,C_NE]) then
  2401. begin
  2402. TransferUsedRegs(TmpUsedRegs);
  2403. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2404. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2405. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2406. begin
  2407. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2408. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2409. taicpu(hp1).opcode:=A_TEST;
  2410. RemoveInstruction(hp2);
  2411. RemoveCurrentP(p, hp1);
  2412. Result:=true;
  2413. exit;
  2414. end;
  2415. end;
  2416. end
  2417. else if IsMOVZXAcceptable and
  2418. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2419. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2420. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2421. then
  2422. begin
  2423. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2424. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2425. case taicpu(p).opsize of
  2426. S_B:
  2427. if (taicpu(hp1).oper[0]^.val = $ff) then
  2428. begin
  2429. { Convert:
  2430. movb x, %regl movb x, %regl
  2431. andw ffh, %regw andl ffh, %regd
  2432. To:
  2433. movzbw x, %regd movzbl x, %regd
  2434. (Identical registers, just different sizes)
  2435. }
  2436. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2437. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2438. case taicpu(hp1).opsize of
  2439. S_W: NewSize := S_BW;
  2440. S_L: NewSize := S_BL;
  2441. {$ifdef x86_64}
  2442. S_Q: NewSize := S_BQ;
  2443. {$endif x86_64}
  2444. else
  2445. InternalError(2018011510);
  2446. end;
  2447. end
  2448. else
  2449. NewSize := S_NO;
  2450. S_W:
  2451. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2452. begin
  2453. { Convert:
  2454. movw x, %regw
  2455. andl ffffh, %regd
  2456. To:
  2457. movzwl x, %regd
  2458. (Identical registers, just different sizes)
  2459. }
  2460. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2461. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2462. case taicpu(hp1).opsize of
  2463. S_L: NewSize := S_WL;
  2464. {$ifdef x86_64}
  2465. S_Q: NewSize := S_WQ;
  2466. {$endif x86_64}
  2467. else
  2468. InternalError(2018011511);
  2469. end;
  2470. end
  2471. else
  2472. NewSize := S_NO;
  2473. else
  2474. NewSize := S_NO;
  2475. end;
  2476. if NewSize <> S_NO then
  2477. begin
  2478. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2479. { The actual optimization }
  2480. taicpu(p).opcode := A_MOVZX;
  2481. taicpu(p).changeopsize(NewSize);
  2482. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2483. { Safeguard if "and" is followed by a conditional command }
  2484. TransferUsedRegs(TmpUsedRegs);
  2485. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2486. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2487. begin
  2488. { At this point, the "and" command is effectively equivalent to
  2489. "test %reg,%reg". This will be handled separately by the
  2490. Peephole Optimizer. [Kit] }
  2491. DebugMsg(SPeepholeOptimization + PreMessage +
  2492. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2493. end
  2494. else
  2495. begin
  2496. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2497. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2498. RemoveInstruction(hp1);
  2499. end;
  2500. Result := True;
  2501. Exit;
  2502. end;
  2503. end;
  2504. end;
  2505. if (taicpu(hp1).opcode = A_OR) and
  2506. (taicpu(p).oper[1]^.typ = top_reg) and
  2507. MatchOperand(taicpu(p).oper[0]^, 0) and
  2508. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2509. begin
  2510. { mov 0, %reg
  2511. or ###,%reg
  2512. Change to (only if the flags are not used):
  2513. mov ###,%reg
  2514. }
  2515. TransferUsedRegs(TmpUsedRegs);
  2516. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2517. DoOptimisation := True;
  2518. { Even if the flags are used, we might be able to do the optimisation
  2519. if the conditions are predictable }
  2520. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2521. begin
  2522. { Only perform if ### = %reg (the same register) or equal to 0,
  2523. so %reg is guaranteed to still have a value of zero }
  2524. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2525. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2526. begin
  2527. hp2 := hp1;
  2528. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2529. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2530. GetNextInstruction(hp2, hp3) do
  2531. begin
  2532. { Don't continue modifying if the flags state is getting changed }
  2533. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2534. Break;
  2535. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2536. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2537. begin
  2538. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2539. begin
  2540. { Condition is always true }
  2541. case taicpu(hp3).opcode of
  2542. A_Jcc:
  2543. begin
  2544. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2545. { Check for jump shortcuts before we destroy the condition }
  2546. DoJumpOptimizations(hp3, TempBool);
  2547. MakeUnconditional(taicpu(hp3));
  2548. Result := True;
  2549. end;
  2550. A_CMOVcc:
  2551. begin
  2552. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2553. taicpu(hp3).opcode := A_MOV;
  2554. taicpu(hp3).condition := C_None;
  2555. Result := True;
  2556. end;
  2557. A_SETcc:
  2558. begin
  2559. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2560. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2561. taicpu(hp3).opcode := A_MOV;
  2562. taicpu(hp3).ops := 2;
  2563. taicpu(hp3).condition := C_None;
  2564. taicpu(hp3).opsize := S_B;
  2565. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2566. taicpu(hp3).loadconst(0, 1);
  2567. Result := True;
  2568. end;
  2569. else
  2570. InternalError(2021090701);
  2571. end;
  2572. end
  2573. 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
  2574. begin
  2575. { Condition is always false }
  2576. case taicpu(hp3).opcode of
  2577. A_Jcc:
  2578. begin
  2579. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2580. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2581. RemoveInstruction(hp3);
  2582. Result := True;
  2583. { Since hp3 was deleted, hp2 must not be updated }
  2584. Continue;
  2585. end;
  2586. A_CMOVcc:
  2587. begin
  2588. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2589. RemoveInstruction(hp3);
  2590. Result := True;
  2591. { Since hp3 was deleted, hp2 must not be updated }
  2592. Continue;
  2593. end;
  2594. A_SETcc:
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2597. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2598. taicpu(hp3).opcode := A_MOV;
  2599. taicpu(hp3).ops := 2;
  2600. taicpu(hp3).condition := C_None;
  2601. taicpu(hp3).opsize := S_B;
  2602. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2603. taicpu(hp3).loadconst(0, 0);
  2604. Result := True;
  2605. end;
  2606. else
  2607. InternalError(2021090702);
  2608. end;
  2609. end
  2610. else
  2611. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2612. DoOptimisation := False;
  2613. end;
  2614. hp2 := hp3;
  2615. end;
  2616. { Flags are still in use - don't optimise }
  2617. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2618. DoOptimisation := False;
  2619. end
  2620. else
  2621. DoOptimisation := False;
  2622. end;
  2623. if DoOptimisation then
  2624. begin
  2625. {$ifdef x86_64}
  2626. { OR only supports 32-bit sign-extended constants for 64-bit
  2627. instructions, so compensate for this if the constant is
  2628. encoded as a value greater than or equal to 2^31 }
  2629. if (taicpu(hp1).opsize = S_Q) and
  2630. (taicpu(hp1).oper[0]^.typ = top_const) and
  2631. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2632. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2633. {$endif x86_64}
  2634. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2635. taicpu(hp1).opcode := A_MOV;
  2636. RemoveCurrentP(p, hp1);
  2637. Result := True;
  2638. Exit;
  2639. end;
  2640. end;
  2641. { Next instruction is also a MOV ? }
  2642. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2643. begin
  2644. if (taicpu(p).oper[1]^.typ = top_reg) and
  2645. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2646. begin
  2647. CurrentReg := taicpu(p).oper[1]^.reg;
  2648. TransferUsedRegs(TmpUsedRegs);
  2649. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2650. { we have
  2651. mov x, %treg
  2652. mov %treg, y
  2653. }
  2654. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2655. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2656. { we've got
  2657. mov x, %treg
  2658. mov %treg, y
  2659. with %treg is not used after }
  2660. case taicpu(p).oper[0]^.typ Of
  2661. { top_reg is covered by DeepMOVOpt }
  2662. top_const:
  2663. begin
  2664. { change
  2665. mov const, %treg
  2666. mov %treg, y
  2667. to
  2668. mov const, y
  2669. }
  2670. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2671. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2672. begin
  2673. if taicpu(hp1).oper[1]^.typ=top_reg then
  2674. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2675. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2676. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2677. RemoveInstruction(hp1);
  2678. Result:=true;
  2679. Exit;
  2680. end;
  2681. end;
  2682. top_ref:
  2683. case taicpu(hp1).oper[1]^.typ of
  2684. top_reg:
  2685. begin
  2686. { change
  2687. mov mem, %treg
  2688. mov %treg, %reg
  2689. to
  2690. mov mem, %reg"
  2691. }
  2692. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2693. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2694. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2695. RemoveInstruction(hp1);
  2696. Result:=true;
  2697. Exit;
  2698. end;
  2699. top_ref:
  2700. begin
  2701. {$ifdef x86_64}
  2702. { Look for the following to simplify:
  2703. mov x(mem1), %reg
  2704. mov %reg, y(mem2)
  2705. mov x+8(mem1), %reg
  2706. mov %reg, y+8(mem2)
  2707. Change to:
  2708. movdqu x(mem1), %xmmreg
  2709. movdqu %xmmreg, y(mem2)
  2710. }
  2711. SourceRef := taicpu(p).oper[0]^.ref^;
  2712. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2713. if (taicpu(p).opsize = S_Q) and
  2714. GetNextInstruction(hp1, hp2) and
  2715. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2716. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2717. begin
  2718. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2719. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2720. Inc(SourceRef.offset, 8);
  2721. if UseAVX then
  2722. begin
  2723. MovAligned := A_VMOVDQA;
  2724. MovUnaligned := A_VMOVDQU;
  2725. end
  2726. else
  2727. begin
  2728. MovAligned := A_MOVDQA;
  2729. MovUnaligned := A_MOVDQU;
  2730. end;
  2731. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2732. begin
  2733. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2734. Inc(TargetRef.offset, 8);
  2735. if GetNextInstruction(hp2, hp3) and
  2736. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2737. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2738. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2739. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2740. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2741. begin
  2742. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2743. if CurrentReg <> NR_NO then
  2744. begin
  2745. { Remember that the offsets are 8 ahead }
  2746. if ((SourceRef.offset mod 16) = 8) and
  2747. (
  2748. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2749. (SourceRef.base = current_procinfo.framepointer) or
  2750. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2751. ) then
  2752. taicpu(p).opcode := MovAligned
  2753. else
  2754. taicpu(p).opcode := MovUnaligned;
  2755. taicpu(p).opsize := S_XMM;
  2756. taicpu(p).oper[1]^.reg := CurrentReg;
  2757. if ((TargetRef.offset mod 16) = 8) and
  2758. (
  2759. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2760. (TargetRef.base = current_procinfo.framepointer) or
  2761. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2762. ) then
  2763. taicpu(hp1).opcode := MovAligned
  2764. else
  2765. taicpu(hp1).opcode := MovUnaligned;
  2766. taicpu(hp1).opsize := S_XMM;
  2767. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2768. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2769. RemoveInstruction(hp2);
  2770. RemoveInstruction(hp3);
  2771. Result := True;
  2772. Exit;
  2773. end;
  2774. end;
  2775. end
  2776. else
  2777. begin
  2778. { See if the next references are 8 less rather than 8 greater }
  2779. Dec(SourceRef.offset, 16); { -8 the other way }
  2780. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2781. begin
  2782. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2783. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2784. if GetNextInstruction(hp2, hp3) and
  2785. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2786. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2787. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2788. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2789. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2790. begin
  2791. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2792. if CurrentReg <> NR_NO then
  2793. begin
  2794. { hp2 and hp3 are the starting offsets, so mod 0 this time }
  2795. if ((SourceRef.offset mod 16) = 0) and
  2796. (
  2797. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2798. (SourceRef.base = current_procinfo.framepointer) or
  2799. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2800. ) then
  2801. taicpu(hp2).opcode := MovAligned
  2802. else
  2803. taicpu(hp2).opcode := MovUnaligned;
  2804. taicpu(hp2).opsize := S_XMM;
  2805. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2806. if ((TargetRef.offset mod 16) = 0) and
  2807. (
  2808. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2809. (TargetRef.base = current_procinfo.framepointer) or
  2810. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2811. ) then
  2812. taicpu(hp3).opcode := MovAligned
  2813. else
  2814. taicpu(hp3).opcode := MovUnaligned;
  2815. taicpu(hp3).opsize := S_XMM;
  2816. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2817. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2818. RemoveInstruction(hp1);
  2819. RemoveCurrentP(p, hp2);
  2820. Result := True;
  2821. Exit;
  2822. end;
  2823. end;
  2824. end;
  2825. end;
  2826. end;
  2827. {$endif x86_64}
  2828. end;
  2829. else
  2830. { The write target should be a reg or a ref }
  2831. InternalError(2021091601);
  2832. end;
  2833. else
  2834. ;
  2835. end
  2836. else
  2837. { %treg is used afterwards, but all eventualities
  2838. other than the first MOV instruction being a constant
  2839. are covered by DeepMOVOpt, so only check for that }
  2840. if (taicpu(p).oper[0]^.typ = top_const) and
  2841. (
  2842. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2843. not (cs_opt_size in current_settings.optimizerswitches) or
  2844. (taicpu(hp1).opsize = S_B)
  2845. ) and
  2846. (
  2847. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2848. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2849. ) then
  2850. begin
  2851. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2852. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2853. end;
  2854. end;
  2855. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2856. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2857. { mov reg1, mem1 or mov mem1, reg1
  2858. mov mem2, reg2 mov reg2, mem2}
  2859. begin
  2860. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2861. { mov reg1, mem1 or mov mem1, reg1
  2862. mov mem2, reg1 mov reg2, mem1}
  2863. begin
  2864. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2865. { Removes the second statement from
  2866. mov reg1, mem1/reg2
  2867. mov mem1/reg2, reg1 }
  2868. begin
  2869. if taicpu(p).oper[0]^.typ=top_reg then
  2870. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2871. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2872. RemoveInstruction(hp1);
  2873. Result:=true;
  2874. exit;
  2875. end
  2876. else
  2877. begin
  2878. TransferUsedRegs(TmpUsedRegs);
  2879. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2880. if (taicpu(p).oper[1]^.typ = top_ref) and
  2881. { mov reg1, mem1
  2882. mov mem2, reg1 }
  2883. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2884. GetNextInstruction(hp1, hp2) and
  2885. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2886. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2887. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2888. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2889. { change to
  2890. mov reg1, mem1 mov reg1, mem1
  2891. mov mem2, reg1 cmp reg1, mem2
  2892. cmp mem1, reg1
  2893. }
  2894. begin
  2895. RemoveInstruction(hp2);
  2896. taicpu(hp1).opcode := A_CMP;
  2897. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2898. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2899. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2900. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2901. end;
  2902. end;
  2903. end
  2904. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2905. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2906. begin
  2907. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2908. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2909. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2910. end
  2911. else
  2912. begin
  2913. TransferUsedRegs(TmpUsedRegs);
  2914. if GetNextInstruction(hp1, hp2) and
  2915. MatchOpType(taicpu(p),top_ref,top_reg) and
  2916. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2917. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2918. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2919. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2920. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2921. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2922. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2923. { mov mem1, %reg1
  2924. mov %reg1, mem2
  2925. mov mem2, reg2
  2926. to:
  2927. mov mem1, reg2
  2928. mov reg2, mem2}
  2929. begin
  2930. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2931. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2932. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2933. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2934. RemoveInstruction(hp2);
  2935. Result := True;
  2936. end
  2937. {$ifdef i386}
  2938. { this is enabled for i386 only, as the rules to create the reg sets below
  2939. are too complicated for x86-64, so this makes this code too error prone
  2940. on x86-64
  2941. }
  2942. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2943. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2944. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2945. { mov mem1, reg1 mov mem1, reg1
  2946. mov reg1, mem2 mov reg1, mem2
  2947. mov mem2, reg2 mov mem2, reg1
  2948. to: to:
  2949. mov mem1, reg1 mov mem1, reg1
  2950. mov mem1, reg2 mov reg1, mem2
  2951. mov reg1, mem2
  2952. or (if mem1 depends on reg1
  2953. and/or if mem2 depends on reg2)
  2954. to:
  2955. mov mem1, reg1
  2956. mov reg1, mem2
  2957. mov reg1, reg2
  2958. }
  2959. begin
  2960. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2961. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2962. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2963. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2964. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2965. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2966. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2967. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2968. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2969. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2970. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2971. end
  2972. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2973. begin
  2974. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2975. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2976. end
  2977. else
  2978. begin
  2979. RemoveInstruction(hp2);
  2980. end
  2981. {$endif i386}
  2982. ;
  2983. end;
  2984. end
  2985. { movl [mem1],reg1
  2986. movl [mem1],reg2
  2987. to
  2988. movl [mem1],reg1
  2989. movl reg1,reg2
  2990. }
  2991. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2992. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2993. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2994. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2995. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2996. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2997. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2998. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2999. begin
  3000. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3001. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3002. end;
  3003. { movl const1,[mem1]
  3004. movl [mem1],reg1
  3005. to
  3006. movl const1,reg1
  3007. movl reg1,[mem1]
  3008. }
  3009. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3010. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3011. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3012. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3013. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3014. begin
  3015. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3016. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3017. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3018. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3019. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3020. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3021. Result:=true;
  3022. exit;
  3023. end;
  3024. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3025. end;
  3026. { search further than the next instruction for a mov (as long as it's not a jump) }
  3027. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3028. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3029. (taicpu(p).oper[1]^.typ = top_reg) and
  3030. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3031. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3032. begin
  3033. { we work with hp2 here, so hp1 can be still used later on when
  3034. checking for GetNextInstruction_p }
  3035. hp3 := hp1;
  3036. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3037. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3038. { Saves on a large number of dereferences }
  3039. ActiveReg := taicpu(p).oper[1]^.reg;
  3040. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3041. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3042. (hp2.typ=ait_instruction) do
  3043. begin
  3044. case taicpu(hp2).opcode of
  3045. A_MOV:
  3046. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3047. ((taicpu(p).oper[0]^.typ=top_const) or
  3048. ((taicpu(p).oper[0]^.typ=top_reg) and
  3049. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3050. )
  3051. ) then
  3052. begin
  3053. { we have
  3054. mov x, %treg
  3055. mov %treg, y
  3056. }
  3057. TransferUsedRegs(TmpUsedRegs);
  3058. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3059. { We don't need to call UpdateUsedRegs for every instruction between
  3060. p and hp2 because the register we're concerned about will not
  3061. become deallocated (otherwise GetNextInstructionUsingReg would
  3062. have stopped at an earlier instruction). [Kit] }
  3063. TempRegUsed :=
  3064. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3065. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) or
  3066. RegReadByInstruction(ActiveReg, hp1);
  3067. case taicpu(p).oper[0]^.typ Of
  3068. top_reg:
  3069. begin
  3070. { change
  3071. mov %reg, %treg
  3072. mov %treg, y
  3073. to
  3074. mov %reg, y
  3075. }
  3076. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3077. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3078. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  3079. begin
  3080. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3081. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3082. if TempRegUsed then
  3083. begin
  3084. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3085. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3086. { Set the start of the next GetNextInstructionUsingRegCond search
  3087. to start at the entry right before hp2 (which is about to be removed) }
  3088. hp3 := tai(hp2.Previous);
  3089. RemoveInstruction(hp2);
  3090. { See if there's more we can optimise }
  3091. Continue;
  3092. end
  3093. else
  3094. begin
  3095. RemoveInstruction(hp2);
  3096. { We can remove the original MOV too }
  3097. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3098. RemoveCurrentP(p, hp1);
  3099. Result:=true;
  3100. Exit;
  3101. end;
  3102. end
  3103. else
  3104. begin
  3105. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3106. taicpu(hp2).loadReg(0, CurrentReg);
  3107. if TempRegUsed then
  3108. begin
  3109. { Don't remove the first instruction if the temporary register is in use }
  3110. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3111. { No need to set Result to True. If there's another instruction later on
  3112. that can be optimised, it will be detected when the main Pass 1 loop
  3113. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3114. end
  3115. else
  3116. begin
  3117. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3118. RemoveCurrentP(p, hp1);
  3119. Result:=true;
  3120. Exit;
  3121. end;
  3122. end;
  3123. end;
  3124. top_const:
  3125. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3126. begin
  3127. { change
  3128. mov const, %treg
  3129. mov %treg, y
  3130. to
  3131. mov const, y
  3132. }
  3133. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3134. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3135. begin
  3136. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3137. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3138. if TempRegUsed then
  3139. begin
  3140. { Don't remove the first instruction if the temporary register is in use }
  3141. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3142. { No need to set Result to True. If there's another instruction later on
  3143. that can be optimised, it will be detected when the main Pass 1 loop
  3144. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3145. end
  3146. else
  3147. begin
  3148. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3149. RemoveCurrentP(p, hp1);
  3150. Result:=true;
  3151. Exit;
  3152. end;
  3153. end;
  3154. end;
  3155. else
  3156. Internalerror(2019103001);
  3157. end;
  3158. end
  3159. else
  3160. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3161. begin
  3162. if not CrossJump and
  3163. not RegUsedBetween(ActiveReg, p, hp2) and
  3164. not RegReadByInstruction(ActiveReg, hp2) then
  3165. begin
  3166. { Register is not used before it is overwritten }
  3167. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3168. RemoveCurrentp(p, hp1);
  3169. Result := True;
  3170. Exit;
  3171. end;
  3172. if (taicpu(p).oper[0]^.typ = top_const) and
  3173. (taicpu(hp2).oper[0]^.typ = top_const) then
  3174. begin
  3175. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3176. begin
  3177. { Same value - register hasn't changed }
  3178. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3179. RemoveInstruction(hp2);
  3180. Result := True;
  3181. { See if there's more we can optimise }
  3182. Continue;
  3183. end;
  3184. end;
  3185. end;
  3186. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3187. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3188. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3189. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3190. begin
  3191. {
  3192. Change from:
  3193. mov ###, %reg
  3194. ...
  3195. movs/z %reg,%reg (Same register, just different sizes)
  3196. To:
  3197. movs/z ###, %reg (Longer version)
  3198. ...
  3199. (remove)
  3200. }
  3201. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3202. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3203. { Keep the first instruction as mov if ### is a constant }
  3204. if taicpu(p).oper[0]^.typ = top_const then
  3205. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3206. else
  3207. begin
  3208. taicpu(p).opcode := taicpu(hp2).opcode;
  3209. taicpu(p).opsize := taicpu(hp2).opsize;
  3210. end;
  3211. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3212. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3213. RemoveInstruction(hp2);
  3214. Result := True;
  3215. Exit;
  3216. end;
  3217. else
  3218. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3219. begin
  3220. TransferUsedRegs(TmpUsedRegs);
  3221. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3222. if
  3223. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  3224. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  3225. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  3226. begin
  3227. { Just in case something didn't get modified (e.g. an
  3228. implicit register) }
  3229. if not RegReadByInstruction(ActiveReg, hp2) and
  3230. { If a conditional jump was crossed, do not delete
  3231. the original MOV no matter what }
  3232. not CrossJump then
  3233. begin
  3234. TransferUsedRegs(TmpUsedRegs);
  3235. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3236. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3237. if
  3238. { Make sure the original register isn't still present
  3239. and has been written to (e.g. with SHRX) }
  3240. RegLoadedWithNewValue(ActiveReg, hp2) or
  3241. not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3242. begin
  3243. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3244. { We can remove the original MOV }
  3245. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3246. RemoveCurrentp(p, hp1);
  3247. Result := True;
  3248. Exit;
  3249. end
  3250. else
  3251. begin
  3252. { See if there's more we can optimise }
  3253. hp3 := hp2;
  3254. Continue;
  3255. end;
  3256. end;
  3257. end;
  3258. end;
  3259. end;
  3260. { Break out of the while loop under normal circumstances }
  3261. Break;
  3262. end;
  3263. end;
  3264. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3265. (taicpu(p).oper[1]^.typ = top_reg) and
  3266. (taicpu(p).opsize = S_L) and
  3267. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3268. (taicpu(hp2).opcode = A_AND) and
  3269. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3270. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3271. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3272. ) then
  3273. begin
  3274. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3275. begin
  3276. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3277. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3278. begin
  3279. { Optimize out:
  3280. mov x, %reg
  3281. and ffffffffh, %reg
  3282. }
  3283. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3284. RemoveInstruction(hp2);
  3285. Result:=true;
  3286. exit;
  3287. end;
  3288. end;
  3289. end;
  3290. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3291. x >= RetOffset) as it doesn't do anything (it writes either to a
  3292. parameter or to the temporary storage room for the function
  3293. result)
  3294. }
  3295. if IsExitCode(hp1) and
  3296. (taicpu(p).oper[1]^.typ = top_ref) and
  3297. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3298. (
  3299. (
  3300. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3301. not (
  3302. assigned(current_procinfo.procdef.funcretsym) and
  3303. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3304. )
  3305. ) or
  3306. { Also discard writes to the stack that are below the base pointer,
  3307. as this is temporary storage rather than a function result on the
  3308. stack, say. }
  3309. (
  3310. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3311. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3312. )
  3313. ) then
  3314. begin
  3315. RemoveCurrentp(p, hp1);
  3316. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3317. RemoveLastDeallocForFuncRes(p);
  3318. Result:=true;
  3319. exit;
  3320. end;
  3321. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3322. begin
  3323. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3324. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3325. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3326. begin
  3327. { change
  3328. mov reg1, mem1
  3329. test/cmp x, mem1
  3330. to
  3331. mov reg1, mem1
  3332. test/cmp x, reg1
  3333. }
  3334. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3335. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3336. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3337. Result := True;
  3338. Exit;
  3339. end;
  3340. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3341. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3342. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3343. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3344. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3345. (
  3346. (
  3347. (taicpu(hp1).opcode = A_TEST)
  3348. ) or (
  3349. (taicpu(hp1).opcode = A_CMP) and
  3350. { A sanity check more than anything }
  3351. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3352. )
  3353. ) then
  3354. begin
  3355. { change
  3356. mov mem, %reg
  3357. cmp/test x, %reg / test %reg,%reg
  3358. (reg deallocated)
  3359. to
  3360. cmp/test x, mem / cmp 0, mem
  3361. }
  3362. TransferUsedRegs(TmpUsedRegs);
  3363. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3364. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3365. begin
  3366. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3367. if (taicpu(hp1).opcode = A_TEST) and
  3368. (
  3369. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3370. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3371. ) then
  3372. begin
  3373. taicpu(hp1).opcode := A_CMP;
  3374. taicpu(hp1).loadconst(0, 0);
  3375. end;
  3376. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3377. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3378. RemoveCurrentP(p, hp1);
  3379. Result := True;
  3380. Exit;
  3381. end;
  3382. end;
  3383. end;
  3384. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3385. { If the flags register is in use, don't change the instruction to an
  3386. ADD otherwise this will scramble the flags. [Kit] }
  3387. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3388. begin
  3389. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3390. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3391. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3392. ) or
  3393. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3394. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3395. )
  3396. ) then
  3397. { mov reg1,ref
  3398. lea reg2,[reg1,reg2]
  3399. to
  3400. add reg2,ref}
  3401. begin
  3402. TransferUsedRegs(TmpUsedRegs);
  3403. { reg1 may not be used afterwards }
  3404. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3405. begin
  3406. Taicpu(hp1).opcode:=A_ADD;
  3407. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3408. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3409. RemoveCurrentp(p, hp1);
  3410. result:=true;
  3411. exit;
  3412. end;
  3413. end;
  3414. { If the LEA instruction can be converted into an arithmetic instruction,
  3415. it may be possible to then fold it in the next optimisation, otherwise
  3416. there's nothing more that can be optimised here. }
  3417. if not ConvertLEA(taicpu(hp1)) then
  3418. Exit;
  3419. end;
  3420. if (taicpu(p).oper[1]^.typ = top_reg) and
  3421. (hp1.typ = ait_instruction) and
  3422. GetNextInstruction(hp1, hp2) and
  3423. MatchInstruction(hp2,A_MOV,[]) and
  3424. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3425. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3426. (
  3427. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3428. {$ifdef x86_64}
  3429. or
  3430. (
  3431. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3432. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3433. )
  3434. {$endif x86_64}
  3435. ) then
  3436. begin
  3437. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3438. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3439. { change movsX/movzX reg/ref, reg2
  3440. add/sub/or/... reg3/$const, reg2
  3441. mov reg2 reg/ref
  3442. dealloc reg2
  3443. to
  3444. add/sub/or/... reg3/$const, reg/ref }
  3445. begin
  3446. TransferUsedRegs(TmpUsedRegs);
  3447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3448. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3449. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3450. begin
  3451. { by example:
  3452. movswl %si,%eax movswl %si,%eax p
  3453. decl %eax addl %edx,%eax hp1
  3454. movw %ax,%si movw %ax,%si hp2
  3455. ->
  3456. movswl %si,%eax movswl %si,%eax p
  3457. decw %eax addw %edx,%eax hp1
  3458. movw %ax,%si movw %ax,%si hp2
  3459. }
  3460. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3461. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3462. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3463. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3464. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3465. {
  3466. ->
  3467. movswl %si,%eax movswl %si,%eax p
  3468. decw %si addw %dx,%si hp1
  3469. movw %ax,%si movw %ax,%si hp2
  3470. }
  3471. case taicpu(hp1).ops of
  3472. 1:
  3473. begin
  3474. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3475. if taicpu(hp1).oper[0]^.typ=top_reg then
  3476. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3477. end;
  3478. 2:
  3479. begin
  3480. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3481. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3482. (taicpu(hp1).opcode<>A_SHL) and
  3483. (taicpu(hp1).opcode<>A_SHR) and
  3484. (taicpu(hp1).opcode<>A_SAR) then
  3485. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3486. end;
  3487. else
  3488. internalerror(2008042701);
  3489. end;
  3490. {
  3491. ->
  3492. decw %si addw %dx,%si p
  3493. }
  3494. RemoveInstruction(hp2);
  3495. RemoveCurrentP(p, hp1);
  3496. Result:=True;
  3497. Exit;
  3498. end;
  3499. end;
  3500. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3501. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3502. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3503. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3504. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3505. )
  3506. {$ifdef i386}
  3507. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3508. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3509. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3510. {$endif i386}
  3511. then
  3512. { change movsX/movzX reg/ref, reg2
  3513. add/sub/or/... regX/$const, reg2
  3514. mov reg2, reg3
  3515. dealloc reg2
  3516. to
  3517. movsX/movzX reg/ref, reg3
  3518. add/sub/or/... reg3/$const, reg3
  3519. }
  3520. begin
  3521. TransferUsedRegs(TmpUsedRegs);
  3522. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3523. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3524. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3525. begin
  3526. { by example:
  3527. movswl %si,%eax movswl %si,%eax p
  3528. decl %eax addl %edx,%eax hp1
  3529. movw %ax,%si movw %ax,%si hp2
  3530. ->
  3531. movswl %si,%eax movswl %si,%eax p
  3532. decw %eax addw %edx,%eax hp1
  3533. movw %ax,%si movw %ax,%si hp2
  3534. }
  3535. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3536. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3537. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3538. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3539. { limit size of constants as well to avoid assembler errors, but
  3540. check opsize to avoid overflow when left shifting the 1 }
  3541. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3542. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3543. {$ifdef x86_64}
  3544. { Be careful of, for example:
  3545. movl %reg1,%reg2
  3546. addl %reg3,%reg2
  3547. movq %reg2,%reg4
  3548. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3549. }
  3550. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3551. begin
  3552. taicpu(hp2).changeopsize(S_L);
  3553. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3554. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3555. end;
  3556. {$endif x86_64}
  3557. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3558. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3559. if taicpu(p).oper[0]^.typ=top_reg then
  3560. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3561. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3562. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3563. {
  3564. ->
  3565. movswl %si,%eax movswl %si,%eax p
  3566. decw %si addw %dx,%si hp1
  3567. movw %ax,%si movw %ax,%si hp2
  3568. }
  3569. case taicpu(hp1).ops of
  3570. 1:
  3571. begin
  3572. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3573. if taicpu(hp1).oper[0]^.typ=top_reg then
  3574. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3575. end;
  3576. 2:
  3577. begin
  3578. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3579. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3580. (taicpu(hp1).opcode<>A_SHL) and
  3581. (taicpu(hp1).opcode<>A_SHR) and
  3582. (taicpu(hp1).opcode<>A_SAR) then
  3583. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3584. end;
  3585. else
  3586. internalerror(2018111801);
  3587. end;
  3588. {
  3589. ->
  3590. decw %si addw %dx,%si p
  3591. }
  3592. RemoveInstruction(hp2);
  3593. end;
  3594. end;
  3595. end;
  3596. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3597. GetNextInstruction(hp1, hp2) and
  3598. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3599. MatchOperand(Taicpu(p).oper[0]^,0) and
  3600. (Taicpu(p).oper[1]^.typ = top_reg) and
  3601. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3602. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3603. { mov reg1,0
  3604. bts reg1,operand1 --> mov reg1,operand2
  3605. or reg1,operand2 bts reg1,operand1}
  3606. begin
  3607. Taicpu(hp2).opcode:=A_MOV;
  3608. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3609. asml.remove(hp1);
  3610. insertllitem(hp2,hp2.next,hp1);
  3611. RemoveCurrentp(p, hp1);
  3612. Result:=true;
  3613. exit;
  3614. end;
  3615. {
  3616. mov ref,reg0
  3617. <op> reg0,reg1
  3618. dealloc reg0
  3619. to
  3620. <op> ref,reg1
  3621. }
  3622. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3623. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3624. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3625. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3626. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3627. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3628. begin
  3629. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3630. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3631. RemoveCurrentp(p, hp1);
  3632. Result:=true;
  3633. exit;
  3634. end;
  3635. {$ifdef x86_64}
  3636. { Convert:
  3637. movq x(ref),%reg64
  3638. shrq y,%reg64
  3639. To:
  3640. movq x+4(ref),%reg32
  3641. shrq y-32,%reg32 (Remove if y = 32)
  3642. }
  3643. if (taicpu(p).opsize = S_Q) and
  3644. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3645. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3646. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3647. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3648. (taicpu(hp1).oper[0]^.val >= 32) and
  3649. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3650. begin
  3651. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3652. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3653. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3654. { Convert to 32-bit }
  3655. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3656. taicpu(p).opsize := S_L;
  3657. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3658. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3659. if (taicpu(hp1).oper[0]^.val = 32) then
  3660. begin
  3661. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3662. RemoveInstruction(hp1);
  3663. end
  3664. else
  3665. begin
  3666. { This will potentially open up more arithmetic operations since
  3667. the peephole optimizer now has a big hint that only the lower
  3668. 32 bits are currently in use (and opcodes are smaller in size) }
  3669. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3670. taicpu(hp1).opsize := S_L;
  3671. Dec(taicpu(hp1).oper[0]^.val, 32);
  3672. DebugMsg(SPeepholeOptimization + PreMessage +
  3673. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3674. end;
  3675. Result := True;
  3676. Exit;
  3677. end;
  3678. {$endif x86_64}
  3679. end;
  3680. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3681. var
  3682. hp1 : tai;
  3683. begin
  3684. Result:=false;
  3685. if taicpu(p).ops <> 2 then
  3686. exit;
  3687. if GetNextInstruction(p,hp1) and
  3688. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3689. (taicpu(hp1).ops = 2) then
  3690. begin
  3691. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3692. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3693. { movXX reg1, mem1 or movXX mem1, reg1
  3694. movXX mem2, reg2 movXX reg2, mem2}
  3695. begin
  3696. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3697. { movXX reg1, mem1 or movXX mem1, reg1
  3698. movXX mem2, reg1 movXX reg2, mem1}
  3699. begin
  3700. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3701. begin
  3702. { Removes the second statement from
  3703. movXX reg1, mem1/reg2
  3704. movXX mem1/reg2, reg1
  3705. }
  3706. if taicpu(p).oper[0]^.typ=top_reg then
  3707. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3708. { Removes the second statement from
  3709. movXX mem1/reg1, reg2
  3710. movXX reg2, mem1/reg1
  3711. }
  3712. if (taicpu(p).oper[1]^.typ=top_reg) and
  3713. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3714. begin
  3715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3716. RemoveInstruction(hp1);
  3717. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3718. end
  3719. else
  3720. begin
  3721. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3722. RemoveInstruction(hp1);
  3723. end;
  3724. Result:=true;
  3725. exit;
  3726. end
  3727. end;
  3728. end;
  3729. end;
  3730. end;
  3731. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3732. var
  3733. hp1 : tai;
  3734. begin
  3735. result:=false;
  3736. { replace
  3737. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3738. MovX %mreg2,%mreg1
  3739. dealloc %mreg2
  3740. by
  3741. <Op>X %mreg2,%mreg1
  3742. ?
  3743. }
  3744. if GetNextInstruction(p,hp1) and
  3745. { we mix single and double opperations here because we assume that the compiler
  3746. generates vmovapd only after double operations and vmovaps only after single operations }
  3747. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3748. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3749. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3750. (taicpu(p).oper[0]^.typ=top_reg) then
  3751. begin
  3752. TransferUsedRegs(TmpUsedRegs);
  3753. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3754. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3755. begin
  3756. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3757. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3758. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3759. RemoveInstruction(hp1);
  3760. result:=true;
  3761. end;
  3762. end;
  3763. end;
  3764. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3765. var
  3766. hp1, p_label, p_dist, hp1_dist: tai;
  3767. JumpLabel, JumpLabel_dist: TAsmLabel;
  3768. begin
  3769. Result := False;
  3770. if GetNextInstruction(p, hp1) and
  3771. MatchInstruction(hp1,A_MOV,[]) and
  3772. (
  3773. (taicpu(p).oper[0]^.typ <> top_reg) or
  3774. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3775. ) and
  3776. (
  3777. (taicpu(p).oper[1]^.typ <> top_reg) or
  3778. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  3779. ) and
  3780. (
  3781. { Make sure the register written to doesn't appear in the
  3782. test instruction (in a reference, say) }
  3783. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3784. not RegInInstruction(taicpu(hp1).oper[1]^.reg, p)
  3785. ) then
  3786. begin
  3787. { If we have something like:
  3788. test %reg1,%reg1
  3789. mov 0,%reg2
  3790. And no registers are shared (the two %reg1's can be different, as
  3791. long as neither of them are also %reg2), move the MOV command to
  3792. before the comparison as this means it can be optimised without
  3793. worrying about the FLAGS register. (This combination is generated
  3794. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3795. }
  3796. SwapMovCmp(p, hp1);
  3797. Result := True;
  3798. Exit;
  3799. end;
  3800. { Search for:
  3801. test %reg,%reg
  3802. j(c1) @lbl1
  3803. ...
  3804. @lbl:
  3805. test %reg,%reg (same register)
  3806. j(c2) @lbl2
  3807. If c2 is a subset of c1, change to:
  3808. test %reg,%reg
  3809. j(c1) @lbl2
  3810. (@lbl1 may become a dead label as a result)
  3811. }
  3812. if (taicpu(p).oper[1]^.typ = top_reg) and
  3813. (taicpu(p).oper[0]^.typ = top_reg) and
  3814. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3815. MatchInstruction(hp1, A_JCC, []) and
  3816. IsJumpToLabel(taicpu(hp1)) then
  3817. begin
  3818. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3819. p_label := nil;
  3820. if Assigned(JumpLabel) then
  3821. p_label := getlabelwithsym(JumpLabel);
  3822. if Assigned(p_label) and
  3823. GetNextInstruction(p_label, p_dist) and
  3824. MatchInstruction(p_dist, A_TEST, []) and
  3825. { It's fine if the second test uses smaller sub-registers }
  3826. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3827. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3828. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3829. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3830. GetNextInstruction(p_dist, hp1_dist) and
  3831. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3832. begin
  3833. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3834. if JumpLabel = JumpLabel_dist then
  3835. { This is an infinite loop }
  3836. Exit;
  3837. { Best optimisation when the first condition is a subset (or equal) of the second }
  3838. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3839. begin
  3840. { Any registers used here will already be allocated }
  3841. if Assigned(JumpLabel_dist) then
  3842. JumpLabel_dist.IncRefs;
  3843. if Assigned(JumpLabel) then
  3844. JumpLabel.DecRefs;
  3845. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3846. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3847. Result := True;
  3848. Exit;
  3849. end;
  3850. end;
  3851. end;
  3852. end;
  3853. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3854. var
  3855. hp1 : tai;
  3856. begin
  3857. result:=false;
  3858. { replace
  3859. addX const,%reg1
  3860. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3861. dealloc %reg1
  3862. by
  3863. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3864. }
  3865. if MatchOpType(taicpu(p),top_const,top_reg) and
  3866. GetNextInstruction(p,hp1) and
  3867. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3868. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3869. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3870. begin
  3871. TransferUsedRegs(TmpUsedRegs);
  3872. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3873. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3874. begin
  3875. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3876. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3877. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3878. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3879. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3880. RemoveCurrentP(p);
  3881. result:=true;
  3882. end;
  3883. end;
  3884. end;
  3885. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3886. var
  3887. hp1: tai;
  3888. ref: Integer;
  3889. saveref: treference;
  3890. TempReg: TRegister;
  3891. Multiple: TCGInt;
  3892. begin
  3893. Result:=false;
  3894. { removes seg register prefixes from LEA operations, as they
  3895. don't do anything}
  3896. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3897. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3898. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3899. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3900. (
  3901. { do not mess with leas accessing the stack pointer
  3902. unless it's a null operation }
  3903. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3904. (
  3905. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3906. (taicpu(p).oper[0]^.ref^.offset = 0)
  3907. )
  3908. ) and
  3909. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3910. begin
  3911. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3912. begin
  3913. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3914. begin
  3915. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3916. taicpu(p).oper[1]^.reg);
  3917. InsertLLItem(p.previous,p.next, hp1);
  3918. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3919. p.free;
  3920. p:=hp1;
  3921. end
  3922. else
  3923. begin
  3924. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3925. RemoveCurrentP(p);
  3926. end;
  3927. Result:=true;
  3928. exit;
  3929. end
  3930. else if (
  3931. { continue to use lea to adjust the stack pointer,
  3932. it is the recommended way, but only if not optimizing for size }
  3933. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3934. (cs_opt_size in current_settings.optimizerswitches)
  3935. ) and
  3936. { If the flags register is in use, don't change the instruction
  3937. to an ADD otherwise this will scramble the flags. [Kit] }
  3938. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3939. ConvertLEA(taicpu(p)) then
  3940. begin
  3941. Result:=true;
  3942. exit;
  3943. end;
  3944. end;
  3945. if GetNextInstruction(p,hp1) and
  3946. (hp1.typ=ait_instruction) then
  3947. begin
  3948. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3949. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3950. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3951. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3952. begin
  3953. TransferUsedRegs(TmpUsedRegs);
  3954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3955. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3956. begin
  3957. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3958. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3959. RemoveInstruction(hp1);
  3960. result:=true;
  3961. exit;
  3962. end;
  3963. end;
  3964. { changes
  3965. lea <ref1>, reg1
  3966. <op> ...,<ref. with reg1>,...
  3967. to
  3968. <op> ...,<ref1>,... }
  3969. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3970. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3971. not(MatchInstruction(hp1,A_LEA,[])) then
  3972. begin
  3973. { find a reference which uses reg1 }
  3974. 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
  3975. ref:=0
  3976. 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
  3977. ref:=1
  3978. else
  3979. ref:=-1;
  3980. if (ref<>-1) and
  3981. { reg1 must be either the base or the index }
  3982. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3983. begin
  3984. { reg1 can be removed from the reference }
  3985. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3986. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3987. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3988. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3989. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3990. else
  3991. Internalerror(2019111201);
  3992. { check if the can insert all data of the lea into the second instruction }
  3993. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3994. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3995. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3996. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3997. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3998. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3999. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4000. {$ifdef x86_64}
  4001. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4002. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4003. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4004. )
  4005. {$endif x86_64}
  4006. then
  4007. begin
  4008. { reg1 might not used by the second instruction after it is remove from the reference }
  4009. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4010. begin
  4011. TransferUsedRegs(TmpUsedRegs);
  4012. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4013. { reg1 is not updated so it might not be used afterwards }
  4014. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4015. begin
  4016. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4017. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4018. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4019. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4020. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4021. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4022. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4023. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4024. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4025. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4026. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4027. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4028. RemoveCurrentP(p, hp1);
  4029. result:=true;
  4030. exit;
  4031. end
  4032. end;
  4033. end;
  4034. { recover }
  4035. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4036. end;
  4037. end;
  4038. end;
  4039. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4040. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4041. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4042. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4043. begin
  4044. { Check common LEA/LEA conditions }
  4045. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4046. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4047. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4048. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4049. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4050. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4051. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4052. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4053. (
  4054. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4055. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4056. ) and (
  4057. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4058. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4059. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4060. ) then
  4061. begin
  4062. { changes
  4063. lea (regX,scale), reg1
  4064. lea offset(reg1,reg1), reg1
  4065. to
  4066. lea offset(regX,scale*2), reg1
  4067. and
  4068. lea (regX,scale1), reg1
  4069. lea offset(reg1,scale2), reg1
  4070. to
  4071. lea offset(regX,scale1*scale2), reg1
  4072. ... so long as the final scale does not exceed 8
  4073. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4074. }
  4075. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4076. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4077. (
  4078. (
  4079. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4080. ) or (
  4081. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4082. (
  4083. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4084. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4085. )
  4086. )
  4087. ) and (
  4088. (
  4089. { lea (reg1,scale2), reg1 variant }
  4090. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4091. (
  4092. (
  4093. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4094. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4095. ) or (
  4096. { lea (regX,regX), reg1 variant }
  4097. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4098. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4099. )
  4100. )
  4101. ) or (
  4102. { lea (reg1,reg1), reg1 variant }
  4103. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4104. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4105. )
  4106. ) then
  4107. begin
  4108. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4109. { Make everything homogeneous to make calculations easier }
  4110. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4111. begin
  4112. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4113. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4114. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4115. else
  4116. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4117. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4118. end;
  4119. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4120. begin
  4121. { Just to prevent miscalculations }
  4122. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4123. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4124. else
  4125. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4126. end
  4127. else
  4128. begin
  4129. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4130. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4131. end;
  4132. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4133. RemoveCurrentP(p);
  4134. result:=true;
  4135. exit;
  4136. end
  4137. { changes
  4138. lea offset1(regX), reg1
  4139. lea offset2(reg1), reg1
  4140. to
  4141. lea offset1+offset2(regX), reg1 }
  4142. else if
  4143. (
  4144. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4145. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4146. ) or (
  4147. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4148. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4149. (
  4150. (
  4151. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4152. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4153. ) or (
  4154. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4155. (
  4156. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4157. (
  4158. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4159. (
  4160. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4161. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4162. )
  4163. )
  4164. )
  4165. )
  4166. )
  4167. ) then
  4168. begin
  4169. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4170. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4171. begin
  4172. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4173. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4174. { if the register is used as index and base, we have to increase for base as well
  4175. and adapt base }
  4176. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4177. begin
  4178. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4179. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4180. end;
  4181. end
  4182. else
  4183. begin
  4184. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4185. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4186. end;
  4187. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4188. begin
  4189. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4190. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4191. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4192. end;
  4193. RemoveCurrentP(p);
  4194. result:=true;
  4195. exit;
  4196. end;
  4197. end;
  4198. { Change:
  4199. leal/q $x(%reg1),%reg2
  4200. ...
  4201. shll/q $y,%reg2
  4202. To:
  4203. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4204. }
  4205. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4206. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4207. (taicpu(hp1).oper[0]^.val <= 3) then
  4208. begin
  4209. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4210. TransferUsedRegs(TmpUsedRegs);
  4211. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4212. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4213. if
  4214. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4215. (this works even if scalefactor is zero) }
  4216. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4217. { Ensure offset doesn't go out of bounds }
  4218. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4219. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4220. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4221. (
  4222. (
  4223. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4224. (
  4225. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4226. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4227. (
  4228. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4229. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4230. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4231. )
  4232. )
  4233. ) or (
  4234. (
  4235. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4236. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4237. ) and
  4238. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4239. )
  4240. ) then
  4241. begin
  4242. repeat
  4243. with taicpu(p).oper[0]^.ref^ do
  4244. begin
  4245. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4246. if index = base then
  4247. begin
  4248. if Multiple > 4 then
  4249. { Optimisation will no longer work because resultant
  4250. scale factor will exceed 8 }
  4251. Break;
  4252. base := NR_NO;
  4253. scalefactor := 2;
  4254. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4255. end
  4256. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4257. begin
  4258. { Scale factor only works on the index register }
  4259. index := base;
  4260. base := NR_NO;
  4261. end;
  4262. { For safety }
  4263. if scalefactor <= 1 then
  4264. begin
  4265. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4266. scalefactor := Multiple;
  4267. end
  4268. else
  4269. begin
  4270. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4271. scalefactor := scalefactor * Multiple;
  4272. end;
  4273. offset := offset * Multiple;
  4274. end;
  4275. RemoveInstruction(hp1);
  4276. Result := True;
  4277. Exit;
  4278. { This repeat..until loop exists for the benefit of Break }
  4279. until True;
  4280. end;
  4281. end;
  4282. end;
  4283. end;
  4284. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4285. var
  4286. hp1 : tai;
  4287. begin
  4288. DoSubAddOpt := False;
  4289. if GetLastInstruction(p, hp1) and
  4290. (hp1.typ = ait_instruction) and
  4291. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4292. case taicpu(hp1).opcode Of
  4293. A_DEC:
  4294. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  4295. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4296. begin
  4297. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4298. RemoveInstruction(hp1);
  4299. end;
  4300. A_SUB:
  4301. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4302. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4303. begin
  4304. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4305. RemoveInstruction(hp1);
  4306. end;
  4307. A_ADD:
  4308. begin
  4309. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4310. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4311. begin
  4312. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4313. RemoveInstruction(hp1);
  4314. if (taicpu(p).oper[0]^.val = 0) then
  4315. begin
  4316. hp1 := tai(p.next);
  4317. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4318. if not GetLastInstruction(hp1, p) then
  4319. p := hp1;
  4320. DoSubAddOpt := True;
  4321. end
  4322. end;
  4323. end;
  4324. else
  4325. ;
  4326. end;
  4327. end;
  4328. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4329. {$ifdef i386}
  4330. var
  4331. hp1 : tai;
  4332. {$endif i386}
  4333. begin
  4334. Result:=false;
  4335. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4336. { * change "sub/add const1, reg" or "dec reg" followed by
  4337. "sub const2, reg" to one "sub ..., reg" }
  4338. if MatchOpType(taicpu(p),top_const,top_reg) then
  4339. begin
  4340. {$ifdef i386}
  4341. if (taicpu(p).oper[0]^.val = 2) and
  4342. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4343. { Don't do the sub/push optimization if the sub }
  4344. { comes from setting up the stack frame (JM) }
  4345. (not(GetLastInstruction(p,hp1)) or
  4346. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4347. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4348. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4349. begin
  4350. hp1 := tai(p.next);
  4351. while Assigned(hp1) and
  4352. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4353. not RegReadByInstruction(NR_ESP,hp1) and
  4354. not RegModifiedByInstruction(NR_ESP,hp1) do
  4355. hp1 := tai(hp1.next);
  4356. if Assigned(hp1) and
  4357. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4358. begin
  4359. taicpu(hp1).changeopsize(S_L);
  4360. if taicpu(hp1).oper[0]^.typ=top_reg then
  4361. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4362. hp1 := tai(p.next);
  4363. RemoveCurrentp(p, hp1);
  4364. Result:=true;
  4365. exit;
  4366. end;
  4367. end;
  4368. {$endif i386}
  4369. if DoSubAddOpt(p) then
  4370. Result:=true;
  4371. end;
  4372. end;
  4373. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4374. var
  4375. TmpBool1,TmpBool2 : Boolean;
  4376. tmpref : treference;
  4377. hp1,hp2: tai;
  4378. mask: tcgint;
  4379. begin
  4380. Result:=false;
  4381. { All these optimisations work on "shl/sal const,%reg" }
  4382. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4383. Exit;
  4384. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4385. (taicpu(p).oper[0]^.val <= 3) then
  4386. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4387. begin
  4388. { should we check the next instruction? }
  4389. TmpBool1 := True;
  4390. { have we found an add/sub which could be
  4391. integrated in the lea? }
  4392. TmpBool2 := False;
  4393. reference_reset(tmpref,2,[]);
  4394. TmpRef.index := taicpu(p).oper[1]^.reg;
  4395. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4396. while TmpBool1 and
  4397. GetNextInstruction(p, hp1) and
  4398. (tai(hp1).typ = ait_instruction) and
  4399. ((((taicpu(hp1).opcode = A_ADD) or
  4400. (taicpu(hp1).opcode = A_SUB)) and
  4401. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4402. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4403. (((taicpu(hp1).opcode = A_INC) or
  4404. (taicpu(hp1).opcode = A_DEC)) and
  4405. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4406. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4407. ((taicpu(hp1).opcode = A_LEA) and
  4408. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4409. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4410. (not GetNextInstruction(hp1,hp2) or
  4411. not instrReadsFlags(hp2)) Do
  4412. begin
  4413. TmpBool1 := False;
  4414. if taicpu(hp1).opcode=A_LEA then
  4415. begin
  4416. if (TmpRef.base = NR_NO) and
  4417. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4418. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4419. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4420. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4421. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4422. begin
  4423. TmpBool1 := True;
  4424. TmpBool2 := True;
  4425. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4426. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4427. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4428. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4429. RemoveInstruction(hp1);
  4430. end
  4431. end
  4432. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4433. begin
  4434. TmpBool1 := True;
  4435. TmpBool2 := True;
  4436. case taicpu(hp1).opcode of
  4437. A_ADD:
  4438. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4439. A_SUB:
  4440. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4441. else
  4442. internalerror(2019050536);
  4443. end;
  4444. RemoveInstruction(hp1);
  4445. end
  4446. else
  4447. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4448. (((taicpu(hp1).opcode = A_ADD) and
  4449. (TmpRef.base = NR_NO)) or
  4450. (taicpu(hp1).opcode = A_INC) or
  4451. (taicpu(hp1).opcode = A_DEC)) then
  4452. begin
  4453. TmpBool1 := True;
  4454. TmpBool2 := True;
  4455. case taicpu(hp1).opcode of
  4456. A_ADD:
  4457. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4458. A_INC:
  4459. inc(TmpRef.offset);
  4460. A_DEC:
  4461. dec(TmpRef.offset);
  4462. else
  4463. internalerror(2019050535);
  4464. end;
  4465. RemoveInstruction(hp1);
  4466. end;
  4467. end;
  4468. if TmpBool2
  4469. {$ifndef x86_64}
  4470. or
  4471. ((current_settings.optimizecputype < cpu_Pentium2) and
  4472. (taicpu(p).oper[0]^.val <= 3) and
  4473. not(cs_opt_size in current_settings.optimizerswitches))
  4474. {$endif x86_64}
  4475. then
  4476. begin
  4477. if not(TmpBool2) and
  4478. (taicpu(p).oper[0]^.val=1) then
  4479. begin
  4480. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4481. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4482. end
  4483. else
  4484. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4485. taicpu(p).oper[1]^.reg);
  4486. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4487. InsertLLItem(p.previous, p.next, hp1);
  4488. p.free;
  4489. p := hp1;
  4490. end;
  4491. end
  4492. {$ifndef x86_64}
  4493. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4494. begin
  4495. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4496. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4497. (unlike shl, which is only Tairable in the U pipe) }
  4498. if taicpu(p).oper[0]^.val=1 then
  4499. begin
  4500. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4501. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4502. InsertLLItem(p.previous, p.next, hp1);
  4503. p.free;
  4504. p := hp1;
  4505. end
  4506. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4507. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4508. else if (taicpu(p).opsize = S_L) and
  4509. (taicpu(p).oper[0]^.val<= 3) then
  4510. begin
  4511. reference_reset(tmpref,2,[]);
  4512. TmpRef.index := taicpu(p).oper[1]^.reg;
  4513. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4514. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4515. InsertLLItem(p.previous, p.next, hp1);
  4516. p.free;
  4517. p := hp1;
  4518. end;
  4519. end
  4520. {$endif x86_64}
  4521. else if
  4522. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4523. (
  4524. (
  4525. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4526. SetAndTest(hp1, hp2)
  4527. {$ifdef x86_64}
  4528. ) or
  4529. (
  4530. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4531. GetNextInstruction(hp1, hp2) and
  4532. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4533. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4534. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4535. {$endif x86_64}
  4536. )
  4537. ) and
  4538. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4539. begin
  4540. { Change:
  4541. shl x, %reg1
  4542. mov -(1<<x), %reg2
  4543. and %reg2, %reg1
  4544. Or:
  4545. shl x, %reg1
  4546. and -(1<<x), %reg1
  4547. To just:
  4548. shl x, %reg1
  4549. Since the and operation only zeroes bits that are already zero from the shl operation
  4550. }
  4551. case taicpu(p).oper[0]^.val of
  4552. 8:
  4553. mask:=$FFFFFFFFFFFFFF00;
  4554. 16:
  4555. mask:=$FFFFFFFFFFFF0000;
  4556. 32:
  4557. mask:=$FFFFFFFF00000000;
  4558. 63:
  4559. { Constant pre-calculated to prevent overflow errors with Int64 }
  4560. mask:=$8000000000000000;
  4561. else
  4562. begin
  4563. if taicpu(p).oper[0]^.val >= 64 then
  4564. { Shouldn't happen realistically, since the register
  4565. is guaranteed to be set to zero at this point }
  4566. mask := 0
  4567. else
  4568. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4569. end;
  4570. end;
  4571. if taicpu(hp1).oper[0]^.val = mask then
  4572. begin
  4573. { Everything checks out, perform the optimisation, as long as
  4574. the FLAGS register isn't being used}
  4575. TransferUsedRegs(TmpUsedRegs);
  4576. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4577. {$ifdef x86_64}
  4578. if (hp1 <> hp2) then
  4579. begin
  4580. { "shl/mov/and" version }
  4581. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4582. { Don't do the optimisation if the FLAGS register is in use }
  4583. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4584. begin
  4585. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4586. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4587. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4588. begin
  4589. RemoveInstruction(hp1);
  4590. Result := True;
  4591. end;
  4592. { Only set Result to True if the 'mov' instruction was removed }
  4593. RemoveInstruction(hp2);
  4594. end;
  4595. end
  4596. else
  4597. {$endif x86_64}
  4598. begin
  4599. { "shl/and" version }
  4600. { Don't do the optimisation if the FLAGS register is in use }
  4601. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4602. begin
  4603. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4604. RemoveInstruction(hp1);
  4605. Result := True;
  4606. end;
  4607. end;
  4608. Exit;
  4609. end
  4610. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4611. begin
  4612. { Even if the mask doesn't allow for its removal, we might be
  4613. able to optimise the mask for the "shl/and" version, which
  4614. may permit other peephole optimisations }
  4615. {$ifdef DEBUG_AOPTCPU}
  4616. mask := taicpu(hp1).oper[0]^.val and mask;
  4617. if taicpu(hp1).oper[0]^.val <> mask then
  4618. begin
  4619. DebugMsg(
  4620. SPeepholeOptimization +
  4621. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4622. ' to $' + debug_tostr(mask) +
  4623. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4624. taicpu(hp1).oper[0]^.val := mask;
  4625. end;
  4626. {$else DEBUG_AOPTCPU}
  4627. { If debugging is off, just set the operand even if it's the same }
  4628. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4629. {$endif DEBUG_AOPTCPU}
  4630. end;
  4631. end;
  4632. {
  4633. change
  4634. shl/sal const,reg
  4635. <op> ...(...,reg,1),...
  4636. into
  4637. <op> ...(...,reg,1 shl const),...
  4638. if const in 1..3
  4639. }
  4640. if MatchOpType(taicpu(p), top_const, top_reg) and
  4641. (taicpu(p).oper[0]^.val in [1..3]) and
  4642. GetNextInstruction(p, hp1) and
  4643. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4644. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4645. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4646. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4647. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4648. begin
  4649. TransferUsedRegs(TmpUsedRegs);
  4650. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4651. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4652. begin
  4653. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4654. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4655. RemoveCurrentP(p);
  4656. Result:=true;
  4657. end;
  4658. end;
  4659. end;
  4660. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4661. var
  4662. CurrentRef: TReference;
  4663. FullReg: TRegister;
  4664. hp1, hp2: tai;
  4665. begin
  4666. Result := False;
  4667. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4668. Exit;
  4669. { We assume you've checked if the operand is actually a reference by
  4670. this point. If it isn't, you'll most likely get an access violation }
  4671. CurrentRef := first_mov.oper[1]^.ref^;
  4672. { Memory must be aligned }
  4673. if (CurrentRef.offset mod 4) <> 0 then
  4674. Exit;
  4675. Inc(CurrentRef.offset);
  4676. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4677. if MatchOperand(second_mov.oper[0]^, 0) and
  4678. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4679. GetNextInstruction(second_mov, hp1) and
  4680. (hp1.typ = ait_instruction) and
  4681. (taicpu(hp1).opcode = A_MOV) and
  4682. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4683. (taicpu(hp1).oper[0]^.val = 0) then
  4684. begin
  4685. Inc(CurrentRef.offset);
  4686. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4687. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4688. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4689. begin
  4690. case taicpu(hp1).opsize of
  4691. S_B:
  4692. if GetNextInstruction(hp1, hp2) and
  4693. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4694. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4695. (taicpu(hp2).oper[0]^.val = 0) then
  4696. begin
  4697. Inc(CurrentRef.offset);
  4698. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4699. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4700. (taicpu(hp2).opsize = S_B) then
  4701. begin
  4702. RemoveInstruction(hp1);
  4703. RemoveInstruction(hp2);
  4704. first_mov.opsize := S_L;
  4705. if first_mov.oper[0]^.typ = top_reg then
  4706. begin
  4707. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4708. { Reuse second_mov as a MOVZX instruction }
  4709. second_mov.opcode := A_MOVZX;
  4710. second_mov.opsize := S_BL;
  4711. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4712. second_mov.loadreg(1, FullReg);
  4713. first_mov.oper[0]^.reg := FullReg;
  4714. asml.Remove(second_mov);
  4715. asml.InsertBefore(second_mov, first_mov);
  4716. end
  4717. else
  4718. { It's a value }
  4719. begin
  4720. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4721. RemoveInstruction(second_mov);
  4722. end;
  4723. Result := True;
  4724. Exit;
  4725. end;
  4726. end;
  4727. S_W:
  4728. begin
  4729. RemoveInstruction(hp1);
  4730. first_mov.opsize := S_L;
  4731. if first_mov.oper[0]^.typ = top_reg then
  4732. begin
  4733. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4734. { Reuse second_mov as a MOVZX instruction }
  4735. second_mov.opcode := A_MOVZX;
  4736. second_mov.opsize := S_BL;
  4737. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4738. second_mov.loadreg(1, FullReg);
  4739. first_mov.oper[0]^.reg := FullReg;
  4740. asml.Remove(second_mov);
  4741. asml.InsertBefore(second_mov, first_mov);
  4742. end
  4743. else
  4744. { It's a value }
  4745. begin
  4746. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4747. RemoveInstruction(second_mov);
  4748. end;
  4749. Result := True;
  4750. Exit;
  4751. end;
  4752. else
  4753. ;
  4754. end;
  4755. end;
  4756. end;
  4757. end;
  4758. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4759. { returns true if a "continue" should be done after this optimization }
  4760. var
  4761. hp1, hp2: tai;
  4762. begin
  4763. Result := false;
  4764. if MatchOpType(taicpu(p),top_ref) and
  4765. GetNextInstruction(p, hp1) and
  4766. (hp1.typ = ait_instruction) and
  4767. (((taicpu(hp1).opcode = A_FLD) and
  4768. (taicpu(p).opcode = A_FSTP)) or
  4769. ((taicpu(p).opcode = A_FISTP) and
  4770. (taicpu(hp1).opcode = A_FILD))) and
  4771. MatchOpType(taicpu(hp1),top_ref) and
  4772. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4773. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4774. begin
  4775. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4776. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4777. GetNextInstruction(hp1, hp2) and
  4778. (hp2.typ = ait_instruction) and
  4779. IsExitCode(hp2) and
  4780. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4781. not(assigned(current_procinfo.procdef.funcretsym) and
  4782. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4783. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4784. begin
  4785. RemoveInstruction(hp1);
  4786. RemoveCurrentP(p, hp2);
  4787. RemoveLastDeallocForFuncRes(p);
  4788. Result := true;
  4789. end
  4790. else
  4791. { we can do this only in fast math mode as fstp is rounding ...
  4792. ... still disabled as it breaks the compiler and/or rtl }
  4793. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4794. { ... or if another fstp equal to the first one follows }
  4795. (GetNextInstruction(hp1,hp2) and
  4796. (hp2.typ = ait_instruction) and
  4797. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4798. (taicpu(p).opsize=taicpu(hp2).opsize))
  4799. ) and
  4800. { fst can't store an extended/comp value }
  4801. (taicpu(p).opsize <> S_FX) and
  4802. (taicpu(p).opsize <> S_IQ) then
  4803. begin
  4804. if (taicpu(p).opcode = A_FSTP) then
  4805. taicpu(p).opcode := A_FST
  4806. else
  4807. taicpu(p).opcode := A_FIST;
  4808. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4809. RemoveInstruction(hp1);
  4810. end;
  4811. end;
  4812. end;
  4813. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4814. var
  4815. hp1, hp2: tai;
  4816. begin
  4817. result:=false;
  4818. if MatchOpType(taicpu(p),top_reg) and
  4819. GetNextInstruction(p, hp1) and
  4820. (hp1.typ = Ait_Instruction) and
  4821. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4822. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4823. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4824. { change to
  4825. fld reg fxxx reg,st
  4826. fxxxp st, st1 (hp1)
  4827. Remark: non commutative operations must be reversed!
  4828. }
  4829. begin
  4830. case taicpu(hp1).opcode Of
  4831. A_FMULP,A_FADDP,
  4832. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4833. begin
  4834. case taicpu(hp1).opcode Of
  4835. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4836. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4837. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4838. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4839. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4840. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4841. else
  4842. internalerror(2019050534);
  4843. end;
  4844. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4845. taicpu(hp1).oper[1]^.reg := NR_ST;
  4846. RemoveCurrentP(p, hp1);
  4847. Result:=true;
  4848. exit;
  4849. end;
  4850. else
  4851. ;
  4852. end;
  4853. end
  4854. else
  4855. if MatchOpType(taicpu(p),top_ref) and
  4856. GetNextInstruction(p, hp2) and
  4857. (hp2.typ = Ait_Instruction) and
  4858. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4859. (taicpu(p).opsize in [S_FS, S_FL]) and
  4860. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4861. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4862. if GetLastInstruction(p, hp1) and
  4863. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4864. MatchOpType(taicpu(hp1),top_ref) and
  4865. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4866. if ((taicpu(hp2).opcode = A_FMULP) or
  4867. (taicpu(hp2).opcode = A_FADDP)) then
  4868. { change to
  4869. fld/fst mem1 (hp1) fld/fst mem1
  4870. fld mem1 (p) fadd/
  4871. faddp/ fmul st, st
  4872. fmulp st, st1 (hp2) }
  4873. begin
  4874. RemoveCurrentP(p, hp1);
  4875. if (taicpu(hp2).opcode = A_FADDP) then
  4876. taicpu(hp2).opcode := A_FADD
  4877. else
  4878. taicpu(hp2).opcode := A_FMUL;
  4879. taicpu(hp2).oper[1]^.reg := NR_ST;
  4880. end
  4881. else
  4882. { change to
  4883. fld/fst mem1 (hp1) fld/fst mem1
  4884. fld mem1 (p) fld st}
  4885. begin
  4886. taicpu(p).changeopsize(S_FL);
  4887. taicpu(p).loadreg(0,NR_ST);
  4888. end
  4889. else
  4890. begin
  4891. case taicpu(hp2).opcode Of
  4892. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4893. { change to
  4894. fld/fst mem1 (hp1) fld/fst mem1
  4895. fld mem2 (p) fxxx mem2
  4896. fxxxp st, st1 (hp2) }
  4897. begin
  4898. case taicpu(hp2).opcode Of
  4899. A_FADDP: taicpu(p).opcode := A_FADD;
  4900. A_FMULP: taicpu(p).opcode := A_FMUL;
  4901. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4902. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4903. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4904. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4905. else
  4906. internalerror(2019050533);
  4907. end;
  4908. RemoveInstruction(hp2);
  4909. end
  4910. else
  4911. ;
  4912. end
  4913. end
  4914. end;
  4915. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4916. begin
  4917. Result := condition_in(cond1, cond2) or
  4918. { Not strictly subsets due to the actual flags checked, but because we're
  4919. comparing integers, E is a subset of AE and GE and their aliases }
  4920. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4921. end;
  4922. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4923. var
  4924. v: TCGInt;
  4925. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4926. FirstMatch: Boolean;
  4927. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4928. begin
  4929. Result:=false;
  4930. { All these optimisations need a next instruction }
  4931. if not GetNextInstruction(p, hp1) then
  4932. Exit;
  4933. { Search for:
  4934. cmp ###,###
  4935. j(c1) @lbl1
  4936. ...
  4937. @lbl:
  4938. cmp ###.### (same comparison as above)
  4939. j(c2) @lbl2
  4940. If c1 is a subset of c2, change to:
  4941. cmp ###,###
  4942. j(c2) @lbl2
  4943. (@lbl1 may become a dead label as a result)
  4944. }
  4945. { Also handle cases where there are multiple jumps in a row }
  4946. p_jump := hp1;
  4947. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4948. begin
  4949. if IsJumpToLabel(taicpu(p_jump)) then
  4950. begin
  4951. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4952. p_label := nil;
  4953. if Assigned(JumpLabel) then
  4954. p_label := getlabelwithsym(JumpLabel);
  4955. if Assigned(p_label) and
  4956. GetNextInstruction(p_label, p_dist) and
  4957. MatchInstruction(p_dist, A_CMP, []) and
  4958. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4959. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4960. GetNextInstruction(p_dist, hp1_dist) and
  4961. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4962. begin
  4963. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4964. if JumpLabel = JumpLabel_dist then
  4965. { This is an infinite loop }
  4966. Exit;
  4967. { Best optimisation when the first condition is a subset (or equal) of the second }
  4968. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4969. begin
  4970. { Any registers used here will already be allocated }
  4971. if Assigned(JumpLabel_dist) then
  4972. JumpLabel_dist.IncRefs;
  4973. if Assigned(JumpLabel) then
  4974. JumpLabel.DecRefs;
  4975. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4976. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4977. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4978. Result := True;
  4979. { Don't exit yet. Since p and p_jump haven't actually been
  4980. removed, we can check for more on this iteration }
  4981. end
  4982. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4983. GetNextInstruction(hp1_dist, hp1_label) and
  4984. SkipAligns(hp1_label, hp1_label) and
  4985. (hp1_label.typ = ait_label) then
  4986. begin
  4987. JumpLabel_far := tai_label(hp1_label).labsym;
  4988. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4989. { This is an infinite loop }
  4990. Exit;
  4991. if Assigned(JumpLabel_far) then
  4992. begin
  4993. { In this situation, if the first jump branches, the second one will never,
  4994. branch so change the destination label to after the second jump }
  4995. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4996. if Assigned(JumpLabel) then
  4997. JumpLabel.DecRefs;
  4998. JumpLabel_far.IncRefs;
  4999. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5000. Result := True;
  5001. { Don't exit yet. Since p and p_jump haven't actually been
  5002. removed, we can check for more on this iteration }
  5003. Continue;
  5004. end;
  5005. end;
  5006. end;
  5007. end;
  5008. { Search for:
  5009. cmp ###,###
  5010. j(c1) @lbl1
  5011. cmp ###,### (same as first)
  5012. Remove second cmp
  5013. }
  5014. if GetNextInstruction(p_jump, hp2) and
  5015. (
  5016. (
  5017. MatchInstruction(hp2, A_CMP, []) and
  5018. (
  5019. (
  5020. MatchOpType(taicpu(p), top_const, top_reg) and
  5021. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5022. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5023. ) or (
  5024. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5025. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5026. )
  5027. )
  5028. ) or (
  5029. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5030. MatchOperand(taicpu(p).oper[0]^, 0) and
  5031. (taicpu(p).oper[1]^.typ = top_reg) and
  5032. MatchInstruction(hp2, A_TEST, []) and
  5033. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5034. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5035. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5036. )
  5037. ) then
  5038. begin
  5039. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5040. RemoveInstruction(hp2);
  5041. Result := True;
  5042. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5043. end;
  5044. GetNextInstruction(p_jump, p_jump);
  5045. end;
  5046. if taicpu(p).oper[0]^.typ = top_const then
  5047. begin
  5048. if (taicpu(p).oper[0]^.val = 0) and
  5049. (taicpu(p).oper[1]^.typ = top_reg) and
  5050. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5051. begin
  5052. hp2 := p;
  5053. FirstMatch := True;
  5054. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5055. anything meaningful once it's converted to "test %reg,%reg";
  5056. additionally, some jumps will always (or never) branch, so
  5057. evaluate every jump immediately following the
  5058. comparison, optimising the conditions if possible.
  5059. Similarly with SETcc... those that are always set to 0 or 1
  5060. are changed to MOV instructions }
  5061. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5062. (
  5063. GetNextInstruction(hp2, hp1) and
  5064. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5065. ) do
  5066. begin
  5067. FirstMatch := False;
  5068. case taicpu(hp1).condition of
  5069. C_B, C_C, C_NAE, C_O:
  5070. { For B/NAE:
  5071. Will never branch since an unsigned integer can never be below zero
  5072. For C/O:
  5073. Result cannot overflow because 0 is being subtracted
  5074. }
  5075. begin
  5076. if taicpu(hp1).opcode = A_Jcc then
  5077. begin
  5078. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5079. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5080. RemoveInstruction(hp1);
  5081. { Since hp1 was deleted, hp2 must not be updated }
  5082. Continue;
  5083. end
  5084. else
  5085. begin
  5086. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5087. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5088. taicpu(hp1).opcode := A_MOV;
  5089. taicpu(hp1).ops := 2;
  5090. taicpu(hp1).condition := C_None;
  5091. taicpu(hp1).opsize := S_B;
  5092. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5093. taicpu(hp1).loadconst(0, 0);
  5094. end;
  5095. end;
  5096. C_BE, C_NA:
  5097. begin
  5098. { Will only branch if equal to zero }
  5099. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5100. taicpu(hp1).condition := C_E;
  5101. end;
  5102. C_A, C_NBE:
  5103. begin
  5104. { Will only branch if not equal to zero }
  5105. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5106. taicpu(hp1).condition := C_NE;
  5107. end;
  5108. C_AE, C_NB, C_NC, C_NO:
  5109. begin
  5110. { Will always branch }
  5111. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5112. if taicpu(hp1).opcode = A_Jcc then
  5113. begin
  5114. MakeUnconditional(taicpu(hp1));
  5115. { Any jumps/set that follow will now be dead code }
  5116. RemoveDeadCodeAfterJump(taicpu(hp1));
  5117. Break;
  5118. end
  5119. else
  5120. begin
  5121. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5122. taicpu(hp1).opcode := A_MOV;
  5123. taicpu(hp1).ops := 2;
  5124. taicpu(hp1).condition := C_None;
  5125. taicpu(hp1).opsize := S_B;
  5126. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5127. taicpu(hp1).loadconst(0, 1);
  5128. end;
  5129. end;
  5130. C_None:
  5131. InternalError(2020012201);
  5132. C_P, C_PE, C_NP, C_PO:
  5133. { We can't handle parity checks and they should never be generated
  5134. after a general-purpose CMP (it's used in some floating-point
  5135. comparisons that don't use CMP) }
  5136. InternalError(2020012202);
  5137. else
  5138. { Zero/Equality, Sign, their complements and all of the
  5139. signed comparisons do not need to be converted };
  5140. end;
  5141. hp2 := hp1;
  5142. end;
  5143. { Convert the instruction to a TEST }
  5144. taicpu(p).opcode := A_TEST;
  5145. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5146. Result := True;
  5147. Exit;
  5148. end
  5149. else if (taicpu(p).oper[0]^.val = 1) and
  5150. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5151. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5152. begin
  5153. { Convert; To:
  5154. cmp $1,r/m cmp $0,r/m
  5155. jl @lbl jle @lbl
  5156. }
  5157. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5158. taicpu(p).oper[0]^.val := 0;
  5159. taicpu(hp1).condition := C_LE;
  5160. { If the instruction is now "cmp $0,%reg", convert it to a
  5161. TEST (and effectively do the work of the "cmp $0,%reg" in
  5162. the block above)
  5163. If it's a reference, we can get away with not setting
  5164. Result to True because he haven't evaluated the jump
  5165. in this pass yet.
  5166. }
  5167. if (taicpu(p).oper[1]^.typ = top_reg) then
  5168. begin
  5169. taicpu(p).opcode := A_TEST;
  5170. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5171. Result := True;
  5172. end;
  5173. Exit;
  5174. end
  5175. else if (taicpu(p).oper[1]^.typ = top_reg)
  5176. {$ifdef x86_64}
  5177. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5178. {$endif x86_64}
  5179. then
  5180. begin
  5181. { cmp register,$8000 neg register
  5182. je target --> jo target
  5183. .... only if register is deallocated before jump.}
  5184. case Taicpu(p).opsize of
  5185. S_B: v:=$80;
  5186. S_W: v:=$8000;
  5187. S_L: v:=qword($80000000);
  5188. else
  5189. internalerror(2013112905);
  5190. end;
  5191. if (taicpu(p).oper[0]^.val=v) and
  5192. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5193. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5194. begin
  5195. TransferUsedRegs(TmpUsedRegs);
  5196. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5197. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5198. begin
  5199. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5200. Taicpu(p).opcode:=A_NEG;
  5201. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5202. Taicpu(p).clearop(1);
  5203. Taicpu(p).ops:=1;
  5204. if Taicpu(hp1).condition=C_E then
  5205. Taicpu(hp1).condition:=C_O
  5206. else
  5207. Taicpu(hp1).condition:=C_NO;
  5208. Result:=true;
  5209. exit;
  5210. end;
  5211. end;
  5212. end;
  5213. end;
  5214. if MatchInstruction(hp1,A_MOV,[]) and
  5215. (
  5216. (taicpu(p).oper[0]^.typ <> top_reg) or
  5217. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  5218. ) and
  5219. (
  5220. (taicpu(p).oper[1]^.typ <> top_reg) or
  5221. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  5222. ) and
  5223. (
  5224. { Make sure the register written to doesn't appear in the
  5225. cmp instruction (in a reference, say) }
  5226. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5227. not RegInInstruction(taicpu(hp1).oper[1]^.reg, p)
  5228. ) then
  5229. begin
  5230. { If we have something like:
  5231. cmp ###,%reg1
  5232. mov 0,%reg2
  5233. And no registers are shared, move the MOV command to before the
  5234. comparison as this means it can be optimised without worrying
  5235. about the FLAGS register. (This combination is generated by
  5236. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  5237. }
  5238. SwapMovCmp(p, hp1);
  5239. Result := True;
  5240. Exit;
  5241. end;
  5242. end;
  5243. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5244. var
  5245. hp1: tai;
  5246. begin
  5247. {
  5248. remove the second (v)pxor from
  5249. pxor reg,reg
  5250. ...
  5251. pxor reg,reg
  5252. }
  5253. Result:=false;
  5254. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5255. MatchOpType(taicpu(p),top_reg,top_reg) and
  5256. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5257. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5258. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5259. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5260. begin
  5261. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5262. RemoveInstruction(hp1);
  5263. Result:=true;
  5264. Exit;
  5265. end
  5266. {
  5267. replace
  5268. pxor reg1,reg1
  5269. movapd/s reg1,reg2
  5270. dealloc reg1
  5271. by
  5272. pxor reg2,reg2
  5273. }
  5274. else if GetNextInstruction(p,hp1) and
  5275. { we mix single and double opperations here because we assume that the compiler
  5276. generates vmovapd only after double operations and vmovaps only after single operations }
  5277. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5278. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5279. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5280. (taicpu(p).oper[0]^.typ=top_reg) then
  5281. begin
  5282. TransferUsedRegs(TmpUsedRegs);
  5283. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5284. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5285. begin
  5286. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5287. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5288. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5289. RemoveInstruction(hp1);
  5290. result:=true;
  5291. end;
  5292. end;
  5293. end;
  5294. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5295. var
  5296. hp1: tai;
  5297. begin
  5298. {
  5299. remove the second (v)pxor from
  5300. (v)pxor reg,reg
  5301. ...
  5302. (v)pxor reg,reg
  5303. }
  5304. Result:=false;
  5305. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5306. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5307. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5308. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5309. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5310. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5311. begin
  5312. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5313. RemoveInstruction(hp1);
  5314. Result:=true;
  5315. Exit;
  5316. end
  5317. else
  5318. Result:=OptPass1VOP(p);
  5319. end;
  5320. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5321. var
  5322. hp1 : tai;
  5323. begin
  5324. result:=false;
  5325. { replace
  5326. IMul const,%mreg1,%mreg2
  5327. Mov %reg2,%mreg3
  5328. dealloc %mreg3
  5329. by
  5330. Imul const,%mreg1,%mreg23
  5331. }
  5332. if (taicpu(p).ops=3) and
  5333. GetNextInstruction(p,hp1) and
  5334. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5335. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5336. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5337. begin
  5338. TransferUsedRegs(TmpUsedRegs);
  5339. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5340. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5341. begin
  5342. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5343. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5344. RemoveInstruction(hp1);
  5345. result:=true;
  5346. end;
  5347. end;
  5348. end;
  5349. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5350. var
  5351. hp1 : tai;
  5352. begin
  5353. result:=false;
  5354. { replace
  5355. IMul %reg0,%reg1,%reg2
  5356. Mov %reg2,%reg3
  5357. dealloc %reg2
  5358. by
  5359. Imul %reg0,%reg1,%reg3
  5360. }
  5361. if GetNextInstruction(p,hp1) and
  5362. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5363. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5364. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5365. begin
  5366. TransferUsedRegs(TmpUsedRegs);
  5367. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5368. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5369. begin
  5370. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5371. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5372. RemoveInstruction(hp1);
  5373. result:=true;
  5374. end;
  5375. end;
  5376. end;
  5377. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5378. var
  5379. hp1, hp2, hp3, hp4, hp5: tai;
  5380. ThisReg: TRegister;
  5381. begin
  5382. Result := False;
  5383. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5384. Exit;
  5385. {
  5386. convert
  5387. j<c> .L1
  5388. mov 1,reg
  5389. jmp .L2
  5390. .L1
  5391. mov 0,reg
  5392. .L2
  5393. into
  5394. mov 0,reg
  5395. set<not(c)> reg
  5396. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5397. would destroy the flag contents
  5398. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5399. executed at the same time as a previous comparison.
  5400. set<not(c)> reg
  5401. movzx reg, reg
  5402. }
  5403. if MatchInstruction(hp1,A_MOV,[]) and
  5404. (taicpu(hp1).oper[0]^.typ = top_const) and
  5405. (
  5406. (
  5407. (taicpu(hp1).oper[1]^.typ = top_reg)
  5408. {$ifdef i386}
  5409. { Under i386, ESI, EDI, EBP and ESP
  5410. don't have an 8-bit representation }
  5411. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5412. {$endif i386}
  5413. ) or (
  5414. {$ifdef i386}
  5415. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5416. {$endif i386}
  5417. (taicpu(hp1).opsize = S_B)
  5418. )
  5419. ) and
  5420. GetNextInstruction(hp1,hp2) and
  5421. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5422. GetNextInstruction(hp2,hp3) and
  5423. SkipAligns(hp3, hp3) and
  5424. (hp3.typ=ait_label) and
  5425. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5426. GetNextInstruction(hp3,hp4) and
  5427. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5428. (taicpu(hp4).oper[0]^.typ = top_const) and
  5429. (
  5430. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5431. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5432. ) and
  5433. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5434. GetNextInstruction(hp4,hp5) and
  5435. SkipAligns(hp5, hp5) and
  5436. (hp5.typ=ait_label) and
  5437. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5438. begin
  5439. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5440. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5441. tai_label(hp3).labsym.DecRefs;
  5442. { If this isn't the only reference to the middle label, we can
  5443. still make a saving - only that the first jump and everything
  5444. that follows will remain. }
  5445. if (tai_label(hp3).labsym.getrefs = 0) then
  5446. begin
  5447. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5448. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5449. else
  5450. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5451. { remove jump, first label and second MOV (also catching any aligns) }
  5452. repeat
  5453. if not GetNextInstruction(hp2, hp3) then
  5454. InternalError(2021040810);
  5455. RemoveInstruction(hp2);
  5456. hp2 := hp3;
  5457. until hp2 = hp5;
  5458. { Don't decrement reference count before the removal loop
  5459. above, otherwise GetNextInstruction won't stop on the
  5460. the label }
  5461. tai_label(hp5).labsym.DecRefs;
  5462. end
  5463. else
  5464. begin
  5465. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5466. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5467. else
  5468. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5469. end;
  5470. taicpu(p).opcode:=A_SETcc;
  5471. taicpu(p).opsize:=S_B;
  5472. taicpu(p).is_jmp:=False;
  5473. if taicpu(hp1).opsize=S_B then
  5474. begin
  5475. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5476. if taicpu(hp1).oper[1]^.typ = top_reg then
  5477. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  5478. RemoveInstruction(hp1);
  5479. end
  5480. else
  5481. begin
  5482. { Will be a register because the size can't be S_B otherwise }
  5483. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5484. taicpu(p).loadreg(0, ThisReg);
  5485. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  5486. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5487. begin
  5488. case taicpu(hp1).opsize of
  5489. S_W:
  5490. taicpu(hp1).opsize := S_BW;
  5491. S_L:
  5492. taicpu(hp1).opsize := S_BL;
  5493. {$ifdef x86_64}
  5494. S_Q:
  5495. begin
  5496. taicpu(hp1).opsize := S_BL;
  5497. { Change the destination register to 32-bit }
  5498. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5499. end;
  5500. {$endif x86_64}
  5501. else
  5502. InternalError(2021040820);
  5503. end;
  5504. taicpu(hp1).opcode := A_MOVZX;
  5505. taicpu(hp1).loadreg(0, ThisReg);
  5506. end
  5507. else
  5508. begin
  5509. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5510. { hp1 is already a MOV instruction with the correct register }
  5511. taicpu(hp1).loadconst(0, 0);
  5512. { Inserting it right before p will guarantee that the flags are also tracked }
  5513. asml.Remove(hp1);
  5514. asml.InsertBefore(hp1, p);
  5515. end;
  5516. end;
  5517. Result:=true;
  5518. exit;
  5519. end
  5520. end;
  5521. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5522. var
  5523. hp2, hp3, first_assignment: tai;
  5524. IncCount, OperIdx: Integer;
  5525. OrigLabel: TAsmLabel;
  5526. begin
  5527. Count := 0;
  5528. Result := False;
  5529. first_assignment := nil;
  5530. if (LoopCount >= 20) then
  5531. begin
  5532. { Guard against infinite loops }
  5533. Exit;
  5534. end;
  5535. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5536. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5537. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5538. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5539. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5540. Exit;
  5541. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5542. {
  5543. change
  5544. jmp .L1
  5545. ...
  5546. .L1:
  5547. mov ##, ## ( multiple movs possible )
  5548. jmp/ret
  5549. into
  5550. mov ##, ##
  5551. jmp/ret
  5552. }
  5553. if not Assigned(hp1) then
  5554. begin
  5555. hp1 := GetLabelWithSym(OrigLabel);
  5556. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5557. Exit;
  5558. end;
  5559. hp2 := hp1;
  5560. while Assigned(hp2) do
  5561. begin
  5562. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5563. SkipLabels(hp2,hp2);
  5564. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5565. Break;
  5566. case taicpu(hp2).opcode of
  5567. A_MOVSS:
  5568. begin
  5569. if taicpu(hp2).ops = 0 then
  5570. { Wrong MOVSS }
  5571. Break;
  5572. Inc(Count);
  5573. if Count >= 5 then
  5574. { Too many to be worthwhile }
  5575. Break;
  5576. GetNextInstruction(hp2, hp2);
  5577. Continue;
  5578. end;
  5579. A_MOV,
  5580. A_MOVD,
  5581. A_MOVQ,
  5582. A_MOVSX,
  5583. {$ifdef x86_64}
  5584. A_MOVSXD,
  5585. {$endif x86_64}
  5586. A_MOVZX,
  5587. A_MOVAPS,
  5588. A_MOVUPS,
  5589. A_MOVSD,
  5590. A_MOVAPD,
  5591. A_MOVUPD,
  5592. A_MOVDQA,
  5593. A_MOVDQU,
  5594. A_VMOVSS,
  5595. A_VMOVAPS,
  5596. A_VMOVUPS,
  5597. A_VMOVSD,
  5598. A_VMOVAPD,
  5599. A_VMOVUPD,
  5600. A_VMOVDQA,
  5601. A_VMOVDQU:
  5602. begin
  5603. Inc(Count);
  5604. if Count >= 5 then
  5605. { Too many to be worthwhile }
  5606. Break;
  5607. GetNextInstruction(hp2, hp2);
  5608. Continue;
  5609. end;
  5610. A_JMP:
  5611. begin
  5612. { Guard against infinite loops }
  5613. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5614. Exit;
  5615. { Analyse this jump first in case it also duplicates assignments }
  5616. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5617. begin
  5618. { Something did change! }
  5619. Result := True;
  5620. Inc(Count, IncCount);
  5621. if Count >= 5 then
  5622. begin
  5623. { Too many to be worthwhile }
  5624. Exit;
  5625. end;
  5626. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5627. Break;
  5628. end;
  5629. Result := True;
  5630. Break;
  5631. end;
  5632. A_RET:
  5633. begin
  5634. Result := True;
  5635. Break;
  5636. end;
  5637. else
  5638. Break;
  5639. end;
  5640. end;
  5641. if Result then
  5642. begin
  5643. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5644. if Count = 0 then
  5645. begin
  5646. Result := False;
  5647. Exit;
  5648. end;
  5649. hp3 := p;
  5650. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5651. while True do
  5652. begin
  5653. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5654. SkipLabels(hp1,hp1);
  5655. if (hp1.typ <> ait_instruction) then
  5656. InternalError(2021040720);
  5657. case taicpu(hp1).opcode of
  5658. A_JMP:
  5659. begin
  5660. { Change the original jump to the new destination }
  5661. OrigLabel.decrefs;
  5662. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5663. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5664. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5665. if not Assigned(first_assignment) then
  5666. InternalError(2021040810)
  5667. else
  5668. p := first_assignment;
  5669. Exit;
  5670. end;
  5671. A_RET:
  5672. begin
  5673. { Now change the jump into a RET instruction }
  5674. ConvertJumpToRET(p, hp1);
  5675. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5676. if not Assigned(first_assignment) then
  5677. InternalError(2021040811)
  5678. else
  5679. p := first_assignment;
  5680. Exit;
  5681. end;
  5682. else
  5683. begin
  5684. { Duplicate the MOV instruction }
  5685. hp3:=tai(hp1.getcopy);
  5686. if first_assignment = nil then
  5687. first_assignment := hp3;
  5688. asml.InsertBefore(hp3, p);
  5689. { Make sure the compiler knows about any final registers written here }
  5690. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5691. with taicpu(hp3).oper[OperIdx]^ do
  5692. begin
  5693. case typ of
  5694. top_ref:
  5695. begin
  5696. if (ref^.base <> NR_NO) and
  5697. (getsupreg(ref^.base) <> RS_ESP) and
  5698. (getsupreg(ref^.base) <> RS_EBP)
  5699. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5700. then
  5701. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5702. if (ref^.index <> NR_NO) and
  5703. (getsupreg(ref^.index) <> RS_ESP) and
  5704. (getsupreg(ref^.index) <> RS_EBP)
  5705. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5706. (ref^.index <> ref^.base) then
  5707. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5708. end;
  5709. top_reg:
  5710. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5711. else
  5712. ;
  5713. end;
  5714. end;
  5715. end;
  5716. end;
  5717. if not GetNextInstruction(hp1, hp1) then
  5718. { Should have dropped out earlier }
  5719. InternalError(2021040710);
  5720. end;
  5721. end;
  5722. end;
  5723. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5724. var
  5725. hp2: tai;
  5726. X: Integer;
  5727. begin
  5728. asml.Remove(hp1);
  5729. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5730. if not GetLastInstruction(p, hp2) then
  5731. asml.InsertBefore(hp1, p)
  5732. else
  5733. asml.InsertAfter(hp1, hp2);
  5734. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5735. for X := 0 to 1 do
  5736. case taicpu(hp1).oper[X]^.typ of
  5737. top_reg:
  5738. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5739. top_ref:
  5740. begin
  5741. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5742. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5743. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5744. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5745. end;
  5746. else
  5747. ;
  5748. end;
  5749. end;
  5750. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5751. function IsXCHGAcceptable: Boolean; inline;
  5752. begin
  5753. { Always accept if optimising for size }
  5754. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5755. (
  5756. {$ifdef x86_64}
  5757. { XCHG takes 3 cycles on AMD Athlon64 }
  5758. (current_settings.optimizecputype >= cpu_core_i)
  5759. {$else x86_64}
  5760. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5761. than 3, so it becomes a saving compared to three MOVs with two of
  5762. them able to execute simultaneously. [Kit] }
  5763. (current_settings.optimizecputype >= cpu_PentiumM)
  5764. {$endif x86_64}
  5765. );
  5766. end;
  5767. var
  5768. NewRef: TReference;
  5769. hp1, hp2, hp3, hp4: Tai;
  5770. {$ifndef x86_64}
  5771. OperIdx: Integer;
  5772. {$endif x86_64}
  5773. NewInstr : Taicpu;
  5774. NewAligh : Tai_align;
  5775. DestLabel: TAsmLabel;
  5776. begin
  5777. Result:=false;
  5778. { This optimisation adds an instruction, so only do it for speed }
  5779. if not (cs_opt_size in current_settings.optimizerswitches) and
  5780. MatchOpType(taicpu(p), top_const, top_reg) and
  5781. (taicpu(p).oper[0]^.val = 0) then
  5782. begin
  5783. { To avoid compiler warning }
  5784. DestLabel := nil;
  5785. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5786. InternalError(2021040750);
  5787. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5788. Exit;
  5789. case hp1.typ of
  5790. ait_label:
  5791. begin
  5792. { Change:
  5793. mov $0,%reg mov $0,%reg
  5794. @Lbl1: @Lbl1:
  5795. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5796. je @Lbl2 jne @Lbl2
  5797. To: To:
  5798. mov $0,%reg mov $0,%reg
  5799. jmp @Lbl2 jmp @Lbl3
  5800. (align) (align)
  5801. @Lbl1: @Lbl1:
  5802. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5803. je @Lbl2 je @Lbl2
  5804. @Lbl3: <-- Only if label exists
  5805. (Not if it's optimised for size)
  5806. }
  5807. if not GetNextInstruction(hp1, hp2) then
  5808. Exit;
  5809. if not (cs_opt_size in current_settings.optimizerswitches) and
  5810. (hp2.typ = ait_instruction) and
  5811. (
  5812. { Register sizes must exactly match }
  5813. (
  5814. (taicpu(hp2).opcode = A_CMP) and
  5815. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5816. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5817. ) or (
  5818. (taicpu(hp2).opcode = A_TEST) and
  5819. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5820. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5821. )
  5822. ) and GetNextInstruction(hp2, hp3) and
  5823. (hp3.typ = ait_instruction) and
  5824. (taicpu(hp3).opcode = A_JCC) and
  5825. (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
  5826. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5827. begin
  5828. { Check condition of jump }
  5829. { Always true? }
  5830. if condition_in(C_E, taicpu(hp3).condition) then
  5831. begin
  5832. { Copy label symbol and obtain matching label entry for the
  5833. conditional jump, as this will be our destination}
  5834. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5835. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5836. Result := True;
  5837. end
  5838. { Always false? }
  5839. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5840. begin
  5841. { This is only worth it if there's a jump to take }
  5842. case hp2.typ of
  5843. ait_instruction:
  5844. begin
  5845. if taicpu(hp2).opcode = A_JMP then
  5846. begin
  5847. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5848. { An unconditional jump follows the conditional jump which will always be false,
  5849. so use this jump's destination for the new jump }
  5850. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5851. Result := True;
  5852. end
  5853. else if taicpu(hp2).opcode = A_JCC then
  5854. begin
  5855. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5856. if condition_in(C_E, taicpu(hp2).condition) then
  5857. begin
  5858. { A second conditional jump follows the conditional jump which will always be false,
  5859. while the second jump is always True, so use this jump's destination for the new jump }
  5860. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5861. Result := True;
  5862. end;
  5863. { Don't risk it if the jump isn't always true (Result remains False) }
  5864. end;
  5865. end;
  5866. else
  5867. { If anything else don't optimise };
  5868. end;
  5869. end;
  5870. if Result then
  5871. begin
  5872. { Just so we have something to insert as a paremeter}
  5873. reference_reset(NewRef, 1, []);
  5874. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5875. { Now actually load the correct parameter }
  5876. NewInstr.loadsymbol(0, DestLabel, 0);
  5877. { Get instruction before original label (may not be p under -O3) }
  5878. if not GetLastInstruction(hp1, hp2) then
  5879. { Shouldn't fail here }
  5880. InternalError(2021040701);
  5881. DestLabel.increfs;
  5882. AsmL.InsertAfter(NewInstr, hp2);
  5883. { Add new alignment field }
  5884. (* AsmL.InsertAfter(
  5885. cai_align.create_max(
  5886. current_settings.alignment.jumpalign,
  5887. current_settings.alignment.jumpalignskipmax
  5888. ),
  5889. NewInstr
  5890. ); *)
  5891. end;
  5892. Exit;
  5893. end;
  5894. end;
  5895. else
  5896. ;
  5897. end;
  5898. end;
  5899. if not GetNextInstruction(p, hp1) then
  5900. Exit;
  5901. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5902. begin
  5903. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5904. further, but we can't just put this jump optimisation in pass 1
  5905. because it tends to perform worse when conditional jumps are
  5906. nearby (e.g. when converting CMOV instructions). [Kit] }
  5907. if OptPass2JMP(hp1) then
  5908. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5909. Result := OptPass1MOV(p)
  5910. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5911. returned True and the instruction is still a MOV, thus checking
  5912. the optimisations below }
  5913. { If OptPass2JMP returned False, no optimisations were done to
  5914. the jump and there are no further optimisations that can be done
  5915. to the MOV instruction on this pass }
  5916. end
  5917. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5918. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5919. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5920. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5921. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5922. { be lazy, checking separately for sub would be slightly better }
  5923. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5924. begin
  5925. { Change:
  5926. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5927. addl/q $x,%reg2 subl/q $x,%reg2
  5928. To:
  5929. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5930. }
  5931. TransferUsedRegs(TmpUsedRegs);
  5932. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5933. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5934. if not GetNextInstruction(hp1, hp2) or
  5935. (
  5936. { The FLAGS register isn't always tracked properly, so do not
  5937. perform this optimisation if a conditional statement follows }
  5938. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5939. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5940. ) then
  5941. begin
  5942. reference_reset(NewRef, 1, []);
  5943. NewRef.base := taicpu(p).oper[0]^.reg;
  5944. NewRef.scalefactor := 1;
  5945. if taicpu(hp1).opcode = A_ADD then
  5946. begin
  5947. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5948. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5949. end
  5950. else
  5951. begin
  5952. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5953. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5954. end;
  5955. taicpu(p).opcode := A_LEA;
  5956. taicpu(p).loadref(0, NewRef);
  5957. RemoveInstruction(hp1);
  5958. Result := True;
  5959. Exit;
  5960. end;
  5961. end
  5962. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5963. {$ifdef x86_64}
  5964. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5965. {$else x86_64}
  5966. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5967. {$endif x86_64}
  5968. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5969. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5970. { mov reg1, reg2 mov reg1, reg2
  5971. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5972. begin
  5973. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5974. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5975. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5976. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5977. TransferUsedRegs(TmpUsedRegs);
  5978. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5979. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5980. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5981. then
  5982. begin
  5983. RemoveCurrentP(p, hp1);
  5984. Result:=true;
  5985. end;
  5986. exit;
  5987. end
  5988. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5989. IsXCHGAcceptable and
  5990. { XCHG doesn't support 8-byte registers }
  5991. (taicpu(p).opsize <> S_B) and
  5992. MatchInstruction(hp1, A_MOV, []) and
  5993. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5994. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5995. GetNextInstruction(hp1, hp2) and
  5996. MatchInstruction(hp2, A_MOV, []) and
  5997. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5998. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5999. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6000. begin
  6001. { mov %reg1,%reg2
  6002. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6003. mov %reg2,%reg3
  6004. (%reg2 not used afterwards)
  6005. Note that xchg takes 3 cycles to execute, and generally mov's take
  6006. only one cycle apiece, but the first two mov's can be executed in
  6007. parallel, only taking 2 cycles overall. Older processors should
  6008. therefore only optimise for size. [Kit]
  6009. }
  6010. TransferUsedRegs(TmpUsedRegs);
  6011. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6013. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6014. begin
  6015. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6016. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6017. taicpu(hp1).opcode := A_XCHG;
  6018. RemoveCurrentP(p, hp1);
  6019. RemoveInstruction(hp2);
  6020. Result := True;
  6021. Exit;
  6022. end;
  6023. end
  6024. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6025. MatchInstruction(hp1, A_SAR, []) then
  6026. begin
  6027. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6028. begin
  6029. { the use of %edx also covers the opsize being S_L }
  6030. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6031. begin
  6032. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6033. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6034. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6035. begin
  6036. { Change:
  6037. movl %eax,%edx
  6038. sarl $31,%edx
  6039. To:
  6040. cltd
  6041. }
  6042. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6043. RemoveInstruction(hp1);
  6044. taicpu(p).opcode := A_CDQ;
  6045. taicpu(p).opsize := S_NO;
  6046. taicpu(p).clearop(1);
  6047. taicpu(p).clearop(0);
  6048. taicpu(p).ops:=0;
  6049. Result := True;
  6050. end
  6051. else if (cs_opt_size in current_settings.optimizerswitches) and
  6052. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6053. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6054. begin
  6055. { Change:
  6056. movl %edx,%eax
  6057. sarl $31,%edx
  6058. To:
  6059. movl %edx,%eax
  6060. cltd
  6061. Note that this creates a dependency between the two instructions,
  6062. so only perform if optimising for size.
  6063. }
  6064. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6065. taicpu(hp1).opcode := A_CDQ;
  6066. taicpu(hp1).opsize := S_NO;
  6067. taicpu(hp1).clearop(1);
  6068. taicpu(hp1).clearop(0);
  6069. taicpu(hp1).ops:=0;
  6070. end;
  6071. {$ifndef x86_64}
  6072. end
  6073. { Don't bother if CMOV is supported, because a more optimal
  6074. sequence would have been generated for the Abs() intrinsic }
  6075. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6076. { the use of %eax also covers the opsize being S_L }
  6077. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6078. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6079. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6080. GetNextInstruction(hp1, hp2) and
  6081. MatchInstruction(hp2, A_XOR, [S_L]) and
  6082. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6083. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6084. GetNextInstruction(hp2, hp3) and
  6085. MatchInstruction(hp3, A_SUB, [S_L]) and
  6086. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6087. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6088. begin
  6089. { Change:
  6090. movl %eax,%edx
  6091. sarl $31,%eax
  6092. xorl %eax,%edx
  6093. subl %eax,%edx
  6094. (Instruction that uses %edx)
  6095. (%eax deallocated)
  6096. (%edx deallocated)
  6097. To:
  6098. cltd
  6099. xorl %edx,%eax <-- Note the registers have swapped
  6100. subl %edx,%eax
  6101. (Instruction that uses %eax) <-- %eax rather than %edx
  6102. }
  6103. TransferUsedRegs(TmpUsedRegs);
  6104. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6105. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6106. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6107. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6108. begin
  6109. if GetNextInstruction(hp3, hp4) and
  6110. not RegModifiedByInstruction(NR_EDX, hp4) and
  6111. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6112. begin
  6113. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6114. taicpu(p).opcode := A_CDQ;
  6115. taicpu(p).clearop(1);
  6116. taicpu(p).clearop(0);
  6117. taicpu(p).ops:=0;
  6118. RemoveInstruction(hp1);
  6119. taicpu(hp2).loadreg(0, NR_EDX);
  6120. taicpu(hp2).loadreg(1, NR_EAX);
  6121. taicpu(hp3).loadreg(0, NR_EDX);
  6122. taicpu(hp3).loadreg(1, NR_EAX);
  6123. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6124. { Convert references in the following instruction (hp4) from %edx to %eax }
  6125. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6126. with taicpu(hp4).oper[OperIdx]^ do
  6127. case typ of
  6128. top_reg:
  6129. if getsupreg(reg) = RS_EDX then
  6130. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6131. top_ref:
  6132. begin
  6133. if getsupreg(reg) = RS_EDX then
  6134. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6135. if getsupreg(reg) = RS_EDX then
  6136. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6137. end;
  6138. else
  6139. ;
  6140. end;
  6141. end;
  6142. end;
  6143. {$else x86_64}
  6144. end;
  6145. end
  6146. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6147. { the use of %rdx also covers the opsize being S_Q }
  6148. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6149. begin
  6150. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6151. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6152. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6153. begin
  6154. { Change:
  6155. movq %rax,%rdx
  6156. sarq $63,%rdx
  6157. To:
  6158. cqto
  6159. }
  6160. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6161. RemoveInstruction(hp1);
  6162. taicpu(p).opcode := A_CQO;
  6163. taicpu(p).opsize := S_NO;
  6164. taicpu(p).clearop(1);
  6165. taicpu(p).clearop(0);
  6166. taicpu(p).ops:=0;
  6167. Result := True;
  6168. end
  6169. else if (cs_opt_size in current_settings.optimizerswitches) and
  6170. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6171. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6172. begin
  6173. { Change:
  6174. movq %rdx,%rax
  6175. sarq $63,%rdx
  6176. To:
  6177. movq %rdx,%rax
  6178. cqto
  6179. Note that this creates a dependency between the two instructions,
  6180. so only perform if optimising for size.
  6181. }
  6182. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6183. taicpu(hp1).opcode := A_CQO;
  6184. taicpu(hp1).opsize := S_NO;
  6185. taicpu(hp1).clearop(1);
  6186. taicpu(hp1).clearop(0);
  6187. taicpu(hp1).ops:=0;
  6188. {$endif x86_64}
  6189. end;
  6190. end;
  6191. end
  6192. else if MatchInstruction(hp1, A_MOV, []) and
  6193. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6194. { Though "GetNextInstruction" could be factored out, along with
  6195. the instructions that depend on hp2, it is an expensive call that
  6196. should be delayed for as long as possible, hence we do cheaper
  6197. checks first that are likely to be False. [Kit] }
  6198. begin
  6199. if (
  6200. (
  6201. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6202. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6203. (
  6204. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6205. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6206. )
  6207. ) or
  6208. (
  6209. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6210. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6211. (
  6212. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6213. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6214. )
  6215. )
  6216. ) and
  6217. GetNextInstruction(hp1, hp2) and
  6218. MatchInstruction(hp2, A_SAR, []) and
  6219. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6220. begin
  6221. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6222. begin
  6223. { Change:
  6224. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6225. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6226. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6227. To:
  6228. movl r/m,%eax <- Note the change in register
  6229. cltd
  6230. }
  6231. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6232. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6233. taicpu(p).loadreg(1, NR_EAX);
  6234. taicpu(hp1).opcode := A_CDQ;
  6235. taicpu(hp1).clearop(1);
  6236. taicpu(hp1).clearop(0);
  6237. taicpu(hp1).ops:=0;
  6238. RemoveInstruction(hp2);
  6239. (*
  6240. {$ifdef x86_64}
  6241. end
  6242. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6243. { This code sequence does not get generated - however it might become useful
  6244. if and when 128-bit signed integer types make an appearance, so the code
  6245. is kept here for when it is eventually needed. [Kit] }
  6246. (
  6247. (
  6248. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6249. (
  6250. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6251. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6252. )
  6253. ) or
  6254. (
  6255. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6256. (
  6257. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6258. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6259. )
  6260. )
  6261. ) and
  6262. GetNextInstruction(hp1, hp2) and
  6263. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6264. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6265. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6266. begin
  6267. { Change:
  6268. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6269. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6270. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6271. To:
  6272. movq r/m,%rax <- Note the change in register
  6273. cqto
  6274. }
  6275. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6276. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6277. taicpu(p).loadreg(1, NR_RAX);
  6278. taicpu(hp1).opcode := A_CQO;
  6279. taicpu(hp1).clearop(1);
  6280. taicpu(hp1).clearop(0);
  6281. taicpu(hp1).ops:=0;
  6282. RemoveInstruction(hp2);
  6283. {$endif x86_64}
  6284. *)
  6285. end;
  6286. end;
  6287. {$ifdef x86_64}
  6288. end
  6289. else if (taicpu(p).opsize = S_L) and
  6290. (taicpu(p).oper[1]^.typ = top_reg) and
  6291. (
  6292. MatchInstruction(hp1, A_MOV,[]) and
  6293. (taicpu(hp1).opsize = S_L) and
  6294. (taicpu(hp1).oper[1]^.typ = top_reg)
  6295. ) and (
  6296. GetNextInstruction(hp1, hp2) and
  6297. (tai(hp2).typ=ait_instruction) and
  6298. (taicpu(hp2).opsize = S_Q) and
  6299. (
  6300. (
  6301. MatchInstruction(hp2, A_ADD,[]) and
  6302. (taicpu(hp2).opsize = S_Q) and
  6303. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6304. (
  6305. (
  6306. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6307. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6308. ) or (
  6309. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6310. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6311. )
  6312. )
  6313. ) or (
  6314. MatchInstruction(hp2, A_LEA,[]) and
  6315. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6316. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6317. (
  6318. (
  6319. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6320. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6321. ) or (
  6322. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6323. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6324. )
  6325. ) and (
  6326. (
  6327. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6328. ) or (
  6329. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6330. )
  6331. )
  6332. )
  6333. )
  6334. ) and (
  6335. GetNextInstruction(hp2, hp3) and
  6336. MatchInstruction(hp3, A_SHR,[]) and
  6337. (taicpu(hp3).opsize = S_Q) and
  6338. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6339. (taicpu(hp3).oper[0]^.val = 1) and
  6340. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6341. ) then
  6342. begin
  6343. { Change movl x, reg1d movl x, reg1d
  6344. movl y, reg2d movl y, reg2d
  6345. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6346. shrq $1, reg1q shrq $1, reg1q
  6347. ( reg1d and reg2d can be switched around in the first two instructions )
  6348. To movl x, reg1d
  6349. addl y, reg1d
  6350. rcrl $1, reg1d
  6351. This corresponds to the common expression (x + y) shr 1, where
  6352. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6353. smaller code, but won't account for x + y causing an overflow). [Kit]
  6354. }
  6355. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6356. { Change first MOV command to have the same register as the final output }
  6357. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6358. else
  6359. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6360. { Change second MOV command to an ADD command. This is easier than
  6361. converting the existing command because it means we don't have to
  6362. touch 'y', which might be a complicated reference, and also the
  6363. fact that the third command might either be ADD or LEA. [Kit] }
  6364. taicpu(hp1).opcode := A_ADD;
  6365. { Delete old ADD/LEA instruction }
  6366. RemoveInstruction(hp2);
  6367. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6368. taicpu(hp3).opcode := A_RCR;
  6369. taicpu(hp3).changeopsize(S_L);
  6370. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6371. {$endif x86_64}
  6372. end;
  6373. end;
  6374. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6375. var
  6376. ThisReg: TRegister;
  6377. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6378. TargetSubReg: TSubRegister;
  6379. hp1, hp2: tai;
  6380. RegInUse, RegChanged, p_removed: Boolean;
  6381. { Store list of found instructions so we don't have to call
  6382. GetNextInstructionUsingReg multiple times }
  6383. InstrList: array of taicpu;
  6384. InstrMax, Index: Integer;
  6385. UpperLimit, TrySmallerLimit: TCgInt;
  6386. PreMessage: string;
  6387. { Data flow analysis }
  6388. TestValMin, TestValMax: TCgInt;
  6389. SmallerOverflow: Boolean;
  6390. begin
  6391. Result := False;
  6392. p_removed := False;
  6393. { This is anything but quick! }
  6394. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6395. Exit;
  6396. SetLength(InstrList, 0);
  6397. InstrMax := -1;
  6398. ThisReg := taicpu(p).oper[1]^.reg;
  6399. case taicpu(p).opsize of
  6400. S_BW, S_BL:
  6401. begin
  6402. {$if defined(i386) or defined(i8086)}
  6403. { If the target size is 8-bit, make sure we can actually encode it }
  6404. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6405. Exit;
  6406. {$endif i386 or i8086}
  6407. UpperLimit := $FF;
  6408. MinSize := S_B;
  6409. if taicpu(p).opsize = S_BW then
  6410. MaxSize := S_W
  6411. else
  6412. MaxSize := S_L;
  6413. end;
  6414. S_WL:
  6415. begin
  6416. UpperLimit := $FFFF;
  6417. MinSize := S_W;
  6418. MaxSize := S_L;
  6419. end
  6420. else
  6421. InternalError(2020112301);
  6422. end;
  6423. TestValMin := 0;
  6424. TestValMax := UpperLimit;
  6425. TrySmallerLimit := UpperLimit;
  6426. TrySmaller := S_NO;
  6427. SmallerOverflow := False;
  6428. RegChanged := False;
  6429. hp1 := p;
  6430. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6431. (hp1.typ = ait_instruction) and
  6432. (
  6433. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6434. instruction that doesn't actually contain ThisReg }
  6435. (cs_opt_level3 in current_settings.optimizerswitches) or
  6436. RegInInstruction(ThisReg, hp1)
  6437. ) do
  6438. begin
  6439. case taicpu(hp1).opcode of
  6440. A_INC,A_DEC:
  6441. begin
  6442. { Has to be an exact match on the register }
  6443. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6444. Break;
  6445. if taicpu(hp1).opcode = A_INC then
  6446. begin
  6447. Inc(TestValMin);
  6448. Inc(TestValMax);
  6449. end
  6450. else
  6451. begin
  6452. Dec(TestValMin);
  6453. Dec(TestValMax);
  6454. end;
  6455. end;
  6456. A_CMP:
  6457. begin
  6458. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6459. { Has to be an exact match on the register }
  6460. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6461. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6462. { Make sure the comparison value is not smaller than the
  6463. smallest allowed signed value for the minimum size (e.g.
  6464. -128 for 8-bit) }
  6465. not (
  6466. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6467. { Is it in the negative range? }
  6468. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6469. ) then
  6470. Break;
  6471. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6472. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6473. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6474. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6475. { Overflow }
  6476. Break;
  6477. { Check to see if the active register is used afterwards }
  6478. TransferUsedRegs(TmpUsedRegs);
  6479. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6480. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6481. begin
  6482. case MinSize of
  6483. S_B:
  6484. TargetSubReg := R_SUBL;
  6485. S_W:
  6486. TargetSubReg := R_SUBW;
  6487. else
  6488. InternalError(2021051002);
  6489. end;
  6490. { Update the register to its new size }
  6491. setsubreg(ThisReg, TargetSubReg);
  6492. taicpu(hp1).oper[1]^.reg := ThisReg;
  6493. taicpu(hp1).opsize := MinSize;
  6494. { Convert the input MOVZX to a MOV }
  6495. if (taicpu(p).oper[0]^.typ = top_reg) and
  6496. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6497. begin
  6498. { Or remove it completely! }
  6499. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6500. RemoveCurrentP(p);
  6501. p_removed := True;
  6502. end
  6503. else
  6504. begin
  6505. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6506. taicpu(p).opcode := A_MOV;
  6507. taicpu(p).oper[1]^.reg := ThisReg;
  6508. taicpu(p).opsize := MinSize;
  6509. end;
  6510. if (InstrMax >= 0) then
  6511. begin
  6512. for Index := 0 to InstrMax do
  6513. begin
  6514. { If p_removed is true, then the original MOV/Z was removed
  6515. and removing the AND instruction may not be safe if it
  6516. appears first }
  6517. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6518. InternalError(2020112311);
  6519. if InstrList[Index].oper[0]^.typ = top_reg then
  6520. InstrList[Index].oper[0]^.reg := ThisReg;
  6521. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6522. InstrList[Index].opsize := MinSize;
  6523. end;
  6524. end;
  6525. Result := True;
  6526. Exit;
  6527. end;
  6528. end;
  6529. { OR and XOR are not included because they can too easily fool
  6530. the data flow analysis (they can cause non-linear behaviour) }
  6531. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6532. begin
  6533. if
  6534. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6535. { Has to be an exact match on the register }
  6536. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6537. (
  6538. (
  6539. (taicpu(hp1).oper[0]^.typ = top_const) and
  6540. (
  6541. (
  6542. (taicpu(hp1).opcode = A_SHL) and
  6543. (
  6544. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6545. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6546. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6547. )
  6548. ) or (
  6549. (taicpu(hp1).opcode <> A_SHL) and
  6550. (
  6551. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6552. { Is it in the negative range? }
  6553. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6554. )
  6555. )
  6556. )
  6557. ) or (
  6558. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6559. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6560. )
  6561. ) then
  6562. Break;
  6563. case taicpu(hp1).opcode of
  6564. A_ADD:
  6565. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6566. begin
  6567. TestValMin := TestValMin * 2;
  6568. TestValMax := TestValMax * 2;
  6569. end
  6570. else
  6571. begin
  6572. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6573. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6574. end;
  6575. A_SUB:
  6576. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6577. begin
  6578. TestValMin := 0;
  6579. TestValMax := 0;
  6580. end
  6581. else
  6582. begin
  6583. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6584. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6585. end;
  6586. A_AND:
  6587. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6588. begin
  6589. { we might be able to go smaller if AND appears first }
  6590. if InstrMax = -1 then
  6591. case MinSize of
  6592. S_B:
  6593. ;
  6594. S_W:
  6595. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6596. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6597. begin
  6598. TrySmaller := S_B;
  6599. TrySmallerLimit := $FF;
  6600. end;
  6601. S_L:
  6602. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6603. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6604. begin
  6605. TrySmaller := S_B;
  6606. TrySmallerLimit := $FF;
  6607. end
  6608. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6609. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6610. begin
  6611. TrySmaller := S_W;
  6612. TrySmallerLimit := $FFFF;
  6613. end;
  6614. else
  6615. InternalError(2020112320);
  6616. end;
  6617. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6618. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6619. end;
  6620. A_SHL:
  6621. begin
  6622. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6623. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6624. end;
  6625. A_SHR:
  6626. begin
  6627. { we might be able to go smaller if SHR appears first }
  6628. if InstrMax = -1 then
  6629. case MinSize of
  6630. S_B:
  6631. ;
  6632. S_W:
  6633. if (taicpu(hp1).oper[0]^.val >= 8) then
  6634. begin
  6635. TrySmaller := S_B;
  6636. TrySmallerLimit := $FF;
  6637. end;
  6638. S_L:
  6639. if (taicpu(hp1).oper[0]^.val >= 24) then
  6640. begin
  6641. TrySmaller := S_B;
  6642. TrySmallerLimit := $FF;
  6643. end
  6644. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6645. begin
  6646. TrySmaller := S_W;
  6647. TrySmallerLimit := $FFFF;
  6648. end;
  6649. else
  6650. InternalError(2020112321);
  6651. end;
  6652. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6653. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6654. end;
  6655. else
  6656. InternalError(2020112303);
  6657. end;
  6658. end;
  6659. (*
  6660. A_IMUL:
  6661. case taicpu(hp1).ops of
  6662. 2:
  6663. begin
  6664. if not MatchOpType(hp1, top_reg, top_reg) or
  6665. { Has to be an exact match on the register }
  6666. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6667. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6668. Break;
  6669. TestValMin := TestValMin * TestValMin;
  6670. TestValMax := TestValMax * TestValMax;
  6671. end;
  6672. 3:
  6673. begin
  6674. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6675. { Has to be an exact match on the register }
  6676. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6677. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6678. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6679. { Is it in the negative range? }
  6680. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6681. Break;
  6682. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6683. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6684. end;
  6685. else
  6686. Break;
  6687. end;
  6688. A_IDIV:
  6689. case taicpu(hp1).ops of
  6690. 3:
  6691. begin
  6692. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6693. { Has to be an exact match on the register }
  6694. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6695. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6696. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6697. { Is it in the negative range? }
  6698. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6699. Break;
  6700. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6701. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6702. end;
  6703. else
  6704. Break;
  6705. end;
  6706. *)
  6707. A_MOVZX:
  6708. begin
  6709. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6710. Break;
  6711. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6712. begin
  6713. { Because hp1 was obtained via GetNextInstructionUsingReg
  6714. and ThisReg doesn't appear in the first operand, it
  6715. must appear in the second operand and hence gets
  6716. overwritten }
  6717. if (InstrMax = -1) and
  6718. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6719. begin
  6720. { The two MOVZX instructions are adjacent, so remove the first one }
  6721. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6722. RemoveCurrentP(p);
  6723. Result := True;
  6724. Exit;
  6725. end;
  6726. Break;
  6727. end;
  6728. { The objective here is to try to find a combination that
  6729. removes one of the MOV/Z instructions. }
  6730. case taicpu(hp1).opsize of
  6731. S_WL:
  6732. if (MinSize in [S_B, S_W]) then
  6733. begin
  6734. TargetSize := S_L;
  6735. TargetSubReg := R_SUBD;
  6736. end
  6737. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6738. begin
  6739. TargetSize := TrySmaller;
  6740. if TrySmaller = S_B then
  6741. TargetSubReg := R_SUBL
  6742. else
  6743. TargetSubReg := R_SUBW;
  6744. end
  6745. else
  6746. Break;
  6747. S_BW:
  6748. if (MinSize in [S_B, S_W]) then
  6749. begin
  6750. TargetSize := S_W;
  6751. TargetSubReg := R_SUBW;
  6752. end
  6753. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6754. begin
  6755. TargetSize := S_B;
  6756. TargetSubReg := R_SUBL;
  6757. end
  6758. else
  6759. Break;
  6760. S_BL:
  6761. if (MinSize in [S_B, S_W]) then
  6762. begin
  6763. TargetSize := S_L;
  6764. TargetSubReg := R_SUBD;
  6765. end
  6766. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6767. begin
  6768. TargetSize := S_B;
  6769. TargetSubReg := R_SUBL;
  6770. end
  6771. else
  6772. Break;
  6773. else
  6774. InternalError(2020112302);
  6775. end;
  6776. { Update the register to its new size }
  6777. setsubreg(ThisReg, TargetSubReg);
  6778. if TargetSize = MinSize then
  6779. begin
  6780. { Convert the input MOVZX to a MOV }
  6781. if (taicpu(p).oper[0]^.typ = top_reg) and
  6782. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6783. begin
  6784. { Or remove it completely! }
  6785. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6786. RemoveCurrentP(p);
  6787. p_removed := True;
  6788. end
  6789. else
  6790. begin
  6791. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6792. taicpu(p).opcode := A_MOV;
  6793. taicpu(p).oper[1]^.reg := ThisReg;
  6794. taicpu(p).opsize := TargetSize;
  6795. end;
  6796. Result := True;
  6797. end
  6798. else if TargetSize <> MaxSize then
  6799. begin
  6800. case MaxSize of
  6801. S_L:
  6802. if TargetSize = S_W then
  6803. begin
  6804. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6805. taicpu(p).opsize := S_BW;
  6806. taicpu(p).oper[1]^.reg := ThisReg;
  6807. Result := True;
  6808. end
  6809. else
  6810. InternalError(2020112341);
  6811. S_W:
  6812. if TargetSize = S_L then
  6813. begin
  6814. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6815. taicpu(p).opsize := S_BL;
  6816. taicpu(p).oper[1]^.reg := ThisReg;
  6817. Result := True;
  6818. end
  6819. else
  6820. InternalError(2020112342);
  6821. else
  6822. ;
  6823. end;
  6824. end;
  6825. if (MaxSize = TargetSize) or
  6826. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6827. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6828. begin
  6829. { Convert the output MOVZX to a MOV }
  6830. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6831. begin
  6832. { Or remove it completely! }
  6833. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6834. { Be careful; if p = hp1 and p was also removed, p
  6835. will become a dangling pointer }
  6836. if p = hp1 then
  6837. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6838. else
  6839. RemoveInstruction(hp1);
  6840. end
  6841. else
  6842. begin
  6843. taicpu(hp1).opcode := A_MOV;
  6844. taicpu(hp1).oper[0]^.reg := ThisReg;
  6845. taicpu(hp1).opsize := TargetSize;
  6846. { Check to see if the active register is used afterwards;
  6847. if not, we can change it and make a saving. }
  6848. RegInUse := False;
  6849. TransferUsedRegs(TmpUsedRegs);
  6850. { The target register may be marked as in use to cross
  6851. a jump to a distant label, so exclude it }
  6852. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6853. hp2 := p;
  6854. repeat
  6855. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6856. { Explicitly check for the excluded register (don't include the first
  6857. instruction as it may be reading from here }
  6858. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6859. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6860. begin
  6861. RegInUse := True;
  6862. Break;
  6863. end;
  6864. if not GetNextInstruction(hp2, hp2) then
  6865. InternalError(2020112340);
  6866. until (hp2 = hp1);
  6867. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6868. begin
  6869. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6870. ThisReg := taicpu(hp1).oper[1]^.reg;
  6871. RegChanged := True;
  6872. TransferUsedRegs(TmpUsedRegs);
  6873. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6874. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6875. if p = hp1 then
  6876. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6877. else
  6878. RemoveInstruction(hp1);
  6879. { Instruction will become "mov %reg,%reg" }
  6880. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6881. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6882. begin
  6883. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6884. RemoveCurrentP(p);
  6885. p_removed := True;
  6886. end
  6887. else
  6888. taicpu(p).oper[1]^.reg := ThisReg;
  6889. Result := True;
  6890. end
  6891. else
  6892. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6893. end;
  6894. end
  6895. else
  6896. InternalError(2020112330);
  6897. { Now go through every instruction we found and change the
  6898. size. If TargetSize = MaxSize, then almost no changes are
  6899. needed and Result can remain False if it hasn't been set
  6900. yet.
  6901. If RegChanged is True, then the register requires changing
  6902. and so the point about TargetSize = MaxSize doesn't apply. }
  6903. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6904. begin
  6905. for Index := 0 to InstrMax do
  6906. begin
  6907. { If p_removed is true, then the original MOV/Z was removed
  6908. and removing the AND instruction may not be safe if it
  6909. appears first }
  6910. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6911. InternalError(2020112310);
  6912. if InstrList[Index].oper[0]^.typ = top_reg then
  6913. InstrList[Index].oper[0]^.reg := ThisReg;
  6914. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6915. InstrList[Index].opsize := TargetSize;
  6916. end;
  6917. Result := True;
  6918. end;
  6919. Exit;
  6920. end;
  6921. else
  6922. { This includes ADC, SBB, IDIV and SAR }
  6923. Break;
  6924. end;
  6925. if (TestValMin < 0) or (TestValMax < 0) or
  6926. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6927. { Overflow }
  6928. Break
  6929. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6930. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6931. SmallerOverflow := True;
  6932. { Contains highest index (so instruction count - 1) }
  6933. Inc(InstrMax);
  6934. if InstrMax > High(InstrList) then
  6935. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6936. InstrList[InstrMax] := taicpu(hp1);
  6937. end;
  6938. end;
  6939. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6940. var
  6941. hp1 : tai;
  6942. begin
  6943. Result:=false;
  6944. if (taicpu(p).ops >= 2) and
  6945. ((taicpu(p).oper[0]^.typ = top_const) or
  6946. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6947. (taicpu(p).oper[1]^.typ = top_reg) and
  6948. ((taicpu(p).ops = 2) or
  6949. ((taicpu(p).oper[2]^.typ = top_reg) and
  6950. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6951. GetLastInstruction(p,hp1) and
  6952. MatchInstruction(hp1,A_MOV,[]) and
  6953. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6954. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6955. begin
  6956. TransferUsedRegs(TmpUsedRegs);
  6957. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6958. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6959. { change
  6960. mov reg1,reg2
  6961. imul y,reg2 to imul y,reg1,reg2 }
  6962. begin
  6963. taicpu(p).ops := 3;
  6964. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6965. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6966. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6967. RemoveInstruction(hp1);
  6968. result:=true;
  6969. end;
  6970. end;
  6971. end;
  6972. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6973. var
  6974. ThisLabel: TAsmLabel;
  6975. begin
  6976. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6977. ThisLabel.decrefs;
  6978. taicpu(p).opcode := A_RET;
  6979. taicpu(p).is_jmp := false;
  6980. taicpu(p).ops := taicpu(ret_p).ops;
  6981. case taicpu(ret_p).ops of
  6982. 0:
  6983. taicpu(p).clearop(0);
  6984. 1:
  6985. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6986. else
  6987. internalerror(2016041301);
  6988. end;
  6989. { If the original label is now dead, it might turn out that the label
  6990. immediately follows p. As a result, everything beyond it, which will
  6991. be just some final register configuration and a RET instruction, is
  6992. now dead code. [Kit] }
  6993. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6994. running RemoveDeadCodeAfterJump for each RET instruction, because
  6995. this optimisation rarely happens and most RETs appear at the end of
  6996. routines where there is nothing that can be stripped. [Kit] }
  6997. if not ThisLabel.is_used then
  6998. RemoveDeadCodeAfterJump(p);
  6999. end;
  7000. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  7001. var
  7002. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  7003. Unconditional, PotentialModified: Boolean;
  7004. OperPtr: POper;
  7005. NewRef: TReference;
  7006. InstrList: array of taicpu;
  7007. InstrMax, Index: Integer;
  7008. const
  7009. {$ifdef DEBUG_AOPTCPU}
  7010. SNoFlags: shortstring = ' so the flags aren''t modified';
  7011. {$else DEBUG_AOPTCPU}
  7012. SNoFlags = '';
  7013. {$endif DEBUG_AOPTCPU}
  7014. begin
  7015. Result:=false;
  7016. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  7017. begin
  7018. if MatchInstruction(hp1, A_TEST, [S_B]) and
  7019. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7020. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7021. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7022. GetNextInstruction(hp1, hp2) and
  7023. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  7024. { Change from: To:
  7025. set(C) %reg j(~C) label
  7026. test %reg,%reg/cmp $0,%reg
  7027. je label
  7028. set(C) %reg j(C) label
  7029. test %reg,%reg/cmp $0,%reg
  7030. jne label
  7031. (Also do something similar with sete/setne instead of je/jne)
  7032. }
  7033. begin
  7034. { Before we do anything else, we need to check the instructions
  7035. in between SETcc and TEST to make sure they don't modify the
  7036. FLAGS register - if -O2 or under, there won't be any
  7037. instructions between SET and TEST }
  7038. TransferUsedRegs(TmpUsedRegs);
  7039. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7040. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7041. begin
  7042. next := p;
  7043. SetLength(InstrList, 0);
  7044. InstrMax := -1;
  7045. PotentialModified := False;
  7046. { Make a note of every instruction that modifies the FLAGS
  7047. register }
  7048. while GetNextInstruction(next, next) and (next <> hp1) do
  7049. begin
  7050. if next.typ <> ait_instruction then
  7051. { GetNextInstructionUsingReg should have returned False }
  7052. InternalError(2021051701);
  7053. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7054. begin
  7055. case taicpu(next).opcode of
  7056. A_SETcc,
  7057. A_CMOVcc,
  7058. A_Jcc:
  7059. begin
  7060. if PotentialModified then
  7061. { Not safe because the flags were modified earlier }
  7062. Exit
  7063. else
  7064. { Condition is the same as the initial SETcc, so this is safe
  7065. (don't add to instruction list though) }
  7066. Continue;
  7067. end;
  7068. A_ADD:
  7069. begin
  7070. if (taicpu(next).opsize = S_B) or
  7071. { LEA doesn't support 8-bit operands }
  7072. (taicpu(next).oper[1]^.typ <> top_reg) or
  7073. { Must write to a register }
  7074. (taicpu(next).oper[0]^.typ = top_ref) then
  7075. { Require a constant or a register }
  7076. Exit;
  7077. PotentialModified := True;
  7078. end;
  7079. A_SUB:
  7080. begin
  7081. if (taicpu(next).opsize = S_B) or
  7082. { LEA doesn't support 8-bit operands }
  7083. (taicpu(next).oper[1]^.typ <> top_reg) or
  7084. { Must write to a register }
  7085. (taicpu(next).oper[0]^.typ <> top_const) or
  7086. (taicpu(next).oper[0]^.val = $80000000) then
  7087. { Can't subtract a register with LEA - also
  7088. check that the value isn't -2^31, as this
  7089. can't be negated }
  7090. Exit;
  7091. PotentialModified := True;
  7092. end;
  7093. A_SAL,
  7094. A_SHL:
  7095. begin
  7096. if (taicpu(next).opsize = S_B) or
  7097. { LEA doesn't support 8-bit operands }
  7098. (taicpu(next).oper[1]^.typ <> top_reg) or
  7099. { Must write to a register }
  7100. (taicpu(next).oper[0]^.typ <> top_const) or
  7101. (taicpu(next).oper[0]^.val < 0) or
  7102. (taicpu(next).oper[0]^.val > 3) then
  7103. Exit;
  7104. PotentialModified := True;
  7105. end;
  7106. A_IMUL:
  7107. begin
  7108. if (taicpu(next).ops <> 3) or
  7109. (taicpu(next).oper[1]^.typ <> top_reg) or
  7110. { Must write to a register }
  7111. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7112. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7113. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7114. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7115. Exit
  7116. else
  7117. PotentialModified := True;
  7118. end;
  7119. else
  7120. { Don't know how to change this, so abort }
  7121. Exit;
  7122. end;
  7123. { Contains highest index (so instruction count - 1) }
  7124. Inc(InstrMax);
  7125. if InstrMax > High(InstrList) then
  7126. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7127. InstrList[InstrMax] := taicpu(next);
  7128. end;
  7129. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7130. end;
  7131. if not Assigned(next) or (next <> hp1) then
  7132. { It should be equal to hp1 }
  7133. InternalError(2021051702);
  7134. { Cycle through each instruction and check to see if we can
  7135. change them to versions that don't modify the flags }
  7136. if (InstrMax >= 0) then
  7137. begin
  7138. for Index := 0 to InstrMax do
  7139. case InstrList[Index].opcode of
  7140. A_ADD:
  7141. begin
  7142. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7143. InstrList[Index].opcode := A_LEA;
  7144. reference_reset(NewRef, 1, []);
  7145. NewRef.base := InstrList[Index].oper[1]^.reg;
  7146. if InstrList[Index].oper[0]^.typ = top_reg then
  7147. begin
  7148. NewRef.index := InstrList[Index].oper[0]^.reg;
  7149. NewRef.scalefactor := 1;
  7150. end
  7151. else
  7152. NewRef.offset := InstrList[Index].oper[0]^.val;
  7153. InstrList[Index].loadref(0, NewRef);
  7154. end;
  7155. A_SUB:
  7156. begin
  7157. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7158. InstrList[Index].opcode := A_LEA;
  7159. reference_reset(NewRef, 1, []);
  7160. NewRef.base := InstrList[Index].oper[1]^.reg;
  7161. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7162. InstrList[Index].loadref(0, NewRef);
  7163. end;
  7164. A_SHL,
  7165. A_SAL:
  7166. begin
  7167. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7168. InstrList[Index].opcode := A_LEA;
  7169. reference_reset(NewRef, 1, []);
  7170. NewRef.index := InstrList[Index].oper[1]^.reg;
  7171. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7172. InstrList[Index].loadref(0, NewRef);
  7173. end;
  7174. A_IMUL:
  7175. begin
  7176. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7177. InstrList[Index].opcode := A_LEA;
  7178. reference_reset(NewRef, 1, []);
  7179. NewRef.index := InstrList[Index].oper[1]^.reg;
  7180. case InstrList[Index].oper[0]^.val of
  7181. 2, 4, 8:
  7182. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7183. else {3, 5 and 9}
  7184. begin
  7185. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7186. NewRef.base := InstrList[Index].oper[1]^.reg;
  7187. end;
  7188. end;
  7189. InstrList[Index].loadref(0, NewRef);
  7190. end;
  7191. else
  7192. InternalError(2021051710);
  7193. end;
  7194. end;
  7195. { Mark the FLAGS register as used across this whole block }
  7196. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7197. end;
  7198. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7199. JumpC := taicpu(hp2).condition;
  7200. Unconditional := False;
  7201. if conditions_equal(JumpC, C_E) then
  7202. SetC := inverse_cond(taicpu(p).condition)
  7203. else if conditions_equal(JumpC, C_NE) then
  7204. SetC := taicpu(p).condition
  7205. else
  7206. { We've got something weird here (and inefficent) }
  7207. begin
  7208. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7209. SetC := C_NONE;
  7210. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7211. if condition_in(C_AE, JumpC) then
  7212. Unconditional := True
  7213. else
  7214. { Not sure what to do with this jump - drop out }
  7215. Exit;
  7216. end;
  7217. RemoveInstruction(hp1);
  7218. if Unconditional then
  7219. MakeUnconditional(taicpu(hp2))
  7220. else
  7221. begin
  7222. if SetC = C_NONE then
  7223. InternalError(2018061402);
  7224. taicpu(hp2).SetCondition(SetC);
  7225. end;
  7226. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7227. TmpUsedRegs }
  7228. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7229. begin
  7230. RemoveCurrentp(p, hp2);
  7231. if taicpu(hp2).opcode = A_SETcc then
  7232. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7233. else
  7234. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7235. end
  7236. else
  7237. if taicpu(hp2).opcode = A_SETcc then
  7238. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7239. else
  7240. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7241. Result := True;
  7242. end
  7243. else if
  7244. { Make sure the instructions are adjacent }
  7245. (
  7246. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7247. GetNextInstruction(p, hp1)
  7248. ) and
  7249. MatchInstruction(hp1, A_MOV, [S_B]) and
  7250. { Writing to memory is allowed }
  7251. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7252. begin
  7253. {
  7254. Watch out for sequences such as:
  7255. set(c)b %regb
  7256. movb %regb,(ref)
  7257. movb $0,1(ref)
  7258. movb $0,2(ref)
  7259. movb $0,3(ref)
  7260. Much more efficient to turn it into:
  7261. movl $0,%regl
  7262. set(c)b %regb
  7263. movl %regl,(ref)
  7264. Or:
  7265. set(c)b %regb
  7266. movzbl %regb,%regl
  7267. movl %regl,(ref)
  7268. }
  7269. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7270. GetNextInstruction(hp1, hp2) and
  7271. MatchInstruction(hp2, A_MOV, [S_B]) and
  7272. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7273. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7274. begin
  7275. { Don't do anything else except set Result to True }
  7276. end
  7277. else
  7278. begin
  7279. if taicpu(p).oper[0]^.typ = top_reg then
  7280. begin
  7281. TransferUsedRegs(TmpUsedRegs);
  7282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7283. end;
  7284. { If it's not a register, it's a memory address }
  7285. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7286. begin
  7287. { Even if the register is still in use, we can minimise the
  7288. pipeline stall by changing the MOV into another SETcc. }
  7289. taicpu(hp1).opcode := A_SETcc;
  7290. taicpu(hp1).condition := taicpu(p).condition;
  7291. if taicpu(hp1).oper[1]^.typ = top_ref then
  7292. begin
  7293. { Swapping the operand pointers like this is probably a
  7294. bit naughty, but it is far faster than using loadoper
  7295. to transfer the reference from oper[1] to oper[0] if
  7296. you take into account the extra procedure calls and
  7297. the memory allocation and deallocation required }
  7298. OperPtr := taicpu(hp1).oper[1];
  7299. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7300. taicpu(hp1).oper[0] := OperPtr;
  7301. end
  7302. else
  7303. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7304. taicpu(hp1).clearop(1);
  7305. taicpu(hp1).ops := 1;
  7306. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7307. end
  7308. else
  7309. begin
  7310. if taicpu(hp1).oper[1]^.typ = top_reg then
  7311. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7312. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7313. RemoveInstruction(hp1);
  7314. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7315. end
  7316. end;
  7317. Result := True;
  7318. end;
  7319. end;
  7320. end;
  7321. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7322. var
  7323. hp1: tai;
  7324. Count: Integer;
  7325. OrigLabel: TAsmLabel;
  7326. begin
  7327. result := False;
  7328. { Sometimes, the optimisations below can permit this }
  7329. RemoveDeadCodeAfterJump(p);
  7330. 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
  7331. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7332. begin
  7333. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7334. { Also a side-effect of optimisations }
  7335. if CollapseZeroDistJump(p, OrigLabel) then
  7336. begin
  7337. Result := True;
  7338. Exit;
  7339. end;
  7340. hp1 := GetLabelWithSym(OrigLabel);
  7341. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7342. begin
  7343. case taicpu(hp1).opcode of
  7344. A_RET:
  7345. {
  7346. change
  7347. jmp .L1
  7348. ...
  7349. .L1:
  7350. ret
  7351. into
  7352. ret
  7353. }
  7354. begin
  7355. ConvertJumpToRET(p, hp1);
  7356. result:=true;
  7357. end;
  7358. { Check any kind of direct assignment instruction }
  7359. A_MOV,
  7360. A_MOVD,
  7361. A_MOVQ,
  7362. A_MOVSX,
  7363. {$ifdef x86_64}
  7364. A_MOVSXD,
  7365. {$endif x86_64}
  7366. A_MOVZX,
  7367. A_MOVAPS,
  7368. A_MOVUPS,
  7369. A_MOVSD,
  7370. A_MOVAPD,
  7371. A_MOVUPD,
  7372. A_MOVDQA,
  7373. A_MOVDQU,
  7374. A_VMOVSS,
  7375. A_VMOVAPS,
  7376. A_VMOVUPS,
  7377. A_VMOVSD,
  7378. A_VMOVAPD,
  7379. A_VMOVUPD,
  7380. A_VMOVDQA,
  7381. A_VMOVDQU:
  7382. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7383. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7384. begin
  7385. Result := True;
  7386. Exit;
  7387. end;
  7388. else
  7389. ;
  7390. end;
  7391. end;
  7392. end;
  7393. end;
  7394. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7395. begin
  7396. CanBeCMOV:=assigned(p) and
  7397. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7398. { we can't use cmov ref,reg because
  7399. ref could be nil and cmov still throws an exception
  7400. if ref=nil but the mov isn't done (FK)
  7401. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7402. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7403. }
  7404. (taicpu(p).oper[1]^.typ = top_reg) and
  7405. (
  7406. (taicpu(p).oper[0]^.typ = top_reg) or
  7407. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7408. it is not expected that this can cause a seg. violation }
  7409. (
  7410. (taicpu(p).oper[0]^.typ = top_ref) and
  7411. IsRefSafe(taicpu(p).oper[0]^.ref)
  7412. )
  7413. );
  7414. end;
  7415. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7416. var
  7417. hp1,hp2: tai;
  7418. {$ifndef i8086}
  7419. hp3,hp4,hpmov2, hp5: tai;
  7420. l : Longint;
  7421. condition : TAsmCond;
  7422. {$endif i8086}
  7423. carryadd_opcode : TAsmOp;
  7424. symbol: TAsmSymbol;
  7425. reg: tsuperregister;
  7426. increg, tmpreg: TRegister;
  7427. begin
  7428. result:=false;
  7429. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7430. begin
  7431. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7432. if (
  7433. (
  7434. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7435. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7436. (Taicpu(hp1).oper[0]^.val=1)
  7437. ) or
  7438. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7439. ) and
  7440. GetNextInstruction(hp1,hp2) and
  7441. SkipAligns(hp2, hp2) and
  7442. (hp2.typ = ait_label) and
  7443. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7444. { jb @@1 cmc
  7445. inc/dec operand --> adc/sbb operand,0
  7446. @@1:
  7447. ... and ...
  7448. jnb @@1
  7449. inc/dec operand --> adc/sbb operand,0
  7450. @@1: }
  7451. begin
  7452. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7453. begin
  7454. case taicpu(hp1).opcode of
  7455. A_INC,
  7456. A_ADD:
  7457. carryadd_opcode:=A_ADC;
  7458. A_DEC,
  7459. A_SUB:
  7460. carryadd_opcode:=A_SBB;
  7461. else
  7462. InternalError(2021011001);
  7463. end;
  7464. Taicpu(p).clearop(0);
  7465. Taicpu(p).ops:=0;
  7466. Taicpu(p).is_jmp:=false;
  7467. Taicpu(p).opcode:=A_CMC;
  7468. Taicpu(p).condition:=C_NONE;
  7469. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7470. Taicpu(hp1).ops:=2;
  7471. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7472. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7473. else
  7474. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7475. Taicpu(hp1).loadconst(0,0);
  7476. Taicpu(hp1).opcode:=carryadd_opcode;
  7477. result:=true;
  7478. exit;
  7479. end
  7480. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7481. begin
  7482. case taicpu(hp1).opcode of
  7483. A_INC,
  7484. A_ADD:
  7485. carryadd_opcode:=A_ADC;
  7486. A_DEC,
  7487. A_SUB:
  7488. carryadd_opcode:=A_SBB;
  7489. else
  7490. InternalError(2021011002);
  7491. end;
  7492. Taicpu(hp1).ops:=2;
  7493. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7494. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7495. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7496. else
  7497. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7498. Taicpu(hp1).loadconst(0,0);
  7499. Taicpu(hp1).opcode:=carryadd_opcode;
  7500. RemoveCurrentP(p, hp1);
  7501. result:=true;
  7502. exit;
  7503. end
  7504. {
  7505. jcc @@1 setcc tmpreg
  7506. inc/dec/add/sub operand -> (movzx tmpreg)
  7507. @@1: add/sub tmpreg,operand
  7508. While this increases code size slightly, it makes the code much faster if the
  7509. jump is unpredictable
  7510. }
  7511. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7512. begin
  7513. { search for an available register which is volatile }
  7514. for reg in tcpuregisterset do
  7515. begin
  7516. if
  7517. {$if defined(i386) or defined(i8086)}
  7518. { Only use registers whose lowest 8-bits can Be accessed }
  7519. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7520. {$endif i386 or i8086}
  7521. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7522. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7523. { We don't need to check if tmpreg is in hp1 or not, because
  7524. it will be marked as in use at p (if not, this is
  7525. indictive of a compiler bug). }
  7526. then
  7527. begin
  7528. TAsmLabel(symbol).decrefs;
  7529. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7530. Taicpu(p).clearop(0);
  7531. Taicpu(p).ops:=1;
  7532. Taicpu(p).is_jmp:=false;
  7533. Taicpu(p).opcode:=A_SETcc;
  7534. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7535. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7536. Taicpu(p).loadreg(0,increg);
  7537. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7538. begin
  7539. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7540. R_SUBW:
  7541. begin
  7542. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7543. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7544. end;
  7545. R_SUBD:
  7546. begin
  7547. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7548. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7549. end;
  7550. {$ifdef x86_64}
  7551. R_SUBQ:
  7552. begin
  7553. { MOVZX doesn't have a 64-bit variant, because
  7554. the 32-bit version implicitly zeroes the
  7555. upper 32-bits of the destination register }
  7556. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7557. newreg(R_INTREGISTER,reg,R_SUBD));
  7558. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7559. end;
  7560. {$endif x86_64}
  7561. else
  7562. Internalerror(2020030601);
  7563. end;
  7564. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7565. asml.InsertAfter(hp2,p);
  7566. end
  7567. else
  7568. tmpreg := increg;
  7569. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7570. begin
  7571. Taicpu(hp1).ops:=2;
  7572. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7573. end;
  7574. Taicpu(hp1).loadreg(0,tmpreg);
  7575. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7576. Result := True;
  7577. { p is no longer a Jcc instruction, so exit }
  7578. Exit;
  7579. end;
  7580. end;
  7581. end;
  7582. end;
  7583. { Detect the following:
  7584. jmp<cond> @Lbl1
  7585. jmp @Lbl2
  7586. ...
  7587. @Lbl1:
  7588. ret
  7589. Change to:
  7590. jmp<inv_cond> @Lbl2
  7591. ret
  7592. }
  7593. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7594. begin
  7595. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7596. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7597. MatchInstruction(hp2,A_RET,[S_NO]) then
  7598. begin
  7599. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7600. { Change label address to that of the unconditional jump }
  7601. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7602. TAsmLabel(symbol).DecRefs;
  7603. taicpu(hp1).opcode := A_RET;
  7604. taicpu(hp1).is_jmp := false;
  7605. taicpu(hp1).ops := taicpu(hp2).ops;
  7606. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7607. case taicpu(hp2).ops of
  7608. 0:
  7609. taicpu(hp1).clearop(0);
  7610. 1:
  7611. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7612. else
  7613. internalerror(2016041302);
  7614. end;
  7615. end;
  7616. {$ifndef i8086}
  7617. end
  7618. {
  7619. convert
  7620. j<c> .L1
  7621. mov 1,reg
  7622. jmp .L2
  7623. .L1
  7624. mov 0,reg
  7625. .L2
  7626. into
  7627. mov 0,reg
  7628. set<not(c)> reg
  7629. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7630. would destroy the flag contents
  7631. }
  7632. else if MatchInstruction(hp1,A_MOV,[]) and
  7633. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7634. {$ifdef i386}
  7635. (
  7636. { Under i386, ESI, EDI, EBP and ESP
  7637. don't have an 8-bit representation }
  7638. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7639. ) and
  7640. {$endif i386}
  7641. (taicpu(hp1).oper[0]^.val=1) and
  7642. GetNextInstruction(hp1,hp2) and
  7643. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7644. GetNextInstruction(hp2,hp3) and
  7645. { skip align }
  7646. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7647. (hp3.typ=ait_label) and
  7648. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7649. (tai_label(hp3).labsym.getrefs=1) and
  7650. GetNextInstruction(hp3,hp4) and
  7651. MatchInstruction(hp4,A_MOV,[]) and
  7652. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7653. (taicpu(hp4).oper[0]^.val=0) and
  7654. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7655. GetNextInstruction(hp4,hp5) and
  7656. (hp5.typ=ait_label) and
  7657. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7658. (tai_label(hp5).labsym.getrefs=1) then
  7659. begin
  7660. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7661. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7662. { remove last label }
  7663. RemoveInstruction(hp5);
  7664. { remove second label }
  7665. RemoveInstruction(hp3);
  7666. { if align is present remove it }
  7667. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7668. RemoveInstruction(hp3);
  7669. { remove jmp }
  7670. RemoveInstruction(hp2);
  7671. if taicpu(hp1).opsize=S_B then
  7672. RemoveInstruction(hp1)
  7673. else
  7674. taicpu(hp1).loadconst(0,0);
  7675. taicpu(hp4).opcode:=A_SETcc;
  7676. taicpu(hp4).opsize:=S_B;
  7677. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7678. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7679. taicpu(hp4).opercnt:=1;
  7680. taicpu(hp4).ops:=1;
  7681. taicpu(hp4).freeop(1);
  7682. RemoveCurrentP(p);
  7683. Result:=true;
  7684. exit;
  7685. end
  7686. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7687. begin
  7688. { check for
  7689. jCC xxx
  7690. <several movs>
  7691. xxx:
  7692. }
  7693. l:=0;
  7694. while assigned(hp1) and
  7695. CanBeCMOV(hp1) and
  7696. { stop on labels }
  7697. not(hp1.typ=ait_label) do
  7698. begin
  7699. inc(l);
  7700. GetNextInstruction(hp1,hp1);
  7701. end;
  7702. if assigned(hp1) then
  7703. begin
  7704. if FindLabel(tasmlabel(symbol),hp1) then
  7705. begin
  7706. if (l<=4) and (l>0) then
  7707. begin
  7708. condition:=inverse_cond(taicpu(p).condition);
  7709. GetNextInstruction(p,hp1);
  7710. repeat
  7711. if not Assigned(hp1) then
  7712. InternalError(2018062900);
  7713. taicpu(hp1).opcode:=A_CMOVcc;
  7714. taicpu(hp1).condition:=condition;
  7715. UpdateUsedRegs(hp1);
  7716. GetNextInstruction(hp1,hp1);
  7717. until not(CanBeCMOV(hp1));
  7718. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7719. hp2 := hp1;
  7720. repeat
  7721. if not Assigned(hp2) then
  7722. InternalError(2018062910);
  7723. case hp2.typ of
  7724. ait_label:
  7725. { What we expected - break out of the loop (it won't be a dead label at the top of
  7726. a cluster because that was optimised at an earlier stage) }
  7727. Break;
  7728. ait_align:
  7729. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7730. begin
  7731. hp2 := tai(hp2.Next);
  7732. Continue;
  7733. end;
  7734. else
  7735. begin
  7736. { Might be a comment or temporary allocation entry }
  7737. if not (hp2.typ in SkipInstr) then
  7738. InternalError(2018062911);
  7739. hp2 := tai(hp2.Next);
  7740. Continue;
  7741. end;
  7742. end;
  7743. until False;
  7744. { Now we can safely decrement the reference count }
  7745. tasmlabel(symbol).decrefs;
  7746. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7747. { Remove the original jump }
  7748. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7749. GetNextInstruction(hp2, p); { Instruction after the label }
  7750. { Remove the label if this is its final reference }
  7751. if (tasmlabel(symbol).getrefs=0) then
  7752. StripLabelFast(hp1);
  7753. if Assigned(p) then
  7754. begin
  7755. UpdateUsedRegs(p);
  7756. result:=true;
  7757. end;
  7758. exit;
  7759. end;
  7760. end
  7761. else
  7762. begin
  7763. { check further for
  7764. jCC xxx
  7765. <several movs 1>
  7766. jmp yyy
  7767. xxx:
  7768. <several movs 2>
  7769. yyy:
  7770. }
  7771. { hp2 points to jmp yyy }
  7772. hp2:=hp1;
  7773. { skip hp1 to xxx (or an align right before it) }
  7774. GetNextInstruction(hp1, hp1);
  7775. if assigned(hp2) and
  7776. assigned(hp1) and
  7777. (l<=3) and
  7778. (hp2.typ=ait_instruction) and
  7779. (taicpu(hp2).is_jmp) and
  7780. (taicpu(hp2).condition=C_None) and
  7781. { real label and jump, no further references to the
  7782. label are allowed }
  7783. (tasmlabel(symbol).getrefs=1) and
  7784. FindLabel(tasmlabel(symbol),hp1) then
  7785. begin
  7786. l:=0;
  7787. { skip hp1 to <several moves 2> }
  7788. if (hp1.typ = ait_align) then
  7789. GetNextInstruction(hp1, hp1);
  7790. GetNextInstruction(hp1, hpmov2);
  7791. hp1 := hpmov2;
  7792. while assigned(hp1) and
  7793. CanBeCMOV(hp1) do
  7794. begin
  7795. inc(l);
  7796. GetNextInstruction(hp1, hp1);
  7797. end;
  7798. { hp1 points to yyy (or an align right before it) }
  7799. hp3 := hp1;
  7800. if assigned(hp1) and
  7801. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7802. begin
  7803. condition:=inverse_cond(taicpu(p).condition);
  7804. GetNextInstruction(p,hp1);
  7805. repeat
  7806. taicpu(hp1).opcode:=A_CMOVcc;
  7807. taicpu(hp1).condition:=condition;
  7808. UpdateUsedRegs(hp1);
  7809. GetNextInstruction(hp1,hp1);
  7810. until not(assigned(hp1)) or
  7811. not(CanBeCMOV(hp1));
  7812. condition:=inverse_cond(condition);
  7813. hp1 := hpmov2;
  7814. { hp1 is now at <several movs 2> }
  7815. while Assigned(hp1) and CanBeCMOV(hp1) do
  7816. begin
  7817. taicpu(hp1).opcode:=A_CMOVcc;
  7818. taicpu(hp1).condition:=condition;
  7819. UpdateUsedRegs(hp1);
  7820. GetNextInstruction(hp1,hp1);
  7821. end;
  7822. hp1 := p;
  7823. { Get first instruction after label }
  7824. GetNextInstruction(hp3, p);
  7825. if assigned(p) and (hp3.typ = ait_align) then
  7826. GetNextInstruction(p, p);
  7827. { Don't dereference yet, as doing so will cause
  7828. GetNextInstruction to skip the label and
  7829. optional align marker. [Kit] }
  7830. GetNextInstruction(hp2, hp4);
  7831. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7832. { remove jCC }
  7833. RemoveInstruction(hp1);
  7834. { Now we can safely decrement it }
  7835. tasmlabel(symbol).decrefs;
  7836. { Remove label xxx (it will have a ref of zero due to the initial check }
  7837. StripLabelFast(hp4);
  7838. { remove jmp }
  7839. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7840. RemoveInstruction(hp2);
  7841. { As before, now we can safely decrement it }
  7842. tasmlabel(symbol).decrefs;
  7843. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7844. if tasmlabel(symbol).getrefs = 0 then
  7845. StripLabelFast(hp3);
  7846. if Assigned(p) then
  7847. begin
  7848. UpdateUsedRegs(p);
  7849. result:=true;
  7850. end;
  7851. exit;
  7852. end;
  7853. end;
  7854. end;
  7855. end;
  7856. {$endif i8086}
  7857. end;
  7858. end;
  7859. end;
  7860. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7861. var
  7862. hp1,hp2: tai;
  7863. reg_and_hp1_is_instr: Boolean;
  7864. begin
  7865. result:=false;
  7866. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7867. GetNextInstruction(p,hp1) and
  7868. (hp1.typ = ait_instruction);
  7869. if reg_and_hp1_is_instr and
  7870. (
  7871. (taicpu(hp1).opcode <> A_LEA) or
  7872. { If the LEA instruction can be converted into an arithmetic instruction,
  7873. it may be possible to then fold it. }
  7874. (
  7875. { If the flags register is in use, don't change the instruction
  7876. to an ADD otherwise this will scramble the flags. [Kit] }
  7877. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7878. ConvertLEA(taicpu(hp1))
  7879. )
  7880. ) and
  7881. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7882. GetNextInstruction(hp1,hp2) and
  7883. MatchInstruction(hp2,A_MOV,[]) and
  7884. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7885. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7886. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7887. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7888. {$ifdef i386}
  7889. { not all registers have byte size sub registers on i386 }
  7890. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7891. {$endif i386}
  7892. (((taicpu(hp1).ops=2) and
  7893. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7894. ((taicpu(hp1).ops=1) and
  7895. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7896. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7897. begin
  7898. { change movsX/movzX reg/ref, reg2
  7899. add/sub/or/... reg3/$const, reg2
  7900. mov reg2 reg/ref
  7901. to add/sub/or/... reg3/$const, reg/ref }
  7902. { by example:
  7903. movswl %si,%eax movswl %si,%eax p
  7904. decl %eax addl %edx,%eax hp1
  7905. movw %ax,%si movw %ax,%si hp2
  7906. ->
  7907. movswl %si,%eax movswl %si,%eax p
  7908. decw %eax addw %edx,%eax hp1
  7909. movw %ax,%si movw %ax,%si hp2
  7910. }
  7911. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7912. {
  7913. ->
  7914. movswl %si,%eax movswl %si,%eax p
  7915. decw %si addw %dx,%si hp1
  7916. movw %ax,%si movw %ax,%si hp2
  7917. }
  7918. case taicpu(hp1).ops of
  7919. 1:
  7920. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7921. 2:
  7922. begin
  7923. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7924. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7925. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7926. end;
  7927. else
  7928. internalerror(2008042702);
  7929. end;
  7930. {
  7931. ->
  7932. decw %si addw %dx,%si p
  7933. }
  7934. DebugMsg(SPeepholeOptimization + 'var3',p);
  7935. RemoveCurrentP(p, hp1);
  7936. RemoveInstruction(hp2);
  7937. end
  7938. else if reg_and_hp1_is_instr and
  7939. (taicpu(hp1).opcode = A_MOV) and
  7940. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7941. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7942. {$ifdef x86_64}
  7943. { check for implicit extension to 64 bit }
  7944. or
  7945. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7946. (taicpu(hp1).opsize=S_Q) and
  7947. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7948. )
  7949. {$endif x86_64}
  7950. )
  7951. then
  7952. begin
  7953. { change
  7954. movx %reg1,%reg2
  7955. mov %reg2,%reg3
  7956. dealloc %reg2
  7957. into
  7958. movx %reg,%reg3
  7959. }
  7960. TransferUsedRegs(TmpUsedRegs);
  7961. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7962. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7963. begin
  7964. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7965. {$ifdef x86_64}
  7966. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7967. (taicpu(hp1).opsize=S_Q) then
  7968. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7969. else
  7970. {$endif x86_64}
  7971. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7972. RemoveInstruction(hp1);
  7973. end;
  7974. end
  7975. else if reg_and_hp1_is_instr and
  7976. (taicpu(hp1).opcode = A_MOV) and
  7977. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7978. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7979. (taicpu(hp1).opsize=S_B)) or
  7980. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7981. (taicpu(hp1).opsize=S_W))
  7982. {$ifdef x86_64}
  7983. or ((taicpu(p).opsize=S_LQ) and
  7984. (taicpu(hp1).opsize=S_L))
  7985. {$endif x86_64}
  7986. ) and
  7987. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7988. begin
  7989. { change
  7990. movx %reg1,%reg2
  7991. mov %reg2,%reg3
  7992. dealloc %reg2
  7993. into
  7994. mov %reg1,%reg3
  7995. if the second mov accesses only the bits stored in reg1
  7996. }
  7997. TransferUsedRegs(TmpUsedRegs);
  7998. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7999. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8000. begin
  8001. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  8002. if taicpu(p).oper[0]^.typ=top_reg then
  8003. begin
  8004. case taicpu(hp1).opsize of
  8005. S_B:
  8006. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  8007. S_W:
  8008. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  8009. S_L:
  8010. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  8011. else
  8012. Internalerror(2020102301);
  8013. end;
  8014. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  8015. end
  8016. else
  8017. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  8018. RemoveCurrentP(p);
  8019. result:=true;
  8020. exit;
  8021. end;
  8022. end
  8023. else if reg_and_hp1_is_instr and
  8024. (taicpu(p).oper[0]^.typ = top_reg) and
  8025. (
  8026. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  8027. ) and
  8028. (taicpu(hp1).oper[0]^.typ = top_const) and
  8029. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8030. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8031. { Minimum shift value allowed is the bit difference between the sizes }
  8032. (taicpu(hp1).oper[0]^.val >=
  8033. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8034. 8 * (
  8035. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  8036. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8037. )
  8038. ) then
  8039. begin
  8040. { For:
  8041. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  8042. shl/sal ##, %reg1
  8043. Remove the movsx/movzx instruction if the shift overwrites the
  8044. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  8045. }
  8046. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  8047. RemoveCurrentP(p, hp1);
  8048. Result := True;
  8049. Exit;
  8050. end
  8051. else if reg_and_hp1_is_instr and
  8052. (taicpu(p).oper[0]^.typ = top_reg) and
  8053. (
  8054. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8055. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8056. ) and
  8057. (taicpu(hp1).oper[0]^.typ = top_const) and
  8058. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8059. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8060. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8061. (taicpu(hp1).oper[0]^.val <
  8062. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8063. 8 * (
  8064. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8065. )
  8066. ) then
  8067. begin
  8068. { For:
  8069. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8070. sar ##, %reg1 shr ##, %reg1
  8071. Move the shift to before the movx instruction if the shift value
  8072. is not too large.
  8073. }
  8074. asml.Remove(hp1);
  8075. asml.InsertBefore(hp1, p);
  8076. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8077. case taicpu(p).opsize of
  8078. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8079. taicpu(hp1).opsize := S_B;
  8080. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8081. taicpu(hp1).opsize := S_W;
  8082. {$ifdef x86_64}
  8083. S_LQ:
  8084. taicpu(hp1).opsize := S_L;
  8085. {$endif}
  8086. else
  8087. InternalError(2020112401);
  8088. end;
  8089. if (taicpu(hp1).opcode = A_SHR) then
  8090. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8091. else
  8092. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8093. Result := True;
  8094. end
  8095. else if taicpu(p).opcode=A_MOVZX then
  8096. begin
  8097. { removes superfluous And's after movzx's }
  8098. if reg_and_hp1_is_instr and
  8099. (taicpu(hp1).opcode = A_AND) and
  8100. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8101. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8102. {$ifdef x86_64}
  8103. { check for implicit extension to 64 bit }
  8104. or
  8105. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8106. (taicpu(hp1).opsize=S_Q) and
  8107. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8108. )
  8109. {$endif x86_64}
  8110. )
  8111. then
  8112. begin
  8113. case taicpu(p).opsize Of
  8114. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8115. if (taicpu(hp1).oper[0]^.val = $ff) then
  8116. begin
  8117. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8118. RemoveInstruction(hp1);
  8119. Result:=true;
  8120. exit;
  8121. end;
  8122. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8123. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8124. begin
  8125. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8126. RemoveInstruction(hp1);
  8127. Result:=true;
  8128. exit;
  8129. end;
  8130. {$ifdef x86_64}
  8131. S_LQ:
  8132. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8133. begin
  8134. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8135. RemoveInstruction(hp1);
  8136. Result:=true;
  8137. exit;
  8138. end;
  8139. {$endif x86_64}
  8140. else
  8141. ;
  8142. end;
  8143. { we cannot get rid of the and, but can we get rid of the movz ?}
  8144. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8145. begin
  8146. case taicpu(p).opsize Of
  8147. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8148. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8149. begin
  8150. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8151. RemoveCurrentP(p,hp1);
  8152. Result:=true;
  8153. exit;
  8154. end;
  8155. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8156. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8157. begin
  8158. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8159. RemoveCurrentP(p,hp1);
  8160. Result:=true;
  8161. exit;
  8162. end;
  8163. {$ifdef x86_64}
  8164. S_LQ:
  8165. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8166. begin
  8167. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8168. RemoveCurrentP(p,hp1);
  8169. Result:=true;
  8170. exit;
  8171. end;
  8172. {$endif x86_64}
  8173. else
  8174. ;
  8175. end;
  8176. end;
  8177. end;
  8178. { changes some movzx constructs to faster synonyms (all examples
  8179. are given with eax/ax, but are also valid for other registers)}
  8180. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8181. begin
  8182. case taicpu(p).opsize of
  8183. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8184. (the machine code is equivalent to movzbl %al,%eax), but the
  8185. code generator still generates that assembler instruction and
  8186. it is silently converted. This should probably be checked.
  8187. [Kit] }
  8188. S_BW:
  8189. begin
  8190. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8191. (
  8192. not IsMOVZXAcceptable
  8193. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8194. or (
  8195. (cs_opt_size in current_settings.optimizerswitches) and
  8196. (taicpu(p).oper[1]^.reg = NR_AX)
  8197. )
  8198. ) then
  8199. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8200. begin
  8201. DebugMsg(SPeepholeOptimization + 'var7',p);
  8202. taicpu(p).opcode := A_AND;
  8203. taicpu(p).changeopsize(S_W);
  8204. taicpu(p).loadConst(0,$ff);
  8205. Result := True;
  8206. end
  8207. else if not IsMOVZXAcceptable and
  8208. GetNextInstruction(p, hp1) and
  8209. (tai(hp1).typ = ait_instruction) and
  8210. (taicpu(hp1).opcode = A_AND) and
  8211. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8212. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8213. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8214. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8215. begin
  8216. DebugMsg(SPeepholeOptimization + 'var8',p);
  8217. taicpu(p).opcode := A_MOV;
  8218. taicpu(p).changeopsize(S_W);
  8219. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8220. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8221. Result := True;
  8222. end;
  8223. end;
  8224. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8225. S_BL:
  8226. begin
  8227. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8228. (
  8229. not IsMOVZXAcceptable
  8230. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8231. or (
  8232. (cs_opt_size in current_settings.optimizerswitches) and
  8233. (taicpu(p).oper[1]^.reg = NR_EAX)
  8234. )
  8235. ) then
  8236. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8237. begin
  8238. DebugMsg(SPeepholeOptimization + 'var9',p);
  8239. taicpu(p).opcode := A_AND;
  8240. taicpu(p).changeopsize(S_L);
  8241. taicpu(p).loadConst(0,$ff);
  8242. Result := True;
  8243. end
  8244. else if not IsMOVZXAcceptable and
  8245. GetNextInstruction(p, hp1) and
  8246. (tai(hp1).typ = ait_instruction) and
  8247. (taicpu(hp1).opcode = A_AND) and
  8248. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8249. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8250. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8251. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8252. begin
  8253. DebugMsg(SPeepholeOptimization + 'var10',p);
  8254. taicpu(p).opcode := A_MOV;
  8255. taicpu(p).changeopsize(S_L);
  8256. { do not use R_SUBWHOLE
  8257. as movl %rdx,%eax
  8258. is invalid in assembler PM }
  8259. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8260. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8261. Result := True;
  8262. end;
  8263. end;
  8264. {$endif i8086}
  8265. S_WL:
  8266. if not IsMOVZXAcceptable then
  8267. begin
  8268. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8269. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8270. begin
  8271. DebugMsg(SPeepholeOptimization + 'var11',p);
  8272. taicpu(p).opcode := A_AND;
  8273. taicpu(p).changeopsize(S_L);
  8274. taicpu(p).loadConst(0,$ffff);
  8275. Result := True;
  8276. end
  8277. else if GetNextInstruction(p, hp1) and
  8278. (tai(hp1).typ = ait_instruction) and
  8279. (taicpu(hp1).opcode = A_AND) and
  8280. (taicpu(hp1).oper[0]^.typ = top_const) and
  8281. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8282. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8283. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8284. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8285. begin
  8286. DebugMsg(SPeepholeOptimization + 'var12',p);
  8287. taicpu(p).opcode := A_MOV;
  8288. taicpu(p).changeopsize(S_L);
  8289. { do not use R_SUBWHOLE
  8290. as movl %rdx,%eax
  8291. is invalid in assembler PM }
  8292. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8293. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8294. Result := True;
  8295. end;
  8296. end;
  8297. else
  8298. InternalError(2017050705);
  8299. end;
  8300. end
  8301. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8302. begin
  8303. if GetNextInstruction(p, hp1) and
  8304. (tai(hp1).typ = ait_instruction) and
  8305. (taicpu(hp1).opcode = A_AND) and
  8306. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8307. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8308. begin
  8309. //taicpu(p).opcode := A_MOV;
  8310. case taicpu(p).opsize Of
  8311. S_BL:
  8312. begin
  8313. DebugMsg(SPeepholeOptimization + 'var13',p);
  8314. taicpu(hp1).changeopsize(S_L);
  8315. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8316. end;
  8317. S_WL:
  8318. begin
  8319. DebugMsg(SPeepholeOptimization + 'var14',p);
  8320. taicpu(hp1).changeopsize(S_L);
  8321. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8322. end;
  8323. S_BW:
  8324. begin
  8325. DebugMsg(SPeepholeOptimization + 'var15',p);
  8326. taicpu(hp1).changeopsize(S_W);
  8327. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8328. end;
  8329. else
  8330. Internalerror(2017050704)
  8331. end;
  8332. Result := True;
  8333. end;
  8334. end;
  8335. end;
  8336. end;
  8337. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8338. var
  8339. hp1, hp2 : tai;
  8340. MaskLength : Cardinal;
  8341. MaskedBits : TCgInt;
  8342. begin
  8343. Result:=false;
  8344. { There are no optimisations for reference targets }
  8345. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8346. Exit;
  8347. while GetNextInstruction(p, hp1) and
  8348. (hp1.typ = ait_instruction) do
  8349. begin
  8350. if (taicpu(p).oper[0]^.typ = top_const) then
  8351. begin
  8352. case taicpu(hp1).opcode of
  8353. A_AND:
  8354. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8355. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8356. { the second register must contain the first one, so compare their subreg types }
  8357. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8358. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8359. { change
  8360. and const1, reg
  8361. and const2, reg
  8362. to
  8363. and (const1 and const2), reg
  8364. }
  8365. begin
  8366. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8367. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8368. RemoveCurrentP(p, hp1);
  8369. Result:=true;
  8370. exit;
  8371. end;
  8372. A_CMP:
  8373. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8374. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8375. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8376. { Just check that the condition on the next instruction is compatible }
  8377. GetNextInstruction(hp1, hp2) and
  8378. (hp2.typ = ait_instruction) and
  8379. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8380. then
  8381. { change
  8382. and 2^n, reg
  8383. cmp 2^n, reg
  8384. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8385. to
  8386. and 2^n, reg
  8387. test reg, reg
  8388. j(~c) / set(~c) / cmov(~c)
  8389. }
  8390. begin
  8391. { Keep TEST instruction in, rather than remove it, because
  8392. it may trigger other optimisations such as MovAndTest2Test }
  8393. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8394. taicpu(hp1).opcode := A_TEST;
  8395. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8396. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8397. Result := True;
  8398. Exit;
  8399. end;
  8400. A_MOVZX:
  8401. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8402. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8403. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8404. (
  8405. (
  8406. (taicpu(p).opsize=S_W) and
  8407. (taicpu(hp1).opsize=S_BW)
  8408. ) or
  8409. (
  8410. (taicpu(p).opsize=S_L) and
  8411. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8412. )
  8413. {$ifdef x86_64}
  8414. or
  8415. (
  8416. (taicpu(p).opsize=S_Q) and
  8417. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8418. )
  8419. {$endif x86_64}
  8420. ) then
  8421. begin
  8422. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8423. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8424. ) or
  8425. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8426. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8427. then
  8428. begin
  8429. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8430. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8431. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8432. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8433. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8434. }
  8435. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8436. RemoveInstruction(hp1);
  8437. { See if there are other optimisations possible }
  8438. Continue;
  8439. end;
  8440. end;
  8441. A_SHL:
  8442. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8443. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8444. begin
  8445. {$ifopt R+}
  8446. {$define RANGE_WAS_ON}
  8447. {$R-}
  8448. {$endif}
  8449. { get length of potential and mask }
  8450. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8451. { really a mask? }
  8452. {$ifdef RANGE_WAS_ON}
  8453. {$R+}
  8454. {$endif}
  8455. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8456. { unmasked part shifted out? }
  8457. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8458. begin
  8459. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8460. RemoveCurrentP(p, hp1);
  8461. Result:=true;
  8462. exit;
  8463. end;
  8464. end;
  8465. A_SHR:
  8466. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8467. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8468. (taicpu(hp1).oper[0]^.val <= 63) then
  8469. begin
  8470. { Does SHR combined with the AND cover all the bits?
  8471. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8472. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8473. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8474. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8475. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8476. begin
  8477. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8478. RemoveCurrentP(p, hp1);
  8479. Result := True;
  8480. Exit;
  8481. end;
  8482. end;
  8483. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8484. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8485. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8486. begin
  8487. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8488. (
  8489. (
  8490. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8491. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8492. ) or (
  8493. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8494. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8495. {$ifdef x86_64}
  8496. ) or (
  8497. (taicpu(hp1).opsize = S_LQ) and
  8498. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8499. {$endif x86_64}
  8500. )
  8501. ) then
  8502. begin
  8503. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8504. begin
  8505. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8506. RemoveInstruction(hp1);
  8507. { See if there are other optimisations possible }
  8508. Continue;
  8509. end;
  8510. { The super-registers are the same though.
  8511. Note that this change by itself doesn't improve
  8512. code speed, but it opens up other optimisations. }
  8513. {$ifdef x86_64}
  8514. { Convert 64-bit register to 32-bit }
  8515. case taicpu(hp1).opsize of
  8516. S_BQ:
  8517. begin
  8518. taicpu(hp1).opsize := S_BL;
  8519. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8520. end;
  8521. S_WQ:
  8522. begin
  8523. taicpu(hp1).opsize := S_WL;
  8524. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8525. end
  8526. else
  8527. ;
  8528. end;
  8529. {$endif x86_64}
  8530. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8531. taicpu(hp1).opcode := A_MOVZX;
  8532. { See if there are other optimisations possible }
  8533. Continue;
  8534. end;
  8535. end;
  8536. else
  8537. ;
  8538. end;
  8539. end;
  8540. if (taicpu(hp1).is_jmp) and
  8541. (taicpu(hp1).opcode<>A_JMP) and
  8542. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8543. begin
  8544. { change
  8545. and x, reg
  8546. jxx
  8547. to
  8548. test x, reg
  8549. jxx
  8550. if reg is deallocated before the
  8551. jump, but only if it's a conditional jump (PFV)
  8552. }
  8553. taicpu(p).opcode := A_TEST;
  8554. Exit;
  8555. end;
  8556. Break;
  8557. end;
  8558. { Lone AND tests }
  8559. if (taicpu(p).oper[0]^.typ = top_const) then
  8560. begin
  8561. {
  8562. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8563. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8564. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8565. }
  8566. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8567. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8568. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8569. begin
  8570. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8571. if taicpu(p).opsize = S_L then
  8572. begin
  8573. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8574. Result := True;
  8575. end;
  8576. end;
  8577. end;
  8578. { Backward check to determine necessity of and %reg,%reg }
  8579. if (taicpu(p).oper[0]^.typ = top_reg) and
  8580. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8581. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8582. GetLastInstruction(p, hp2) and
  8583. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8584. { Check size of adjacent instruction to determine if the AND is
  8585. effectively a null operation }
  8586. (
  8587. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8588. { Note: Don't include S_Q }
  8589. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8590. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8591. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8592. ) then
  8593. begin
  8594. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8595. { If GetNextInstruction returned False, hp1 will be nil }
  8596. RemoveCurrentP(p, hp1);
  8597. Result := True;
  8598. Exit;
  8599. end;
  8600. end;
  8601. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8602. var
  8603. hp1: tai; NewRef: TReference;
  8604. { This entire nested function is used in an if-statement below, but we
  8605. want to avoid all the used reg transfers and GetNextInstruction calls
  8606. until we really have to check }
  8607. function MemRegisterNotUsedLater: Boolean; inline;
  8608. var
  8609. hp2: tai;
  8610. begin
  8611. TransferUsedRegs(TmpUsedRegs);
  8612. hp2 := p;
  8613. repeat
  8614. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8615. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8616. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8617. end;
  8618. begin
  8619. Result := False;
  8620. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8621. Exit;
  8622. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8623. begin
  8624. { Change:
  8625. add %reg2,%reg1
  8626. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8627. To:
  8628. mov/s/z #(%reg1,%reg2),%reg1
  8629. }
  8630. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8631. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8632. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8633. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8634. (
  8635. (
  8636. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8637. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8638. { r/esp cannot be an index }
  8639. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8640. ) or (
  8641. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8642. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8643. )
  8644. ) and (
  8645. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8646. (
  8647. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8648. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8649. MemRegisterNotUsedLater
  8650. )
  8651. ) then
  8652. begin
  8653. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8654. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8655. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8656. RemoveCurrentp(p, hp1);
  8657. Result := True;
  8658. Exit;
  8659. end;
  8660. { Change:
  8661. addl/q $x,%reg1
  8662. movl/q %reg1,%reg2
  8663. To:
  8664. leal/q $x(%reg1),%reg2
  8665. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8666. Breaks the dependency chain.
  8667. }
  8668. if MatchOpType(taicpu(p),top_const,top_reg) and
  8669. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8670. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8671. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8672. (
  8673. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8674. not (cs_opt_size in current_settings.optimizerswitches) or
  8675. (
  8676. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8677. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8678. )
  8679. ) then
  8680. begin
  8681. { Change the MOV instruction to a LEA instruction, and update the
  8682. first operand }
  8683. reference_reset(NewRef, 1, []);
  8684. NewRef.base := taicpu(p).oper[1]^.reg;
  8685. NewRef.scalefactor := 1;
  8686. NewRef.offset := taicpu(p).oper[0]^.val;
  8687. taicpu(hp1).opcode := A_LEA;
  8688. taicpu(hp1).loadref(0, NewRef);
  8689. TransferUsedRegs(TmpUsedRegs);
  8690. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8691. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8692. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8693. begin
  8694. { Move what is now the LEA instruction to before the SUB instruction }
  8695. Asml.Remove(hp1);
  8696. Asml.InsertBefore(hp1, p);
  8697. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8698. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8699. p := hp1;
  8700. end
  8701. else
  8702. begin
  8703. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8704. RemoveCurrentP(p, hp1);
  8705. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8706. end;
  8707. Result := True;
  8708. end;
  8709. end;
  8710. end;
  8711. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8712. begin
  8713. Result:=false;
  8714. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8715. begin
  8716. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8717. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8718. begin
  8719. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8720. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8721. taicpu(p).opcode:=A_ADD;
  8722. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8723. result:=true;
  8724. end
  8725. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8726. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8727. begin
  8728. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8729. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8730. taicpu(p).opcode:=A_ADD;
  8731. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8732. result:=true;
  8733. end;
  8734. end;
  8735. end;
  8736. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8737. var
  8738. hp1: tai; NewRef: TReference;
  8739. begin
  8740. { Change:
  8741. subl/q $x,%reg1
  8742. movl/q %reg1,%reg2
  8743. To:
  8744. leal/q $-x(%reg1),%reg2
  8745. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8746. Breaks the dependency chain and potentially permits the removal of
  8747. a CMP instruction if one follows.
  8748. }
  8749. Result := False;
  8750. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8751. MatchOpType(taicpu(p),top_const,top_reg) and
  8752. GetNextInstruction(p, hp1) and
  8753. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8754. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8755. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8756. (
  8757. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8758. not (cs_opt_size in current_settings.optimizerswitches) or
  8759. (
  8760. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8761. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8762. )
  8763. ) then
  8764. begin
  8765. { Change the MOV instruction to a LEA instruction, and update the
  8766. first operand }
  8767. reference_reset(NewRef, 1, []);
  8768. NewRef.base := taicpu(p).oper[1]^.reg;
  8769. NewRef.scalefactor := 1;
  8770. NewRef.offset := -taicpu(p).oper[0]^.val;
  8771. taicpu(hp1).opcode := A_LEA;
  8772. taicpu(hp1).loadref(0, NewRef);
  8773. TransferUsedRegs(TmpUsedRegs);
  8774. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8775. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8776. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8777. begin
  8778. { Move what is now the LEA instruction to before the SUB instruction }
  8779. Asml.Remove(hp1);
  8780. Asml.InsertBefore(hp1, p);
  8781. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8782. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8783. p := hp1;
  8784. end
  8785. else
  8786. begin
  8787. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8788. RemoveCurrentP(p, hp1);
  8789. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8790. end;
  8791. Result := True;
  8792. end;
  8793. end;
  8794. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8795. begin
  8796. { we can skip all instructions not messing with the stack pointer }
  8797. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8798. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8799. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8800. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8801. ({(taicpu(hp1).ops=0) or }
  8802. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8803. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8804. ) and }
  8805. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8806. )
  8807. ) do
  8808. GetNextInstruction(hp1,hp1);
  8809. Result:=assigned(hp1);
  8810. end;
  8811. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8812. var
  8813. hp1, hp2, hp3, hp4, hp5: tai;
  8814. begin
  8815. Result:=false;
  8816. hp5:=nil;
  8817. { replace
  8818. leal(q) x(<stackpointer>),<stackpointer>
  8819. call procname
  8820. leal(q) -x(<stackpointer>),<stackpointer>
  8821. ret
  8822. by
  8823. jmp procname
  8824. but do it only on level 4 because it destroys stack back traces
  8825. }
  8826. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8827. MatchOpType(taicpu(p),top_ref,top_reg) and
  8828. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8829. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8830. { the -8 or -24 are not required, but bail out early if possible,
  8831. higher values are unlikely }
  8832. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8833. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8834. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8835. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8836. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8837. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8838. GetNextInstruction(p, hp1) and
  8839. { Take a copy of hp1 }
  8840. SetAndTest(hp1, hp4) and
  8841. { trick to skip label }
  8842. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8843. SkipSimpleInstructions(hp1) and
  8844. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8845. GetNextInstruction(hp1, hp2) and
  8846. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8847. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8848. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8849. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8850. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8851. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8852. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8853. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8854. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8855. GetNextInstruction(hp2, hp3) and
  8856. { trick to skip label }
  8857. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8858. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8859. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8860. SetAndTest(hp3,hp5) and
  8861. GetNextInstruction(hp3,hp3) and
  8862. MatchInstruction(hp3,A_RET,[S_NO])
  8863. )
  8864. ) and
  8865. (taicpu(hp3).ops=0) then
  8866. begin
  8867. taicpu(hp1).opcode := A_JMP;
  8868. taicpu(hp1).is_jmp := true;
  8869. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8870. RemoveCurrentP(p, hp4);
  8871. RemoveInstruction(hp2);
  8872. RemoveInstruction(hp3);
  8873. if Assigned(hp5) then
  8874. begin
  8875. AsmL.Remove(hp5);
  8876. ASmL.InsertBefore(hp5,hp1)
  8877. end;
  8878. Result:=true;
  8879. end;
  8880. end;
  8881. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8882. {$ifdef x86_64}
  8883. var
  8884. hp1, hp2, hp3, hp4, hp5: tai;
  8885. {$endif x86_64}
  8886. begin
  8887. Result:=false;
  8888. {$ifdef x86_64}
  8889. hp5:=nil;
  8890. { replace
  8891. push %rax
  8892. call procname
  8893. pop %rcx
  8894. ret
  8895. by
  8896. jmp procname
  8897. but do it only on level 4 because it destroys stack back traces
  8898. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8899. for all supported calling conventions
  8900. }
  8901. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8902. MatchOpType(taicpu(p),top_reg) and
  8903. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8904. GetNextInstruction(p, hp1) and
  8905. { Take a copy of hp1 }
  8906. SetAndTest(hp1, hp4) and
  8907. { trick to skip label }
  8908. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8909. SkipSimpleInstructions(hp1) and
  8910. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8911. GetNextInstruction(hp1, hp2) and
  8912. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8913. MatchOpType(taicpu(hp2),top_reg) and
  8914. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8915. GetNextInstruction(hp2, hp3) and
  8916. { trick to skip label }
  8917. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8918. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8919. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8920. SetAndTest(hp3,hp5) and
  8921. GetNextInstruction(hp3,hp3) and
  8922. MatchInstruction(hp3,A_RET,[S_NO])
  8923. )
  8924. ) and
  8925. (taicpu(hp3).ops=0) then
  8926. begin
  8927. taicpu(hp1).opcode := A_JMP;
  8928. taicpu(hp1).is_jmp := true;
  8929. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8930. RemoveCurrentP(p, hp4);
  8931. RemoveInstruction(hp2);
  8932. RemoveInstruction(hp3);
  8933. if Assigned(hp5) then
  8934. begin
  8935. AsmL.Remove(hp5);
  8936. ASmL.InsertBefore(hp5,hp1)
  8937. end;
  8938. Result:=true;
  8939. end;
  8940. {$endif x86_64}
  8941. end;
  8942. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8943. var
  8944. Value, RegName: string;
  8945. begin
  8946. Result:=false;
  8947. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8948. begin
  8949. case taicpu(p).oper[0]^.val of
  8950. 0:
  8951. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8952. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8953. begin
  8954. { change "mov $0,%reg" into "xor %reg,%reg" }
  8955. taicpu(p).opcode := A_XOR;
  8956. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8957. Result := True;
  8958. {$ifdef x86_64}
  8959. end
  8960. else if (taicpu(p).opsize = S_Q) then
  8961. begin
  8962. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8963. { The actual optimization }
  8964. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8965. taicpu(p).changeopsize(S_L);
  8966. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8967. Result := True;
  8968. end;
  8969. $1..$FFFFFFFF:
  8970. begin
  8971. { Code size reduction by J. Gareth "Kit" Moreton }
  8972. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8973. case taicpu(p).opsize of
  8974. S_Q:
  8975. begin
  8976. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8977. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8978. { The actual optimization }
  8979. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8980. taicpu(p).changeopsize(S_L);
  8981. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8982. Result := True;
  8983. end;
  8984. else
  8985. { Do nothing };
  8986. end;
  8987. {$endif x86_64}
  8988. end;
  8989. -1:
  8990. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8991. if (cs_opt_size in current_settings.optimizerswitches) and
  8992. (taicpu(p).opsize <> S_B) and
  8993. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8994. begin
  8995. { change "mov $-1,%reg" into "or $-1,%reg" }
  8996. { NOTES:
  8997. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8998. - This operation creates a false dependency on the register, so only do it when optimising for size
  8999. - 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
  9000. }
  9001. taicpu(p).opcode := A_OR;
  9002. Result := True;
  9003. end;
  9004. else
  9005. { Do nothing };
  9006. end;
  9007. end;
  9008. end;
  9009. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  9010. var
  9011. hp1: tai;
  9012. begin
  9013. { Detect:
  9014. andw x, %ax (0 <= x < $8000)
  9015. ...
  9016. movzwl %ax,%eax
  9017. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9018. }
  9019. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  9020. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9021. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  9022. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9023. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9024. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9025. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9026. begin
  9027. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  9028. taicpu(hp1).opcode := A_CWDE;
  9029. taicpu(hp1).clearop(0);
  9030. taicpu(hp1).clearop(1);
  9031. taicpu(hp1).ops := 0;
  9032. { A change was made, but not with p, so move forward 1 }
  9033. p := tai(p.Next);
  9034. Result := True;
  9035. end;
  9036. end;
  9037. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  9038. begin
  9039. Result := False;
  9040. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  9041. Exit;
  9042. { Convert:
  9043. movswl %ax,%eax -> cwtl
  9044. movslq %eax,%rax -> cdqe
  9045. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  9046. refer to the same opcode and depends only on the assembler's
  9047. current operand-size attribute. [Kit]
  9048. }
  9049. with taicpu(p) do
  9050. case opsize of
  9051. S_WL:
  9052. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  9053. begin
  9054. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  9055. opcode := A_CWDE;
  9056. clearop(0);
  9057. clearop(1);
  9058. ops := 0;
  9059. Result := True;
  9060. end;
  9061. {$ifdef x86_64}
  9062. S_LQ:
  9063. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  9064. begin
  9065. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9066. opcode := A_CDQE;
  9067. clearop(0);
  9068. clearop(1);
  9069. ops := 0;
  9070. Result := True;
  9071. end;
  9072. {$endif x86_64}
  9073. else
  9074. ;
  9075. end;
  9076. end;
  9077. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9078. var
  9079. hp1: tai;
  9080. begin
  9081. { Detect:
  9082. shr x, %ax (x > 0)
  9083. ...
  9084. movzwl %ax,%eax
  9085. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9086. }
  9087. Result := False;
  9088. if MatchOpType(taicpu(p), top_const, top_reg) and
  9089. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9090. (taicpu(p).oper[0]^.val > 0) and
  9091. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9092. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9093. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9094. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9095. begin
  9096. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9097. taicpu(hp1).opcode := A_CWDE;
  9098. taicpu(hp1).clearop(0);
  9099. taicpu(hp1).clearop(1);
  9100. taicpu(hp1).ops := 0;
  9101. { A change was made, but not with p, so move forward 1 }
  9102. p := tai(p.Next);
  9103. Result := True;
  9104. end;
  9105. end;
  9106. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9107. begin
  9108. Result:=false;
  9109. { change "cmp $0, %reg" to "test %reg, %reg" }
  9110. if MatchOpType(taicpu(p),top_const,top_reg) and
  9111. (taicpu(p).oper[0]^.val = 0) then
  9112. begin
  9113. taicpu(p).opcode := A_TEST;
  9114. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9115. Result:=true;
  9116. end;
  9117. end;
  9118. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9119. var
  9120. IsTestConstX : Boolean;
  9121. hp1,hp2 : tai;
  9122. begin
  9123. Result:=false;
  9124. { removes the line marked with (x) from the sequence
  9125. and/or/xor/add/sub/... $x, %y
  9126. test/or %y, %y | test $-1, %y (x)
  9127. j(n)z _Label
  9128. as the first instruction already adjusts the ZF
  9129. %y operand may also be a reference }
  9130. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9131. MatchOperand(taicpu(p).oper[0]^,-1);
  9132. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9133. GetLastInstruction(p, hp1) and
  9134. (tai(hp1).typ = ait_instruction) and
  9135. GetNextInstruction(p,hp2) and
  9136. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9137. case taicpu(hp1).opcode Of
  9138. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9139. begin
  9140. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9141. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9142. { and in case of carry for A(E)/B(E)/C/NC }
  9143. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9144. ((taicpu(hp1).opcode <> A_ADD) and
  9145. (taicpu(hp1).opcode <> A_SUB))) then
  9146. begin
  9147. RemoveCurrentP(p, hp2);
  9148. Result:=true;
  9149. Exit;
  9150. end;
  9151. end;
  9152. A_SHL, A_SAL, A_SHR, A_SAR:
  9153. begin
  9154. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9155. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9156. { therefore, it's only safe to do this optimization for }
  9157. { shifts by a (nonzero) constant }
  9158. (taicpu(hp1).oper[0]^.typ = top_const) and
  9159. (taicpu(hp1).oper[0]^.val <> 0) and
  9160. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9161. { and in case of carry for A(E)/B(E)/C/NC }
  9162. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9163. begin
  9164. RemoveCurrentP(p, hp2);
  9165. Result:=true;
  9166. Exit;
  9167. end;
  9168. end;
  9169. A_DEC, A_INC, A_NEG:
  9170. begin
  9171. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9172. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9173. { and in case of carry for A(E)/B(E)/C/NC }
  9174. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9175. begin
  9176. RemoveCurrentP(p, hp2);
  9177. Result:=true;
  9178. Exit;
  9179. end;
  9180. end
  9181. else
  9182. ;
  9183. end; { case }
  9184. { change "test $-1,%reg" into "test %reg,%reg" }
  9185. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9186. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9187. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9188. if MatchInstruction(p, A_OR, []) and
  9189. { Can only match if they're both registers }
  9190. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9191. begin
  9192. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9193. taicpu(p).opcode := A_TEST;
  9194. { No need to set Result to True, as we've done all the optimisations we can }
  9195. end;
  9196. end;
  9197. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9198. var
  9199. hp1,hp3 : tai;
  9200. {$ifndef x86_64}
  9201. hp2 : taicpu;
  9202. {$endif x86_64}
  9203. begin
  9204. Result:=false;
  9205. hp3:=nil;
  9206. {$ifndef x86_64}
  9207. { don't do this on modern CPUs, this really hurts them due to
  9208. broken call/ret pairing }
  9209. if (current_settings.optimizecputype < cpu_Pentium2) and
  9210. not(cs_create_pic in current_settings.moduleswitches) and
  9211. GetNextInstruction(p, hp1) and
  9212. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9213. MatchOpType(taicpu(hp1),top_ref) and
  9214. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9215. begin
  9216. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9217. InsertLLItem(p.previous, p, hp2);
  9218. taicpu(p).opcode := A_JMP;
  9219. taicpu(p).is_jmp := true;
  9220. RemoveInstruction(hp1);
  9221. Result:=true;
  9222. end
  9223. else
  9224. {$endif x86_64}
  9225. { replace
  9226. call procname
  9227. ret
  9228. by
  9229. jmp procname
  9230. but do it only on level 4 because it destroys stack back traces
  9231. else if the subroutine is marked as no return, remove the ret
  9232. }
  9233. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9234. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9235. GetNextInstruction(p, hp1) and
  9236. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9237. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9238. SetAndTest(hp1,hp3) and
  9239. GetNextInstruction(hp1,hp1) and
  9240. MatchInstruction(hp1,A_RET,[S_NO])
  9241. )
  9242. ) and
  9243. (taicpu(hp1).ops=0) then
  9244. begin
  9245. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9246. { we might destroy stack alignment here if we do not do a call }
  9247. (target_info.stackalign<=sizeof(SizeUInt)) then
  9248. begin
  9249. taicpu(p).opcode := A_JMP;
  9250. taicpu(p).is_jmp := true;
  9251. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9252. end
  9253. else
  9254. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9255. RemoveInstruction(hp1);
  9256. if Assigned(hp3) then
  9257. begin
  9258. AsmL.Remove(hp3);
  9259. AsmL.InsertBefore(hp3,p)
  9260. end;
  9261. Result:=true;
  9262. end;
  9263. end;
  9264. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9265. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9266. begin
  9267. case OpSize of
  9268. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9269. Result := (Val <= $FF) and (Val >= -128);
  9270. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9271. Result := (Val <= $FFFF) and (Val >= -32768);
  9272. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9273. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9274. else
  9275. Result := True;
  9276. end;
  9277. end;
  9278. var
  9279. hp1, hp2 : tai;
  9280. SizeChange: Boolean;
  9281. PreMessage: string;
  9282. begin
  9283. Result := False;
  9284. if (taicpu(p).oper[0]^.typ = top_reg) and
  9285. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9286. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  9287. begin
  9288. { Change (using movzbl %al,%eax as an example):
  9289. movzbl %al, %eax movzbl %al, %eax
  9290. cmpl x, %eax testl %eax,%eax
  9291. To:
  9292. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  9293. movzbl %al, %eax movzbl %al, %eax
  9294. Smaller instruction and minimises pipeline stall as the CPU
  9295. doesn't have to wait for the register to get zero-extended. [Kit]
  9296. Also allow if the smaller of the two registers is being checked,
  9297. as this still removes the false dependency.
  9298. }
  9299. if
  9300. (
  9301. (
  9302. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  9303. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  9304. ) or (
  9305. { If MatchOperand returns True, they must both be registers }
  9306. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  9307. )
  9308. ) and
  9309. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  9310. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  9311. begin
  9312. 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);
  9313. asml.Remove(hp1);
  9314. asml.InsertBefore(hp1, p);
  9315. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  9316. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  9317. begin
  9318. taicpu(hp1).opcode := A_TEST;
  9319. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  9320. end;
  9321. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9322. case taicpu(p).opsize of
  9323. S_BW, S_BL:
  9324. begin
  9325. SizeChange := taicpu(hp1).opsize <> S_B;
  9326. taicpu(hp1).changeopsize(S_B);
  9327. end;
  9328. S_WL:
  9329. begin
  9330. SizeChange := taicpu(hp1).opsize <> S_W;
  9331. taicpu(hp1).changeopsize(S_W);
  9332. end
  9333. else
  9334. InternalError(2020112701);
  9335. end;
  9336. UpdateUsedRegs(tai(p.Next));
  9337. { Check if the register is used aferwards - if not, we can
  9338. remove the movzx instruction completely }
  9339. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9340. begin
  9341. { Hp1 is a better position than p for debugging purposes }
  9342. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9343. RemoveCurrentp(p, hp1);
  9344. Result := True;
  9345. end;
  9346. if SizeChange then
  9347. DebugMsg(SPeepholeOptimization + PreMessage +
  9348. 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)
  9349. else
  9350. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9351. Exit;
  9352. end;
  9353. { Change (using movzwl %ax,%eax as an example):
  9354. movzwl %ax, %eax
  9355. movb %al, (dest) (Register is smaller than read register in movz)
  9356. To:
  9357. movb %al, (dest) (Move one back to avoid a false dependency)
  9358. movzwl %ax, %eax
  9359. }
  9360. if (taicpu(hp1).opcode = A_MOV) and
  9361. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9362. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9363. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9364. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9365. begin
  9366. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9367. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9368. asml.Remove(hp1);
  9369. asml.InsertBefore(hp1, p);
  9370. if taicpu(hp1).oper[1]^.typ = top_reg then
  9371. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9372. { Check if the register is used aferwards - if not, we can
  9373. remove the movzx instruction completely }
  9374. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9375. begin
  9376. { Hp1 is a better position than p for debugging purposes }
  9377. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9378. RemoveCurrentp(p, hp1);
  9379. Result := True;
  9380. end;
  9381. Exit;
  9382. end;
  9383. end;
  9384. {$ifdef x86_64}
  9385. { Code size reduction by J. Gareth "Kit" Moreton }
  9386. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  9387. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  9388. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  9389. then
  9390. begin
  9391. { Has 64-bit register name and opcode suffix }
  9392. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  9393. { The actual optimization }
  9394. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9395. if taicpu(p).opsize = S_BQ then
  9396. taicpu(p).changeopsize(S_BL)
  9397. else
  9398. taicpu(p).changeopsize(S_WL);
  9399. DebugMsg(SPeepholeOptimization + PreMessage +
  9400. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  9401. end;
  9402. {$endif}
  9403. end;
  9404. {$ifdef x86_64}
  9405. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9406. var
  9407. PreMessage, RegName: string;
  9408. begin
  9409. { Code size reduction by J. Gareth "Kit" Moreton }
  9410. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9411. as this removes the REX prefix }
  9412. Result := False;
  9413. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9414. Exit;
  9415. if taicpu(p).oper[0]^.typ <> top_reg then
  9416. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9417. InternalError(2018011500);
  9418. case taicpu(p).opsize of
  9419. S_Q:
  9420. begin
  9421. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  9422. begin
  9423. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9424. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9425. { The actual optimization }
  9426. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9427. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9428. taicpu(p).changeopsize(S_L);
  9429. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9430. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  9431. end;
  9432. end;
  9433. else
  9434. ;
  9435. end;
  9436. end;
  9437. {$endif}
  9438. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9439. var
  9440. OperIdx: Integer;
  9441. begin
  9442. for OperIdx := 0 to p.ops - 1 do
  9443. if p.oper[OperIdx]^.typ = top_ref then
  9444. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9445. end;
  9446. end.