aoptx86.pas 425 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979
  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. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function PrePeepholeOptAND(var p : tai) : boolean;
  98. function OptPass1Test(var p: tai): boolean;
  99. function OptPass1Add(var p: tai): boolean;
  100. function OptPass1AND(var p : tai) : boolean;
  101. function OptPass1_V_MOVAP(var p : tai) : boolean;
  102. function OptPass1VOP(var p : tai) : boolean;
  103. function OptPass1MOV(var p : tai) : boolean;
  104. function OptPass1Movx(var p : tai) : boolean;
  105. function OptPass1MOVXX(var p : tai) : boolean;
  106. function OptPass1OP(var p : tai) : boolean;
  107. function OptPass1LEA(var p : tai) : boolean;
  108. function OptPass1Sub(var p : tai) : boolean;
  109. function OptPass1SHLSAL(var p : tai) : boolean;
  110. function OptPass1FSTP(var p : tai) : boolean;
  111. function OptPass1FLD(var p : tai) : boolean;
  112. function OptPass1Cmp(var p : tai) : boolean;
  113. function OptPass1PXor(var p : tai) : boolean;
  114. function OptPass1VPXor(var p: tai): boolean;
  115. function OptPass1Imul(var p : tai) : boolean;
  116. function OptPass1Jcc(var p : tai) : boolean;
  117. function OptPass1SHXX(var p: tai): boolean;
  118. function OptPass2Movx(var p : tai): Boolean;
  119. function OptPass2MOV(var p : tai) : boolean;
  120. function OptPass2Imul(var p : tai) : boolean;
  121. function OptPass2Jmp(var p : tai) : boolean;
  122. function OptPass2Jcc(var p : tai) : boolean;
  123. function OptPass2Lea(var p: tai): Boolean;
  124. function OptPass2SUB(var p: tai): Boolean;
  125. function OptPass2ADD(var p : tai): Boolean;
  126. function OptPass2SETcc(var p : tai) : boolean;
  127. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  128. function PostPeepholeOptMov(var p : tai) : Boolean;
  129. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  130. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  131. function PostPeepholeOptXor(var p : tai) : Boolean;
  132. {$endif}
  133. function PostPeepholeOptAnd(var p : tai) : boolean;
  134. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  135. function PostPeepholeOptCmp(var p : tai) : Boolean;
  136. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  137. function PostPeepholeOptCall(var p : tai) : Boolean;
  138. function PostPeepholeOptLea(var p : tai) : Boolean;
  139. function PostPeepholeOptPush(var p: tai): Boolean;
  140. function PostPeepholeOptShr(var p : tai) : boolean;
  141. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  142. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  143. procedure SwapMovCmp(var p, hp1: tai);
  144. { Processor-dependent reference optimisation }
  145. class procedure OptimizeRefs(var p: taicpu); static;
  146. end;
  147. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  150. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  151. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  152. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  153. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  154. {$if max_operands>2}
  155. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  156. {$endif max_operands>2}
  157. function RefsEqual(const r1, r2: treference): boolean;
  158. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  159. { returns true, if ref is a reference using only the registers passed as base and index
  160. and having an offset }
  161. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  162. implementation
  163. uses
  164. cutils,verbose,
  165. systems,
  166. globals,
  167. cpuinfo,
  168. procinfo,
  169. paramgr,
  170. aasmbase,
  171. aoptbase,aoptutils,
  172. symconst,symsym,
  173. cgx86,
  174. itcpugas;
  175. {$ifdef DEBUG_AOPTCPU}
  176. const
  177. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  178. {$else DEBUG_AOPTCPU}
  179. { Empty strings help the optimizer to remove string concatenations that won't
  180. ever appear to the user on release builds. [Kit] }
  181. const
  182. SPeepholeOptimization = '';
  183. {$endif DEBUG_AOPTCPU}
  184. LIST_STEP_SIZE = 4;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. begin
  187. result :=
  188. (instr.typ = ait_instruction) and
  189. (taicpu(instr).opcode = op) and
  190. ((opsize = []) or (taicpu(instr).opsize in opsize));
  191. end;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. begin
  194. result :=
  195. (instr.typ = ait_instruction) and
  196. ((taicpu(instr).opcode = op1) or
  197. (taicpu(instr).opcode = op2)
  198. ) and
  199. ((opsize = []) or (taicpu(instr).opsize in opsize));
  200. end;
  201. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. ((taicpu(instr).opcode = op1) or
  206. (taicpu(instr).opcode = op2) or
  207. (taicpu(instr).opcode = op3)
  208. ) and
  209. ((opsize = []) or (taicpu(instr).opsize in opsize));
  210. end;
  211. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  212. const opsize : topsizes) : boolean;
  213. var
  214. op : TAsmOp;
  215. begin
  216. result:=false;
  217. for op in ops do
  218. begin
  219. if (instr.typ = ait_instruction) and
  220. (taicpu(instr).opcode = op) and
  221. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  222. begin
  223. result:=true;
  224. exit;
  225. end;
  226. end;
  227. end;
  228. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  229. begin
  230. result := (oper.typ = top_reg) and (oper.reg = reg);
  231. end;
  232. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  233. begin
  234. result := (oper.typ = top_const) and (oper.val = a);
  235. end;
  236. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  237. begin
  238. result := oper1.typ = oper2.typ;
  239. if result then
  240. case oper1.typ of
  241. top_const:
  242. Result:=oper1.val = oper2.val;
  243. top_reg:
  244. Result:=oper1.reg = oper2.reg;
  245. top_ref:
  246. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  247. else
  248. internalerror(2013102801);
  249. end
  250. end;
  251. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  252. begin
  253. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  254. if result then
  255. case oper1.typ of
  256. top_const:
  257. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  258. top_reg:
  259. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  260. top_ref:
  261. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  262. else
  263. internalerror(2020052401);
  264. end
  265. end;
  266. function RefsEqual(const r1, r2: treference): boolean;
  267. begin
  268. RefsEqual :=
  269. (r1.offset = r2.offset) and
  270. (r1.segment = r2.segment) and (r1.base = r2.base) and
  271. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  272. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  273. (r1.relsymbol = r2.relsymbol) and
  274. (r1.volatility=[]) and
  275. (r2.volatility=[]);
  276. end;
  277. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  278. begin
  279. Result:=(ref.offset=0) and
  280. (ref.scalefactor in [0,1]) and
  281. (ref.segment=NR_NO) and
  282. (ref.symbol=nil) and
  283. (ref.relsymbol=nil) and
  284. ((base=NR_INVALID) or
  285. (ref.base=base)) and
  286. ((index=NR_INVALID) or
  287. (ref.index=index)) and
  288. (ref.volatility=[]);
  289. end;
  290. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  291. begin
  292. Result:=(ref.scalefactor in [0,1]) and
  293. (ref.segment=NR_NO) and
  294. (ref.symbol=nil) and
  295. (ref.relsymbol=nil) and
  296. ((base=NR_INVALID) or
  297. (ref.base=base)) and
  298. ((index=NR_INVALID) or
  299. (ref.index=index)) and
  300. (ref.volatility=[]);
  301. end;
  302. function InstrReadsFlags(p: tai): boolean;
  303. begin
  304. InstrReadsFlags := true;
  305. case p.typ of
  306. ait_instruction:
  307. if InsProp[taicpu(p).opcode].Ch*
  308. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  309. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  310. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  311. exit;
  312. ait_label:
  313. exit;
  314. else
  315. ;
  316. end;
  317. InstrReadsFlags := false;
  318. end;
  319. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  320. begin
  321. Next:=Current;
  322. repeat
  323. Result:=GetNextInstruction(Next,Next);
  324. until not (Result) or
  325. not(cs_opt_level3 in current_settings.optimizerswitches) or
  326. (Next.typ<>ait_instruction) or
  327. RegInInstruction(reg,Next) or
  328. is_calljmp(taicpu(Next).opcode);
  329. end;
  330. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  331. begin
  332. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  333. Next := Current;
  334. repeat
  335. Result := GetNextInstruction(Next,Next);
  336. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  337. if is_calljmpuncond(taicpu(Next).opcode) then
  338. begin
  339. Result := False;
  340. Exit;
  341. end
  342. else
  343. CrossJump := True;
  344. until not Result or
  345. not (cs_opt_level3 in current_settings.optimizerswitches) or
  346. (Next.typ <> ait_instruction) or
  347. RegInInstruction(reg,Next);
  348. end;
  349. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  350. begin
  351. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  352. begin
  353. Result:=GetNextInstruction(Current,Next);
  354. exit;
  355. end;
  356. Next:=tai(Current.Next);
  357. Result:=false;
  358. while assigned(Next) do
  359. begin
  360. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  361. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  362. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  363. exit
  364. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  365. begin
  366. Result:=true;
  367. exit;
  368. end;
  369. Next:=tai(Next.Next);
  370. end;
  371. end;
  372. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  373. begin
  374. Result:=RegReadByInstruction(reg,hp);
  375. end;
  376. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  377. var
  378. p: taicpu;
  379. opcount: longint;
  380. begin
  381. RegReadByInstruction := false;
  382. if hp.typ <> ait_instruction then
  383. exit;
  384. p := taicpu(hp);
  385. case p.opcode of
  386. A_CALL:
  387. regreadbyinstruction := true;
  388. A_IMUL:
  389. case p.ops of
  390. 1:
  391. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  392. (
  393. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  394. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  395. );
  396. 2,3:
  397. regReadByInstruction :=
  398. reginop(reg,p.oper[0]^) or
  399. reginop(reg,p.oper[1]^);
  400. else
  401. InternalError(2019112801);
  402. end;
  403. A_MUL:
  404. begin
  405. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  406. (
  407. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  408. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  409. );
  410. end;
  411. A_IDIV,A_DIV:
  412. begin
  413. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  414. (
  415. (getregtype(reg)=R_INTREGISTER) and
  416. (
  417. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  418. )
  419. );
  420. end;
  421. else
  422. begin
  423. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  424. begin
  425. RegReadByInstruction := false;
  426. exit;
  427. end;
  428. for opcount := 0 to p.ops-1 do
  429. if (p.oper[opCount]^.typ = top_ref) and
  430. RegInRef(reg,p.oper[opcount]^.ref^) then
  431. begin
  432. RegReadByInstruction := true;
  433. exit
  434. end;
  435. { special handling for SSE MOVSD }
  436. if (p.opcode=A_MOVSD) and (p.ops>0) then
  437. begin
  438. if p.ops<>2 then
  439. internalerror(2017042702);
  440. regReadByInstruction := reginop(reg,p.oper[0]^) or
  441. (
  442. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  443. );
  444. exit;
  445. end;
  446. with insprop[p.opcode] do
  447. begin
  448. if getregtype(reg)=R_INTREGISTER then
  449. begin
  450. case getsupreg(reg) of
  451. RS_EAX:
  452. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  453. begin
  454. RegReadByInstruction := true;
  455. exit
  456. end;
  457. RS_ECX:
  458. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  459. begin
  460. RegReadByInstruction := true;
  461. exit
  462. end;
  463. RS_EDX:
  464. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  465. begin
  466. RegReadByInstruction := true;
  467. exit
  468. end;
  469. RS_EBX:
  470. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ESP:
  476. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EBP:
  482. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_ESI:
  488. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_EDI:
  494. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. end;
  500. end;
  501. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  502. begin
  503. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  504. begin
  505. case p.condition of
  506. C_A,C_NBE, { CF=0 and ZF=0 }
  507. C_BE,C_NA: { CF=1 or ZF=1 }
  508. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  509. C_AE,C_NB,C_NC, { CF=0 }
  510. C_B,C_NAE,C_C: { CF=1 }
  511. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  512. C_NE,C_NZ, { ZF=0 }
  513. C_E,C_Z: { ZF=1 }
  514. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  515. C_G,C_NLE, { ZF=0 and SF=OF }
  516. C_LE,C_NG: { ZF=1 or SF<>OF }
  517. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  518. C_GE,C_NL, { SF=OF }
  519. C_L,C_NGE: { SF<>OF }
  520. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  521. C_NO, { OF=0 }
  522. C_O: { OF=1 }
  523. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  524. C_NP,C_PO, { PF=0 }
  525. C_P,C_PE: { PF=1 }
  526. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  527. C_NS, { SF=0 }
  528. C_S: { SF=1 }
  529. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  530. else
  531. internalerror(2017042701);
  532. end;
  533. if RegReadByInstruction then
  534. exit;
  535. end;
  536. case getsubreg(reg) of
  537. R_SUBW,R_SUBD,R_SUBQ:
  538. RegReadByInstruction :=
  539. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  540. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  541. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  542. R_SUBFLAGCARRY:
  543. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  544. R_SUBFLAGPARITY:
  545. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  546. R_SUBFLAGAUXILIARY:
  547. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  548. R_SUBFLAGZERO:
  549. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  550. R_SUBFLAGSIGN:
  551. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  552. R_SUBFLAGOVERFLOW:
  553. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  554. R_SUBFLAGINTERRUPT:
  555. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  556. R_SUBFLAGDIRECTION:
  557. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  558. else
  559. internalerror(2017042601);
  560. end;
  561. exit;
  562. end;
  563. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  564. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  565. (p.oper[0]^.reg=p.oper[1]^.reg) then
  566. exit;
  567. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  568. begin
  569. RegReadByInstruction := true;
  570. exit
  571. end;
  572. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  573. begin
  574. RegReadByInstruction := true;
  575. exit
  576. end;
  577. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  578. begin
  579. RegReadByInstruction := true;
  580. exit
  581. end;
  582. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  583. begin
  584. RegReadByInstruction := true;
  585. exit
  586. end;
  587. end;
  588. end;
  589. end;
  590. end;
  591. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  592. begin
  593. result:=false;
  594. if p1.typ<>ait_instruction then
  595. exit;
  596. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  597. exit(true);
  598. if (getregtype(reg)=R_INTREGISTER) and
  599. { change information for xmm movsd are not correct }
  600. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  601. begin
  602. case getsupreg(reg) of
  603. { RS_EAX = RS_RAX on x86-64 }
  604. RS_EAX:
  605. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  606. RS_ECX:
  607. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  608. RS_EDX:
  609. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  610. RS_EBX:
  611. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  612. RS_ESP:
  613. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  614. RS_EBP:
  615. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  616. RS_ESI:
  617. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  618. RS_EDI:
  619. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  620. else
  621. ;
  622. end;
  623. if result then
  624. exit;
  625. end
  626. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  627. begin
  628. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  629. exit(true);
  630. case getsubreg(reg) of
  631. R_SUBFLAGCARRY:
  632. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  633. R_SUBFLAGPARITY:
  634. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  635. R_SUBFLAGAUXILIARY:
  636. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. R_SUBFLAGZERO:
  638. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. R_SUBFLAGSIGN:
  640. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. R_SUBFLAGOVERFLOW:
  642. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. R_SUBFLAGINTERRUPT:
  644. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. R_SUBFLAGDIRECTION:
  646. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. else
  648. ;
  649. end;
  650. if result then
  651. exit;
  652. end
  653. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  654. exit(true);
  655. Result:=inherited RegInInstruction(Reg, p1);
  656. end;
  657. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  658. begin
  659. Result := False;
  660. if p1.typ <> ait_instruction then
  661. exit;
  662. with insprop[taicpu(p1).opcode] do
  663. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  664. begin
  665. case getsubreg(reg) of
  666. R_SUBW,R_SUBD,R_SUBQ:
  667. Result :=
  668. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  669. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  670. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  671. R_SUBFLAGCARRY:
  672. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  673. R_SUBFLAGPARITY:
  674. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  675. R_SUBFLAGAUXILIARY:
  676. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  677. R_SUBFLAGZERO:
  678. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  679. R_SUBFLAGSIGN:
  680. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  681. R_SUBFLAGOVERFLOW:
  682. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  683. R_SUBFLAGINTERRUPT:
  684. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  685. R_SUBFLAGDIRECTION:
  686. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  687. else
  688. internalerror(2017042602);
  689. end;
  690. exit;
  691. end;
  692. case taicpu(p1).opcode of
  693. A_CALL:
  694. { We could potentially set Result to False if the register in
  695. question is non-volatile for the subroutine's calling convention,
  696. but this would require detecting the calling convention in use and
  697. also assuming that the routine doesn't contain malformed assembly
  698. language, for example... so it could only be done under -O4 as it
  699. would be considered a side-effect. [Kit] }
  700. Result := True;
  701. A_MOVSD:
  702. { special handling for SSE MOVSD }
  703. if (taicpu(p1).ops>0) then
  704. begin
  705. if taicpu(p1).ops<>2 then
  706. internalerror(2017042703);
  707. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  708. end;
  709. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  710. so fix it here (FK)
  711. }
  712. A_VMOVSS,
  713. A_VMOVSD:
  714. begin
  715. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  716. exit;
  717. end;
  718. A_IMUL:
  719. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  720. else
  721. ;
  722. end;
  723. if Result then
  724. exit;
  725. with insprop[taicpu(p1).opcode] do
  726. begin
  727. if getregtype(reg)=R_INTREGISTER then
  728. begin
  729. case getsupreg(reg) of
  730. RS_EAX:
  731. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  732. begin
  733. Result := True;
  734. exit
  735. end;
  736. RS_ECX:
  737. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  738. begin
  739. Result := True;
  740. exit
  741. end;
  742. RS_EDX:
  743. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  744. begin
  745. Result := True;
  746. exit
  747. end;
  748. RS_EBX:
  749. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  750. begin
  751. Result := True;
  752. exit
  753. end;
  754. RS_ESP:
  755. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  756. begin
  757. Result := True;
  758. exit
  759. end;
  760. RS_EBP:
  761. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  762. begin
  763. Result := True;
  764. exit
  765. end;
  766. RS_ESI:
  767. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  768. begin
  769. Result := True;
  770. exit
  771. end;
  772. RS_EDI:
  773. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  774. begin
  775. Result := True;
  776. exit
  777. end;
  778. end;
  779. end;
  780. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  781. begin
  782. Result := true;
  783. exit
  784. end;
  785. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  786. begin
  787. Result := true;
  788. exit
  789. end;
  790. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  791. begin
  792. Result := true;
  793. exit
  794. end;
  795. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  796. begin
  797. Result := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. {$ifdef DEBUG_AOPTCPU}
  803. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  804. begin
  805. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  806. end;
  807. function debug_tostr(i: tcgint): string; inline;
  808. begin
  809. Result := tostr(i);
  810. end;
  811. function debug_regname(r: TRegister): string; inline;
  812. begin
  813. Result := '%' + std_regname(r);
  814. end;
  815. { Debug output function - creates a string representation of an operator }
  816. function debug_operstr(oper: TOper): string;
  817. begin
  818. case oper.typ of
  819. top_const:
  820. Result := '$' + debug_tostr(oper.val);
  821. top_reg:
  822. Result := debug_regname(oper.reg);
  823. top_ref:
  824. begin
  825. if oper.ref^.offset <> 0 then
  826. Result := debug_tostr(oper.ref^.offset) + '('
  827. else
  828. Result := '(';
  829. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  830. begin
  831. Result := Result + debug_regname(oper.ref^.base);
  832. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  833. Result := Result + ',' + debug_regname(oper.ref^.index);
  834. end
  835. else
  836. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  837. Result := Result + debug_regname(oper.ref^.index);
  838. if (oper.ref^.scalefactor > 1) then
  839. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  840. else
  841. Result := Result + ')';
  842. end;
  843. else
  844. Result := '[UNKNOWN]';
  845. end;
  846. end;
  847. function debug_op2str(opcode: tasmop): string; inline;
  848. begin
  849. Result := std_op2str[opcode];
  850. end;
  851. function debug_opsize2str(opsize: topsize): string; inline;
  852. begin
  853. Result := gas_opsize2str[opsize];
  854. end;
  855. {$else DEBUG_AOPTCPU}
  856. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  857. begin
  858. end;
  859. function debug_tostr(i: tcgint): string; inline;
  860. begin
  861. Result := '';
  862. end;
  863. function debug_regname(r: TRegister): string; inline;
  864. begin
  865. Result := '';
  866. end;
  867. function debug_operstr(oper: TOper): string; inline;
  868. begin
  869. Result := '';
  870. end;
  871. function debug_op2str(opcode: tasmop): string; inline;
  872. begin
  873. Result := '';
  874. end;
  875. function debug_opsize2str(opsize: topsize): string; inline;
  876. begin
  877. Result := '';
  878. end;
  879. {$endif DEBUG_AOPTCPU}
  880. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  881. begin
  882. {$ifdef x86_64}
  883. { Always fine on x86-64 }
  884. Result := True;
  885. {$else x86_64}
  886. Result :=
  887. {$ifdef i8086}
  888. (current_settings.cputype >= cpu_386) and
  889. {$endif i8086}
  890. (
  891. { Always accept if optimising for size }
  892. (cs_opt_size in current_settings.optimizerswitches) or
  893. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  894. (current_settings.optimizecputype >= cpu_Pentium2)
  895. );
  896. {$endif x86_64}
  897. end;
  898. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  899. begin
  900. if not SuperRegistersEqual(reg1,reg2) then
  901. exit(false);
  902. if getregtype(reg1)<>R_INTREGISTER then
  903. exit(true); {because SuperRegisterEqual is true}
  904. case getsubreg(reg1) of
  905. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  906. higher, it preserves the high bits, so the new value depends on
  907. reg2's previous value. In other words, it is equivalent to doing:
  908. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  909. R_SUBL:
  910. exit(getsubreg(reg2)=R_SUBL);
  911. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  912. higher, it actually does a:
  913. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  914. R_SUBH:
  915. exit(getsubreg(reg2)=R_SUBH);
  916. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  917. bits of reg2:
  918. reg2 := (reg2 and $ffff0000) or word(reg1); }
  919. R_SUBW:
  920. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  921. { a write to R_SUBD always overwrites every other subregister,
  922. because it clears the high 32 bits of R_SUBQ on x86_64 }
  923. R_SUBD,
  924. R_SUBQ:
  925. exit(true);
  926. else
  927. internalerror(2017042801);
  928. end;
  929. end;
  930. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  931. begin
  932. if not SuperRegistersEqual(reg1,reg2) then
  933. exit(false);
  934. if getregtype(reg1)<>R_INTREGISTER then
  935. exit(true); {because SuperRegisterEqual is true}
  936. case getsubreg(reg1) of
  937. R_SUBL:
  938. exit(getsubreg(reg2)<>R_SUBH);
  939. R_SUBH:
  940. exit(getsubreg(reg2)<>R_SUBL);
  941. R_SUBW,
  942. R_SUBD,
  943. R_SUBQ:
  944. exit(true);
  945. else
  946. internalerror(2017042802);
  947. end;
  948. end;
  949. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  950. var
  951. hp1 : tai;
  952. l : TCGInt;
  953. begin
  954. result:=false;
  955. { changes the code sequence
  956. shr/sar const1, x
  957. shl const2, x
  958. to
  959. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  960. if GetNextInstruction(p, hp1) and
  961. MatchInstruction(hp1,A_SHL,[]) and
  962. (taicpu(p).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).oper[0]^.typ = top_const) and
  964. (taicpu(hp1).opsize = taicpu(p).opsize) and
  965. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  966. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  967. begin
  968. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  969. not(cs_opt_size in current_settings.optimizerswitches) then
  970. begin
  971. { shr/sar const1, %reg
  972. shl const2, %reg
  973. with const1 > const2 }
  974. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  975. taicpu(hp1).opcode := A_AND;
  976. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  977. case taicpu(p).opsize Of
  978. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  979. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  980. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  981. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  982. else
  983. Internalerror(2017050703)
  984. end;
  985. end
  986. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  987. not(cs_opt_size in current_settings.optimizerswitches) then
  988. begin
  989. { shr/sar const1, %reg
  990. shl const2, %reg
  991. with const1 < const2 }
  992. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  993. taicpu(p).opcode := A_AND;
  994. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  995. case taicpu(p).opsize Of
  996. S_B: taicpu(p).loadConst(0,l Xor $ff);
  997. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  998. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  999. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1000. else
  1001. Internalerror(2017050702)
  1002. end;
  1003. end
  1004. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1005. begin
  1006. { shr/sar const1, %reg
  1007. shl const2, %reg
  1008. with const1 = const2 }
  1009. taicpu(p).opcode := A_AND;
  1010. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1011. case taicpu(p).opsize Of
  1012. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1013. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1014. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1015. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1016. else
  1017. Internalerror(2017050701)
  1018. end;
  1019. RemoveInstruction(hp1);
  1020. end;
  1021. end;
  1022. end;
  1023. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1024. var
  1025. opsize : topsize;
  1026. hp1 : tai;
  1027. tmpref : treference;
  1028. ShiftValue : Cardinal;
  1029. BaseValue : TCGInt;
  1030. begin
  1031. result:=false;
  1032. opsize:=taicpu(p).opsize;
  1033. { changes certain "imul const, %reg"'s to lea sequences }
  1034. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1035. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1036. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1037. if (taicpu(p).oper[0]^.val = 1) then
  1038. if (taicpu(p).ops = 2) then
  1039. { remove "imul $1, reg" }
  1040. begin
  1041. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1042. Result := RemoveCurrentP(p);
  1043. end
  1044. else
  1045. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1046. begin
  1047. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1048. InsertLLItem(p.previous, p.next, hp1);
  1049. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1050. p.free;
  1051. p := hp1;
  1052. end
  1053. else if ((taicpu(p).ops <= 2) or
  1054. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1055. not(cs_opt_size in current_settings.optimizerswitches) and
  1056. (not(GetNextInstruction(p, hp1)) or
  1057. not((tai(hp1).typ = ait_instruction) and
  1058. ((taicpu(hp1).opcode=A_Jcc) and
  1059. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1060. begin
  1061. {
  1062. imul X, reg1, reg2 to
  1063. lea (reg1,reg1,Y), reg2
  1064. shl ZZ,reg2
  1065. imul XX, reg1 to
  1066. lea (reg1,reg1,YY), reg1
  1067. shl ZZ,reg2
  1068. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1069. it does not exist as a separate optimization target in FPC though.
  1070. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1071. at most two zeros
  1072. }
  1073. reference_reset(tmpref,1,[]);
  1074. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1075. begin
  1076. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1077. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1078. TmpRef.base := taicpu(p).oper[1]^.reg;
  1079. TmpRef.index := taicpu(p).oper[1]^.reg;
  1080. if not(BaseValue in [3,5,9]) then
  1081. Internalerror(2018110101);
  1082. TmpRef.ScaleFactor := BaseValue-1;
  1083. if (taicpu(p).ops = 2) then
  1084. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1085. else
  1086. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1087. AsmL.InsertAfter(hp1,p);
  1088. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1089. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1090. RemoveCurrentP(p, hp1);
  1091. if ShiftValue>0 then
  1092. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1093. end;
  1094. end;
  1095. end;
  1096. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1097. begin
  1098. Result := False;
  1099. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1100. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1101. begin
  1102. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1103. taicpu(p).opcode := A_MOV;
  1104. Result := True;
  1105. end;
  1106. end;
  1107. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1108. var
  1109. p: taicpu absolute hp;
  1110. i: Integer;
  1111. begin
  1112. Result := False;
  1113. if not assigned(hp) or
  1114. (hp.typ <> ait_instruction) then
  1115. Exit;
  1116. // p := taicpu(hp);
  1117. Prefetch(insprop[p.opcode]);
  1118. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1119. with insprop[p.opcode] do
  1120. begin
  1121. case getsubreg(reg) of
  1122. R_SUBW,R_SUBD,R_SUBQ:
  1123. Result:=
  1124. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1125. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1126. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1127. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1128. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1129. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1130. R_SUBFLAGCARRY:
  1131. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGPARITY:
  1133. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1134. R_SUBFLAGAUXILIARY:
  1135. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1136. R_SUBFLAGZERO:
  1137. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1138. R_SUBFLAGSIGN:
  1139. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1140. R_SUBFLAGOVERFLOW:
  1141. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1142. R_SUBFLAGINTERRUPT:
  1143. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1144. R_SUBFLAGDIRECTION:
  1145. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1146. else
  1147. begin
  1148. writeln(getsubreg(reg));
  1149. internalerror(2017050501);
  1150. end;
  1151. end;
  1152. exit;
  1153. end;
  1154. { Handle special cases first }
  1155. case p.opcode of
  1156. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1157. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1158. begin
  1159. Result :=
  1160. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1161. (p.oper[1]^.typ = top_reg) and
  1162. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1163. (
  1164. (p.oper[0]^.typ = top_const) or
  1165. (
  1166. (p.oper[0]^.typ = top_reg) and
  1167. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1168. ) or (
  1169. (p.oper[0]^.typ = top_ref) and
  1170. not RegInRef(reg,p.oper[0]^.ref^)
  1171. )
  1172. );
  1173. end;
  1174. A_MUL, A_IMUL:
  1175. Result :=
  1176. (
  1177. (p.ops=3) and { IMUL only }
  1178. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1179. (
  1180. (
  1181. (p.oper[1]^.typ=top_reg) and
  1182. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1183. ) or (
  1184. (p.oper[1]^.typ=top_ref) and
  1185. not RegInRef(reg,p.oper[1]^.ref^)
  1186. )
  1187. )
  1188. ) or (
  1189. (
  1190. (p.ops=1) and
  1191. (
  1192. (
  1193. (
  1194. (p.oper[0]^.typ=top_reg) and
  1195. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1196. )
  1197. ) or (
  1198. (p.oper[0]^.typ=top_ref) and
  1199. not RegInRef(reg,p.oper[0]^.ref^)
  1200. )
  1201. ) and (
  1202. (
  1203. (p.opsize=S_B) and
  1204. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1205. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1206. ) or (
  1207. (p.opsize=S_W) and
  1208. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1209. ) or (
  1210. (p.opsize=S_L) and
  1211. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1212. {$ifdef x86_64}
  1213. ) or (
  1214. (p.opsize=S_Q) and
  1215. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1216. {$endif x86_64}
  1217. )
  1218. )
  1219. )
  1220. );
  1221. A_CBW:
  1222. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1223. {$ifndef x86_64}
  1224. A_LDS:
  1225. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1226. A_LES:
  1227. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1228. {$endif not x86_64}
  1229. A_LFS:
  1230. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1231. A_LGS:
  1232. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1233. A_LSS:
  1234. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1235. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1236. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1237. A_LODSB:
  1238. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1239. A_LODSW:
  1240. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1241. {$ifdef x86_64}
  1242. A_LODSQ:
  1243. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1244. {$endif x86_64}
  1245. A_LODSD:
  1246. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1247. A_FSTSW, A_FNSTSW:
  1248. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1249. else
  1250. begin
  1251. with insprop[p.opcode] do
  1252. begin
  1253. if (
  1254. { xor %reg,%reg etc. is classed as a new value }
  1255. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1256. MatchOpType(p, top_reg, top_reg) and
  1257. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1258. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1259. ) then
  1260. begin
  1261. Result := True;
  1262. Exit;
  1263. end;
  1264. { Make sure the entire register is overwritten }
  1265. if (getregtype(reg) = R_INTREGISTER) then
  1266. begin
  1267. if (p.ops > 0) then
  1268. begin
  1269. if RegInOp(reg, p.oper[0]^) then
  1270. begin
  1271. if (p.oper[0]^.typ = top_ref) then
  1272. begin
  1273. if RegInRef(reg, p.oper[0]^.ref^) then
  1274. begin
  1275. Result := False;
  1276. Exit;
  1277. end;
  1278. end
  1279. else if (p.oper[0]^.typ = top_reg) then
  1280. begin
  1281. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1282. begin
  1283. Result := False;
  1284. Exit;
  1285. end
  1286. else if ([Ch_WOp1]*Ch<>[]) then
  1287. begin
  1288. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1289. Result := True
  1290. else
  1291. begin
  1292. Result := False;
  1293. Exit;
  1294. end;
  1295. end;
  1296. end;
  1297. end;
  1298. if (p.ops > 1) then
  1299. begin
  1300. if RegInOp(reg, p.oper[1]^) then
  1301. begin
  1302. if (p.oper[1]^.typ = top_ref) then
  1303. begin
  1304. if RegInRef(reg, p.oper[1]^.ref^) then
  1305. begin
  1306. Result := False;
  1307. Exit;
  1308. end;
  1309. end
  1310. else if (p.oper[1]^.typ = top_reg) then
  1311. begin
  1312. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1313. begin
  1314. Result := False;
  1315. Exit;
  1316. end
  1317. else if ([Ch_WOp2]*Ch<>[]) then
  1318. begin
  1319. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1320. Result := True
  1321. else
  1322. begin
  1323. Result := False;
  1324. Exit;
  1325. end;
  1326. end;
  1327. end;
  1328. end;
  1329. if (p.ops > 2) then
  1330. begin
  1331. if RegInOp(reg, p.oper[2]^) then
  1332. begin
  1333. if (p.oper[2]^.typ = top_ref) then
  1334. begin
  1335. if RegInRef(reg, p.oper[2]^.ref^) then
  1336. begin
  1337. Result := False;
  1338. Exit;
  1339. end;
  1340. end
  1341. else if (p.oper[2]^.typ = top_reg) then
  1342. begin
  1343. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1344. begin
  1345. Result := False;
  1346. Exit;
  1347. end
  1348. else if ([Ch_WOp3]*Ch<>[]) then
  1349. begin
  1350. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1351. Result := True
  1352. else
  1353. begin
  1354. Result := False;
  1355. Exit;
  1356. end;
  1357. end;
  1358. end;
  1359. end;
  1360. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1361. begin
  1362. if (p.oper[3]^.typ = top_ref) then
  1363. begin
  1364. if RegInRef(reg, p.oper[3]^.ref^) then
  1365. begin
  1366. Result := False;
  1367. Exit;
  1368. end;
  1369. end
  1370. else if (p.oper[3]^.typ = top_reg) then
  1371. begin
  1372. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1373. begin
  1374. Result := False;
  1375. Exit;
  1376. end
  1377. else if ([Ch_WOp4]*Ch<>[]) then
  1378. begin
  1379. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1380. Result := True
  1381. else
  1382. begin
  1383. Result := False;
  1384. Exit;
  1385. end;
  1386. end;
  1387. end;
  1388. end;
  1389. end;
  1390. end;
  1391. end;
  1392. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1393. case getsupreg(reg) of
  1394. RS_EAX:
  1395. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1396. begin
  1397. Result := True;
  1398. Exit;
  1399. end;
  1400. RS_ECX:
  1401. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1402. begin
  1403. Result := True;
  1404. Exit;
  1405. end;
  1406. RS_EDX:
  1407. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1408. begin
  1409. Result := True;
  1410. Exit;
  1411. end;
  1412. RS_EBX:
  1413. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1414. begin
  1415. Result := True;
  1416. Exit;
  1417. end;
  1418. RS_ESP:
  1419. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1420. begin
  1421. Result := True;
  1422. Exit;
  1423. end;
  1424. RS_EBP:
  1425. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1426. begin
  1427. Result := True;
  1428. Exit;
  1429. end;
  1430. RS_ESI:
  1431. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1432. begin
  1433. Result := True;
  1434. Exit;
  1435. end;
  1436. RS_EDI:
  1437. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. else
  1443. ;
  1444. end;
  1445. end;
  1446. end;
  1447. end;
  1448. end;
  1449. end;
  1450. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1451. var
  1452. hp2,hp3 : tai;
  1453. begin
  1454. { some x86-64 issue a NOP before the real exit code }
  1455. if MatchInstruction(p,A_NOP,[]) then
  1456. GetNextInstruction(p,p);
  1457. result:=assigned(p) and (p.typ=ait_instruction) and
  1458. ((taicpu(p).opcode = A_RET) or
  1459. ((taicpu(p).opcode=A_LEAVE) and
  1460. GetNextInstruction(p,hp2) and
  1461. MatchInstruction(hp2,A_RET,[S_NO])
  1462. ) or
  1463. (((taicpu(p).opcode=A_LEA) and
  1464. MatchOpType(taicpu(p),top_ref,top_reg) and
  1465. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1466. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1467. ) and
  1468. GetNextInstruction(p,hp2) and
  1469. MatchInstruction(hp2,A_RET,[S_NO])
  1470. ) or
  1471. ((((taicpu(p).opcode=A_MOV) and
  1472. MatchOpType(taicpu(p),top_reg,top_reg) and
  1473. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1474. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1475. ((taicpu(p).opcode=A_LEA) and
  1476. MatchOpType(taicpu(p),top_ref,top_reg) and
  1477. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1478. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1479. )
  1480. ) and
  1481. GetNextInstruction(p,hp2) and
  1482. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1483. MatchOpType(taicpu(hp2),top_reg) and
  1484. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1485. GetNextInstruction(hp2,hp3) and
  1486. MatchInstruction(hp3,A_RET,[S_NO])
  1487. )
  1488. );
  1489. end;
  1490. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1491. begin
  1492. isFoldableArithOp := False;
  1493. case hp1.opcode of
  1494. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1495. isFoldableArithOp :=
  1496. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1497. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1498. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1499. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1500. (taicpu(hp1).oper[1]^.reg = reg);
  1501. A_INC,A_DEC,A_NEG,A_NOT:
  1502. isFoldableArithOp :=
  1503. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1504. (taicpu(hp1).oper[0]^.reg = reg);
  1505. else
  1506. ;
  1507. end;
  1508. end;
  1509. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1510. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1511. var
  1512. hp2: tai;
  1513. begin
  1514. hp2 := p;
  1515. repeat
  1516. hp2 := tai(hp2.previous);
  1517. if assigned(hp2) and
  1518. (hp2.typ = ait_regalloc) and
  1519. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1520. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1521. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1522. begin
  1523. RemoveInstruction(hp2);
  1524. break;
  1525. end;
  1526. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1527. end;
  1528. begin
  1529. case current_procinfo.procdef.returndef.typ of
  1530. arraydef,recorddef,pointerdef,
  1531. stringdef,enumdef,procdef,objectdef,errordef,
  1532. filedef,setdef,procvardef,
  1533. classrefdef,forwarddef:
  1534. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1535. orddef:
  1536. if current_procinfo.procdef.returndef.size <> 0 then
  1537. begin
  1538. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1539. { for int64/qword }
  1540. if current_procinfo.procdef.returndef.size = 8 then
  1541. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1542. end;
  1543. else
  1544. ;
  1545. end;
  1546. end;
  1547. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1548. var
  1549. hp1,hp2 : tai;
  1550. begin
  1551. result:=false;
  1552. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1553. begin
  1554. { vmova* reg1,reg1
  1555. =>
  1556. <nop> }
  1557. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1558. begin
  1559. RemoveCurrentP(p);
  1560. result:=true;
  1561. exit;
  1562. end
  1563. else if GetNextInstruction(p,hp1) then
  1564. begin
  1565. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1566. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1567. begin
  1568. { vmova* reg1,reg2
  1569. vmova* reg2,reg3
  1570. dealloc reg2
  1571. =>
  1572. vmova* reg1,reg3 }
  1573. TransferUsedRegs(TmpUsedRegs);
  1574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1575. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1576. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1577. begin
  1578. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1579. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1580. RemoveInstruction(hp1);
  1581. result:=true;
  1582. exit;
  1583. end
  1584. { special case:
  1585. vmova* reg1,<op>
  1586. vmova* <op>,reg1
  1587. =>
  1588. vmova* reg1,<op> }
  1589. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1590. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1591. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1592. ) then
  1593. begin
  1594. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1595. RemoveInstruction(hp1);
  1596. result:=true;
  1597. exit;
  1598. end
  1599. end
  1600. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1601. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1602. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1603. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1604. ) and
  1605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1606. begin
  1607. { vmova* reg1,reg2
  1608. vmovs* reg2,<op>
  1609. dealloc reg2
  1610. =>
  1611. vmovs* reg1,reg3 }
  1612. TransferUsedRegs(TmpUsedRegs);
  1613. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1614. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1615. begin
  1616. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1617. taicpu(p).opcode:=taicpu(hp1).opcode;
  1618. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1619. RemoveInstruction(hp1);
  1620. result:=true;
  1621. exit;
  1622. end
  1623. end;
  1624. end;
  1625. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1626. begin
  1627. if MatchInstruction(hp1,[A_VFMADDPD,
  1628. A_VFMADD132PD,
  1629. A_VFMADD132PS,
  1630. A_VFMADD132SD,
  1631. A_VFMADD132SS,
  1632. A_VFMADD213PD,
  1633. A_VFMADD213PS,
  1634. A_VFMADD213SD,
  1635. A_VFMADD213SS,
  1636. A_VFMADD231PD,
  1637. A_VFMADD231PS,
  1638. A_VFMADD231SD,
  1639. A_VFMADD231SS,
  1640. A_VFMADDSUB132PD,
  1641. A_VFMADDSUB132PS,
  1642. A_VFMADDSUB213PD,
  1643. A_VFMADDSUB213PS,
  1644. A_VFMADDSUB231PD,
  1645. A_VFMADDSUB231PS,
  1646. A_VFMSUB132PD,
  1647. A_VFMSUB132PS,
  1648. A_VFMSUB132SD,
  1649. A_VFMSUB132SS,
  1650. A_VFMSUB213PD,
  1651. A_VFMSUB213PS,
  1652. A_VFMSUB213SD,
  1653. A_VFMSUB213SS,
  1654. A_VFMSUB231PD,
  1655. A_VFMSUB231PS,
  1656. A_VFMSUB231SD,
  1657. A_VFMSUB231SS,
  1658. A_VFMSUBADD132PD,
  1659. A_VFMSUBADD132PS,
  1660. A_VFMSUBADD213PD,
  1661. A_VFMSUBADD213PS,
  1662. A_VFMSUBADD231PD,
  1663. A_VFMSUBADD231PS,
  1664. A_VFNMADD132PD,
  1665. A_VFNMADD132PS,
  1666. A_VFNMADD132SD,
  1667. A_VFNMADD132SS,
  1668. A_VFNMADD213PD,
  1669. A_VFNMADD213PS,
  1670. A_VFNMADD213SD,
  1671. A_VFNMADD213SS,
  1672. A_VFNMADD231PD,
  1673. A_VFNMADD231PS,
  1674. A_VFNMADD231SD,
  1675. A_VFNMADD231SS,
  1676. A_VFNMSUB132PD,
  1677. A_VFNMSUB132PS,
  1678. A_VFNMSUB132SD,
  1679. A_VFNMSUB132SS,
  1680. A_VFNMSUB213PD,
  1681. A_VFNMSUB213PS,
  1682. A_VFNMSUB213SD,
  1683. A_VFNMSUB213SS,
  1684. A_VFNMSUB231PD,
  1685. A_VFNMSUB231PS,
  1686. A_VFNMSUB231SD,
  1687. A_VFNMSUB231SS],[S_NO]) and
  1688. { we mix single and double opperations here because we assume that the compiler
  1689. generates vmovapd only after double operations and vmovaps only after single operations }
  1690. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1691. GetNextInstruction(hp1,hp2) and
  1692. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1693. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1694. begin
  1695. TransferUsedRegs(TmpUsedRegs);
  1696. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1697. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1698. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1699. begin
  1700. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1701. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1702. RemoveInstruction(hp2);
  1703. end;
  1704. end
  1705. else if (hp1.typ = ait_instruction) and
  1706. GetNextInstruction(hp1, hp2) and
  1707. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1708. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1709. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1710. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1711. (((taicpu(p).opcode=A_MOVAPS) and
  1712. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1713. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1714. ((taicpu(p).opcode=A_MOVAPD) and
  1715. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1716. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1717. ) then
  1718. { change
  1719. movapX reg,reg2
  1720. addsX/subsX/... reg3, reg2
  1721. movapX reg2,reg
  1722. to
  1723. addsX/subsX/... reg3,reg
  1724. }
  1725. begin
  1726. TransferUsedRegs(TmpUsedRegs);
  1727. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1729. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1730. begin
  1731. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1732. debug_op2str(taicpu(p).opcode)+' '+
  1733. debug_op2str(taicpu(hp1).opcode)+' '+
  1734. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1735. { we cannot eliminate the first move if
  1736. the operations uses the same register for source and dest }
  1737. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1738. RemoveCurrentP(p, nil);
  1739. p:=hp1;
  1740. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1741. RemoveInstruction(hp2);
  1742. result:=true;
  1743. end;
  1744. end;
  1745. end;
  1746. end;
  1747. end;
  1748. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1749. var
  1750. hp1 : tai;
  1751. begin
  1752. result:=false;
  1753. { replace
  1754. V<Op>X %mreg1,%mreg2,%mreg3
  1755. VMovX %mreg3,%mreg4
  1756. dealloc %mreg3
  1757. by
  1758. V<Op>X %mreg1,%mreg2,%mreg4
  1759. ?
  1760. }
  1761. if GetNextInstruction(p,hp1) and
  1762. { we mix single and double operations here because we assume that the compiler
  1763. generates vmovapd only after double operations and vmovaps only after single operations }
  1764. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1765. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1766. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1767. begin
  1768. TransferUsedRegs(TmpUsedRegs);
  1769. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1770. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1773. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. end;
  1777. end;
  1778. end;
  1779. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1780. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1781. begin
  1782. Result := False;
  1783. { For safety reasons, only check for exact register matches }
  1784. { Check base register }
  1785. if (ref.base = AOldReg) then
  1786. begin
  1787. ref.base := ANewReg;
  1788. Result := True;
  1789. end;
  1790. { Check index register }
  1791. if (ref.index = AOldReg) then
  1792. begin
  1793. ref.index := ANewReg;
  1794. Result := True;
  1795. end;
  1796. end;
  1797. { Replaces all references to AOldReg in an operand to ANewReg }
  1798. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1799. var
  1800. OldSupReg, NewSupReg: TSuperRegister;
  1801. OldSubReg, NewSubReg: TSubRegister;
  1802. OldRegType: TRegisterType;
  1803. ThisOper: POper;
  1804. begin
  1805. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1806. Result := False;
  1807. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1808. InternalError(2020011801);
  1809. OldSupReg := getsupreg(AOldReg);
  1810. OldSubReg := getsubreg(AOldReg);
  1811. OldRegType := getregtype(AOldReg);
  1812. NewSupReg := getsupreg(ANewReg);
  1813. NewSubReg := getsubreg(ANewReg);
  1814. if OldRegType <> getregtype(ANewReg) then
  1815. InternalError(2020011802);
  1816. if OldSubReg <> NewSubReg then
  1817. InternalError(2020011803);
  1818. case ThisOper^.typ of
  1819. top_reg:
  1820. if (
  1821. (ThisOper^.reg = AOldReg) or
  1822. (
  1823. (OldRegType = R_INTREGISTER) and
  1824. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1825. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1826. (
  1827. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1828. {$ifndef x86_64}
  1829. and (
  1830. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1831. don't have an 8-bit representation }
  1832. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1833. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1834. )
  1835. {$endif x86_64}
  1836. )
  1837. )
  1838. ) then
  1839. begin
  1840. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1841. Result := True;
  1842. end;
  1843. top_ref:
  1844. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1845. Result := True;
  1846. else
  1847. ;
  1848. end;
  1849. end;
  1850. { Replaces all references to AOldReg in an instruction to ANewReg }
  1851. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1852. const
  1853. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1854. var
  1855. OperIdx: Integer;
  1856. begin
  1857. Result := False;
  1858. for OperIdx := 0 to p.ops - 1 do
  1859. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1860. { The shift and rotate instructions can only use CL }
  1861. not (
  1862. (OperIdx = 0) and
  1863. { This second condition just helps to avoid unnecessarily
  1864. calling MatchInstruction for 10 different opcodes }
  1865. (p.oper[0]^.reg = NR_CL) and
  1866. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1867. ) then
  1868. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1869. end;
  1870. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1871. begin
  1872. Result :=
  1873. (ref^.index = NR_NO) and
  1874. (
  1875. {$ifdef x86_64}
  1876. (
  1877. (ref^.base = NR_RIP) and
  1878. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1879. ) or
  1880. {$endif x86_64}
  1881. (ref^.base = NR_STACK_POINTER_REG) or
  1882. (ref^.base = current_procinfo.framepointer)
  1883. );
  1884. end;
  1885. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1886. var
  1887. l: asizeint;
  1888. begin
  1889. Result := False;
  1890. { Should have been checked previously }
  1891. if p.opcode <> A_LEA then
  1892. InternalError(2020072501);
  1893. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1894. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1895. not(cs_opt_size in current_settings.optimizerswitches) then
  1896. exit;
  1897. with p.oper[0]^.ref^ do
  1898. begin
  1899. if (base <> p.oper[1]^.reg) or
  1900. (index <> NR_NO) or
  1901. assigned(symbol) then
  1902. exit;
  1903. l:=offset;
  1904. if (l=1) and UseIncDec then
  1905. begin
  1906. p.opcode:=A_INC;
  1907. p.loadreg(0,p.oper[1]^.reg);
  1908. p.ops:=1;
  1909. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1910. end
  1911. else if (l=-1) and UseIncDec then
  1912. begin
  1913. p.opcode:=A_DEC;
  1914. p.loadreg(0,p.oper[1]^.reg);
  1915. p.ops:=1;
  1916. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1917. end
  1918. else
  1919. begin
  1920. if (l<0) and (l<>-2147483648) then
  1921. begin
  1922. p.opcode:=A_SUB;
  1923. p.loadConst(0,-l);
  1924. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1925. end
  1926. else
  1927. begin
  1928. p.opcode:=A_ADD;
  1929. p.loadConst(0,l);
  1930. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1931. end;
  1932. end;
  1933. end;
  1934. Result := True;
  1935. end;
  1936. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1937. var
  1938. CurrentReg, ReplaceReg: TRegister;
  1939. begin
  1940. Result := False;
  1941. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1942. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1943. case hp.opcode of
  1944. A_FSTSW, A_FNSTSW,
  1945. A_IN, A_INS, A_OUT, A_OUTS,
  1946. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1947. { These routines have explicit operands, but they are restricted in
  1948. what they can be (e.g. IN and OUT can only read from AL, AX or
  1949. EAX. }
  1950. Exit;
  1951. A_IMUL:
  1952. begin
  1953. { The 1-operand version writes to implicit registers
  1954. The 2-operand version reads from the first operator, and reads
  1955. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1956. the 3-operand version reads from a register that it doesn't write to
  1957. }
  1958. case hp.ops of
  1959. 1:
  1960. if (
  1961. (
  1962. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1963. ) or
  1964. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1965. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1966. begin
  1967. Result := True;
  1968. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1969. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1970. end;
  1971. 2:
  1972. { Only modify the first parameter }
  1973. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1974. begin
  1975. Result := True;
  1976. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1977. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1978. end;
  1979. 3:
  1980. { Only modify the second parameter }
  1981. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1982. begin
  1983. Result := True;
  1984. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1985. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1986. end;
  1987. else
  1988. InternalError(2020012901);
  1989. end;
  1990. end;
  1991. else
  1992. if (hp.ops > 0) and
  1993. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1994. begin
  1995. Result := True;
  1996. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1997. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1998. end;
  1999. end;
  2000. end;
  2001. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2002. var
  2003. hp1, hp2, hp3: tai;
  2004. DoOptimisation, TempBool: Boolean;
  2005. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2006. begin
  2007. if taicpu(hp1).opcode = signed_movop then
  2008. begin
  2009. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2010. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2011. end
  2012. else
  2013. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2014. end;
  2015. var
  2016. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2017. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2018. NewSize: topsize;
  2019. CurrentReg: TRegister;
  2020. begin
  2021. Result:=false;
  2022. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2023. { remove mov reg1,reg1? }
  2024. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2025. then
  2026. begin
  2027. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2028. { take care of the register (de)allocs following p }
  2029. RemoveCurrentP(p, hp1);
  2030. Result:=true;
  2031. exit;
  2032. end;
  2033. { All the next optimisations require a next instruction }
  2034. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2035. Exit;
  2036. { Look for:
  2037. mov %reg1,%reg2
  2038. ??? %reg2,r/m
  2039. Change to:
  2040. mov %reg1,%reg2
  2041. ??? %reg1,r/m
  2042. }
  2043. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2044. begin
  2045. CurrentReg := taicpu(p).oper[1]^.reg;
  2046. if RegReadByInstruction(CurrentReg, hp1) and
  2047. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2048. begin
  2049. TransferUsedRegs(TmpUsedRegs);
  2050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2051. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2052. { Just in case something didn't get modified (e.g. an
  2053. implicit register) }
  2054. not RegReadByInstruction(CurrentReg, hp1) then
  2055. begin
  2056. { We can remove the original MOV }
  2057. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2058. RemoveCurrentp(p, hp1);
  2059. { UsedRegs got updated by RemoveCurrentp }
  2060. Result := True;
  2061. Exit;
  2062. end;
  2063. { If we know a MOV instruction has become a null operation, we might as well
  2064. get rid of it now to save time. }
  2065. if (taicpu(hp1).opcode = A_MOV) and
  2066. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2067. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2068. { Just being a register is enough to confirm it's a null operation }
  2069. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2070. begin
  2071. Result := True;
  2072. { Speed-up to reduce a pipeline stall... if we had something like...
  2073. movl %eax,%edx
  2074. movw %dx,%ax
  2075. ... the second instruction would change to movw %ax,%ax, but
  2076. given that it is now %ax that's active rather than %eax,
  2077. penalties might occur due to a partial register write, so instead,
  2078. change it to a MOVZX instruction when optimising for speed.
  2079. }
  2080. if not (cs_opt_size in current_settings.optimizerswitches) and
  2081. IsMOVZXAcceptable and
  2082. (taicpu(hp1).opsize < taicpu(p).opsize)
  2083. {$ifdef x86_64}
  2084. { operations already implicitly set the upper 64 bits to zero }
  2085. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2086. {$endif x86_64}
  2087. then
  2088. begin
  2089. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2090. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2091. case taicpu(p).opsize of
  2092. S_W:
  2093. if taicpu(hp1).opsize = S_B then
  2094. taicpu(hp1).opsize := S_BL
  2095. else
  2096. InternalError(2020012911);
  2097. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2098. case taicpu(hp1).opsize of
  2099. S_B:
  2100. taicpu(hp1).opsize := S_BL;
  2101. S_W:
  2102. taicpu(hp1).opsize := S_WL;
  2103. else
  2104. InternalError(2020012912);
  2105. end;
  2106. else
  2107. InternalError(2020012910);
  2108. end;
  2109. taicpu(hp1).opcode := A_MOVZX;
  2110. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2111. end
  2112. else
  2113. begin
  2114. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2115. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2116. RemoveInstruction(hp1);
  2117. { The instruction after what was hp1 is now the immediate next instruction,
  2118. so we can continue to make optimisations if it's present }
  2119. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2120. Exit;
  2121. hp1 := hp2;
  2122. end;
  2123. end;
  2124. end;
  2125. end;
  2126. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2127. overwrites the original destination register. e.g.
  2128. movl ###,%reg2d
  2129. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2130. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2131. }
  2132. if (taicpu(p).oper[1]^.typ = top_reg) and
  2133. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2134. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2135. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2136. begin
  2137. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2138. begin
  2139. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2140. case taicpu(p).oper[0]^.typ of
  2141. top_const:
  2142. { We have something like:
  2143. movb $x, %regb
  2144. movzbl %regb,%regd
  2145. Change to:
  2146. movl $x, %regd
  2147. }
  2148. begin
  2149. case taicpu(hp1).opsize of
  2150. S_BW:
  2151. begin
  2152. convert_mov_value(A_MOVSX, $FF);
  2153. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2154. taicpu(p).opsize := S_W;
  2155. end;
  2156. S_BL:
  2157. begin
  2158. convert_mov_value(A_MOVSX, $FF);
  2159. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2160. taicpu(p).opsize := S_L;
  2161. end;
  2162. S_WL:
  2163. begin
  2164. convert_mov_value(A_MOVSX, $FFFF);
  2165. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2166. taicpu(p).opsize := S_L;
  2167. end;
  2168. {$ifdef x86_64}
  2169. S_BQ:
  2170. begin
  2171. convert_mov_value(A_MOVSX, $FF);
  2172. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2173. taicpu(p).opsize := S_Q;
  2174. end;
  2175. S_WQ:
  2176. begin
  2177. convert_mov_value(A_MOVSX, $FFFF);
  2178. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2179. taicpu(p).opsize := S_Q;
  2180. end;
  2181. S_LQ:
  2182. begin
  2183. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2184. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2185. taicpu(p).opsize := S_Q;
  2186. end;
  2187. {$endif x86_64}
  2188. else
  2189. { If hp1 was a MOV instruction, it should have been
  2190. optimised already }
  2191. InternalError(2020021001);
  2192. end;
  2193. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2194. RemoveInstruction(hp1);
  2195. Result := True;
  2196. Exit;
  2197. end;
  2198. top_ref:
  2199. { We have something like:
  2200. movb mem, %regb
  2201. movzbl %regb,%regd
  2202. Change to:
  2203. movzbl mem, %regd
  2204. }
  2205. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2206. begin
  2207. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2208. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2209. RemoveCurrentP(p, hp1);
  2210. Result:=True;
  2211. Exit;
  2212. end;
  2213. else
  2214. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2215. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2216. Exit;
  2217. end;
  2218. end
  2219. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2220. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2221. optimised }
  2222. else
  2223. begin
  2224. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2225. RemoveCurrentP(p, hp1);
  2226. Result := True;
  2227. Exit;
  2228. end;
  2229. end;
  2230. if (taicpu(hp1).opcode = A_AND) and
  2231. (taicpu(p).oper[1]^.typ = top_reg) and
  2232. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2233. begin
  2234. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2235. begin
  2236. case taicpu(p).opsize of
  2237. S_L:
  2238. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2239. begin
  2240. { Optimize out:
  2241. mov x, %reg
  2242. and ffffffffh, %reg
  2243. }
  2244. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2245. RemoveInstruction(hp1);
  2246. Result:=true;
  2247. exit;
  2248. end;
  2249. S_Q: { TODO: Confirm if this is even possible }
  2250. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2251. begin
  2252. { Optimize out:
  2253. mov x, %reg
  2254. and ffffffffffffffffh, %reg
  2255. }
  2256. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2257. RemoveInstruction(hp1);
  2258. Result:=true;
  2259. exit;
  2260. end;
  2261. else
  2262. ;
  2263. end;
  2264. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2265. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2266. GetNextInstruction(hp1,hp2) and
  2267. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2268. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2269. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2270. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2271. GetNextInstruction(hp2,hp3) and
  2272. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2273. (taicpu(hp3).condition in [C_E,C_NE]) then
  2274. begin
  2275. TransferUsedRegs(TmpUsedRegs);
  2276. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2277. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2278. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2279. begin
  2280. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2281. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2282. taicpu(hp1).opcode:=A_TEST;
  2283. RemoveInstruction(hp2);
  2284. RemoveCurrentP(p, hp1);
  2285. Result:=true;
  2286. exit;
  2287. end;
  2288. end;
  2289. end
  2290. else if IsMOVZXAcceptable and
  2291. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2292. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2293. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2294. then
  2295. begin
  2296. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2297. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2298. case taicpu(p).opsize of
  2299. S_B:
  2300. if (taicpu(hp1).oper[0]^.val = $ff) then
  2301. begin
  2302. { Convert:
  2303. movb x, %regl movb x, %regl
  2304. andw ffh, %regw andl ffh, %regd
  2305. To:
  2306. movzbw x, %regd movzbl x, %regd
  2307. (Identical registers, just different sizes)
  2308. }
  2309. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2310. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2311. case taicpu(hp1).opsize of
  2312. S_W: NewSize := S_BW;
  2313. S_L: NewSize := S_BL;
  2314. {$ifdef x86_64}
  2315. S_Q: NewSize := S_BQ;
  2316. {$endif x86_64}
  2317. else
  2318. InternalError(2018011510);
  2319. end;
  2320. end
  2321. else
  2322. NewSize := S_NO;
  2323. S_W:
  2324. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2325. begin
  2326. { Convert:
  2327. movw x, %regw
  2328. andl ffffh, %regd
  2329. To:
  2330. movzwl x, %regd
  2331. (Identical registers, just different sizes)
  2332. }
  2333. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2334. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2335. case taicpu(hp1).opsize of
  2336. S_L: NewSize := S_WL;
  2337. {$ifdef x86_64}
  2338. S_Q: NewSize := S_WQ;
  2339. {$endif x86_64}
  2340. else
  2341. InternalError(2018011511);
  2342. end;
  2343. end
  2344. else
  2345. NewSize := S_NO;
  2346. else
  2347. NewSize := S_NO;
  2348. end;
  2349. if NewSize <> S_NO then
  2350. begin
  2351. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2352. { The actual optimization }
  2353. taicpu(p).opcode := A_MOVZX;
  2354. taicpu(p).changeopsize(NewSize);
  2355. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2356. { Safeguard if "and" is followed by a conditional command }
  2357. TransferUsedRegs(TmpUsedRegs);
  2358. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2359. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2360. begin
  2361. { At this point, the "and" command is effectively equivalent to
  2362. "test %reg,%reg". This will be handled separately by the
  2363. Peephole Optimizer. [Kit] }
  2364. DebugMsg(SPeepholeOptimization + PreMessage +
  2365. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2366. end
  2367. else
  2368. begin
  2369. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2370. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2371. RemoveInstruction(hp1);
  2372. end;
  2373. Result := True;
  2374. Exit;
  2375. end;
  2376. end;
  2377. end;
  2378. if (taicpu(hp1).opcode = A_OR) and
  2379. (taicpu(p).oper[1]^.typ = top_reg) and
  2380. MatchOperand(taicpu(p).oper[0]^, 0) and
  2381. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2382. begin
  2383. { mov 0, %reg
  2384. or ###,%reg
  2385. Change to (only if the flags are not used):
  2386. mov ###,%reg
  2387. }
  2388. TransferUsedRegs(TmpUsedRegs);
  2389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2390. DoOptimisation := True;
  2391. { Even if the flags are used, we might be able to do the optimisation
  2392. if the conditions are predictable }
  2393. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2394. begin
  2395. { Only perform if ### = %reg (the same register) or equal to 0,
  2396. so %reg is guaranteed to still have a value of zero }
  2397. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2398. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2399. begin
  2400. hp2 := hp1;
  2401. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2402. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2403. GetNextInstruction(hp2, hp3) do
  2404. begin
  2405. { Don't continue modifying if the flags state is getting changed }
  2406. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2407. Break;
  2408. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2409. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2410. begin
  2411. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2412. begin
  2413. { Condition is always true }
  2414. case taicpu(hp3).opcode of
  2415. A_Jcc:
  2416. begin
  2417. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2418. { Check for jump shortcuts before we destroy the condition }
  2419. DoJumpOptimizations(hp3, TempBool);
  2420. MakeUnconditional(taicpu(hp3));
  2421. Result := True;
  2422. end;
  2423. A_CMOVcc:
  2424. begin
  2425. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2426. taicpu(hp3).opcode := A_MOV;
  2427. taicpu(hp3).condition := C_None;
  2428. Result := True;
  2429. end;
  2430. A_SETcc:
  2431. begin
  2432. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2433. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2434. taicpu(hp3).opcode := A_MOV;
  2435. taicpu(hp3).ops := 2;
  2436. taicpu(hp3).condition := C_None;
  2437. taicpu(hp3).opsize := S_B;
  2438. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2439. taicpu(hp3).loadconst(0, 1);
  2440. Result := True;
  2441. end;
  2442. else
  2443. InternalError(2021090701);
  2444. end;
  2445. end
  2446. 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
  2447. begin
  2448. { Condition is always false }
  2449. case taicpu(hp3).opcode of
  2450. A_Jcc:
  2451. begin
  2452. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2453. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2454. RemoveInstruction(hp3);
  2455. Result := True;
  2456. { Since hp3 was deleted, hp2 must not be updated }
  2457. Continue;
  2458. end;
  2459. A_CMOVcc:
  2460. begin
  2461. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2462. RemoveInstruction(hp3);
  2463. Result := True;
  2464. { Since hp3 was deleted, hp2 must not be updated }
  2465. Continue;
  2466. end;
  2467. A_SETcc:
  2468. begin
  2469. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2470. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2471. taicpu(hp3).opcode := A_MOV;
  2472. taicpu(hp3).ops := 2;
  2473. taicpu(hp3).condition := C_None;
  2474. taicpu(hp3).opsize := S_B;
  2475. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2476. taicpu(hp3).loadconst(0, 0);
  2477. Result := True;
  2478. end;
  2479. else
  2480. InternalError(2021090702);
  2481. end;
  2482. end
  2483. else
  2484. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2485. DoOptimisation := False;
  2486. end;
  2487. hp2 := hp3;
  2488. end;
  2489. { Flags are still in use - don't optimise }
  2490. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2491. DoOptimisation := False;
  2492. end
  2493. else
  2494. DoOptimisation := False;
  2495. end;
  2496. if DoOptimisation then
  2497. begin
  2498. {$ifdef x86_64}
  2499. { OR only supports 32-bit sign-extended constants for 64-bit
  2500. instructions, so compensate for this if the constant is
  2501. encoded as a value greater than or equal to 2^31 }
  2502. if (taicpu(hp1).opsize = S_Q) and
  2503. (taicpu(hp1).oper[0]^.typ = top_const) and
  2504. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2505. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2506. {$endif x86_64}
  2507. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2508. taicpu(hp1).opcode := A_MOV;
  2509. RemoveCurrentP(p, hp1);
  2510. Result := True;
  2511. Exit;
  2512. end;
  2513. end;
  2514. { Next instruction is also a MOV ? }
  2515. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2516. begin
  2517. if (taicpu(p).oper[1]^.typ = top_reg) and
  2518. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2519. begin
  2520. CurrentReg := taicpu(p).oper[1]^.reg;
  2521. TransferUsedRegs(TmpUsedRegs);
  2522. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2523. { we have
  2524. mov x, %treg
  2525. mov %treg, y
  2526. }
  2527. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2528. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2529. { we've got
  2530. mov x, %treg
  2531. mov %treg, y
  2532. with %treg is not used after }
  2533. case taicpu(p).oper[0]^.typ Of
  2534. { top_reg is covered by DeepMOVOpt }
  2535. top_const:
  2536. begin
  2537. { change
  2538. mov const, %treg
  2539. mov %treg, y
  2540. to
  2541. mov const, y
  2542. }
  2543. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2544. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2545. begin
  2546. if taicpu(hp1).oper[1]^.typ=top_reg then
  2547. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2548. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2549. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2550. RemoveInstruction(hp1);
  2551. Result:=true;
  2552. Exit;
  2553. end;
  2554. end;
  2555. top_ref:
  2556. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2557. begin
  2558. { change
  2559. mov mem, %treg
  2560. mov %treg, %reg
  2561. to
  2562. mov mem, %reg"
  2563. }
  2564. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2565. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2566. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2567. RemoveInstruction(hp1);
  2568. Result:=true;
  2569. Exit;
  2570. end;
  2571. else
  2572. ;
  2573. end
  2574. else
  2575. { %treg is used afterwards, but all eventualities
  2576. other than the first MOV instruction being a constant
  2577. are covered by DeepMOVOpt, so only check for that }
  2578. if (taicpu(p).oper[0]^.typ = top_const) and
  2579. (
  2580. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2581. not (cs_opt_size in current_settings.optimizerswitches) or
  2582. (taicpu(hp1).opsize = S_B)
  2583. ) and
  2584. (
  2585. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2586. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2587. ) then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2590. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2591. end;
  2592. end;
  2593. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2594. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2595. { mov reg1, mem1 or mov mem1, reg1
  2596. mov mem2, reg2 mov reg2, mem2}
  2597. begin
  2598. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2599. { mov reg1, mem1 or mov mem1, reg1
  2600. mov mem2, reg1 mov reg2, mem1}
  2601. begin
  2602. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2603. { Removes the second statement from
  2604. mov reg1, mem1/reg2
  2605. mov mem1/reg2, reg1 }
  2606. begin
  2607. if taicpu(p).oper[0]^.typ=top_reg then
  2608. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2609. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2610. RemoveInstruction(hp1);
  2611. Result:=true;
  2612. exit;
  2613. end
  2614. else
  2615. begin
  2616. TransferUsedRegs(TmpUsedRegs);
  2617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2618. if (taicpu(p).oper[1]^.typ = top_ref) and
  2619. { mov reg1, mem1
  2620. mov mem2, reg1 }
  2621. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2622. GetNextInstruction(hp1, hp2) and
  2623. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2624. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2625. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2626. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2627. { change to
  2628. mov reg1, mem1 mov reg1, mem1
  2629. mov mem2, reg1 cmp reg1, mem2
  2630. cmp mem1, reg1
  2631. }
  2632. begin
  2633. RemoveInstruction(hp2);
  2634. taicpu(hp1).opcode := A_CMP;
  2635. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2636. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2637. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2638. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2639. end;
  2640. end;
  2641. end
  2642. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2643. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2644. begin
  2645. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2646. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2647. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2648. end
  2649. else
  2650. begin
  2651. TransferUsedRegs(TmpUsedRegs);
  2652. if GetNextInstruction(hp1, hp2) and
  2653. MatchOpType(taicpu(p),top_ref,top_reg) and
  2654. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2655. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2656. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2657. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2658. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2659. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2660. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2661. { mov mem1, %reg1
  2662. mov %reg1, mem2
  2663. mov mem2, reg2
  2664. to:
  2665. mov mem1, reg2
  2666. mov reg2, mem2}
  2667. begin
  2668. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2669. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2670. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2671. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2672. RemoveInstruction(hp2);
  2673. end
  2674. {$ifdef i386}
  2675. { this is enabled for i386 only, as the rules to create the reg sets below
  2676. are too complicated for x86-64, so this makes this code too error prone
  2677. on x86-64
  2678. }
  2679. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2680. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2681. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2682. { mov mem1, reg1 mov mem1, reg1
  2683. mov reg1, mem2 mov reg1, mem2
  2684. mov mem2, reg2 mov mem2, reg1
  2685. to: to:
  2686. mov mem1, reg1 mov mem1, reg1
  2687. mov mem1, reg2 mov reg1, mem2
  2688. mov reg1, mem2
  2689. or (if mem1 depends on reg1
  2690. and/or if mem2 depends on reg2)
  2691. to:
  2692. mov mem1, reg1
  2693. mov reg1, mem2
  2694. mov reg1, reg2
  2695. }
  2696. begin
  2697. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2698. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2699. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2700. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2701. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2702. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2703. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2704. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2705. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2706. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2707. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2708. end
  2709. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2710. begin
  2711. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2712. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2713. end
  2714. else
  2715. begin
  2716. RemoveInstruction(hp2);
  2717. end
  2718. {$endif i386}
  2719. ;
  2720. end;
  2721. end
  2722. { movl [mem1],reg1
  2723. movl [mem1],reg2
  2724. to
  2725. movl [mem1],reg1
  2726. movl reg1,reg2
  2727. }
  2728. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2729. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2730. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2731. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2732. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2733. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2734. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2735. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2736. begin
  2737. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2738. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2739. end;
  2740. { movl const1,[mem1]
  2741. movl [mem1],reg1
  2742. to
  2743. movl const1,reg1
  2744. movl reg1,[mem1]
  2745. }
  2746. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2747. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2748. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2749. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2750. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2751. begin
  2752. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2753. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2754. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2755. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2756. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2757. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2758. Result:=true;
  2759. exit;
  2760. end;
  2761. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2762. end;
  2763. { search further than the next instruction for a mov }
  2764. if
  2765. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2766. (taicpu(p).oper[1]^.typ = top_reg) and
  2767. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2768. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2769. begin
  2770. { we work with hp2 here, so hp1 can be still used later on when
  2771. checking for GetNextInstruction_p }
  2772. hp3 := hp1;
  2773. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2774. CrossJump := False;
  2775. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2776. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2777. (hp2.typ=ait_instruction) do
  2778. begin
  2779. case taicpu(hp2).opcode of
  2780. A_MOV:
  2781. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2782. ((taicpu(p).oper[0]^.typ=top_const) or
  2783. ((taicpu(p).oper[0]^.typ=top_reg) and
  2784. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2785. )
  2786. ) then
  2787. begin
  2788. { we have
  2789. mov x, %treg
  2790. mov %treg, y
  2791. }
  2792. TransferUsedRegs(TmpUsedRegs);
  2793. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2794. { We don't need to call UpdateUsedRegs for every instruction between
  2795. p and hp2 because the register we're concerned about will not
  2796. become deallocated (otherwise GetNextInstructionUsingReg would
  2797. have stopped at an earlier instruction). [Kit] }
  2798. TempRegUsed :=
  2799. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2800. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2801. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2802. case taicpu(p).oper[0]^.typ Of
  2803. top_reg:
  2804. begin
  2805. { change
  2806. mov %reg, %treg
  2807. mov %treg, y
  2808. to
  2809. mov %reg, y
  2810. }
  2811. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2812. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2813. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2814. begin
  2815. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2816. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2817. if TempRegUsed then
  2818. begin
  2819. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2820. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2821. { Set the start of the next GetNextInstructionUsingRegCond search
  2822. to start at the entry right before hp2 (which is about to be removed) }
  2823. hp3 := tai(hp2.Previous);
  2824. RemoveInstruction(hp2);
  2825. { See if there's more we can optimise }
  2826. Continue;
  2827. end
  2828. else
  2829. begin
  2830. RemoveInstruction(hp2);
  2831. { We can remove the original MOV too }
  2832. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2833. RemoveCurrentP(p, hp1);
  2834. Result:=true;
  2835. Exit;
  2836. end;
  2837. end
  2838. else
  2839. begin
  2840. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2841. taicpu(hp2).loadReg(0, CurrentReg);
  2842. if TempRegUsed then
  2843. begin
  2844. { Don't remove the first instruction if the temporary register is in use }
  2845. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2846. { No need to set Result to True. If there's another instruction later on
  2847. that can be optimised, it will be detected when the main Pass 1 loop
  2848. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2849. end
  2850. else
  2851. begin
  2852. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2853. RemoveCurrentP(p, hp1);
  2854. Result:=true;
  2855. Exit;
  2856. end;
  2857. end;
  2858. end;
  2859. top_const:
  2860. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2861. begin
  2862. { change
  2863. mov const, %treg
  2864. mov %treg, y
  2865. to
  2866. mov const, y
  2867. }
  2868. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2869. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2870. begin
  2871. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2872. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2873. if TempRegUsed then
  2874. begin
  2875. { Don't remove the first instruction if the temporary register is in use }
  2876. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2877. { No need to set Result to True. If there's another instruction later on
  2878. that can be optimised, it will be detected when the main Pass 1 loop
  2879. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2880. end
  2881. else
  2882. begin
  2883. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2884. RemoveCurrentP(p, hp1);
  2885. Result:=true;
  2886. Exit;
  2887. end;
  2888. end;
  2889. end;
  2890. else
  2891. Internalerror(2019103001);
  2892. end;
  2893. end;
  2894. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2895. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2896. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2897. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2898. begin
  2899. {
  2900. Change from:
  2901. mov ###, %reg
  2902. ...
  2903. movs/z %reg,%reg (Same register, just different sizes)
  2904. To:
  2905. movs/z ###, %reg (Longer version)
  2906. ...
  2907. (remove)
  2908. }
  2909. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2910. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2911. { Keep the first instruction as mov if ### is a constant }
  2912. if taicpu(p).oper[0]^.typ = top_const then
  2913. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2914. else
  2915. begin
  2916. taicpu(p).opcode := taicpu(hp2).opcode;
  2917. taicpu(p).opsize := taicpu(hp2).opsize;
  2918. end;
  2919. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2920. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2921. RemoveInstruction(hp2);
  2922. Result := True;
  2923. Exit;
  2924. end;
  2925. else
  2926. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2927. begin
  2928. CurrentReg := taicpu(p).oper[1]^.reg;
  2929. TransferUsedRegs(TmpUsedRegs);
  2930. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2931. if
  2932. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2933. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2934. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2935. begin
  2936. { Just in case something didn't get modified (e.g. an
  2937. implicit register) }
  2938. if not RegReadByInstruction(CurrentReg, hp2) and
  2939. { If a conditional jump was crossed, do not delete
  2940. the original MOV no matter what }
  2941. not CrossJump then
  2942. begin
  2943. TransferUsedRegs(TmpUsedRegs);
  2944. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2945. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2946. if
  2947. { Make sure the original register isn't still present
  2948. and has been written to (e.g. with SHRX) }
  2949. RegLoadedWithNewValue(CurrentReg, hp2) or
  2950. not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2951. begin
  2952. RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs);
  2953. { We can remove the original MOV }
  2954. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2955. RemoveCurrentp(p, hp1);
  2956. Result := True;
  2957. Exit;
  2958. end
  2959. else
  2960. begin
  2961. { See if there's more we can optimise }
  2962. hp3 := hp2;
  2963. Continue;
  2964. end;
  2965. end;
  2966. end;
  2967. end;
  2968. end;
  2969. { Break out of the while loop under normal circumstances }
  2970. Break;
  2971. end;
  2972. end;
  2973. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2974. (taicpu(p).oper[1]^.typ = top_reg) and
  2975. (taicpu(p).opsize = S_L) and
  2976. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2977. (taicpu(hp2).opcode = A_AND) and
  2978. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2979. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2980. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2981. ) then
  2982. begin
  2983. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2984. begin
  2985. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2986. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2987. begin
  2988. { Optimize out:
  2989. mov x, %reg
  2990. and ffffffffh, %reg
  2991. }
  2992. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2993. RemoveInstruction(hp2);
  2994. Result:=true;
  2995. exit;
  2996. end;
  2997. end;
  2998. end;
  2999. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3000. x >= RetOffset) as it doesn't do anything (it writes either to a
  3001. parameter or to the temporary storage room for the function
  3002. result)
  3003. }
  3004. if IsExitCode(hp1) and
  3005. (taicpu(p).oper[1]^.typ = top_ref) and
  3006. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3007. (
  3008. (
  3009. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3010. not (
  3011. assigned(current_procinfo.procdef.funcretsym) and
  3012. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3013. )
  3014. ) or
  3015. { Also discard writes to the stack that are below the base pointer,
  3016. as this is temporary storage rather than a function result on the
  3017. stack, say. }
  3018. (
  3019. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3020. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3021. )
  3022. ) then
  3023. begin
  3024. RemoveCurrentp(p, hp1);
  3025. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3026. RemoveLastDeallocForFuncRes(p);
  3027. Result:=true;
  3028. exit;
  3029. end;
  3030. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3031. begin
  3032. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3033. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3034. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3035. begin
  3036. { change
  3037. mov reg1, mem1
  3038. test/cmp x, mem1
  3039. to
  3040. mov reg1, mem1
  3041. test/cmp x, reg1
  3042. }
  3043. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3044. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3045. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3046. Result := True;
  3047. Exit;
  3048. end;
  3049. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3050. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3051. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3052. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3053. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3054. (
  3055. (
  3056. (taicpu(hp1).opcode = A_TEST)
  3057. ) or (
  3058. (taicpu(hp1).opcode = A_CMP) and
  3059. { A sanity check more than anything }
  3060. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3061. )
  3062. ) then
  3063. begin
  3064. { change
  3065. mov mem, %reg
  3066. cmp/test x, %reg / test %reg,%reg
  3067. (reg deallocated)
  3068. to
  3069. cmp/test x, mem / cmp 0, mem
  3070. }
  3071. TransferUsedRegs(TmpUsedRegs);
  3072. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3073. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3074. begin
  3075. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3076. if (taicpu(hp1).opcode = A_TEST) and
  3077. (
  3078. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3079. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3080. ) then
  3081. begin
  3082. taicpu(hp1).opcode := A_CMP;
  3083. taicpu(hp1).loadconst(0, 0);
  3084. end;
  3085. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3086. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3087. RemoveCurrentP(p, hp1);
  3088. Result := True;
  3089. Exit;
  3090. end;
  3091. end;
  3092. end;
  3093. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3094. { If the flags register is in use, don't change the instruction to an
  3095. ADD otherwise this will scramble the flags. [Kit] }
  3096. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3097. begin
  3098. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3099. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3100. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3101. ) or
  3102. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3103. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3104. )
  3105. ) then
  3106. { mov reg1,ref
  3107. lea reg2,[reg1,reg2]
  3108. to
  3109. add reg2,ref}
  3110. begin
  3111. TransferUsedRegs(TmpUsedRegs);
  3112. { reg1 may not be used afterwards }
  3113. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3114. begin
  3115. Taicpu(hp1).opcode:=A_ADD;
  3116. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3117. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3118. RemoveCurrentp(p, hp1);
  3119. result:=true;
  3120. exit;
  3121. end;
  3122. end;
  3123. { If the LEA instruction can be converted into an arithmetic instruction,
  3124. it may be possible to then fold it in the next optimisation, otherwise
  3125. there's nothing more that can be optimised here. }
  3126. if not ConvertLEA(taicpu(hp1)) then
  3127. Exit;
  3128. end;
  3129. if (taicpu(p).oper[1]^.typ = top_reg) and
  3130. (hp1.typ = ait_instruction) and
  3131. GetNextInstruction(hp1, hp2) and
  3132. MatchInstruction(hp2,A_MOV,[]) and
  3133. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3134. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3135. (
  3136. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3137. {$ifdef x86_64}
  3138. or
  3139. (
  3140. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3141. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3142. )
  3143. {$endif x86_64}
  3144. ) then
  3145. begin
  3146. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3147. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3148. { change movsX/movzX reg/ref, reg2
  3149. add/sub/or/... reg3/$const, reg2
  3150. mov reg2 reg/ref
  3151. dealloc reg2
  3152. to
  3153. add/sub/or/... reg3/$const, reg/ref }
  3154. begin
  3155. TransferUsedRegs(TmpUsedRegs);
  3156. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3157. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3158. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3159. begin
  3160. { by example:
  3161. movswl %si,%eax movswl %si,%eax p
  3162. decl %eax addl %edx,%eax hp1
  3163. movw %ax,%si movw %ax,%si hp2
  3164. ->
  3165. movswl %si,%eax movswl %si,%eax p
  3166. decw %eax addw %edx,%eax hp1
  3167. movw %ax,%si movw %ax,%si hp2
  3168. }
  3169. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3170. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3171. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3172. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3173. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3174. {
  3175. ->
  3176. movswl %si,%eax movswl %si,%eax p
  3177. decw %si addw %dx,%si hp1
  3178. movw %ax,%si movw %ax,%si hp2
  3179. }
  3180. case taicpu(hp1).ops of
  3181. 1:
  3182. begin
  3183. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3184. if taicpu(hp1).oper[0]^.typ=top_reg then
  3185. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3186. end;
  3187. 2:
  3188. begin
  3189. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3190. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3191. (taicpu(hp1).opcode<>A_SHL) and
  3192. (taicpu(hp1).opcode<>A_SHR) and
  3193. (taicpu(hp1).opcode<>A_SAR) then
  3194. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3195. end;
  3196. else
  3197. internalerror(2008042701);
  3198. end;
  3199. {
  3200. ->
  3201. decw %si addw %dx,%si p
  3202. }
  3203. RemoveInstruction(hp2);
  3204. RemoveCurrentP(p, hp1);
  3205. Result:=True;
  3206. Exit;
  3207. end;
  3208. end;
  3209. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3210. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3211. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3212. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3213. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3214. )
  3215. {$ifdef i386}
  3216. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3217. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3218. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3219. {$endif i386}
  3220. then
  3221. { change movsX/movzX reg/ref, reg2
  3222. add/sub/or/... regX/$const, reg2
  3223. mov reg2, reg3
  3224. dealloc reg2
  3225. to
  3226. movsX/movzX reg/ref, reg3
  3227. add/sub/or/... reg3/$const, reg3
  3228. }
  3229. begin
  3230. TransferUsedRegs(TmpUsedRegs);
  3231. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3232. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3233. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3234. begin
  3235. { by example:
  3236. movswl %si,%eax movswl %si,%eax p
  3237. decl %eax addl %edx,%eax hp1
  3238. movw %ax,%si movw %ax,%si hp2
  3239. ->
  3240. movswl %si,%eax movswl %si,%eax p
  3241. decw %eax addw %edx,%eax hp1
  3242. movw %ax,%si movw %ax,%si hp2
  3243. }
  3244. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3245. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3246. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3247. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3248. { limit size of constants as well to avoid assembler errors, but
  3249. check opsize to avoid overflow when left shifting the 1 }
  3250. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3251. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3252. {$ifdef x86_64}
  3253. { Be careful of, for example:
  3254. movl %reg1,%reg2
  3255. addl %reg3,%reg2
  3256. movq %reg2,%reg4
  3257. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3258. }
  3259. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3260. begin
  3261. taicpu(hp2).changeopsize(S_L);
  3262. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3263. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3264. end;
  3265. {$endif x86_64}
  3266. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3267. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3268. if taicpu(p).oper[0]^.typ=top_reg then
  3269. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3270. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3271. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3272. {
  3273. ->
  3274. movswl %si,%eax movswl %si,%eax p
  3275. decw %si addw %dx,%si hp1
  3276. movw %ax,%si movw %ax,%si hp2
  3277. }
  3278. case taicpu(hp1).ops of
  3279. 1:
  3280. begin
  3281. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3282. if taicpu(hp1).oper[0]^.typ=top_reg then
  3283. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3284. end;
  3285. 2:
  3286. begin
  3287. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3288. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3289. (taicpu(hp1).opcode<>A_SHL) and
  3290. (taicpu(hp1).opcode<>A_SHR) and
  3291. (taicpu(hp1).opcode<>A_SAR) then
  3292. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3293. end;
  3294. else
  3295. internalerror(2018111801);
  3296. end;
  3297. {
  3298. ->
  3299. decw %si addw %dx,%si p
  3300. }
  3301. RemoveInstruction(hp2);
  3302. end;
  3303. end;
  3304. end;
  3305. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3306. GetNextInstruction(hp1, hp2) and
  3307. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3308. MatchOperand(Taicpu(p).oper[0]^,0) and
  3309. (Taicpu(p).oper[1]^.typ = top_reg) and
  3310. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3311. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3312. { mov reg1,0
  3313. bts reg1,operand1 --> mov reg1,operand2
  3314. or reg1,operand2 bts reg1,operand1}
  3315. begin
  3316. Taicpu(hp2).opcode:=A_MOV;
  3317. asml.remove(hp1);
  3318. insertllitem(hp2,hp2.next,hp1);
  3319. RemoveCurrentp(p, hp1);
  3320. Result:=true;
  3321. exit;
  3322. end;
  3323. {$ifdef x86_64}
  3324. { Convert:
  3325. movq x(ref),%reg64
  3326. shrq y,%reg64
  3327. To:
  3328. movq x+4(ref),%reg32
  3329. shrq y-32,%reg32 (Remove if y = 32)
  3330. }
  3331. if (taicpu(p).opsize = S_Q) and
  3332. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3333. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3334. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3335. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3336. (taicpu(hp1).oper[0]^.val >= 32) and
  3337. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3338. begin
  3339. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3340. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3341. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3342. { Convert to 32-bit }
  3343. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3344. taicpu(p).opsize := S_L;
  3345. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3346. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3347. if (taicpu(hp1).oper[0]^.val = 32) then
  3348. begin
  3349. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3350. RemoveInstruction(hp1);
  3351. end
  3352. else
  3353. begin
  3354. { This will potentially open up more arithmetic operations since
  3355. the peephole optimizer now has a big hint that only the lower
  3356. 32 bits are currently in use (and opcodes are smaller in size) }
  3357. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3358. taicpu(hp1).opsize := S_L;
  3359. Dec(taicpu(hp1).oper[0]^.val, 32);
  3360. DebugMsg(SPeepholeOptimization + PreMessage +
  3361. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3362. end;
  3363. Result := True;
  3364. Exit;
  3365. end;
  3366. {$endif x86_64}
  3367. end;
  3368. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3369. var
  3370. hp1 : tai;
  3371. begin
  3372. Result:=false;
  3373. if taicpu(p).ops <> 2 then
  3374. exit;
  3375. if GetNextInstruction(p,hp1) and
  3376. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3377. (taicpu(hp1).ops = 2) then
  3378. begin
  3379. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3380. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3381. { movXX reg1, mem1 or movXX mem1, reg1
  3382. movXX mem2, reg2 movXX reg2, mem2}
  3383. begin
  3384. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3385. { movXX reg1, mem1 or movXX mem1, reg1
  3386. movXX mem2, reg1 movXX reg2, mem1}
  3387. begin
  3388. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3389. begin
  3390. { Removes the second statement from
  3391. movXX reg1, mem1/reg2
  3392. movXX mem1/reg2, reg1
  3393. }
  3394. if taicpu(p).oper[0]^.typ=top_reg then
  3395. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3396. { Removes the second statement from
  3397. movXX mem1/reg1, reg2
  3398. movXX reg2, mem1/reg1
  3399. }
  3400. if (taicpu(p).oper[1]^.typ=top_reg) and
  3401. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3402. begin
  3403. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3404. RemoveInstruction(hp1);
  3405. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3406. end
  3407. else
  3408. begin
  3409. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3410. RemoveInstruction(hp1);
  3411. end;
  3412. Result:=true;
  3413. exit;
  3414. end
  3415. end;
  3416. end;
  3417. end;
  3418. end;
  3419. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3420. var
  3421. hp1 : tai;
  3422. begin
  3423. result:=false;
  3424. { replace
  3425. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3426. MovX %mreg2,%mreg1
  3427. dealloc %mreg2
  3428. by
  3429. <Op>X %mreg2,%mreg1
  3430. ?
  3431. }
  3432. if GetNextInstruction(p,hp1) and
  3433. { we mix single and double opperations here because we assume that the compiler
  3434. generates vmovapd only after double operations and vmovaps only after single operations }
  3435. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3436. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3437. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3438. (taicpu(p).oper[0]^.typ=top_reg) then
  3439. begin
  3440. TransferUsedRegs(TmpUsedRegs);
  3441. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3442. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3443. begin
  3444. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3445. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3446. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3447. RemoveInstruction(hp1);
  3448. result:=true;
  3449. end;
  3450. end;
  3451. end;
  3452. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3453. var
  3454. hp1, p_label, p_dist, hp1_dist: tai;
  3455. JumpLabel, JumpLabel_dist: TAsmLabel;
  3456. begin
  3457. Result := False;
  3458. if (taicpu(p).oper[1]^.typ = top_reg) then
  3459. begin
  3460. if GetNextInstruction(p, hp1) and
  3461. MatchInstruction(hp1,A_MOV,[]) and
  3462. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3463. (
  3464. (taicpu(p).oper[0]^.typ <> top_reg) or
  3465. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3466. ) then
  3467. begin
  3468. { If we have something like:
  3469. test %reg1,%reg1
  3470. mov 0,%reg2
  3471. And no registers are shared (the two %reg1's can be different, as
  3472. long as neither of them are also %reg2), move the MOV command to
  3473. before the comparison as this means it can be optimised without
  3474. worrying about the FLAGS register. (This combination is generated
  3475. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3476. }
  3477. SwapMovCmp(p, hp1);
  3478. Result := True;
  3479. Exit;
  3480. end;
  3481. { Search for:
  3482. test %reg,%reg
  3483. j(c1) @lbl1
  3484. ...
  3485. @lbl:
  3486. test %reg,%reg (same register)
  3487. j(c2) @lbl2
  3488. If c2 is a subset of c1, change to:
  3489. test %reg,%reg
  3490. j(c1) @lbl2
  3491. (@lbl1 may become a dead label as a result)
  3492. }
  3493. if (taicpu(p).oper[0]^.typ = top_reg) and
  3494. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3495. MatchInstruction(hp1, A_JCC, []) and
  3496. IsJumpToLabel(taicpu(hp1)) then
  3497. begin
  3498. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3499. p_label := nil;
  3500. if Assigned(JumpLabel) then
  3501. p_label := getlabelwithsym(JumpLabel);
  3502. if Assigned(p_label) and
  3503. GetNextInstruction(p_label, p_dist) and
  3504. MatchInstruction(p_dist, A_TEST, []) and
  3505. { It's fine if the second test uses smaller sub-registers }
  3506. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3507. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3508. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3509. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3510. GetNextInstruction(p_dist, hp1_dist) and
  3511. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3512. begin
  3513. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3514. if JumpLabel = JumpLabel_dist then
  3515. { This is an infinite loop }
  3516. Exit;
  3517. { Best optimisation when the first condition is a subset (or equal) of the second }
  3518. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3519. begin
  3520. { Any registers used here will already be allocated }
  3521. if Assigned(JumpLabel_dist) then
  3522. JumpLabel_dist.IncRefs;
  3523. if Assigned(JumpLabel) then
  3524. JumpLabel.DecRefs;
  3525. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3526. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3527. Result := True;
  3528. Exit;
  3529. end;
  3530. end;
  3531. end;
  3532. end;
  3533. end;
  3534. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3535. var
  3536. hp1 : tai;
  3537. begin
  3538. result:=false;
  3539. { replace
  3540. addX const,%reg1
  3541. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3542. dealloc %reg1
  3543. by
  3544. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3545. }
  3546. if MatchOpType(taicpu(p),top_const,top_reg) and
  3547. GetNextInstruction(p,hp1) and
  3548. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3549. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3550. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3551. begin
  3552. TransferUsedRegs(TmpUsedRegs);
  3553. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3554. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3555. begin
  3556. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3557. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3558. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3559. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3560. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3561. RemoveCurrentP(p);
  3562. result:=true;
  3563. end;
  3564. end;
  3565. end;
  3566. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3567. var
  3568. hp1: tai;
  3569. ref: Integer;
  3570. saveref: treference;
  3571. TempReg: TRegister;
  3572. Multiple: TCGInt;
  3573. begin
  3574. Result:=false;
  3575. { removes seg register prefixes from LEA operations, as they
  3576. don't do anything}
  3577. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3578. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3579. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3580. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3581. (
  3582. { do not mess with leas accessing the stack pointer
  3583. unless it's a null operation }
  3584. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3585. (
  3586. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3587. (taicpu(p).oper[0]^.ref^.offset = 0)
  3588. )
  3589. ) and
  3590. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3591. begin
  3592. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3593. begin
  3594. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3595. begin
  3596. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3597. taicpu(p).oper[1]^.reg);
  3598. InsertLLItem(p.previous,p.next, hp1);
  3599. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3600. p.free;
  3601. p:=hp1;
  3602. end
  3603. else
  3604. begin
  3605. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3606. RemoveCurrentP(p);
  3607. end;
  3608. Result:=true;
  3609. exit;
  3610. end
  3611. else if (
  3612. { continue to use lea to adjust the stack pointer,
  3613. it is the recommended way, but only if not optimizing for size }
  3614. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3615. (cs_opt_size in current_settings.optimizerswitches)
  3616. ) and
  3617. { If the flags register is in use, don't change the instruction
  3618. to an ADD otherwise this will scramble the flags. [Kit] }
  3619. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3620. ConvertLEA(taicpu(p)) then
  3621. begin
  3622. Result:=true;
  3623. exit;
  3624. end;
  3625. end;
  3626. if GetNextInstruction(p,hp1) and
  3627. (hp1.typ=ait_instruction) then
  3628. begin
  3629. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3631. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3632. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3633. begin
  3634. TransferUsedRegs(TmpUsedRegs);
  3635. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3636. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3637. begin
  3638. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3639. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3640. RemoveInstruction(hp1);
  3641. result:=true;
  3642. exit;
  3643. end;
  3644. end;
  3645. { changes
  3646. lea <ref1>, reg1
  3647. <op> ...,<ref. with reg1>,...
  3648. to
  3649. <op> ...,<ref1>,... }
  3650. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3651. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3652. not(MatchInstruction(hp1,A_LEA,[])) then
  3653. begin
  3654. { find a reference which uses reg1 }
  3655. 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
  3656. ref:=0
  3657. 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
  3658. ref:=1
  3659. else
  3660. ref:=-1;
  3661. if (ref<>-1) and
  3662. { reg1 must be either the base or the index }
  3663. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3664. begin
  3665. { reg1 can be removed from the reference }
  3666. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3667. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3668. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3669. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3670. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3671. else
  3672. Internalerror(2019111201);
  3673. { check if the can insert all data of the lea into the second instruction }
  3674. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3675. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3676. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3677. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3678. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3679. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3680. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3681. {$ifdef x86_64}
  3682. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3683. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3684. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3685. )
  3686. {$endif x86_64}
  3687. then
  3688. begin
  3689. { reg1 might not used by the second instruction after it is remove from the reference }
  3690. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3691. begin
  3692. TransferUsedRegs(TmpUsedRegs);
  3693. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3694. { reg1 is not updated so it might not be used afterwards }
  3695. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3696. begin
  3697. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3698. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3699. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3700. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3701. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3702. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3703. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3704. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3705. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3706. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3707. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3708. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3709. RemoveCurrentP(p, hp1);
  3710. result:=true;
  3711. exit;
  3712. end
  3713. end;
  3714. end;
  3715. { recover }
  3716. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3717. end;
  3718. end;
  3719. end;
  3720. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3721. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3722. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3723. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3724. begin
  3725. { Check common LEA/LEA conditions }
  3726. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3727. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3728. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3729. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3730. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3731. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3732. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3733. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3734. (
  3735. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3736. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3737. ) and (
  3738. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3739. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3740. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3741. ) then
  3742. begin
  3743. { changes
  3744. lea (regX,scale), reg1
  3745. lea offset(reg1,reg1), reg1
  3746. to
  3747. lea offset(regX,scale*2), reg1
  3748. and
  3749. lea (regX,scale1), reg1
  3750. lea offset(reg1,scale2), reg1
  3751. to
  3752. lea offset(regX,scale1*scale2), reg1
  3753. ... so long as the final scale does not exceed 8
  3754. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3755. }
  3756. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3757. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3758. (
  3759. (
  3760. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3761. ) or (
  3762. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3763. (
  3764. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3765. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3766. )
  3767. )
  3768. ) and (
  3769. (
  3770. { lea (reg1,scale2), reg1 variant }
  3771. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3772. (
  3773. (
  3774. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3775. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3776. ) or (
  3777. { lea (regX,regX), reg1 variant }
  3778. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3779. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3780. )
  3781. )
  3782. ) or (
  3783. { lea (reg1,reg1), reg1 variant }
  3784. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3785. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3786. )
  3787. ) then
  3788. begin
  3789. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3790. { Make everything homogeneous to make calculations easier }
  3791. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3792. begin
  3793. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3794. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3795. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3796. else
  3797. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3798. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3799. end;
  3800. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3801. begin
  3802. { Just to prevent miscalculations }
  3803. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3804. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3805. else
  3806. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3807. end
  3808. else
  3809. begin
  3810. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3811. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3812. end;
  3813. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3814. RemoveCurrentP(p);
  3815. result:=true;
  3816. exit;
  3817. end
  3818. { changes
  3819. lea offset1(regX), reg1
  3820. lea offset2(reg1), reg1
  3821. to
  3822. lea offset1+offset2(regX), reg1 }
  3823. else if
  3824. (
  3825. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3826. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3827. ) or (
  3828. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3829. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3830. (
  3831. (
  3832. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3833. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3834. ) or (
  3835. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3836. (
  3837. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3838. (
  3839. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3840. (
  3841. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3842. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3843. )
  3844. )
  3845. )
  3846. )
  3847. )
  3848. ) then
  3849. begin
  3850. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3851. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3852. begin
  3853. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3854. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3855. { if the register is used as index and base, we have to increase for base as well
  3856. and adapt base }
  3857. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3858. begin
  3859. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3860. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3861. end;
  3862. end
  3863. else
  3864. begin
  3865. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3866. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3867. end;
  3868. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3869. begin
  3870. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3871. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3872. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3873. end;
  3874. RemoveCurrentP(p);
  3875. result:=true;
  3876. exit;
  3877. end;
  3878. end;
  3879. { Change:
  3880. leal/q $x(%reg1),%reg2
  3881. ...
  3882. shll/q $y,%reg2
  3883. To:
  3884. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3885. }
  3886. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3887. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3888. (taicpu(hp1).oper[0]^.val <= 3) then
  3889. begin
  3890. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3891. TransferUsedRegs(TmpUsedRegs);
  3892. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3893. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3894. if
  3895. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3896. (this works even if scalefactor is zero) }
  3897. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3898. { Ensure offset doesn't go out of bounds }
  3899. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3900. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3901. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3902. (
  3903. (
  3904. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3905. (
  3906. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3907. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3908. (
  3909. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3910. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3911. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3912. )
  3913. )
  3914. ) or (
  3915. (
  3916. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3917. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3918. ) and
  3919. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3920. )
  3921. ) then
  3922. begin
  3923. repeat
  3924. with taicpu(p).oper[0]^.ref^ do
  3925. begin
  3926. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3927. if index = base then
  3928. begin
  3929. if Multiple > 4 then
  3930. { Optimisation will no longer work because resultant
  3931. scale factor will exceed 8 }
  3932. Break;
  3933. base := NR_NO;
  3934. scalefactor := 2;
  3935. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3936. end
  3937. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3938. begin
  3939. { Scale factor only works on the index register }
  3940. index := base;
  3941. base := NR_NO;
  3942. end;
  3943. { For safety }
  3944. if scalefactor <= 1 then
  3945. begin
  3946. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3947. scalefactor := Multiple;
  3948. end
  3949. else
  3950. begin
  3951. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3952. scalefactor := scalefactor * Multiple;
  3953. end;
  3954. offset := offset * Multiple;
  3955. end;
  3956. RemoveInstruction(hp1);
  3957. Result := True;
  3958. Exit;
  3959. { This repeat..until loop exists for the benefit of Break }
  3960. until True;
  3961. end;
  3962. end;
  3963. end;
  3964. end;
  3965. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3966. var
  3967. hp1 : tai;
  3968. begin
  3969. DoSubAddOpt := False;
  3970. if GetLastInstruction(p, hp1) and
  3971. (hp1.typ = ait_instruction) and
  3972. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3973. case taicpu(hp1).opcode Of
  3974. A_DEC:
  3975. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3976. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3977. begin
  3978. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3979. RemoveInstruction(hp1);
  3980. end;
  3981. A_SUB:
  3982. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3983. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3984. begin
  3985. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3986. RemoveInstruction(hp1);
  3987. end;
  3988. A_ADD:
  3989. begin
  3990. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3991. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3992. begin
  3993. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3994. RemoveInstruction(hp1);
  3995. if (taicpu(p).oper[0]^.val = 0) then
  3996. begin
  3997. hp1 := tai(p.next);
  3998. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3999. if not GetLastInstruction(hp1, p) then
  4000. p := hp1;
  4001. DoSubAddOpt := True;
  4002. end
  4003. end;
  4004. end;
  4005. else
  4006. ;
  4007. end;
  4008. end;
  4009. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4010. {$ifdef i386}
  4011. var
  4012. hp1 : tai;
  4013. {$endif i386}
  4014. begin
  4015. Result:=false;
  4016. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4017. { * change "sub/add const1, reg" or "dec reg" followed by
  4018. "sub const2, reg" to one "sub ..., reg" }
  4019. if MatchOpType(taicpu(p),top_const,top_reg) then
  4020. begin
  4021. {$ifdef i386}
  4022. if (taicpu(p).oper[0]^.val = 2) and
  4023. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4024. { Don't do the sub/push optimization if the sub }
  4025. { comes from setting up the stack frame (JM) }
  4026. (not(GetLastInstruction(p,hp1)) or
  4027. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4028. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4029. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4030. begin
  4031. hp1 := tai(p.next);
  4032. while Assigned(hp1) and
  4033. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4034. not RegReadByInstruction(NR_ESP,hp1) and
  4035. not RegModifiedByInstruction(NR_ESP,hp1) do
  4036. hp1 := tai(hp1.next);
  4037. if Assigned(hp1) and
  4038. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4039. begin
  4040. taicpu(hp1).changeopsize(S_L);
  4041. if taicpu(hp1).oper[0]^.typ=top_reg then
  4042. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4043. hp1 := tai(p.next);
  4044. RemoveCurrentp(p, hp1);
  4045. Result:=true;
  4046. exit;
  4047. end;
  4048. end;
  4049. {$endif i386}
  4050. if DoSubAddOpt(p) then
  4051. Result:=true;
  4052. end;
  4053. end;
  4054. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4055. var
  4056. TmpBool1,TmpBool2 : Boolean;
  4057. tmpref : treference;
  4058. hp1,hp2: tai;
  4059. mask: tcgint;
  4060. begin
  4061. Result:=false;
  4062. { All these optimisations work on "shl/sal const,%reg" }
  4063. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4064. Exit;
  4065. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4066. (taicpu(p).oper[0]^.val <= 3) then
  4067. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4068. begin
  4069. { should we check the next instruction? }
  4070. TmpBool1 := True;
  4071. { have we found an add/sub which could be
  4072. integrated in the lea? }
  4073. TmpBool2 := False;
  4074. reference_reset(tmpref,2,[]);
  4075. TmpRef.index := taicpu(p).oper[1]^.reg;
  4076. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4077. while TmpBool1 and
  4078. GetNextInstruction(p, hp1) and
  4079. (tai(hp1).typ = ait_instruction) and
  4080. ((((taicpu(hp1).opcode = A_ADD) or
  4081. (taicpu(hp1).opcode = A_SUB)) and
  4082. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4083. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4084. (((taicpu(hp1).opcode = A_INC) or
  4085. (taicpu(hp1).opcode = A_DEC)) and
  4086. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4087. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4088. ((taicpu(hp1).opcode = A_LEA) and
  4089. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4090. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4091. (not GetNextInstruction(hp1,hp2) or
  4092. not instrReadsFlags(hp2)) Do
  4093. begin
  4094. TmpBool1 := False;
  4095. if taicpu(hp1).opcode=A_LEA then
  4096. begin
  4097. if (TmpRef.base = NR_NO) and
  4098. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4099. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4100. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4101. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4102. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4103. begin
  4104. TmpBool1 := True;
  4105. TmpBool2 := True;
  4106. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4107. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4108. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4109. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4110. RemoveInstruction(hp1);
  4111. end
  4112. end
  4113. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4114. begin
  4115. TmpBool1 := True;
  4116. TmpBool2 := True;
  4117. case taicpu(hp1).opcode of
  4118. A_ADD:
  4119. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4120. A_SUB:
  4121. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4122. else
  4123. internalerror(2019050536);
  4124. end;
  4125. RemoveInstruction(hp1);
  4126. end
  4127. else
  4128. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4129. (((taicpu(hp1).opcode = A_ADD) and
  4130. (TmpRef.base = NR_NO)) or
  4131. (taicpu(hp1).opcode = A_INC) or
  4132. (taicpu(hp1).opcode = A_DEC)) then
  4133. begin
  4134. TmpBool1 := True;
  4135. TmpBool2 := True;
  4136. case taicpu(hp1).opcode of
  4137. A_ADD:
  4138. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4139. A_INC:
  4140. inc(TmpRef.offset);
  4141. A_DEC:
  4142. dec(TmpRef.offset);
  4143. else
  4144. internalerror(2019050535);
  4145. end;
  4146. RemoveInstruction(hp1);
  4147. end;
  4148. end;
  4149. if TmpBool2
  4150. {$ifndef x86_64}
  4151. or
  4152. ((current_settings.optimizecputype < cpu_Pentium2) and
  4153. (taicpu(p).oper[0]^.val <= 3) and
  4154. not(cs_opt_size in current_settings.optimizerswitches))
  4155. {$endif x86_64}
  4156. then
  4157. begin
  4158. if not(TmpBool2) and
  4159. (taicpu(p).oper[0]^.val=1) then
  4160. begin
  4161. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4162. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4163. end
  4164. else
  4165. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4166. taicpu(p).oper[1]^.reg);
  4167. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4168. InsertLLItem(p.previous, p.next, hp1);
  4169. p.free;
  4170. p := hp1;
  4171. end;
  4172. end
  4173. {$ifndef x86_64}
  4174. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4175. begin
  4176. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4177. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4178. (unlike shl, which is only Tairable in the U pipe) }
  4179. if taicpu(p).oper[0]^.val=1 then
  4180. begin
  4181. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4182. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4183. InsertLLItem(p.previous, p.next, hp1);
  4184. p.free;
  4185. p := hp1;
  4186. end
  4187. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4188. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4189. else if (taicpu(p).opsize = S_L) and
  4190. (taicpu(p).oper[0]^.val<= 3) then
  4191. begin
  4192. reference_reset(tmpref,2,[]);
  4193. TmpRef.index := taicpu(p).oper[1]^.reg;
  4194. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4195. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4196. InsertLLItem(p.previous, p.next, hp1);
  4197. p.free;
  4198. p := hp1;
  4199. end;
  4200. end
  4201. {$endif x86_64}
  4202. else if
  4203. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4204. (
  4205. (
  4206. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4207. SetAndTest(hp1, hp2)
  4208. {$ifdef x86_64}
  4209. ) or
  4210. (
  4211. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4212. GetNextInstruction(hp1, hp2) and
  4213. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4214. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4215. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4216. {$endif x86_64}
  4217. )
  4218. ) and
  4219. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4220. begin
  4221. { Change:
  4222. shl x, %reg1
  4223. mov -(1<<x), %reg2
  4224. and %reg2, %reg1
  4225. Or:
  4226. shl x, %reg1
  4227. and -(1<<x), %reg1
  4228. To just:
  4229. shl x, %reg1
  4230. Since the and operation only zeroes bits that are already zero from the shl operation
  4231. }
  4232. case taicpu(p).oper[0]^.val of
  4233. 8:
  4234. mask:=$FFFFFFFFFFFFFF00;
  4235. 16:
  4236. mask:=$FFFFFFFFFFFF0000;
  4237. 32:
  4238. mask:=$FFFFFFFF00000000;
  4239. 63:
  4240. { Constant pre-calculated to prevent overflow errors with Int64 }
  4241. mask:=$8000000000000000;
  4242. else
  4243. begin
  4244. if taicpu(p).oper[0]^.val >= 64 then
  4245. { Shouldn't happen realistically, since the register
  4246. is guaranteed to be set to zero at this point }
  4247. mask := 0
  4248. else
  4249. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4250. end;
  4251. end;
  4252. if taicpu(hp1).oper[0]^.val = mask then
  4253. begin
  4254. { Everything checks out, perform the optimisation, as long as
  4255. the FLAGS register isn't being used}
  4256. TransferUsedRegs(TmpUsedRegs);
  4257. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4258. {$ifdef x86_64}
  4259. if (hp1 <> hp2) then
  4260. begin
  4261. { "shl/mov/and" version }
  4262. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4263. { Don't do the optimisation if the FLAGS register is in use }
  4264. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4265. begin
  4266. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4267. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4268. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4269. begin
  4270. RemoveInstruction(hp1);
  4271. Result := True;
  4272. end;
  4273. { Only set Result to True if the 'mov' instruction was removed }
  4274. RemoveInstruction(hp2);
  4275. end;
  4276. end
  4277. else
  4278. {$endif x86_64}
  4279. begin
  4280. { "shl/and" version }
  4281. { Don't do the optimisation if the FLAGS register is in use }
  4282. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4283. begin
  4284. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4285. RemoveInstruction(hp1);
  4286. Result := True;
  4287. end;
  4288. end;
  4289. Exit;
  4290. end
  4291. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4292. begin
  4293. { Even if the mask doesn't allow for its removal, we might be
  4294. able to optimise the mask for the "shl/and" version, which
  4295. may permit other peephole optimisations }
  4296. {$ifdef DEBUG_AOPTCPU}
  4297. mask := taicpu(hp1).oper[0]^.val and mask;
  4298. if taicpu(hp1).oper[0]^.val <> mask then
  4299. begin
  4300. DebugMsg(
  4301. SPeepholeOptimization +
  4302. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4303. ' to $' + debug_tostr(mask) +
  4304. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4305. taicpu(hp1).oper[0]^.val := mask;
  4306. end;
  4307. {$else DEBUG_AOPTCPU}
  4308. { If debugging is off, just set the operand even if it's the same }
  4309. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4310. {$endif DEBUG_AOPTCPU}
  4311. end;
  4312. end;
  4313. {
  4314. change
  4315. shl/sal const,reg
  4316. <op> ...(...,reg,1),...
  4317. into
  4318. <op> ...(...,reg,1 shl const),...
  4319. if const in 1..3
  4320. }
  4321. if MatchOpType(taicpu(p), top_const, top_reg) and
  4322. (taicpu(p).oper[0]^.val in [1..3]) and
  4323. GetNextInstruction(p, hp1) and
  4324. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4325. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4326. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4327. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4328. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4329. begin
  4330. TransferUsedRegs(TmpUsedRegs);
  4331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4332. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4333. begin
  4334. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4335. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4336. RemoveCurrentP(p);
  4337. Result:=true;
  4338. end;
  4339. end;
  4340. end;
  4341. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4342. var
  4343. CurrentRef: TReference;
  4344. FullReg: TRegister;
  4345. hp1, hp2: tai;
  4346. begin
  4347. Result := False;
  4348. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4349. Exit;
  4350. { We assume you've checked if the operand is actually a reference by
  4351. this point. If it isn't, you'll most likely get an access violation }
  4352. CurrentRef := first_mov.oper[1]^.ref^;
  4353. { Memory must be aligned }
  4354. if (CurrentRef.offset mod 4) <> 0 then
  4355. Exit;
  4356. Inc(CurrentRef.offset);
  4357. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4358. if MatchOperand(second_mov.oper[0]^, 0) and
  4359. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4360. GetNextInstruction(second_mov, hp1) and
  4361. (hp1.typ = ait_instruction) and
  4362. (taicpu(hp1).opcode = A_MOV) and
  4363. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4364. (taicpu(hp1).oper[0]^.val = 0) then
  4365. begin
  4366. Inc(CurrentRef.offset);
  4367. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4368. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4369. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4370. begin
  4371. case taicpu(hp1).opsize of
  4372. S_B:
  4373. if GetNextInstruction(hp1, hp2) and
  4374. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4375. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4376. (taicpu(hp2).oper[0]^.val = 0) then
  4377. begin
  4378. Inc(CurrentRef.offset);
  4379. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4380. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4381. (taicpu(hp2).opsize = S_B) then
  4382. begin
  4383. RemoveInstruction(hp1);
  4384. RemoveInstruction(hp2);
  4385. first_mov.opsize := S_L;
  4386. if first_mov.oper[0]^.typ = top_reg then
  4387. begin
  4388. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4389. { Reuse second_mov as a MOVZX instruction }
  4390. second_mov.opcode := A_MOVZX;
  4391. second_mov.opsize := S_BL;
  4392. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4393. second_mov.loadreg(1, FullReg);
  4394. first_mov.oper[0]^.reg := FullReg;
  4395. asml.Remove(second_mov);
  4396. asml.InsertBefore(second_mov, first_mov);
  4397. end
  4398. else
  4399. { It's a value }
  4400. begin
  4401. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4402. RemoveInstruction(second_mov);
  4403. end;
  4404. Result := True;
  4405. Exit;
  4406. end;
  4407. end;
  4408. S_W:
  4409. begin
  4410. RemoveInstruction(hp1);
  4411. first_mov.opsize := S_L;
  4412. if first_mov.oper[0]^.typ = top_reg then
  4413. begin
  4414. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4415. { Reuse second_mov as a MOVZX instruction }
  4416. second_mov.opcode := A_MOVZX;
  4417. second_mov.opsize := S_BL;
  4418. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4419. second_mov.loadreg(1, FullReg);
  4420. first_mov.oper[0]^.reg := FullReg;
  4421. asml.Remove(second_mov);
  4422. asml.InsertBefore(second_mov, first_mov);
  4423. end
  4424. else
  4425. { It's a value }
  4426. begin
  4427. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4428. RemoveInstruction(second_mov);
  4429. end;
  4430. Result := True;
  4431. Exit;
  4432. end;
  4433. else
  4434. ;
  4435. end;
  4436. end;
  4437. end;
  4438. end;
  4439. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4440. { returns true if a "continue" should be done after this optimization }
  4441. var
  4442. hp1, hp2: tai;
  4443. begin
  4444. Result := false;
  4445. if MatchOpType(taicpu(p),top_ref) and
  4446. GetNextInstruction(p, hp1) and
  4447. (hp1.typ = ait_instruction) and
  4448. (((taicpu(hp1).opcode = A_FLD) and
  4449. (taicpu(p).opcode = A_FSTP)) or
  4450. ((taicpu(p).opcode = A_FISTP) and
  4451. (taicpu(hp1).opcode = A_FILD))) and
  4452. MatchOpType(taicpu(hp1),top_ref) and
  4453. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4454. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4455. begin
  4456. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4457. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4458. GetNextInstruction(hp1, hp2) and
  4459. (hp2.typ = ait_instruction) and
  4460. IsExitCode(hp2) and
  4461. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4462. not(assigned(current_procinfo.procdef.funcretsym) and
  4463. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4464. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4465. begin
  4466. RemoveInstruction(hp1);
  4467. RemoveCurrentP(p, hp2);
  4468. RemoveLastDeallocForFuncRes(p);
  4469. Result := true;
  4470. end
  4471. else
  4472. { we can do this only in fast math mode as fstp is rounding ...
  4473. ... still disabled as it breaks the compiler and/or rtl }
  4474. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4475. { ... or if another fstp equal to the first one follows }
  4476. (GetNextInstruction(hp1,hp2) and
  4477. (hp2.typ = ait_instruction) and
  4478. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4479. (taicpu(p).opsize=taicpu(hp2).opsize))
  4480. ) and
  4481. { fst can't store an extended/comp value }
  4482. (taicpu(p).opsize <> S_FX) and
  4483. (taicpu(p).opsize <> S_IQ) then
  4484. begin
  4485. if (taicpu(p).opcode = A_FSTP) then
  4486. taicpu(p).opcode := A_FST
  4487. else
  4488. taicpu(p).opcode := A_FIST;
  4489. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4490. RemoveInstruction(hp1);
  4491. end;
  4492. end;
  4493. end;
  4494. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4495. var
  4496. hp1, hp2: tai;
  4497. begin
  4498. result:=false;
  4499. if MatchOpType(taicpu(p),top_reg) and
  4500. GetNextInstruction(p, hp1) and
  4501. (hp1.typ = Ait_Instruction) and
  4502. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4503. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4504. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4505. { change to
  4506. fld reg fxxx reg,st
  4507. fxxxp st, st1 (hp1)
  4508. Remark: non commutative operations must be reversed!
  4509. }
  4510. begin
  4511. case taicpu(hp1).opcode Of
  4512. A_FMULP,A_FADDP,
  4513. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4514. begin
  4515. case taicpu(hp1).opcode Of
  4516. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4517. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4518. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4519. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4520. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4521. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4522. else
  4523. internalerror(2019050534);
  4524. end;
  4525. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4526. taicpu(hp1).oper[1]^.reg := NR_ST;
  4527. RemoveCurrentP(p, hp1);
  4528. Result:=true;
  4529. exit;
  4530. end;
  4531. else
  4532. ;
  4533. end;
  4534. end
  4535. else
  4536. if MatchOpType(taicpu(p),top_ref) and
  4537. GetNextInstruction(p, hp2) and
  4538. (hp2.typ = Ait_Instruction) and
  4539. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4540. (taicpu(p).opsize in [S_FS, S_FL]) and
  4541. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4542. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4543. if GetLastInstruction(p, hp1) and
  4544. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4545. MatchOpType(taicpu(hp1),top_ref) and
  4546. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4547. if ((taicpu(hp2).opcode = A_FMULP) or
  4548. (taicpu(hp2).opcode = A_FADDP)) then
  4549. { change to
  4550. fld/fst mem1 (hp1) fld/fst mem1
  4551. fld mem1 (p) fadd/
  4552. faddp/ fmul st, st
  4553. fmulp st, st1 (hp2) }
  4554. begin
  4555. RemoveCurrentP(p, hp1);
  4556. if (taicpu(hp2).opcode = A_FADDP) then
  4557. taicpu(hp2).opcode := A_FADD
  4558. else
  4559. taicpu(hp2).opcode := A_FMUL;
  4560. taicpu(hp2).oper[1]^.reg := NR_ST;
  4561. end
  4562. else
  4563. { change to
  4564. fld/fst mem1 (hp1) fld/fst mem1
  4565. fld mem1 (p) fld st}
  4566. begin
  4567. taicpu(p).changeopsize(S_FL);
  4568. taicpu(p).loadreg(0,NR_ST);
  4569. end
  4570. else
  4571. begin
  4572. case taicpu(hp2).opcode Of
  4573. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4574. { change to
  4575. fld/fst mem1 (hp1) fld/fst mem1
  4576. fld mem2 (p) fxxx mem2
  4577. fxxxp st, st1 (hp2) }
  4578. begin
  4579. case taicpu(hp2).opcode Of
  4580. A_FADDP: taicpu(p).opcode := A_FADD;
  4581. A_FMULP: taicpu(p).opcode := A_FMUL;
  4582. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4583. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4584. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4585. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4586. else
  4587. internalerror(2019050533);
  4588. end;
  4589. RemoveInstruction(hp2);
  4590. end
  4591. else
  4592. ;
  4593. end
  4594. end
  4595. end;
  4596. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4597. begin
  4598. Result := condition_in(cond1, cond2) or
  4599. { Not strictly subsets due to the actual flags checked, but because we're
  4600. comparing integers, E is a subset of AE and GE and their aliases }
  4601. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4602. end;
  4603. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4604. var
  4605. v: TCGInt;
  4606. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4607. FirstMatch: Boolean;
  4608. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4609. begin
  4610. Result:=false;
  4611. { All these optimisations need a next instruction }
  4612. if not GetNextInstruction(p, hp1) then
  4613. Exit;
  4614. { Search for:
  4615. cmp ###,###
  4616. j(c1) @lbl1
  4617. ...
  4618. @lbl:
  4619. cmp ###.### (same comparison as above)
  4620. j(c2) @lbl2
  4621. If c1 is a subset of c2, change to:
  4622. cmp ###,###
  4623. j(c2) @lbl2
  4624. (@lbl1 may become a dead label as a result)
  4625. }
  4626. { Also handle cases where there are multiple jumps in a row }
  4627. p_jump := hp1;
  4628. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4629. begin
  4630. if IsJumpToLabel(taicpu(p_jump)) then
  4631. begin
  4632. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4633. p_label := nil;
  4634. if Assigned(JumpLabel) then
  4635. p_label := getlabelwithsym(JumpLabel);
  4636. if Assigned(p_label) and
  4637. GetNextInstruction(p_label, p_dist) and
  4638. MatchInstruction(p_dist, A_CMP, []) and
  4639. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4640. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4641. GetNextInstruction(p_dist, hp1_dist) and
  4642. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4643. begin
  4644. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4645. if JumpLabel = JumpLabel_dist then
  4646. { This is an infinite loop }
  4647. Exit;
  4648. { Best optimisation when the first condition is a subset (or equal) of the second }
  4649. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4650. begin
  4651. { Any registers used here will already be allocated }
  4652. if Assigned(JumpLabel_dist) then
  4653. JumpLabel_dist.IncRefs;
  4654. if Assigned(JumpLabel) then
  4655. JumpLabel.DecRefs;
  4656. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4657. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4658. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4659. Result := True;
  4660. { Don't exit yet. Since p and p_jump haven't actually been
  4661. removed, we can check for more on this iteration }
  4662. end
  4663. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4664. GetNextInstruction(hp1_dist, hp1_label) and
  4665. SkipAligns(hp1_label, hp1_label) and
  4666. (hp1_label.typ = ait_label) then
  4667. begin
  4668. JumpLabel_far := tai_label(hp1_label).labsym;
  4669. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4670. { This is an infinite loop }
  4671. Exit;
  4672. if Assigned(JumpLabel_far) then
  4673. begin
  4674. { In this situation, if the first jump branches, the second one will never,
  4675. branch so change the destination label to after the second jump }
  4676. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4677. if Assigned(JumpLabel) then
  4678. JumpLabel.DecRefs;
  4679. JumpLabel_far.IncRefs;
  4680. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4681. Result := True;
  4682. { Don't exit yet. Since p and p_jump haven't actually been
  4683. removed, we can check for more on this iteration }
  4684. Continue;
  4685. end;
  4686. end;
  4687. end;
  4688. end;
  4689. { Search for:
  4690. cmp ###,###
  4691. j(c1) @lbl1
  4692. cmp ###,### (same as first)
  4693. Remove second cmp
  4694. }
  4695. if GetNextInstruction(p_jump, hp2) and
  4696. (
  4697. (
  4698. MatchInstruction(hp2, A_CMP, []) and
  4699. (
  4700. (
  4701. MatchOpType(taicpu(p), top_const, top_reg) and
  4702. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4703. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4704. ) or (
  4705. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4706. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4707. )
  4708. )
  4709. ) or (
  4710. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4711. MatchOperand(taicpu(p).oper[0]^, 0) and
  4712. (taicpu(p).oper[1]^.typ = top_reg) and
  4713. MatchInstruction(hp2, A_TEST, []) and
  4714. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4715. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4716. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4717. )
  4718. ) then
  4719. begin
  4720. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4721. RemoveInstruction(hp2);
  4722. Result := True;
  4723. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  4724. end;
  4725. GetNextInstruction(p_jump, p_jump);
  4726. end;
  4727. if taicpu(p).oper[0]^.typ = top_const then
  4728. begin
  4729. if (taicpu(p).oper[0]^.val = 0) and
  4730. (taicpu(p).oper[1]^.typ = top_reg) and
  4731. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4732. begin
  4733. hp2 := p;
  4734. FirstMatch := True;
  4735. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4736. anything meaningful once it's converted to "test %reg,%reg";
  4737. additionally, some jumps will always (or never) branch, so
  4738. evaluate every jump immediately following the
  4739. comparison, optimising the conditions if possible.
  4740. Similarly with SETcc... those that are always set to 0 or 1
  4741. are changed to MOV instructions }
  4742. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4743. (
  4744. GetNextInstruction(hp2, hp1) and
  4745. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4746. ) do
  4747. begin
  4748. FirstMatch := False;
  4749. case taicpu(hp1).condition of
  4750. C_B, C_C, C_NAE, C_O:
  4751. { For B/NAE:
  4752. Will never branch since an unsigned integer can never be below zero
  4753. For C/O:
  4754. Result cannot overflow because 0 is being subtracted
  4755. }
  4756. begin
  4757. if taicpu(hp1).opcode = A_Jcc then
  4758. begin
  4759. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4760. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4761. RemoveInstruction(hp1);
  4762. { Since hp1 was deleted, hp2 must not be updated }
  4763. Continue;
  4764. end
  4765. else
  4766. begin
  4767. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4768. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4769. taicpu(hp1).opcode := A_MOV;
  4770. taicpu(hp1).ops := 2;
  4771. taicpu(hp1).condition := C_None;
  4772. taicpu(hp1).opsize := S_B;
  4773. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4774. taicpu(hp1).loadconst(0, 0);
  4775. end;
  4776. end;
  4777. C_BE, C_NA:
  4778. begin
  4779. { Will only branch if equal to zero }
  4780. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4781. taicpu(hp1).condition := C_E;
  4782. end;
  4783. C_A, C_NBE:
  4784. begin
  4785. { Will only branch if not equal to zero }
  4786. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4787. taicpu(hp1).condition := C_NE;
  4788. end;
  4789. C_AE, C_NB, C_NC, C_NO:
  4790. begin
  4791. { Will always branch }
  4792. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4793. if taicpu(hp1).opcode = A_Jcc then
  4794. begin
  4795. MakeUnconditional(taicpu(hp1));
  4796. { Any jumps/set that follow will now be dead code }
  4797. RemoveDeadCodeAfterJump(taicpu(hp1));
  4798. Break;
  4799. end
  4800. else
  4801. begin
  4802. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4803. taicpu(hp1).opcode := A_MOV;
  4804. taicpu(hp1).ops := 2;
  4805. taicpu(hp1).condition := C_None;
  4806. taicpu(hp1).opsize := S_B;
  4807. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4808. taicpu(hp1).loadconst(0, 1);
  4809. end;
  4810. end;
  4811. C_None:
  4812. InternalError(2020012201);
  4813. C_P, C_PE, C_NP, C_PO:
  4814. { We can't handle parity checks and they should never be generated
  4815. after a general-purpose CMP (it's used in some floating-point
  4816. comparisons that don't use CMP) }
  4817. InternalError(2020012202);
  4818. else
  4819. { Zero/Equality, Sign, their complements and all of the
  4820. signed comparisons do not need to be converted };
  4821. end;
  4822. hp2 := hp1;
  4823. end;
  4824. { Convert the instruction to a TEST }
  4825. taicpu(p).opcode := A_TEST;
  4826. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4827. Result := True;
  4828. Exit;
  4829. end
  4830. else if (taicpu(p).oper[0]^.val = 1) and
  4831. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4832. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4833. begin
  4834. { Convert; To:
  4835. cmp $1,r/m cmp $0,r/m
  4836. jl @lbl jle @lbl
  4837. }
  4838. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4839. taicpu(p).oper[0]^.val := 0;
  4840. taicpu(hp1).condition := C_LE;
  4841. { If the instruction is now "cmp $0,%reg", convert it to a
  4842. TEST (and effectively do the work of the "cmp $0,%reg" in
  4843. the block above)
  4844. If it's a reference, we can get away with not setting
  4845. Result to True because he haven't evaluated the jump
  4846. in this pass yet.
  4847. }
  4848. if (taicpu(p).oper[1]^.typ = top_reg) then
  4849. begin
  4850. taicpu(p).opcode := A_TEST;
  4851. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4852. Result := True;
  4853. end;
  4854. Exit;
  4855. end
  4856. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4857. begin
  4858. { cmp register,$8000 neg register
  4859. je target --> jo target
  4860. .... only if register is deallocated before jump.}
  4861. case Taicpu(p).opsize of
  4862. S_B: v:=$80;
  4863. S_W: v:=$8000;
  4864. S_L: v:=qword($80000000);
  4865. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4866. S_Q:
  4867. Exit;
  4868. else
  4869. internalerror(2013112905);
  4870. end;
  4871. if (taicpu(p).oper[0]^.val=v) and
  4872. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4873. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4874. begin
  4875. TransferUsedRegs(TmpUsedRegs);
  4876. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4877. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4878. begin
  4879. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4880. Taicpu(p).opcode:=A_NEG;
  4881. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4882. Taicpu(p).clearop(1);
  4883. Taicpu(p).ops:=1;
  4884. if Taicpu(hp1).condition=C_E then
  4885. Taicpu(hp1).condition:=C_O
  4886. else
  4887. Taicpu(hp1).condition:=C_NO;
  4888. Result:=true;
  4889. exit;
  4890. end;
  4891. end;
  4892. end;
  4893. end;
  4894. if (taicpu(p).oper[1]^.typ = top_reg) and
  4895. MatchInstruction(hp1,A_MOV,[]) and
  4896. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4897. (
  4898. (taicpu(p).oper[0]^.typ <> top_reg) or
  4899. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4900. ) then
  4901. begin
  4902. { If we have something like:
  4903. cmp ###,%reg1
  4904. mov 0,%reg2
  4905. And no registers are shared, move the MOV command to before the
  4906. comparison as this means it can be optimised without worrying
  4907. about the FLAGS register. (This combination is generated by
  4908. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4909. }
  4910. SwapMovCmp(p, hp1);
  4911. Result := True;
  4912. Exit;
  4913. end;
  4914. end;
  4915. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4916. var
  4917. hp1: tai;
  4918. begin
  4919. {
  4920. remove the second (v)pxor from
  4921. pxor reg,reg
  4922. ...
  4923. pxor reg,reg
  4924. }
  4925. Result:=false;
  4926. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4927. MatchOpType(taicpu(p),top_reg,top_reg) and
  4928. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4929. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4930. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4931. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4932. begin
  4933. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4934. RemoveInstruction(hp1);
  4935. Result:=true;
  4936. Exit;
  4937. end
  4938. {
  4939. replace
  4940. pxor reg1,reg1
  4941. movapd/s reg1,reg2
  4942. dealloc reg1
  4943. by
  4944. pxor reg2,reg2
  4945. }
  4946. else if GetNextInstruction(p,hp1) and
  4947. { we mix single and double opperations here because we assume that the compiler
  4948. generates vmovapd only after double operations and vmovaps only after single operations }
  4949. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4950. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4951. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4952. (taicpu(p).oper[0]^.typ=top_reg) then
  4953. begin
  4954. TransferUsedRegs(TmpUsedRegs);
  4955. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4956. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4957. begin
  4958. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4959. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4960. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4961. RemoveInstruction(hp1);
  4962. result:=true;
  4963. end;
  4964. end;
  4965. end;
  4966. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4967. var
  4968. hp1: tai;
  4969. begin
  4970. {
  4971. remove the second (v)pxor from
  4972. (v)pxor reg,reg
  4973. ...
  4974. (v)pxor reg,reg
  4975. }
  4976. Result:=false;
  4977. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4978. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4979. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4980. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4981. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4982. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4983. begin
  4984. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4985. RemoveInstruction(hp1);
  4986. Result:=true;
  4987. Exit;
  4988. end
  4989. else
  4990. Result:=OptPass1VOP(p);
  4991. end;
  4992. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4993. var
  4994. hp1 : tai;
  4995. begin
  4996. result:=false;
  4997. { replace
  4998. IMul const,%mreg1,%mreg2
  4999. Mov %reg2,%mreg3
  5000. dealloc %mreg3
  5001. by
  5002. Imul const,%mreg1,%mreg23
  5003. }
  5004. if (taicpu(p).ops=3) and
  5005. GetNextInstruction(p,hp1) and
  5006. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5007. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5008. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5009. begin
  5010. TransferUsedRegs(TmpUsedRegs);
  5011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5012. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5013. begin
  5014. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5015. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5016. RemoveInstruction(hp1);
  5017. result:=true;
  5018. end;
  5019. end;
  5020. end;
  5021. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5022. var
  5023. hp1 : tai;
  5024. begin
  5025. result:=false;
  5026. { replace
  5027. IMul %reg0,%reg1,%reg2
  5028. Mov %reg2,%reg3
  5029. dealloc %reg2
  5030. by
  5031. Imul %reg0,%reg1,%reg3
  5032. }
  5033. if GetNextInstruction(p,hp1) and
  5034. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5035. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5036. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5037. begin
  5038. TransferUsedRegs(TmpUsedRegs);
  5039. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5040. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5041. begin
  5042. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5043. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5044. RemoveInstruction(hp1);
  5045. result:=true;
  5046. end;
  5047. end;
  5048. end;
  5049. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5050. var
  5051. hp1, hp2, hp3, hp4, hp5: tai;
  5052. ThisReg: TRegister;
  5053. begin
  5054. Result := False;
  5055. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5056. Exit;
  5057. {
  5058. convert
  5059. j<c> .L1
  5060. mov 1,reg
  5061. jmp .L2
  5062. .L1
  5063. mov 0,reg
  5064. .L2
  5065. into
  5066. mov 0,reg
  5067. set<not(c)> reg
  5068. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5069. would destroy the flag contents
  5070. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5071. executed at the same time as a previous comparison.
  5072. set<not(c)> reg
  5073. movzx reg, reg
  5074. }
  5075. if MatchInstruction(hp1,A_MOV,[]) and
  5076. (taicpu(hp1).oper[0]^.typ = top_const) and
  5077. (
  5078. (
  5079. (taicpu(hp1).oper[1]^.typ = top_reg)
  5080. {$ifdef i386}
  5081. { Under i386, ESI, EDI, EBP and ESP
  5082. don't have an 8-bit representation }
  5083. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5084. {$endif i386}
  5085. ) or (
  5086. {$ifdef i386}
  5087. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5088. {$endif i386}
  5089. (taicpu(hp1).opsize = S_B)
  5090. )
  5091. ) and
  5092. GetNextInstruction(hp1,hp2) and
  5093. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5094. GetNextInstruction(hp2,hp3) and
  5095. SkipAligns(hp3, hp3) and
  5096. (hp3.typ=ait_label) and
  5097. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5098. GetNextInstruction(hp3,hp4) and
  5099. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5100. (taicpu(hp4).oper[0]^.typ = top_const) and
  5101. (
  5102. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5103. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5104. ) and
  5105. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5106. GetNextInstruction(hp4,hp5) and
  5107. SkipAligns(hp5, hp5) and
  5108. (hp5.typ=ait_label) and
  5109. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5110. begin
  5111. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5112. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5113. tai_label(hp3).labsym.DecRefs;
  5114. { If this isn't the only reference to the middle label, we can
  5115. still make a saving - only that the first jump and everything
  5116. that follows will remain. }
  5117. if (tai_label(hp3).labsym.getrefs = 0) then
  5118. begin
  5119. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5120. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5121. else
  5122. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5123. { remove jump, first label and second MOV (also catching any aligns) }
  5124. repeat
  5125. if not GetNextInstruction(hp2, hp3) then
  5126. InternalError(2021040810);
  5127. RemoveInstruction(hp2);
  5128. hp2 := hp3;
  5129. until hp2 = hp5;
  5130. { Don't decrement reference count before the removal loop
  5131. above, otherwise GetNextInstruction won't stop on the
  5132. the label }
  5133. tai_label(hp5).labsym.DecRefs;
  5134. end
  5135. else
  5136. begin
  5137. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5138. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5139. else
  5140. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5141. end;
  5142. taicpu(p).opcode:=A_SETcc;
  5143. taicpu(p).opsize:=S_B;
  5144. taicpu(p).is_jmp:=False;
  5145. if taicpu(hp1).opsize=S_B then
  5146. begin
  5147. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5148. RemoveInstruction(hp1);
  5149. end
  5150. else
  5151. begin
  5152. { Will be a register because the size can't be S_B otherwise }
  5153. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5154. taicpu(p).loadreg(0, ThisReg);
  5155. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5156. begin
  5157. case taicpu(hp1).opsize of
  5158. S_W:
  5159. taicpu(hp1).opsize := S_BW;
  5160. S_L:
  5161. taicpu(hp1).opsize := S_BL;
  5162. {$ifdef x86_64}
  5163. S_Q:
  5164. begin
  5165. taicpu(hp1).opsize := S_BL;
  5166. { Change the destination register to 32-bit }
  5167. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5168. end;
  5169. {$endif x86_64}
  5170. else
  5171. InternalError(2021040820);
  5172. end;
  5173. taicpu(hp1).opcode := A_MOVZX;
  5174. taicpu(hp1).loadreg(0, ThisReg);
  5175. end
  5176. else
  5177. begin
  5178. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5179. { hp1 is already a MOV instruction with the correct register }
  5180. taicpu(hp1).loadconst(0, 0);
  5181. { Inserting it right before p will guarantee that the flags are also tracked }
  5182. asml.Remove(hp1);
  5183. asml.InsertBefore(hp1, p);
  5184. end;
  5185. end;
  5186. Result:=true;
  5187. exit;
  5188. end
  5189. end;
  5190. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5191. var
  5192. hp2, hp3, first_assignment: tai;
  5193. IncCount, OperIdx: Integer;
  5194. OrigLabel: TAsmLabel;
  5195. begin
  5196. Count := 0;
  5197. Result := False;
  5198. first_assignment := nil;
  5199. if (LoopCount >= 20) then
  5200. begin
  5201. { Guard against infinite loops }
  5202. Exit;
  5203. end;
  5204. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5205. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5206. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5207. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5208. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5209. Exit;
  5210. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5211. {
  5212. change
  5213. jmp .L1
  5214. ...
  5215. .L1:
  5216. mov ##, ## ( multiple movs possible )
  5217. jmp/ret
  5218. into
  5219. mov ##, ##
  5220. jmp/ret
  5221. }
  5222. if not Assigned(hp1) then
  5223. begin
  5224. hp1 := GetLabelWithSym(OrigLabel);
  5225. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5226. Exit;
  5227. end;
  5228. hp2 := hp1;
  5229. while Assigned(hp2) do
  5230. begin
  5231. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5232. SkipLabels(hp2,hp2);
  5233. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5234. Break;
  5235. case taicpu(hp2).opcode of
  5236. A_MOVSS:
  5237. begin
  5238. if taicpu(hp2).ops = 0 then
  5239. { Wrong MOVSS }
  5240. Break;
  5241. Inc(Count);
  5242. if Count >= 5 then
  5243. { Too many to be worthwhile }
  5244. Break;
  5245. GetNextInstruction(hp2, hp2);
  5246. Continue;
  5247. end;
  5248. A_MOV,
  5249. A_MOVD,
  5250. A_MOVQ,
  5251. A_MOVSX,
  5252. {$ifdef x86_64}
  5253. A_MOVSXD,
  5254. {$endif x86_64}
  5255. A_MOVZX,
  5256. A_MOVAPS,
  5257. A_MOVUPS,
  5258. A_MOVSD,
  5259. A_MOVAPD,
  5260. A_MOVUPD,
  5261. A_MOVDQA,
  5262. A_MOVDQU,
  5263. A_VMOVSS,
  5264. A_VMOVAPS,
  5265. A_VMOVUPS,
  5266. A_VMOVSD,
  5267. A_VMOVAPD,
  5268. A_VMOVUPD,
  5269. A_VMOVDQA,
  5270. A_VMOVDQU:
  5271. begin
  5272. Inc(Count);
  5273. if Count >= 5 then
  5274. { Too many to be worthwhile }
  5275. Break;
  5276. GetNextInstruction(hp2, hp2);
  5277. Continue;
  5278. end;
  5279. A_JMP:
  5280. begin
  5281. { Guard against infinite loops }
  5282. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5283. Exit;
  5284. { Analyse this jump first in case it also duplicates assignments }
  5285. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5286. begin
  5287. { Something did change! }
  5288. Result := True;
  5289. Inc(Count, IncCount);
  5290. if Count >= 5 then
  5291. begin
  5292. { Too many to be worthwhile }
  5293. Exit;
  5294. end;
  5295. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5296. Break;
  5297. end;
  5298. Result := True;
  5299. Break;
  5300. end;
  5301. A_RET:
  5302. begin
  5303. Result := True;
  5304. Break;
  5305. end;
  5306. else
  5307. Break;
  5308. end;
  5309. end;
  5310. if Result then
  5311. begin
  5312. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5313. if Count = 0 then
  5314. begin
  5315. Result := False;
  5316. Exit;
  5317. end;
  5318. hp3 := p;
  5319. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5320. while True do
  5321. begin
  5322. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5323. SkipLabels(hp1,hp1);
  5324. if (hp1.typ <> ait_instruction) then
  5325. InternalError(2021040720);
  5326. case taicpu(hp1).opcode of
  5327. A_JMP:
  5328. begin
  5329. { Change the original jump to the new destination }
  5330. OrigLabel.decrefs;
  5331. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5332. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5333. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5334. if not Assigned(first_assignment) then
  5335. InternalError(2021040810)
  5336. else
  5337. p := first_assignment;
  5338. Exit;
  5339. end;
  5340. A_RET:
  5341. begin
  5342. { Now change the jump into a RET instruction }
  5343. ConvertJumpToRET(p, hp1);
  5344. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5345. if not Assigned(first_assignment) then
  5346. InternalError(2021040811)
  5347. else
  5348. p := first_assignment;
  5349. Exit;
  5350. end;
  5351. else
  5352. begin
  5353. { Duplicate the MOV instruction }
  5354. hp3:=tai(hp1.getcopy);
  5355. if first_assignment = nil then
  5356. first_assignment := hp3;
  5357. asml.InsertBefore(hp3, p);
  5358. { Make sure the compiler knows about any final registers written here }
  5359. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5360. with taicpu(hp3).oper[OperIdx]^ do
  5361. begin
  5362. case typ of
  5363. top_ref:
  5364. begin
  5365. if (ref^.base <> NR_NO) and
  5366. (getsupreg(ref^.base) <> RS_ESP) and
  5367. (getsupreg(ref^.base) <> RS_EBP)
  5368. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5369. then
  5370. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5371. if (ref^.index <> NR_NO) and
  5372. (getsupreg(ref^.index) <> RS_ESP) and
  5373. (getsupreg(ref^.index) <> RS_EBP)
  5374. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5375. (ref^.index <> ref^.base) then
  5376. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5377. end;
  5378. top_reg:
  5379. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5380. else
  5381. ;
  5382. end;
  5383. end;
  5384. end;
  5385. end;
  5386. if not GetNextInstruction(hp1, hp1) then
  5387. { Should have dropped out earlier }
  5388. InternalError(2021040710);
  5389. end;
  5390. end;
  5391. end;
  5392. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5393. var
  5394. hp2: tai;
  5395. X: Integer;
  5396. begin
  5397. asml.Remove(hp1);
  5398. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5399. if not GetLastInstruction(p, hp2) then
  5400. asml.InsertBefore(hp1, p)
  5401. else
  5402. asml.InsertAfter(hp1, hp2);
  5403. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5404. for X := 0 to 1 do
  5405. case taicpu(hp1).oper[X]^.typ of
  5406. top_reg:
  5407. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5408. top_ref:
  5409. begin
  5410. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5411. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5412. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5413. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5414. end;
  5415. else
  5416. ;
  5417. end;
  5418. end;
  5419. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5420. function IsXCHGAcceptable: Boolean; inline;
  5421. begin
  5422. { Always accept if optimising for size }
  5423. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5424. (
  5425. {$ifdef x86_64}
  5426. { XCHG takes 3 cycles on AMD Athlon64 }
  5427. (current_settings.optimizecputype >= cpu_core_i)
  5428. {$else x86_64}
  5429. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5430. than 3, so it becomes a saving compared to three MOVs with two of
  5431. them able to execute simultaneously. [Kit] }
  5432. (current_settings.optimizecputype >= cpu_PentiumM)
  5433. {$endif x86_64}
  5434. );
  5435. end;
  5436. var
  5437. NewRef: TReference;
  5438. hp1, hp2, hp3, hp4: Tai;
  5439. {$ifndef x86_64}
  5440. OperIdx: Integer;
  5441. {$endif x86_64}
  5442. NewInstr : Taicpu;
  5443. NewAligh : Tai_align;
  5444. DestLabel: TAsmLabel;
  5445. begin
  5446. Result:=false;
  5447. { This optimisation adds an instruction, so only do it for speed }
  5448. if not (cs_opt_size in current_settings.optimizerswitches) and
  5449. MatchOpType(taicpu(p), top_const, top_reg) and
  5450. (taicpu(p).oper[0]^.val = 0) then
  5451. begin
  5452. { To avoid compiler warning }
  5453. DestLabel := nil;
  5454. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5455. InternalError(2021040750);
  5456. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5457. Exit;
  5458. case hp1.typ of
  5459. ait_label:
  5460. begin
  5461. { Change:
  5462. mov $0,%reg mov $0,%reg
  5463. @Lbl1: @Lbl1:
  5464. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5465. je @Lbl2 jne @Lbl2
  5466. To: To:
  5467. mov $0,%reg mov $0,%reg
  5468. jmp @Lbl2 jmp @Lbl3
  5469. (align) (align)
  5470. @Lbl1: @Lbl1:
  5471. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5472. je @Lbl2 je @Lbl2
  5473. @Lbl3: <-- Only if label exists
  5474. (Not if it's optimised for size)
  5475. }
  5476. if not GetNextInstruction(hp1, hp2) then
  5477. Exit;
  5478. if not (cs_opt_size in current_settings.optimizerswitches) and
  5479. (hp2.typ = ait_instruction) and
  5480. (
  5481. { Register sizes must exactly match }
  5482. (
  5483. (taicpu(hp2).opcode = A_CMP) and
  5484. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5485. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5486. ) or (
  5487. (taicpu(hp2).opcode = A_TEST) and
  5488. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5489. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5490. )
  5491. ) and GetNextInstruction(hp2, hp3) and
  5492. (hp3.typ = ait_instruction) and
  5493. (taicpu(hp3).opcode = A_JCC) and
  5494. (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
  5495. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5496. begin
  5497. { Check condition of jump }
  5498. { Always true? }
  5499. if condition_in(C_E, taicpu(hp3).condition) then
  5500. begin
  5501. { Copy label symbol and obtain matching label entry for the
  5502. conditional jump, as this will be our destination}
  5503. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5504. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5505. Result := True;
  5506. end
  5507. { Always false? }
  5508. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5509. begin
  5510. { This is only worth it if there's a jump to take }
  5511. case hp2.typ of
  5512. ait_instruction:
  5513. begin
  5514. if taicpu(hp2).opcode = A_JMP then
  5515. begin
  5516. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5517. { An unconditional jump follows the conditional jump which will always be false,
  5518. so use this jump's destination for the new jump }
  5519. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5520. Result := True;
  5521. end
  5522. else if taicpu(hp2).opcode = A_JCC then
  5523. begin
  5524. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5525. if condition_in(C_E, taicpu(hp2).condition) then
  5526. begin
  5527. { A second conditional jump follows the conditional jump which will always be false,
  5528. while the second jump is always True, so use this jump's destination for the new jump }
  5529. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5530. Result := True;
  5531. end;
  5532. { Don't risk it if the jump isn't always true (Result remains False) }
  5533. end;
  5534. end;
  5535. else
  5536. { If anything else don't optimise };
  5537. end;
  5538. end;
  5539. if Result then
  5540. begin
  5541. { Just so we have something to insert as a paremeter}
  5542. reference_reset(NewRef, 1, []);
  5543. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5544. { Now actually load the correct parameter }
  5545. NewInstr.loadsymbol(0, DestLabel, 0);
  5546. { Get instruction before original label (may not be p under -O3) }
  5547. if not GetLastInstruction(hp1, hp2) then
  5548. { Shouldn't fail here }
  5549. InternalError(2021040701);
  5550. DestLabel.increfs;
  5551. AsmL.InsertAfter(NewInstr, hp2);
  5552. { Add new alignment field }
  5553. (* AsmL.InsertAfter(
  5554. cai_align.create_max(
  5555. current_settings.alignment.jumpalign,
  5556. current_settings.alignment.jumpalignskipmax
  5557. ),
  5558. NewInstr
  5559. ); *)
  5560. end;
  5561. Exit;
  5562. end;
  5563. end;
  5564. else
  5565. ;
  5566. end;
  5567. end;
  5568. if not GetNextInstruction(p, hp1) then
  5569. Exit;
  5570. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5571. begin
  5572. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5573. further, but we can't just put this jump optimisation in pass 1
  5574. because it tends to perform worse when conditional jumps are
  5575. nearby (e.g. when converting CMOV instructions). [Kit] }
  5576. if OptPass2JMP(hp1) then
  5577. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5578. Result := OptPass1MOV(p)
  5579. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5580. returned True and the instruction is still a MOV, thus checking
  5581. the optimisations below }
  5582. { If OptPass2JMP returned False, no optimisations were done to
  5583. the jump and there are no further optimisations that can be done
  5584. to the MOV instruction on this pass }
  5585. end
  5586. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5587. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5588. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5589. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5590. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5591. { be lazy, checking separately for sub would be slightly better }
  5592. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5593. begin
  5594. { Change:
  5595. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5596. addl/q $x,%reg2 subl/q $x,%reg2
  5597. To:
  5598. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5599. }
  5600. TransferUsedRegs(TmpUsedRegs);
  5601. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5602. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5603. if not GetNextInstruction(hp1, hp2) or
  5604. (
  5605. { The FLAGS register isn't always tracked properly, so do not
  5606. perform this optimisation if a conditional statement follows }
  5607. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5608. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5609. ) then
  5610. begin
  5611. reference_reset(NewRef, 1, []);
  5612. NewRef.base := taicpu(p).oper[0]^.reg;
  5613. NewRef.scalefactor := 1;
  5614. if taicpu(hp1).opcode = A_ADD then
  5615. begin
  5616. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5617. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5618. end
  5619. else
  5620. begin
  5621. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5622. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5623. end;
  5624. taicpu(p).opcode := A_LEA;
  5625. taicpu(p).loadref(0, NewRef);
  5626. RemoveInstruction(hp1);
  5627. Result := True;
  5628. Exit;
  5629. end;
  5630. end
  5631. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5632. {$ifdef x86_64}
  5633. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5634. {$else x86_64}
  5635. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5636. {$endif x86_64}
  5637. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5638. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5639. { mov reg1, reg2 mov reg1, reg2
  5640. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5641. begin
  5642. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5643. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5644. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5645. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5646. TransferUsedRegs(TmpUsedRegs);
  5647. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5648. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5649. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5650. then
  5651. begin
  5652. RemoveCurrentP(p, hp1);
  5653. Result:=true;
  5654. end;
  5655. exit;
  5656. end
  5657. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5658. IsXCHGAcceptable and
  5659. { XCHG doesn't support 8-byte registers }
  5660. (taicpu(p).opsize <> S_B) and
  5661. MatchInstruction(hp1, A_MOV, []) and
  5662. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5663. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5664. GetNextInstruction(hp1, hp2) and
  5665. MatchInstruction(hp2, A_MOV, []) and
  5666. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5667. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5668. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5669. begin
  5670. { mov %reg1,%reg2
  5671. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5672. mov %reg2,%reg3
  5673. (%reg2 not used afterwards)
  5674. Note that xchg takes 3 cycles to execute, and generally mov's take
  5675. only one cycle apiece, but the first two mov's can be executed in
  5676. parallel, only taking 2 cycles overall. Older processors should
  5677. therefore only optimise for size. [Kit]
  5678. }
  5679. TransferUsedRegs(TmpUsedRegs);
  5680. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5681. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5682. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5683. begin
  5684. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5685. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5686. taicpu(hp1).opcode := A_XCHG;
  5687. RemoveCurrentP(p, hp1);
  5688. RemoveInstruction(hp2);
  5689. Result := True;
  5690. Exit;
  5691. end;
  5692. end
  5693. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5694. MatchInstruction(hp1, A_SAR, []) then
  5695. begin
  5696. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5697. begin
  5698. { the use of %edx also covers the opsize being S_L }
  5699. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5700. begin
  5701. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5702. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5703. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5704. begin
  5705. { Change:
  5706. movl %eax,%edx
  5707. sarl $31,%edx
  5708. To:
  5709. cltd
  5710. }
  5711. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5712. RemoveInstruction(hp1);
  5713. taicpu(p).opcode := A_CDQ;
  5714. taicpu(p).opsize := S_NO;
  5715. taicpu(p).clearop(1);
  5716. taicpu(p).clearop(0);
  5717. taicpu(p).ops:=0;
  5718. Result := True;
  5719. end
  5720. else if (cs_opt_size in current_settings.optimizerswitches) and
  5721. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5722. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5723. begin
  5724. { Change:
  5725. movl %edx,%eax
  5726. sarl $31,%edx
  5727. To:
  5728. movl %edx,%eax
  5729. cltd
  5730. Note that this creates a dependency between the two instructions,
  5731. so only perform if optimising for size.
  5732. }
  5733. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5734. taicpu(hp1).opcode := A_CDQ;
  5735. taicpu(hp1).opsize := S_NO;
  5736. taicpu(hp1).clearop(1);
  5737. taicpu(hp1).clearop(0);
  5738. taicpu(hp1).ops:=0;
  5739. end;
  5740. {$ifndef x86_64}
  5741. end
  5742. { Don't bother if CMOV is supported, because a more optimal
  5743. sequence would have been generated for the Abs() intrinsic }
  5744. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5745. { the use of %eax also covers the opsize being S_L }
  5746. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5747. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5748. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5749. GetNextInstruction(hp1, hp2) and
  5750. MatchInstruction(hp2, A_XOR, [S_L]) and
  5751. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5752. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5753. GetNextInstruction(hp2, hp3) and
  5754. MatchInstruction(hp3, A_SUB, [S_L]) and
  5755. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5756. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5757. begin
  5758. { Change:
  5759. movl %eax,%edx
  5760. sarl $31,%eax
  5761. xorl %eax,%edx
  5762. subl %eax,%edx
  5763. (Instruction that uses %edx)
  5764. (%eax deallocated)
  5765. (%edx deallocated)
  5766. To:
  5767. cltd
  5768. xorl %edx,%eax <-- Note the registers have swapped
  5769. subl %edx,%eax
  5770. (Instruction that uses %eax) <-- %eax rather than %edx
  5771. }
  5772. TransferUsedRegs(TmpUsedRegs);
  5773. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5774. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5775. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5776. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5777. begin
  5778. if GetNextInstruction(hp3, hp4) and
  5779. not RegModifiedByInstruction(NR_EDX, hp4) and
  5780. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5781. begin
  5782. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5783. taicpu(p).opcode := A_CDQ;
  5784. taicpu(p).clearop(1);
  5785. taicpu(p).clearop(0);
  5786. taicpu(p).ops:=0;
  5787. RemoveInstruction(hp1);
  5788. taicpu(hp2).loadreg(0, NR_EDX);
  5789. taicpu(hp2).loadreg(1, NR_EAX);
  5790. taicpu(hp3).loadreg(0, NR_EDX);
  5791. taicpu(hp3).loadreg(1, NR_EAX);
  5792. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5793. { Convert references in the following instruction (hp4) from %edx to %eax }
  5794. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5795. with taicpu(hp4).oper[OperIdx]^ do
  5796. case typ of
  5797. top_reg:
  5798. if getsupreg(reg) = RS_EDX then
  5799. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5800. top_ref:
  5801. begin
  5802. if getsupreg(reg) = RS_EDX then
  5803. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5804. if getsupreg(reg) = RS_EDX then
  5805. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5806. end;
  5807. else
  5808. ;
  5809. end;
  5810. end;
  5811. end;
  5812. {$else x86_64}
  5813. end;
  5814. end
  5815. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5816. { the use of %rdx also covers the opsize being S_Q }
  5817. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5818. begin
  5819. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5820. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5821. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5822. begin
  5823. { Change:
  5824. movq %rax,%rdx
  5825. sarq $63,%rdx
  5826. To:
  5827. cqto
  5828. }
  5829. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5830. RemoveInstruction(hp1);
  5831. taicpu(p).opcode := A_CQO;
  5832. taicpu(p).opsize := S_NO;
  5833. taicpu(p).clearop(1);
  5834. taicpu(p).clearop(0);
  5835. taicpu(p).ops:=0;
  5836. Result := True;
  5837. end
  5838. else if (cs_opt_size in current_settings.optimizerswitches) and
  5839. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5840. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5841. begin
  5842. { Change:
  5843. movq %rdx,%rax
  5844. sarq $63,%rdx
  5845. To:
  5846. movq %rdx,%rax
  5847. cqto
  5848. Note that this creates a dependency between the two instructions,
  5849. so only perform if optimising for size.
  5850. }
  5851. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5852. taicpu(hp1).opcode := A_CQO;
  5853. taicpu(hp1).opsize := S_NO;
  5854. taicpu(hp1).clearop(1);
  5855. taicpu(hp1).clearop(0);
  5856. taicpu(hp1).ops:=0;
  5857. {$endif x86_64}
  5858. end;
  5859. end;
  5860. end
  5861. else if MatchInstruction(hp1, A_MOV, []) and
  5862. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5863. { Though "GetNextInstruction" could be factored out, along with
  5864. the instructions that depend on hp2, it is an expensive call that
  5865. should be delayed for as long as possible, hence we do cheaper
  5866. checks first that are likely to be False. [Kit] }
  5867. begin
  5868. if (
  5869. (
  5870. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5871. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5872. (
  5873. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5874. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5875. )
  5876. ) or
  5877. (
  5878. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5879. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5880. (
  5881. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5882. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5883. )
  5884. )
  5885. ) and
  5886. GetNextInstruction(hp1, hp2) and
  5887. MatchInstruction(hp2, A_SAR, []) and
  5888. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5889. begin
  5890. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5891. begin
  5892. { Change:
  5893. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5894. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5895. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5896. To:
  5897. movl r/m,%eax <- Note the change in register
  5898. cltd
  5899. }
  5900. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5901. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5902. taicpu(p).loadreg(1, NR_EAX);
  5903. taicpu(hp1).opcode := A_CDQ;
  5904. taicpu(hp1).clearop(1);
  5905. taicpu(hp1).clearop(0);
  5906. taicpu(hp1).ops:=0;
  5907. RemoveInstruction(hp2);
  5908. (*
  5909. {$ifdef x86_64}
  5910. end
  5911. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5912. { This code sequence does not get generated - however it might become useful
  5913. if and when 128-bit signed integer types make an appearance, so the code
  5914. is kept here for when it is eventually needed. [Kit] }
  5915. (
  5916. (
  5917. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5918. (
  5919. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5920. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5921. )
  5922. ) or
  5923. (
  5924. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5925. (
  5926. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5927. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5928. )
  5929. )
  5930. ) and
  5931. GetNextInstruction(hp1, hp2) and
  5932. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5933. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5934. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5935. begin
  5936. { Change:
  5937. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5938. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5939. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5940. To:
  5941. movq r/m,%rax <- Note the change in register
  5942. cqto
  5943. }
  5944. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5945. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5946. taicpu(p).loadreg(1, NR_RAX);
  5947. taicpu(hp1).opcode := A_CQO;
  5948. taicpu(hp1).clearop(1);
  5949. taicpu(hp1).clearop(0);
  5950. taicpu(hp1).ops:=0;
  5951. RemoveInstruction(hp2);
  5952. {$endif x86_64}
  5953. *)
  5954. end;
  5955. end;
  5956. {$ifdef x86_64}
  5957. end
  5958. else if (taicpu(p).opsize = S_L) and
  5959. (taicpu(p).oper[1]^.typ = top_reg) and
  5960. (
  5961. MatchInstruction(hp1, A_MOV,[]) and
  5962. (taicpu(hp1).opsize = S_L) and
  5963. (taicpu(hp1).oper[1]^.typ = top_reg)
  5964. ) and (
  5965. GetNextInstruction(hp1, hp2) and
  5966. (tai(hp2).typ=ait_instruction) and
  5967. (taicpu(hp2).opsize = S_Q) and
  5968. (
  5969. (
  5970. MatchInstruction(hp2, A_ADD,[]) and
  5971. (taicpu(hp2).opsize = S_Q) and
  5972. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5973. (
  5974. (
  5975. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5976. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5977. ) or (
  5978. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5979. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5980. )
  5981. )
  5982. ) or (
  5983. MatchInstruction(hp2, A_LEA,[]) and
  5984. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5985. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5986. (
  5987. (
  5988. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5989. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5990. ) or (
  5991. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5992. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5993. )
  5994. ) and (
  5995. (
  5996. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5997. ) or (
  5998. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5999. )
  6000. )
  6001. )
  6002. )
  6003. ) and (
  6004. GetNextInstruction(hp2, hp3) and
  6005. MatchInstruction(hp3, A_SHR,[]) and
  6006. (taicpu(hp3).opsize = S_Q) and
  6007. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6008. (taicpu(hp3).oper[0]^.val = 1) and
  6009. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6010. ) then
  6011. begin
  6012. { Change movl x, reg1d movl x, reg1d
  6013. movl y, reg2d movl y, reg2d
  6014. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6015. shrq $1, reg1q shrq $1, reg1q
  6016. ( reg1d and reg2d can be switched around in the first two instructions )
  6017. To movl x, reg1d
  6018. addl y, reg1d
  6019. rcrl $1, reg1d
  6020. This corresponds to the common expression (x + y) shr 1, where
  6021. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6022. smaller code, but won't account for x + y causing an overflow). [Kit]
  6023. }
  6024. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6025. { Change first MOV command to have the same register as the final output }
  6026. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6027. else
  6028. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6029. { Change second MOV command to an ADD command. This is easier than
  6030. converting the existing command because it means we don't have to
  6031. touch 'y', which might be a complicated reference, and also the
  6032. fact that the third command might either be ADD or LEA. [Kit] }
  6033. taicpu(hp1).opcode := A_ADD;
  6034. { Delete old ADD/LEA instruction }
  6035. RemoveInstruction(hp2);
  6036. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6037. taicpu(hp3).opcode := A_RCR;
  6038. taicpu(hp3).changeopsize(S_L);
  6039. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6040. {$endif x86_64}
  6041. end;
  6042. end;
  6043. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6044. var
  6045. ThisReg: TRegister;
  6046. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6047. TargetSubReg: TSubRegister;
  6048. hp1, hp2: tai;
  6049. RegInUse, RegChanged, p_removed: Boolean;
  6050. { Store list of found instructions so we don't have to call
  6051. GetNextInstructionUsingReg multiple times }
  6052. InstrList: array of taicpu;
  6053. InstrMax, Index: Integer;
  6054. UpperLimit, TrySmallerLimit: TCgInt;
  6055. PreMessage: string;
  6056. { Data flow analysis }
  6057. TestValMin, TestValMax: TCgInt;
  6058. SmallerOverflow: Boolean;
  6059. begin
  6060. Result := False;
  6061. p_removed := False;
  6062. { This is anything but quick! }
  6063. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6064. Exit;
  6065. SetLength(InstrList, 0);
  6066. InstrMax := -1;
  6067. ThisReg := taicpu(p).oper[1]^.reg;
  6068. case taicpu(p).opsize of
  6069. S_BW, S_BL:
  6070. begin
  6071. {$if defined(i386) or defined(i8086)}
  6072. { If the target size is 8-bit, make sure we can actually encode it }
  6073. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6074. Exit;
  6075. {$endif i386 or i8086}
  6076. UpperLimit := $FF;
  6077. MinSize := S_B;
  6078. if taicpu(p).opsize = S_BW then
  6079. MaxSize := S_W
  6080. else
  6081. MaxSize := S_L;
  6082. end;
  6083. S_WL:
  6084. begin
  6085. UpperLimit := $FFFF;
  6086. MinSize := S_W;
  6087. MaxSize := S_L;
  6088. end
  6089. else
  6090. InternalError(2020112301);
  6091. end;
  6092. TestValMin := 0;
  6093. TestValMax := UpperLimit;
  6094. TrySmallerLimit := UpperLimit;
  6095. TrySmaller := S_NO;
  6096. SmallerOverflow := False;
  6097. RegChanged := False;
  6098. hp1 := p;
  6099. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6100. (hp1.typ = ait_instruction) and
  6101. (
  6102. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6103. instruction that doesn't actually contain ThisReg }
  6104. (cs_opt_level3 in current_settings.optimizerswitches) or
  6105. RegInInstruction(ThisReg, hp1)
  6106. ) do
  6107. begin
  6108. case taicpu(hp1).opcode of
  6109. A_INC,A_DEC:
  6110. begin
  6111. { Has to be an exact match on the register }
  6112. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6113. Break;
  6114. if taicpu(hp1).opcode = A_INC then
  6115. begin
  6116. Inc(TestValMin);
  6117. Inc(TestValMax);
  6118. end
  6119. else
  6120. begin
  6121. Dec(TestValMin);
  6122. Dec(TestValMax);
  6123. end;
  6124. end;
  6125. A_CMP:
  6126. begin
  6127. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6128. { Has to be an exact match on the register }
  6129. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6130. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6131. { Make sure the comparison value is not smaller than the
  6132. smallest allowed signed value for the minimum size (e.g.
  6133. -128 for 8-bit) }
  6134. not (
  6135. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6136. { Is it in the negative range? }
  6137. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6138. ) then
  6139. Break;
  6140. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6141. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6142. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6143. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6144. { Overflow }
  6145. Break;
  6146. { Check to see if the active register is used afterwards }
  6147. TransferUsedRegs(TmpUsedRegs);
  6148. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6149. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6150. begin
  6151. case MinSize of
  6152. S_B:
  6153. TargetSubReg := R_SUBL;
  6154. S_W:
  6155. TargetSubReg := R_SUBW;
  6156. else
  6157. InternalError(2021051002);
  6158. end;
  6159. { Update the register to its new size }
  6160. setsubreg(ThisReg, TargetSubReg);
  6161. taicpu(hp1).oper[1]^.reg := ThisReg;
  6162. taicpu(hp1).opsize := MinSize;
  6163. { Convert the input MOVZX to a MOV }
  6164. if (taicpu(p).oper[0]^.typ = top_reg) and
  6165. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6166. begin
  6167. { Or remove it completely! }
  6168. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6169. RemoveCurrentP(p);
  6170. p_removed := True;
  6171. end
  6172. else
  6173. begin
  6174. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6175. taicpu(p).opcode := A_MOV;
  6176. taicpu(p).oper[1]^.reg := ThisReg;
  6177. taicpu(p).opsize := MinSize;
  6178. end;
  6179. if (InstrMax >= 0) then
  6180. begin
  6181. for Index := 0 to InstrMax do
  6182. begin
  6183. { If p_removed is true, then the original MOV/Z was removed
  6184. and removing the AND instruction may not be safe if it
  6185. appears first }
  6186. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6187. InternalError(2020112311);
  6188. if InstrList[Index].oper[0]^.typ = top_reg then
  6189. InstrList[Index].oper[0]^.reg := ThisReg;
  6190. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6191. InstrList[Index].opsize := MinSize;
  6192. end;
  6193. end;
  6194. Result := True;
  6195. Exit;
  6196. end;
  6197. end;
  6198. { OR and XOR are not included because they can too easily fool
  6199. the data flow analysis (they can cause non-linear behaviour) }
  6200. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6201. begin
  6202. if
  6203. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6204. { Has to be an exact match on the register }
  6205. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6206. (
  6207. (
  6208. (taicpu(hp1).oper[0]^.typ = top_const) and
  6209. (
  6210. (
  6211. (taicpu(hp1).opcode = A_SHL) and
  6212. (
  6213. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6214. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6215. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6216. )
  6217. ) or (
  6218. (taicpu(hp1).opcode <> A_SHL) and
  6219. (
  6220. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6221. { Is it in the negative range? }
  6222. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6223. )
  6224. )
  6225. )
  6226. ) or (
  6227. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6228. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6229. )
  6230. ) then
  6231. Break;
  6232. case taicpu(hp1).opcode of
  6233. A_ADD:
  6234. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6235. begin
  6236. TestValMin := TestValMin * 2;
  6237. TestValMax := TestValMax * 2;
  6238. end
  6239. else
  6240. begin
  6241. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6242. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6243. end;
  6244. A_SUB:
  6245. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6246. begin
  6247. TestValMin := 0;
  6248. TestValMax := 0;
  6249. end
  6250. else
  6251. begin
  6252. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6253. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6254. end;
  6255. A_AND:
  6256. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6257. begin
  6258. { we might be able to go smaller if AND appears first }
  6259. if InstrMax = -1 then
  6260. case MinSize of
  6261. S_B:
  6262. ;
  6263. S_W:
  6264. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6265. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6266. begin
  6267. TrySmaller := S_B;
  6268. TrySmallerLimit := $FF;
  6269. end;
  6270. S_L:
  6271. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6272. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6273. begin
  6274. TrySmaller := S_B;
  6275. TrySmallerLimit := $FF;
  6276. end
  6277. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6278. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6279. begin
  6280. TrySmaller := S_W;
  6281. TrySmallerLimit := $FFFF;
  6282. end;
  6283. else
  6284. InternalError(2020112320);
  6285. end;
  6286. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6287. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6288. end;
  6289. A_SHL:
  6290. begin
  6291. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6292. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6293. end;
  6294. A_SHR:
  6295. begin
  6296. { we might be able to go smaller if SHR appears first }
  6297. if InstrMax = -1 then
  6298. case MinSize of
  6299. S_B:
  6300. ;
  6301. S_W:
  6302. if (taicpu(hp1).oper[0]^.val >= 8) then
  6303. begin
  6304. TrySmaller := S_B;
  6305. TrySmallerLimit := $FF;
  6306. end;
  6307. S_L:
  6308. if (taicpu(hp1).oper[0]^.val >= 24) then
  6309. begin
  6310. TrySmaller := S_B;
  6311. TrySmallerLimit := $FF;
  6312. end
  6313. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6314. begin
  6315. TrySmaller := S_W;
  6316. TrySmallerLimit := $FFFF;
  6317. end;
  6318. else
  6319. InternalError(2020112321);
  6320. end;
  6321. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6322. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6323. end;
  6324. else
  6325. InternalError(2020112303);
  6326. end;
  6327. end;
  6328. (*
  6329. A_IMUL:
  6330. case taicpu(hp1).ops of
  6331. 2:
  6332. begin
  6333. if not MatchOpType(hp1, top_reg, top_reg) or
  6334. { Has to be an exact match on the register }
  6335. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6336. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6337. Break;
  6338. TestValMin := TestValMin * TestValMin;
  6339. TestValMax := TestValMax * TestValMax;
  6340. end;
  6341. 3:
  6342. begin
  6343. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6344. { Has to be an exact match on the register }
  6345. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6346. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6347. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6348. { Is it in the negative range? }
  6349. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6350. Break;
  6351. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6352. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6353. end;
  6354. else
  6355. Break;
  6356. end;
  6357. A_IDIV:
  6358. case taicpu(hp1).ops of
  6359. 3:
  6360. begin
  6361. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6362. { Has to be an exact match on the register }
  6363. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6364. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6365. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6366. { Is it in the negative range? }
  6367. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6368. Break;
  6369. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6370. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6371. end;
  6372. else
  6373. Break;
  6374. end;
  6375. *)
  6376. A_MOVZX:
  6377. begin
  6378. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6379. Break;
  6380. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6381. begin
  6382. { Because hp1 was obtained via GetNextInstructionUsingReg
  6383. and ThisReg doesn't appear in the first operand, it
  6384. must appear in the second operand and hence gets
  6385. overwritten }
  6386. if (InstrMax = -1) and
  6387. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6388. begin
  6389. { The two MOVZX instructions are adjacent, so remove the first one }
  6390. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6391. RemoveCurrentP(p);
  6392. Result := True;
  6393. Exit;
  6394. end;
  6395. Break;
  6396. end;
  6397. { The objective here is to try to find a combination that
  6398. removes one of the MOV/Z instructions. }
  6399. case taicpu(hp1).opsize of
  6400. S_WL:
  6401. if (MinSize in [S_B, S_W]) then
  6402. begin
  6403. TargetSize := S_L;
  6404. TargetSubReg := R_SUBD;
  6405. end
  6406. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6407. begin
  6408. TargetSize := TrySmaller;
  6409. if TrySmaller = S_B then
  6410. TargetSubReg := R_SUBL
  6411. else
  6412. TargetSubReg := R_SUBW;
  6413. end
  6414. else
  6415. Break;
  6416. S_BW:
  6417. if (MinSize in [S_B, S_W]) then
  6418. begin
  6419. TargetSize := S_W;
  6420. TargetSubReg := R_SUBW;
  6421. end
  6422. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6423. begin
  6424. TargetSize := S_B;
  6425. TargetSubReg := R_SUBL;
  6426. end
  6427. else
  6428. Break;
  6429. S_BL:
  6430. if (MinSize in [S_B, S_W]) then
  6431. begin
  6432. TargetSize := S_L;
  6433. TargetSubReg := R_SUBD;
  6434. end
  6435. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6436. begin
  6437. TargetSize := S_B;
  6438. TargetSubReg := R_SUBL;
  6439. end
  6440. else
  6441. Break;
  6442. else
  6443. InternalError(2020112302);
  6444. end;
  6445. { Update the register to its new size }
  6446. setsubreg(ThisReg, TargetSubReg);
  6447. if TargetSize = MinSize then
  6448. begin
  6449. { Convert the input MOVZX to a MOV }
  6450. if (taicpu(p).oper[0]^.typ = top_reg) and
  6451. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6452. begin
  6453. { Or remove it completely! }
  6454. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6455. RemoveCurrentP(p);
  6456. p_removed := True;
  6457. end
  6458. else
  6459. begin
  6460. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6461. taicpu(p).opcode := A_MOV;
  6462. taicpu(p).oper[1]^.reg := ThisReg;
  6463. taicpu(p).opsize := TargetSize;
  6464. end;
  6465. Result := True;
  6466. end
  6467. else if TargetSize <> MaxSize then
  6468. begin
  6469. case MaxSize of
  6470. S_L:
  6471. if TargetSize = S_W then
  6472. begin
  6473. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6474. taicpu(p).opsize := S_BW;
  6475. taicpu(p).oper[1]^.reg := ThisReg;
  6476. Result := True;
  6477. end
  6478. else
  6479. InternalError(2020112341);
  6480. S_W:
  6481. if TargetSize = S_L then
  6482. begin
  6483. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6484. taicpu(p).opsize := S_BL;
  6485. taicpu(p).oper[1]^.reg := ThisReg;
  6486. Result := True;
  6487. end
  6488. else
  6489. InternalError(2020112342);
  6490. else
  6491. ;
  6492. end;
  6493. end;
  6494. if (MaxSize = TargetSize) or
  6495. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6496. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6497. begin
  6498. { Convert the output MOVZX to a MOV }
  6499. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6500. begin
  6501. { Or remove it completely! }
  6502. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6503. { Be careful; if p = hp1 and p was also removed, p
  6504. will become a dangling pointer }
  6505. if p = hp1 then
  6506. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6507. else
  6508. RemoveInstruction(hp1);
  6509. end
  6510. else
  6511. begin
  6512. taicpu(hp1).opcode := A_MOV;
  6513. taicpu(hp1).oper[0]^.reg := ThisReg;
  6514. taicpu(hp1).opsize := TargetSize;
  6515. { Check to see if the active register is used afterwards;
  6516. if not, we can change it and make a saving. }
  6517. RegInUse := False;
  6518. TransferUsedRegs(TmpUsedRegs);
  6519. { The target register may be marked as in use to cross
  6520. a jump to a distant label, so exclude it }
  6521. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6522. hp2 := p;
  6523. repeat
  6524. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6525. { Explicitly check for the excluded register (don't include the first
  6526. instruction as it may be reading from here }
  6527. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6528. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6529. begin
  6530. RegInUse := True;
  6531. Break;
  6532. end;
  6533. if not GetNextInstruction(hp2, hp2) then
  6534. InternalError(2020112340);
  6535. until (hp2 = hp1);
  6536. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6537. begin
  6538. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6539. ThisReg := taicpu(hp1).oper[1]^.reg;
  6540. RegChanged := True;
  6541. TransferUsedRegs(TmpUsedRegs);
  6542. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6543. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6544. if p = hp1 then
  6545. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6546. else
  6547. RemoveInstruction(hp1);
  6548. { Instruction will become "mov %reg,%reg" }
  6549. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6550. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6551. begin
  6552. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6553. RemoveCurrentP(p);
  6554. p_removed := True;
  6555. end
  6556. else
  6557. taicpu(p).oper[1]^.reg := ThisReg;
  6558. Result := True;
  6559. end
  6560. else
  6561. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6562. end;
  6563. end
  6564. else
  6565. InternalError(2020112330);
  6566. { Now go through every instruction we found and change the
  6567. size. If TargetSize = MaxSize, then almost no changes are
  6568. needed and Result can remain False if it hasn't been set
  6569. yet.
  6570. If RegChanged is True, then the register requires changing
  6571. and so the point about TargetSize = MaxSize doesn't apply. }
  6572. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6573. begin
  6574. for Index := 0 to InstrMax do
  6575. begin
  6576. { If p_removed is true, then the original MOV/Z was removed
  6577. and removing the AND instruction may not be safe if it
  6578. appears first }
  6579. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6580. InternalError(2020112310);
  6581. if InstrList[Index].oper[0]^.typ = top_reg then
  6582. InstrList[Index].oper[0]^.reg := ThisReg;
  6583. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6584. InstrList[Index].opsize := TargetSize;
  6585. end;
  6586. Result := True;
  6587. end;
  6588. Exit;
  6589. end;
  6590. else
  6591. { This includes ADC, SBB, IDIV and SAR }
  6592. Break;
  6593. end;
  6594. if (TestValMin < 0) or (TestValMax < 0) or
  6595. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6596. { Overflow }
  6597. Break
  6598. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6599. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6600. SmallerOverflow := True;
  6601. { Contains highest index (so instruction count - 1) }
  6602. Inc(InstrMax);
  6603. if InstrMax > High(InstrList) then
  6604. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6605. InstrList[InstrMax] := taicpu(hp1);
  6606. end;
  6607. end;
  6608. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6609. var
  6610. hp1 : tai;
  6611. begin
  6612. Result:=false;
  6613. if (taicpu(p).ops >= 2) and
  6614. ((taicpu(p).oper[0]^.typ = top_const) or
  6615. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6616. (taicpu(p).oper[1]^.typ = top_reg) and
  6617. ((taicpu(p).ops = 2) or
  6618. ((taicpu(p).oper[2]^.typ = top_reg) and
  6619. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6620. GetLastInstruction(p,hp1) and
  6621. MatchInstruction(hp1,A_MOV,[]) and
  6622. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6623. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6624. begin
  6625. TransferUsedRegs(TmpUsedRegs);
  6626. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6627. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6628. { change
  6629. mov reg1,reg2
  6630. imul y,reg2 to imul y,reg1,reg2 }
  6631. begin
  6632. taicpu(p).ops := 3;
  6633. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6634. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6635. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6636. RemoveInstruction(hp1);
  6637. result:=true;
  6638. end;
  6639. end;
  6640. end;
  6641. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6642. var
  6643. ThisLabel: TAsmLabel;
  6644. begin
  6645. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6646. ThisLabel.decrefs;
  6647. taicpu(p).opcode := A_RET;
  6648. taicpu(p).is_jmp := false;
  6649. taicpu(p).ops := taicpu(ret_p).ops;
  6650. case taicpu(ret_p).ops of
  6651. 0:
  6652. taicpu(p).clearop(0);
  6653. 1:
  6654. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6655. else
  6656. internalerror(2016041301);
  6657. end;
  6658. { If the original label is now dead, it might turn out that the label
  6659. immediately follows p. As a result, everything beyond it, which will
  6660. be just some final register configuration and a RET instruction, is
  6661. now dead code. [Kit] }
  6662. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6663. running RemoveDeadCodeAfterJump for each RET instruction, because
  6664. this optimisation rarely happens and most RETs appear at the end of
  6665. routines where there is nothing that can be stripped. [Kit] }
  6666. if not ThisLabel.is_used then
  6667. RemoveDeadCodeAfterJump(p);
  6668. end;
  6669. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6670. var
  6671. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6672. Unconditional, PotentialModified: Boolean;
  6673. OperPtr: POper;
  6674. NewRef: TReference;
  6675. InstrList: array of taicpu;
  6676. InstrMax, Index: Integer;
  6677. const
  6678. {$ifdef DEBUG_AOPTCPU}
  6679. SNoFlags: shortstring = ' so the flags aren''t modified';
  6680. {$else DEBUG_AOPTCPU}
  6681. SNoFlags = '';
  6682. {$endif DEBUG_AOPTCPU}
  6683. begin
  6684. Result:=false;
  6685. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6686. begin
  6687. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6688. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6689. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6690. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6691. GetNextInstruction(hp1, hp2) and
  6692. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  6693. { Change from: To:
  6694. set(C) %reg j(~C) label
  6695. test %reg,%reg/cmp $0,%reg
  6696. je label
  6697. set(C) %reg j(C) label
  6698. test %reg,%reg/cmp $0,%reg
  6699. jne label
  6700. (Also do something similar with sete/setne instead of je/jne)
  6701. }
  6702. begin
  6703. { Before we do anything else, we need to check the instructions
  6704. in between SETcc and TEST to make sure they don't modify the
  6705. FLAGS register - if -O2 or under, there won't be any
  6706. instructions between SET and TEST }
  6707. TransferUsedRegs(TmpUsedRegs);
  6708. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6709. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6710. begin
  6711. next := p;
  6712. SetLength(InstrList, 0);
  6713. InstrMax := -1;
  6714. PotentialModified := False;
  6715. { Make a note of every instruction that modifies the FLAGS
  6716. register }
  6717. while GetNextInstruction(next, next) and (next <> hp1) do
  6718. begin
  6719. if next.typ <> ait_instruction then
  6720. { GetNextInstructionUsingReg should have returned False }
  6721. InternalError(2021051701);
  6722. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6723. begin
  6724. case taicpu(next).opcode of
  6725. A_SETcc,
  6726. A_CMOVcc,
  6727. A_Jcc:
  6728. begin
  6729. if PotentialModified then
  6730. { Not safe because the flags were modified earlier }
  6731. Exit
  6732. else
  6733. { Condition is the same as the initial SETcc, so this is safe
  6734. (don't add to instruction list though) }
  6735. Continue;
  6736. end;
  6737. A_ADD:
  6738. begin
  6739. if (taicpu(next).opsize = S_B) or
  6740. { LEA doesn't support 8-bit operands }
  6741. (taicpu(next).oper[1]^.typ <> top_reg) or
  6742. { Must write to a register }
  6743. (taicpu(next).oper[0]^.typ = top_ref) then
  6744. { Require a constant or a register }
  6745. Exit;
  6746. PotentialModified := True;
  6747. end;
  6748. A_SUB:
  6749. begin
  6750. if (taicpu(next).opsize = S_B) or
  6751. { LEA doesn't support 8-bit operands }
  6752. (taicpu(next).oper[1]^.typ <> top_reg) or
  6753. { Must write to a register }
  6754. (taicpu(next).oper[0]^.typ <> top_const) or
  6755. (taicpu(next).oper[0]^.val = $80000000) then
  6756. { Can't subtract a register with LEA - also
  6757. check that the value isn't -2^31, as this
  6758. can't be negated }
  6759. Exit;
  6760. PotentialModified := True;
  6761. end;
  6762. A_SAL,
  6763. A_SHL:
  6764. begin
  6765. if (taicpu(next).opsize = S_B) or
  6766. { LEA doesn't support 8-bit operands }
  6767. (taicpu(next).oper[1]^.typ <> top_reg) or
  6768. { Must write to a register }
  6769. (taicpu(next).oper[0]^.typ <> top_const) or
  6770. (taicpu(next).oper[0]^.val < 0) or
  6771. (taicpu(next).oper[0]^.val > 3) then
  6772. Exit;
  6773. PotentialModified := True;
  6774. end;
  6775. A_IMUL:
  6776. begin
  6777. if (taicpu(next).ops <> 3) or
  6778. (taicpu(next).oper[1]^.typ <> top_reg) or
  6779. { Must write to a register }
  6780. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6781. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6782. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6783. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6784. Exit
  6785. else
  6786. PotentialModified := True;
  6787. end;
  6788. else
  6789. { Don't know how to change this, so abort }
  6790. Exit;
  6791. end;
  6792. { Contains highest index (so instruction count - 1) }
  6793. Inc(InstrMax);
  6794. if InstrMax > High(InstrList) then
  6795. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6796. InstrList[InstrMax] := taicpu(next);
  6797. end;
  6798. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6799. end;
  6800. if not Assigned(next) or (next <> hp1) then
  6801. { It should be equal to hp1 }
  6802. InternalError(2021051702);
  6803. { Cycle through each instruction and check to see if we can
  6804. change them to versions that don't modify the flags }
  6805. if (InstrMax >= 0) then
  6806. begin
  6807. for Index := 0 to InstrMax do
  6808. case InstrList[Index].opcode of
  6809. A_ADD:
  6810. begin
  6811. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6812. InstrList[Index].opcode := A_LEA;
  6813. reference_reset(NewRef, 1, []);
  6814. NewRef.base := InstrList[Index].oper[1]^.reg;
  6815. if InstrList[Index].oper[0]^.typ = top_reg then
  6816. begin
  6817. NewRef.index := InstrList[Index].oper[0]^.reg;
  6818. NewRef.scalefactor := 1;
  6819. end
  6820. else
  6821. NewRef.offset := InstrList[Index].oper[0]^.val;
  6822. InstrList[Index].loadref(0, NewRef);
  6823. end;
  6824. A_SUB:
  6825. begin
  6826. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6827. InstrList[Index].opcode := A_LEA;
  6828. reference_reset(NewRef, 1, []);
  6829. NewRef.base := InstrList[Index].oper[1]^.reg;
  6830. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6831. InstrList[Index].loadref(0, NewRef);
  6832. end;
  6833. A_SHL,
  6834. A_SAL:
  6835. begin
  6836. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6837. InstrList[Index].opcode := A_LEA;
  6838. reference_reset(NewRef, 1, []);
  6839. NewRef.index := InstrList[Index].oper[1]^.reg;
  6840. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6841. InstrList[Index].loadref(0, NewRef);
  6842. end;
  6843. A_IMUL:
  6844. begin
  6845. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6846. InstrList[Index].opcode := A_LEA;
  6847. reference_reset(NewRef, 1, []);
  6848. NewRef.index := InstrList[Index].oper[1]^.reg;
  6849. case InstrList[Index].oper[0]^.val of
  6850. 2, 4, 8:
  6851. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6852. else {3, 5 and 9}
  6853. begin
  6854. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6855. NewRef.base := InstrList[Index].oper[1]^.reg;
  6856. end;
  6857. end;
  6858. InstrList[Index].loadref(0, NewRef);
  6859. end;
  6860. else
  6861. InternalError(2021051710);
  6862. end;
  6863. end;
  6864. { Mark the FLAGS register as used across this whole block }
  6865. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6866. end;
  6867. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6868. JumpC := taicpu(hp2).condition;
  6869. Unconditional := False;
  6870. if conditions_equal(JumpC, C_E) then
  6871. SetC := inverse_cond(taicpu(p).condition)
  6872. else if conditions_equal(JumpC, C_NE) then
  6873. SetC := taicpu(p).condition
  6874. else
  6875. { We've got something weird here (and inefficent) }
  6876. begin
  6877. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6878. SetC := C_NONE;
  6879. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6880. if condition_in(C_AE, JumpC) then
  6881. Unconditional := True
  6882. else
  6883. { Not sure what to do with this jump - drop out }
  6884. Exit;
  6885. end;
  6886. RemoveInstruction(hp1);
  6887. if Unconditional then
  6888. MakeUnconditional(taicpu(hp2))
  6889. else
  6890. begin
  6891. if SetC = C_NONE then
  6892. InternalError(2018061402);
  6893. taicpu(hp2).SetCondition(SetC);
  6894. end;
  6895. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6896. TmpUsedRegs }
  6897. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6898. begin
  6899. RemoveCurrentp(p, hp2);
  6900. if taicpu(hp2).opcode = A_SETcc then
  6901. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  6902. else
  6903. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6904. end
  6905. else
  6906. if taicpu(hp2).opcode = A_SETcc then
  6907. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  6908. else
  6909. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6910. Result := True;
  6911. end
  6912. else if
  6913. { Make sure the instructions are adjacent }
  6914. (
  6915. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6916. GetNextInstruction(p, hp1)
  6917. ) and
  6918. MatchInstruction(hp1, A_MOV, [S_B]) and
  6919. { Writing to memory is allowed }
  6920. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6921. begin
  6922. {
  6923. Watch out for sequences such as:
  6924. set(c)b %regb
  6925. movb %regb,(ref)
  6926. movb $0,1(ref)
  6927. movb $0,2(ref)
  6928. movb $0,3(ref)
  6929. Much more efficient to turn it into:
  6930. movl $0,%regl
  6931. set(c)b %regb
  6932. movl %regl,(ref)
  6933. Or:
  6934. set(c)b %regb
  6935. movzbl %regb,%regl
  6936. movl %regl,(ref)
  6937. }
  6938. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6939. GetNextInstruction(hp1, hp2) and
  6940. MatchInstruction(hp2, A_MOV, [S_B]) and
  6941. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6942. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6943. begin
  6944. { Don't do anything else except set Result to True }
  6945. end
  6946. else
  6947. begin
  6948. if taicpu(p).oper[0]^.typ = top_reg then
  6949. begin
  6950. TransferUsedRegs(TmpUsedRegs);
  6951. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6952. end;
  6953. { If it's not a register, it's a memory address }
  6954. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6955. begin
  6956. { Even if the register is still in use, we can minimise the
  6957. pipeline stall by changing the MOV into another SETcc. }
  6958. taicpu(hp1).opcode := A_SETcc;
  6959. taicpu(hp1).condition := taicpu(p).condition;
  6960. if taicpu(hp1).oper[1]^.typ = top_ref then
  6961. begin
  6962. { Swapping the operand pointers like this is probably a
  6963. bit naughty, but it is far faster than using loadoper
  6964. to transfer the reference from oper[1] to oper[0] if
  6965. you take into account the extra procedure calls and
  6966. the memory allocation and deallocation required }
  6967. OperPtr := taicpu(hp1).oper[1];
  6968. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6969. taicpu(hp1).oper[0] := OperPtr;
  6970. end
  6971. else
  6972. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6973. taicpu(hp1).clearop(1);
  6974. taicpu(hp1).ops := 1;
  6975. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6976. end
  6977. else
  6978. begin
  6979. if taicpu(hp1).oper[1]^.typ = top_reg then
  6980. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6981. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6982. RemoveInstruction(hp1);
  6983. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6984. end
  6985. end;
  6986. Result := True;
  6987. end;
  6988. end;
  6989. end;
  6990. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6991. var
  6992. hp1: tai;
  6993. Count: Integer;
  6994. OrigLabel: TAsmLabel;
  6995. begin
  6996. result := False;
  6997. { Sometimes, the optimisations below can permit this }
  6998. RemoveDeadCodeAfterJump(p);
  6999. 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
  7000. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7001. begin
  7002. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7003. { Also a side-effect of optimisations }
  7004. if CollapseZeroDistJump(p, OrigLabel) then
  7005. begin
  7006. Result := True;
  7007. Exit;
  7008. end;
  7009. hp1 := GetLabelWithSym(OrigLabel);
  7010. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7011. begin
  7012. case taicpu(hp1).opcode of
  7013. A_RET:
  7014. {
  7015. change
  7016. jmp .L1
  7017. ...
  7018. .L1:
  7019. ret
  7020. into
  7021. ret
  7022. }
  7023. begin
  7024. ConvertJumpToRET(p, hp1);
  7025. result:=true;
  7026. end;
  7027. { Check any kind of direct assignment instruction }
  7028. A_MOV,
  7029. A_MOVD,
  7030. A_MOVQ,
  7031. A_MOVSX,
  7032. {$ifdef x86_64}
  7033. A_MOVSXD,
  7034. {$endif x86_64}
  7035. A_MOVZX,
  7036. A_MOVAPS,
  7037. A_MOVUPS,
  7038. A_MOVSD,
  7039. A_MOVAPD,
  7040. A_MOVUPD,
  7041. A_MOVDQA,
  7042. A_MOVDQU,
  7043. A_VMOVSS,
  7044. A_VMOVAPS,
  7045. A_VMOVUPS,
  7046. A_VMOVSD,
  7047. A_VMOVAPD,
  7048. A_VMOVUPD,
  7049. A_VMOVDQA,
  7050. A_VMOVDQU:
  7051. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7052. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7053. begin
  7054. Result := True;
  7055. Exit;
  7056. end;
  7057. else
  7058. ;
  7059. end;
  7060. end;
  7061. end;
  7062. end;
  7063. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7064. begin
  7065. CanBeCMOV:=assigned(p) and
  7066. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7067. { we can't use cmov ref,reg because
  7068. ref could be nil and cmov still throws an exception
  7069. if ref=nil but the mov isn't done (FK)
  7070. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7071. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7072. }
  7073. (taicpu(p).oper[1]^.typ = top_reg) and
  7074. (
  7075. (taicpu(p).oper[0]^.typ = top_reg) or
  7076. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7077. it is not expected that this can cause a seg. violation }
  7078. (
  7079. (taicpu(p).oper[0]^.typ = top_ref) and
  7080. IsRefSafe(taicpu(p).oper[0]^.ref)
  7081. )
  7082. );
  7083. end;
  7084. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7085. var
  7086. hp1,hp2: tai;
  7087. {$ifndef i8086}
  7088. hp3,hp4,hpmov2, hp5: tai;
  7089. l : Longint;
  7090. condition : TAsmCond;
  7091. {$endif i8086}
  7092. carryadd_opcode : TAsmOp;
  7093. symbol: TAsmSymbol;
  7094. reg: tsuperregister;
  7095. increg, tmpreg: TRegister;
  7096. begin
  7097. result:=false;
  7098. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7099. begin
  7100. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7101. if (
  7102. (
  7103. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7104. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7105. (Taicpu(hp1).oper[0]^.val=1)
  7106. ) or
  7107. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7108. ) and
  7109. GetNextInstruction(hp1,hp2) and
  7110. SkipAligns(hp2, hp2) and
  7111. (hp2.typ = ait_label) and
  7112. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7113. { jb @@1 cmc
  7114. inc/dec operand --> adc/sbb operand,0
  7115. @@1:
  7116. ... and ...
  7117. jnb @@1
  7118. inc/dec operand --> adc/sbb operand,0
  7119. @@1: }
  7120. begin
  7121. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7122. begin
  7123. case taicpu(hp1).opcode of
  7124. A_INC,
  7125. A_ADD:
  7126. carryadd_opcode:=A_ADC;
  7127. A_DEC,
  7128. A_SUB:
  7129. carryadd_opcode:=A_SBB;
  7130. else
  7131. InternalError(2021011001);
  7132. end;
  7133. Taicpu(p).clearop(0);
  7134. Taicpu(p).ops:=0;
  7135. Taicpu(p).is_jmp:=false;
  7136. Taicpu(p).opcode:=A_CMC;
  7137. Taicpu(p).condition:=C_NONE;
  7138. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7139. Taicpu(hp1).ops:=2;
  7140. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7141. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7142. else
  7143. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7144. Taicpu(hp1).loadconst(0,0);
  7145. Taicpu(hp1).opcode:=carryadd_opcode;
  7146. result:=true;
  7147. exit;
  7148. end
  7149. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7150. begin
  7151. case taicpu(hp1).opcode of
  7152. A_INC,
  7153. A_ADD:
  7154. carryadd_opcode:=A_ADC;
  7155. A_DEC,
  7156. A_SUB:
  7157. carryadd_opcode:=A_SBB;
  7158. else
  7159. InternalError(2021011002);
  7160. end;
  7161. Taicpu(hp1).ops:=2;
  7162. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7163. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7164. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7165. else
  7166. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7167. Taicpu(hp1).loadconst(0,0);
  7168. Taicpu(hp1).opcode:=carryadd_opcode;
  7169. RemoveCurrentP(p, hp1);
  7170. result:=true;
  7171. exit;
  7172. end
  7173. {
  7174. jcc @@1 setcc tmpreg
  7175. inc/dec/add/sub operand -> (movzx tmpreg)
  7176. @@1: add/sub tmpreg,operand
  7177. While this increases code size slightly, it makes the code much faster if the
  7178. jump is unpredictable
  7179. }
  7180. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7181. begin
  7182. { search for an available register which is volatile }
  7183. for reg in tcpuregisterset do
  7184. begin
  7185. if
  7186. {$if defined(i386) or defined(i8086)}
  7187. { Only use registers whose lowest 8-bits can Be accessed }
  7188. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7189. {$endif i386 or i8086}
  7190. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7191. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7192. { We don't need to check if tmpreg is in hp1 or not, because
  7193. it will be marked as in use at p (if not, this is
  7194. indictive of a compiler bug). }
  7195. then
  7196. begin
  7197. TAsmLabel(symbol).decrefs;
  7198. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7199. Taicpu(p).clearop(0);
  7200. Taicpu(p).ops:=1;
  7201. Taicpu(p).is_jmp:=false;
  7202. Taicpu(p).opcode:=A_SETcc;
  7203. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7204. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7205. Taicpu(p).loadreg(0,increg);
  7206. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7207. begin
  7208. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7209. R_SUBW:
  7210. begin
  7211. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7212. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7213. end;
  7214. R_SUBD:
  7215. begin
  7216. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7217. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7218. end;
  7219. {$ifdef x86_64}
  7220. R_SUBQ:
  7221. begin
  7222. { MOVZX doesn't have a 64-bit variant, because
  7223. the 32-bit version implicitly zeroes the
  7224. upper 32-bits of the destination register }
  7225. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7226. newreg(R_INTREGISTER,reg,R_SUBD));
  7227. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7228. end;
  7229. {$endif x86_64}
  7230. else
  7231. Internalerror(2020030601);
  7232. end;
  7233. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7234. asml.InsertAfter(hp2,p);
  7235. end
  7236. else
  7237. tmpreg := increg;
  7238. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7239. begin
  7240. Taicpu(hp1).ops:=2;
  7241. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7242. end;
  7243. Taicpu(hp1).loadreg(0,tmpreg);
  7244. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7245. Result := True;
  7246. { p is no longer a Jcc instruction, so exit }
  7247. Exit;
  7248. end;
  7249. end;
  7250. end;
  7251. end;
  7252. { Detect the following:
  7253. jmp<cond> @Lbl1
  7254. jmp @Lbl2
  7255. ...
  7256. @Lbl1:
  7257. ret
  7258. Change to:
  7259. jmp<inv_cond> @Lbl2
  7260. ret
  7261. }
  7262. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7263. begin
  7264. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7265. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7266. MatchInstruction(hp2,A_RET,[S_NO]) then
  7267. begin
  7268. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7269. { Change label address to that of the unconditional jump }
  7270. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7271. TAsmLabel(symbol).DecRefs;
  7272. taicpu(hp1).opcode := A_RET;
  7273. taicpu(hp1).is_jmp := false;
  7274. taicpu(hp1).ops := taicpu(hp2).ops;
  7275. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7276. case taicpu(hp2).ops of
  7277. 0:
  7278. taicpu(hp1).clearop(0);
  7279. 1:
  7280. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7281. else
  7282. internalerror(2016041302);
  7283. end;
  7284. end;
  7285. {$ifndef i8086}
  7286. end
  7287. {
  7288. convert
  7289. j<c> .L1
  7290. mov 1,reg
  7291. jmp .L2
  7292. .L1
  7293. mov 0,reg
  7294. .L2
  7295. into
  7296. mov 0,reg
  7297. set<not(c)> reg
  7298. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7299. would destroy the flag contents
  7300. }
  7301. else if MatchInstruction(hp1,A_MOV,[]) and
  7302. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7303. {$ifdef i386}
  7304. (
  7305. { Under i386, ESI, EDI, EBP and ESP
  7306. don't have an 8-bit representation }
  7307. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7308. ) and
  7309. {$endif i386}
  7310. (taicpu(hp1).oper[0]^.val=1) and
  7311. GetNextInstruction(hp1,hp2) and
  7312. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7313. GetNextInstruction(hp2,hp3) and
  7314. { skip align }
  7315. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7316. (hp3.typ=ait_label) and
  7317. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7318. (tai_label(hp3).labsym.getrefs=1) and
  7319. GetNextInstruction(hp3,hp4) and
  7320. MatchInstruction(hp4,A_MOV,[]) and
  7321. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7322. (taicpu(hp4).oper[0]^.val=0) and
  7323. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7324. GetNextInstruction(hp4,hp5) and
  7325. (hp5.typ=ait_label) and
  7326. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7327. (tai_label(hp5).labsym.getrefs=1) then
  7328. begin
  7329. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7330. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7331. { remove last label }
  7332. RemoveInstruction(hp5);
  7333. { remove second label }
  7334. RemoveInstruction(hp3);
  7335. { if align is present remove it }
  7336. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7337. RemoveInstruction(hp3);
  7338. { remove jmp }
  7339. RemoveInstruction(hp2);
  7340. if taicpu(hp1).opsize=S_B then
  7341. RemoveInstruction(hp1)
  7342. else
  7343. taicpu(hp1).loadconst(0,0);
  7344. taicpu(hp4).opcode:=A_SETcc;
  7345. taicpu(hp4).opsize:=S_B;
  7346. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7347. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7348. taicpu(hp4).opercnt:=1;
  7349. taicpu(hp4).ops:=1;
  7350. taicpu(hp4).freeop(1);
  7351. RemoveCurrentP(p);
  7352. Result:=true;
  7353. exit;
  7354. end
  7355. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7356. begin
  7357. { check for
  7358. jCC xxx
  7359. <several movs>
  7360. xxx:
  7361. }
  7362. l:=0;
  7363. while assigned(hp1) and
  7364. CanBeCMOV(hp1) and
  7365. { stop on labels }
  7366. not(hp1.typ=ait_label) do
  7367. begin
  7368. inc(l);
  7369. GetNextInstruction(hp1,hp1);
  7370. end;
  7371. if assigned(hp1) then
  7372. begin
  7373. if FindLabel(tasmlabel(symbol),hp1) then
  7374. begin
  7375. if (l<=4) and (l>0) then
  7376. begin
  7377. condition:=inverse_cond(taicpu(p).condition);
  7378. GetNextInstruction(p,hp1);
  7379. repeat
  7380. if not Assigned(hp1) then
  7381. InternalError(2018062900);
  7382. taicpu(hp1).opcode:=A_CMOVcc;
  7383. taicpu(hp1).condition:=condition;
  7384. UpdateUsedRegs(hp1);
  7385. GetNextInstruction(hp1,hp1);
  7386. until not(CanBeCMOV(hp1));
  7387. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7388. hp2 := hp1;
  7389. repeat
  7390. if not Assigned(hp2) then
  7391. InternalError(2018062910);
  7392. case hp2.typ of
  7393. ait_label:
  7394. { What we expected - break out of the loop (it won't be a dead label at the top of
  7395. a cluster because that was optimised at an earlier stage) }
  7396. Break;
  7397. ait_align:
  7398. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7399. begin
  7400. hp2 := tai(hp2.Next);
  7401. Continue;
  7402. end;
  7403. else
  7404. begin
  7405. { Might be a comment or temporary allocation entry }
  7406. if not (hp2.typ in SkipInstr) then
  7407. InternalError(2018062911);
  7408. hp2 := tai(hp2.Next);
  7409. Continue;
  7410. end;
  7411. end;
  7412. until False;
  7413. { Now we can safely decrement the reference count }
  7414. tasmlabel(symbol).decrefs;
  7415. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7416. { Remove the original jump }
  7417. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7418. GetNextInstruction(hp2, p); { Instruction after the label }
  7419. { Remove the label if this is its final reference }
  7420. if (tasmlabel(symbol).getrefs=0) then
  7421. StripLabelFast(hp1);
  7422. if Assigned(p) then
  7423. begin
  7424. UpdateUsedRegs(p);
  7425. result:=true;
  7426. end;
  7427. exit;
  7428. end;
  7429. end
  7430. else
  7431. begin
  7432. { check further for
  7433. jCC xxx
  7434. <several movs 1>
  7435. jmp yyy
  7436. xxx:
  7437. <several movs 2>
  7438. yyy:
  7439. }
  7440. { hp2 points to jmp yyy }
  7441. hp2:=hp1;
  7442. { skip hp1 to xxx (or an align right before it) }
  7443. GetNextInstruction(hp1, hp1);
  7444. if assigned(hp2) and
  7445. assigned(hp1) and
  7446. (l<=3) and
  7447. (hp2.typ=ait_instruction) and
  7448. (taicpu(hp2).is_jmp) and
  7449. (taicpu(hp2).condition=C_None) and
  7450. { real label and jump, no further references to the
  7451. label are allowed }
  7452. (tasmlabel(symbol).getrefs=1) and
  7453. FindLabel(tasmlabel(symbol),hp1) then
  7454. begin
  7455. l:=0;
  7456. { skip hp1 to <several moves 2> }
  7457. if (hp1.typ = ait_align) then
  7458. GetNextInstruction(hp1, hp1);
  7459. GetNextInstruction(hp1, hpmov2);
  7460. hp1 := hpmov2;
  7461. while assigned(hp1) and
  7462. CanBeCMOV(hp1) do
  7463. begin
  7464. inc(l);
  7465. GetNextInstruction(hp1, hp1);
  7466. end;
  7467. { hp1 points to yyy (or an align right before it) }
  7468. hp3 := hp1;
  7469. if assigned(hp1) and
  7470. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7471. begin
  7472. condition:=inverse_cond(taicpu(p).condition);
  7473. GetNextInstruction(p,hp1);
  7474. repeat
  7475. taicpu(hp1).opcode:=A_CMOVcc;
  7476. taicpu(hp1).condition:=condition;
  7477. UpdateUsedRegs(hp1);
  7478. GetNextInstruction(hp1,hp1);
  7479. until not(assigned(hp1)) or
  7480. not(CanBeCMOV(hp1));
  7481. condition:=inverse_cond(condition);
  7482. hp1 := hpmov2;
  7483. { hp1 is now at <several movs 2> }
  7484. while Assigned(hp1) and CanBeCMOV(hp1) do
  7485. begin
  7486. taicpu(hp1).opcode:=A_CMOVcc;
  7487. taicpu(hp1).condition:=condition;
  7488. UpdateUsedRegs(hp1);
  7489. GetNextInstruction(hp1,hp1);
  7490. end;
  7491. hp1 := p;
  7492. { Get first instruction after label }
  7493. GetNextInstruction(hp3, p);
  7494. if assigned(p) and (hp3.typ = ait_align) then
  7495. GetNextInstruction(p, p);
  7496. { Don't dereference yet, as doing so will cause
  7497. GetNextInstruction to skip the label and
  7498. optional align marker. [Kit] }
  7499. GetNextInstruction(hp2, hp4);
  7500. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7501. { remove jCC }
  7502. RemoveInstruction(hp1);
  7503. { Now we can safely decrement it }
  7504. tasmlabel(symbol).decrefs;
  7505. { Remove label xxx (it will have a ref of zero due to the initial check }
  7506. StripLabelFast(hp4);
  7507. { remove jmp }
  7508. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7509. RemoveInstruction(hp2);
  7510. { As before, now we can safely decrement it }
  7511. tasmlabel(symbol).decrefs;
  7512. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7513. if tasmlabel(symbol).getrefs = 0 then
  7514. StripLabelFast(hp3);
  7515. if Assigned(p) then
  7516. begin
  7517. UpdateUsedRegs(p);
  7518. result:=true;
  7519. end;
  7520. exit;
  7521. end;
  7522. end;
  7523. end;
  7524. end;
  7525. {$endif i8086}
  7526. end;
  7527. end;
  7528. end;
  7529. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7530. var
  7531. hp1,hp2: tai;
  7532. reg_and_hp1_is_instr: Boolean;
  7533. begin
  7534. result:=false;
  7535. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7536. GetNextInstruction(p,hp1) and
  7537. (hp1.typ = ait_instruction);
  7538. if reg_and_hp1_is_instr and
  7539. (
  7540. (taicpu(hp1).opcode <> A_LEA) or
  7541. { If the LEA instruction can be converted into an arithmetic instruction,
  7542. it may be possible to then fold it. }
  7543. (
  7544. { If the flags register is in use, don't change the instruction
  7545. to an ADD otherwise this will scramble the flags. [Kit] }
  7546. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7547. ConvertLEA(taicpu(hp1))
  7548. )
  7549. ) and
  7550. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7551. GetNextInstruction(hp1,hp2) and
  7552. MatchInstruction(hp2,A_MOV,[]) and
  7553. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7554. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7555. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7556. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7557. {$ifdef i386}
  7558. { not all registers have byte size sub registers on i386 }
  7559. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7560. {$endif i386}
  7561. (((taicpu(hp1).ops=2) and
  7562. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7563. ((taicpu(hp1).ops=1) and
  7564. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7565. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7566. begin
  7567. { change movsX/movzX reg/ref, reg2
  7568. add/sub/or/... reg3/$const, reg2
  7569. mov reg2 reg/ref
  7570. to add/sub/or/... reg3/$const, reg/ref }
  7571. { by example:
  7572. movswl %si,%eax movswl %si,%eax p
  7573. decl %eax addl %edx,%eax hp1
  7574. movw %ax,%si movw %ax,%si hp2
  7575. ->
  7576. movswl %si,%eax movswl %si,%eax p
  7577. decw %eax addw %edx,%eax hp1
  7578. movw %ax,%si movw %ax,%si hp2
  7579. }
  7580. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7581. {
  7582. ->
  7583. movswl %si,%eax movswl %si,%eax p
  7584. decw %si addw %dx,%si hp1
  7585. movw %ax,%si movw %ax,%si hp2
  7586. }
  7587. case taicpu(hp1).ops of
  7588. 1:
  7589. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7590. 2:
  7591. begin
  7592. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7593. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7594. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7595. end;
  7596. else
  7597. internalerror(2008042702);
  7598. end;
  7599. {
  7600. ->
  7601. decw %si addw %dx,%si p
  7602. }
  7603. DebugMsg(SPeepholeOptimization + 'var3',p);
  7604. RemoveCurrentP(p, hp1);
  7605. RemoveInstruction(hp2);
  7606. end
  7607. else if reg_and_hp1_is_instr and
  7608. (taicpu(hp1).opcode = A_MOV) and
  7609. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7610. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7611. {$ifdef x86_64}
  7612. { check for implicit extension to 64 bit }
  7613. or
  7614. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7615. (taicpu(hp1).opsize=S_Q) and
  7616. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7617. )
  7618. {$endif x86_64}
  7619. )
  7620. then
  7621. begin
  7622. { change
  7623. movx %reg1,%reg2
  7624. mov %reg2,%reg3
  7625. dealloc %reg2
  7626. into
  7627. movx %reg,%reg3
  7628. }
  7629. TransferUsedRegs(TmpUsedRegs);
  7630. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7631. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7632. begin
  7633. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7634. {$ifdef x86_64}
  7635. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7636. (taicpu(hp1).opsize=S_Q) then
  7637. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7638. else
  7639. {$endif x86_64}
  7640. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7641. RemoveInstruction(hp1);
  7642. end;
  7643. end
  7644. else if reg_and_hp1_is_instr and
  7645. (taicpu(hp1).opcode = A_MOV) and
  7646. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7647. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7648. (taicpu(hp1).opsize=S_B)) or
  7649. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7650. (taicpu(hp1).opsize=S_W))
  7651. {$ifdef x86_64}
  7652. or ((taicpu(p).opsize=S_LQ) and
  7653. (taicpu(hp1).opsize=S_L))
  7654. {$endif x86_64}
  7655. ) and
  7656. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7657. begin
  7658. { change
  7659. movx %reg1,%reg2
  7660. mov %reg2,%reg3
  7661. dealloc %reg2
  7662. into
  7663. mov %reg1,%reg3
  7664. if the second mov accesses only the bits stored in reg1
  7665. }
  7666. TransferUsedRegs(TmpUsedRegs);
  7667. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7668. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7669. begin
  7670. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7671. if taicpu(p).oper[0]^.typ=top_reg then
  7672. begin
  7673. case taicpu(hp1).opsize of
  7674. S_B:
  7675. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7676. S_W:
  7677. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7678. S_L:
  7679. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7680. else
  7681. Internalerror(2020102301);
  7682. end;
  7683. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7684. end
  7685. else
  7686. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7687. RemoveCurrentP(p);
  7688. result:=true;
  7689. exit;
  7690. end;
  7691. end
  7692. else if reg_and_hp1_is_instr and
  7693. (taicpu(p).oper[0]^.typ = top_reg) and
  7694. (
  7695. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7696. ) and
  7697. (taicpu(hp1).oper[0]^.typ = top_const) and
  7698. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7699. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7700. { Minimum shift value allowed is the bit difference between the sizes }
  7701. (taicpu(hp1).oper[0]^.val >=
  7702. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7703. 8 * (
  7704. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7705. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7706. )
  7707. ) then
  7708. begin
  7709. { For:
  7710. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7711. shl/sal ##, %reg1
  7712. Remove the movsx/movzx instruction if the shift overwrites the
  7713. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7714. }
  7715. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7716. RemoveCurrentP(p, hp1);
  7717. Result := True;
  7718. Exit;
  7719. end
  7720. else if reg_and_hp1_is_instr and
  7721. (taicpu(p).oper[0]^.typ = top_reg) and
  7722. (
  7723. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7724. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7725. ) and
  7726. (taicpu(hp1).oper[0]^.typ = top_const) and
  7727. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7728. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7729. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7730. (taicpu(hp1).oper[0]^.val <
  7731. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7732. 8 * (
  7733. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7734. )
  7735. ) then
  7736. begin
  7737. { For:
  7738. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7739. sar ##, %reg1 shr ##, %reg1
  7740. Move the shift to before the movx instruction if the shift value
  7741. is not too large.
  7742. }
  7743. asml.Remove(hp1);
  7744. asml.InsertBefore(hp1, p);
  7745. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7746. case taicpu(p).opsize of
  7747. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7748. taicpu(hp1).opsize := S_B;
  7749. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7750. taicpu(hp1).opsize := S_W;
  7751. {$ifdef x86_64}
  7752. S_LQ:
  7753. taicpu(hp1).opsize := S_L;
  7754. {$endif}
  7755. else
  7756. InternalError(2020112401);
  7757. end;
  7758. if (taicpu(hp1).opcode = A_SHR) then
  7759. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7760. else
  7761. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7762. Result := True;
  7763. end
  7764. else if taicpu(p).opcode=A_MOVZX then
  7765. begin
  7766. { removes superfluous And's after movzx's }
  7767. if reg_and_hp1_is_instr and
  7768. (taicpu(hp1).opcode = A_AND) and
  7769. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7770. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7771. {$ifdef x86_64}
  7772. { check for implicit extension to 64 bit }
  7773. or
  7774. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7775. (taicpu(hp1).opsize=S_Q) and
  7776. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7777. )
  7778. {$endif x86_64}
  7779. )
  7780. then
  7781. begin
  7782. case taicpu(p).opsize Of
  7783. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7784. if (taicpu(hp1).oper[0]^.val = $ff) then
  7785. begin
  7786. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7787. RemoveInstruction(hp1);
  7788. Result:=true;
  7789. exit;
  7790. end;
  7791. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7792. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7793. begin
  7794. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7795. RemoveInstruction(hp1);
  7796. Result:=true;
  7797. exit;
  7798. end;
  7799. {$ifdef x86_64}
  7800. S_LQ:
  7801. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7802. begin
  7803. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7804. RemoveInstruction(hp1);
  7805. Result:=true;
  7806. exit;
  7807. end;
  7808. {$endif x86_64}
  7809. else
  7810. ;
  7811. end;
  7812. { we cannot get rid of the and, but can we get rid of the movz ?}
  7813. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7814. begin
  7815. case taicpu(p).opsize Of
  7816. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7817. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7818. begin
  7819. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7820. RemoveCurrentP(p,hp1);
  7821. Result:=true;
  7822. exit;
  7823. end;
  7824. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7825. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7826. begin
  7827. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7828. RemoveCurrentP(p,hp1);
  7829. Result:=true;
  7830. exit;
  7831. end;
  7832. {$ifdef x86_64}
  7833. S_LQ:
  7834. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7835. begin
  7836. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7837. RemoveCurrentP(p,hp1);
  7838. Result:=true;
  7839. exit;
  7840. end;
  7841. {$endif x86_64}
  7842. else
  7843. ;
  7844. end;
  7845. end;
  7846. end;
  7847. { changes some movzx constructs to faster synonyms (all examples
  7848. are given with eax/ax, but are also valid for other registers)}
  7849. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7850. begin
  7851. case taicpu(p).opsize of
  7852. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7853. (the machine code is equivalent to movzbl %al,%eax), but the
  7854. code generator still generates that assembler instruction and
  7855. it is silently converted. This should probably be checked.
  7856. [Kit] }
  7857. S_BW:
  7858. begin
  7859. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7860. (
  7861. not IsMOVZXAcceptable
  7862. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7863. or (
  7864. (cs_opt_size in current_settings.optimizerswitches) and
  7865. (taicpu(p).oper[1]^.reg = NR_AX)
  7866. )
  7867. ) then
  7868. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7869. begin
  7870. DebugMsg(SPeepholeOptimization + 'var7',p);
  7871. taicpu(p).opcode := A_AND;
  7872. taicpu(p).changeopsize(S_W);
  7873. taicpu(p).loadConst(0,$ff);
  7874. Result := True;
  7875. end
  7876. else if not IsMOVZXAcceptable and
  7877. GetNextInstruction(p, hp1) and
  7878. (tai(hp1).typ = ait_instruction) and
  7879. (taicpu(hp1).opcode = A_AND) and
  7880. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7881. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7882. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7883. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7884. begin
  7885. DebugMsg(SPeepholeOptimization + 'var8',p);
  7886. taicpu(p).opcode := A_MOV;
  7887. taicpu(p).changeopsize(S_W);
  7888. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7889. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7890. Result := True;
  7891. end;
  7892. end;
  7893. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7894. S_BL:
  7895. begin
  7896. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7897. (
  7898. not IsMOVZXAcceptable
  7899. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7900. or (
  7901. (cs_opt_size in current_settings.optimizerswitches) and
  7902. (taicpu(p).oper[1]^.reg = NR_EAX)
  7903. )
  7904. ) then
  7905. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7906. begin
  7907. DebugMsg(SPeepholeOptimization + 'var9',p);
  7908. taicpu(p).opcode := A_AND;
  7909. taicpu(p).changeopsize(S_L);
  7910. taicpu(p).loadConst(0,$ff);
  7911. Result := True;
  7912. end
  7913. else if not IsMOVZXAcceptable and
  7914. GetNextInstruction(p, hp1) and
  7915. (tai(hp1).typ = ait_instruction) and
  7916. (taicpu(hp1).opcode = A_AND) and
  7917. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7918. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7919. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7920. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7921. begin
  7922. DebugMsg(SPeepholeOptimization + 'var10',p);
  7923. taicpu(p).opcode := A_MOV;
  7924. taicpu(p).changeopsize(S_L);
  7925. { do not use R_SUBWHOLE
  7926. as movl %rdx,%eax
  7927. is invalid in assembler PM }
  7928. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7929. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7930. Result := True;
  7931. end;
  7932. end;
  7933. {$endif i8086}
  7934. S_WL:
  7935. if not IsMOVZXAcceptable then
  7936. begin
  7937. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7938. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7939. begin
  7940. DebugMsg(SPeepholeOptimization + 'var11',p);
  7941. taicpu(p).opcode := A_AND;
  7942. taicpu(p).changeopsize(S_L);
  7943. taicpu(p).loadConst(0,$ffff);
  7944. Result := True;
  7945. end
  7946. else if GetNextInstruction(p, hp1) and
  7947. (tai(hp1).typ = ait_instruction) and
  7948. (taicpu(hp1).opcode = A_AND) and
  7949. (taicpu(hp1).oper[0]^.typ = top_const) and
  7950. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7951. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7952. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7953. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7954. begin
  7955. DebugMsg(SPeepholeOptimization + 'var12',p);
  7956. taicpu(p).opcode := A_MOV;
  7957. taicpu(p).changeopsize(S_L);
  7958. { do not use R_SUBWHOLE
  7959. as movl %rdx,%eax
  7960. is invalid in assembler PM }
  7961. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7962. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7963. Result := True;
  7964. end;
  7965. end;
  7966. else
  7967. InternalError(2017050705);
  7968. end;
  7969. end
  7970. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7971. begin
  7972. if GetNextInstruction(p, hp1) and
  7973. (tai(hp1).typ = ait_instruction) and
  7974. (taicpu(hp1).opcode = A_AND) and
  7975. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7976. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7977. begin
  7978. //taicpu(p).opcode := A_MOV;
  7979. case taicpu(p).opsize Of
  7980. S_BL:
  7981. begin
  7982. DebugMsg(SPeepholeOptimization + 'var13',p);
  7983. taicpu(hp1).changeopsize(S_L);
  7984. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7985. end;
  7986. S_WL:
  7987. begin
  7988. DebugMsg(SPeepholeOptimization + 'var14',p);
  7989. taicpu(hp1).changeopsize(S_L);
  7990. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7991. end;
  7992. S_BW:
  7993. begin
  7994. DebugMsg(SPeepholeOptimization + 'var15',p);
  7995. taicpu(hp1).changeopsize(S_W);
  7996. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7997. end;
  7998. else
  7999. Internalerror(2017050704)
  8000. end;
  8001. Result := True;
  8002. end;
  8003. end;
  8004. end;
  8005. end;
  8006. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8007. var
  8008. hp1, hp2 : tai;
  8009. MaskLength : Cardinal;
  8010. MaskedBits : TCgInt;
  8011. begin
  8012. Result:=false;
  8013. { There are no optimisations for reference targets }
  8014. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8015. Exit;
  8016. while GetNextInstruction(p, hp1) and
  8017. (hp1.typ = ait_instruction) do
  8018. begin
  8019. if (taicpu(p).oper[0]^.typ = top_const) then
  8020. begin
  8021. case taicpu(hp1).opcode of
  8022. A_AND:
  8023. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8024. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8025. { the second register must contain the first one, so compare their subreg types }
  8026. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8027. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8028. { change
  8029. and const1, reg
  8030. and const2, reg
  8031. to
  8032. and (const1 and const2), reg
  8033. }
  8034. begin
  8035. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8036. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8037. RemoveCurrentP(p, hp1);
  8038. Result:=true;
  8039. exit;
  8040. end;
  8041. A_CMP:
  8042. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8043. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8044. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8045. { Just check that the condition on the next instruction is compatible }
  8046. GetNextInstruction(hp1, hp2) and
  8047. (hp2.typ = ait_instruction) and
  8048. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8049. then
  8050. { change
  8051. and 2^n, reg
  8052. cmp 2^n, reg
  8053. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8054. to
  8055. and 2^n, reg
  8056. test reg, reg
  8057. j(~c) / set(~c) / cmov(~c)
  8058. }
  8059. begin
  8060. { Keep TEST instruction in, rather than remove it, because
  8061. it may trigger other optimisations such as MovAndTest2Test }
  8062. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8063. taicpu(hp1).opcode := A_TEST;
  8064. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8065. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8066. Result := True;
  8067. Exit;
  8068. end;
  8069. A_MOVZX:
  8070. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8071. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8072. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8073. (
  8074. (
  8075. (taicpu(p).opsize=S_W) and
  8076. (taicpu(hp1).opsize=S_BW)
  8077. ) or
  8078. (
  8079. (taicpu(p).opsize=S_L) and
  8080. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8081. )
  8082. {$ifdef x86_64}
  8083. or
  8084. (
  8085. (taicpu(p).opsize=S_Q) and
  8086. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8087. )
  8088. {$endif x86_64}
  8089. ) then
  8090. begin
  8091. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8092. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8093. ) or
  8094. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8095. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8096. then
  8097. begin
  8098. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8099. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8100. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8101. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8102. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8103. }
  8104. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8105. RemoveInstruction(hp1);
  8106. { See if there are other optimisations possible }
  8107. Continue;
  8108. end;
  8109. end;
  8110. A_SHL:
  8111. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8112. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8113. begin
  8114. {$ifopt R+}
  8115. {$define RANGE_WAS_ON}
  8116. {$R-}
  8117. {$endif}
  8118. { get length of potential and mask }
  8119. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8120. { really a mask? }
  8121. {$ifdef RANGE_WAS_ON}
  8122. {$R+}
  8123. {$endif}
  8124. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8125. { unmasked part shifted out? }
  8126. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8127. begin
  8128. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8129. RemoveCurrentP(p, hp1);
  8130. Result:=true;
  8131. exit;
  8132. end;
  8133. end;
  8134. A_SHR:
  8135. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8136. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8137. (taicpu(hp1).oper[0]^.val <= 63) then
  8138. begin
  8139. { Does SHR combined with the AND cover all the bits?
  8140. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8141. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8142. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8143. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8144. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8145. begin
  8146. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8147. RemoveCurrentP(p, hp1);
  8148. Result := True;
  8149. Exit;
  8150. end;
  8151. end;
  8152. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8153. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8154. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8155. begin
  8156. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8157. (
  8158. (
  8159. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8160. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8161. ) or (
  8162. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8163. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8164. {$ifdef x86_64}
  8165. ) or (
  8166. (taicpu(hp1).opsize = S_LQ) and
  8167. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8168. {$endif x86_64}
  8169. )
  8170. ) then
  8171. begin
  8172. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8173. begin
  8174. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8175. RemoveInstruction(hp1);
  8176. { See if there are other optimisations possible }
  8177. Continue;
  8178. end;
  8179. { The super-registers are the same though.
  8180. Note that this change by itself doesn't improve
  8181. code speed, but it opens up other optimisations. }
  8182. {$ifdef x86_64}
  8183. { Convert 64-bit register to 32-bit }
  8184. case taicpu(hp1).opsize of
  8185. S_BQ:
  8186. begin
  8187. taicpu(hp1).opsize := S_BL;
  8188. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8189. end;
  8190. S_WQ:
  8191. begin
  8192. taicpu(hp1).opsize := S_WL;
  8193. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8194. end
  8195. else
  8196. ;
  8197. end;
  8198. {$endif x86_64}
  8199. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8200. taicpu(hp1).opcode := A_MOVZX;
  8201. { See if there are other optimisations possible }
  8202. Continue;
  8203. end;
  8204. end;
  8205. else
  8206. ;
  8207. end;
  8208. end;
  8209. if (taicpu(hp1).is_jmp) and
  8210. (taicpu(hp1).opcode<>A_JMP) and
  8211. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8212. begin
  8213. { change
  8214. and x, reg
  8215. jxx
  8216. to
  8217. test x, reg
  8218. jxx
  8219. if reg is deallocated before the
  8220. jump, but only if it's a conditional jump (PFV)
  8221. }
  8222. taicpu(p).opcode := A_TEST;
  8223. Exit;
  8224. end;
  8225. Break;
  8226. end;
  8227. { Lone AND tests }
  8228. if (taicpu(p).oper[0]^.typ = top_const) then
  8229. begin
  8230. {
  8231. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8232. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8233. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8234. }
  8235. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8236. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8237. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8238. begin
  8239. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8240. if taicpu(p).opsize = S_L then
  8241. begin
  8242. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8243. Result := True;
  8244. end;
  8245. end;
  8246. end;
  8247. { Backward check to determine necessity of and %reg,%reg }
  8248. if (taicpu(p).oper[0]^.typ = top_reg) and
  8249. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8250. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8251. GetLastInstruction(p, hp2) and
  8252. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8253. { Check size of adjacent instruction to determine if the AND is
  8254. effectively a null operation }
  8255. (
  8256. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8257. { Note: Don't include S_Q }
  8258. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8259. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8260. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8261. ) then
  8262. begin
  8263. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8264. { If GetNextInstruction returned False, hp1 will be nil }
  8265. RemoveCurrentP(p, hp1);
  8266. Result := True;
  8267. Exit;
  8268. end;
  8269. end;
  8270. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8271. var
  8272. hp1: tai; NewRef: TReference;
  8273. { This entire nested function is used in an if-statement below, but we
  8274. want to avoid all the used reg transfers and GetNextInstruction calls
  8275. until we really have to check }
  8276. function MemRegisterNotUsedLater: Boolean; inline;
  8277. var
  8278. hp2: tai;
  8279. begin
  8280. TransferUsedRegs(TmpUsedRegs);
  8281. hp2 := p;
  8282. repeat
  8283. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8284. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8285. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8286. end;
  8287. begin
  8288. Result := False;
  8289. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8290. Exit;
  8291. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8292. begin
  8293. { Change:
  8294. add %reg2,%reg1
  8295. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8296. To:
  8297. mov/s/z #(%reg1,%reg2),%reg1
  8298. }
  8299. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8300. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8301. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8302. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8303. (
  8304. (
  8305. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8306. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8307. { r/esp cannot be an index }
  8308. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8309. ) or (
  8310. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8311. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8312. )
  8313. ) and (
  8314. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8315. (
  8316. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8317. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8318. MemRegisterNotUsedLater
  8319. )
  8320. ) then
  8321. begin
  8322. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8323. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8324. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8325. RemoveCurrentp(p, hp1);
  8326. Result := True;
  8327. Exit;
  8328. end;
  8329. { Change:
  8330. addl/q $x,%reg1
  8331. movl/q %reg1,%reg2
  8332. To:
  8333. leal/q $x(%reg1),%reg2
  8334. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8335. Breaks the dependency chain.
  8336. }
  8337. if MatchOpType(taicpu(p),top_const,top_reg) and
  8338. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8339. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8340. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8341. (
  8342. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8343. not (cs_opt_size in current_settings.optimizerswitches) or
  8344. (
  8345. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8346. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8347. )
  8348. ) then
  8349. begin
  8350. { Change the MOV instruction to a LEA instruction, and update the
  8351. first operand }
  8352. reference_reset(NewRef, 1, []);
  8353. NewRef.base := taicpu(p).oper[1]^.reg;
  8354. NewRef.scalefactor := 1;
  8355. NewRef.offset := taicpu(p).oper[0]^.val;
  8356. taicpu(hp1).opcode := A_LEA;
  8357. taicpu(hp1).loadref(0, NewRef);
  8358. TransferUsedRegs(TmpUsedRegs);
  8359. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8360. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8361. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8362. begin
  8363. { Move what is now the LEA instruction to before the SUB instruction }
  8364. Asml.Remove(hp1);
  8365. Asml.InsertBefore(hp1, p);
  8366. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8367. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8368. p := hp1;
  8369. end
  8370. else
  8371. begin
  8372. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8373. RemoveCurrentP(p, hp1);
  8374. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8375. end;
  8376. Result := True;
  8377. end;
  8378. end;
  8379. end;
  8380. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8381. begin
  8382. Result:=false;
  8383. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8384. begin
  8385. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8386. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8387. begin
  8388. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8389. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8390. taicpu(p).opcode:=A_ADD;
  8391. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8392. result:=true;
  8393. end
  8394. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8395. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8396. begin
  8397. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8398. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8399. taicpu(p).opcode:=A_ADD;
  8400. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8401. result:=true;
  8402. end;
  8403. end;
  8404. end;
  8405. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8406. var
  8407. hp1: tai; NewRef: TReference;
  8408. begin
  8409. { Change:
  8410. subl/q $x,%reg1
  8411. movl/q %reg1,%reg2
  8412. To:
  8413. leal/q $-x(%reg1),%reg2
  8414. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8415. Breaks the dependency chain and potentially permits the removal of
  8416. a CMP instruction if one follows.
  8417. }
  8418. Result := False;
  8419. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8420. MatchOpType(taicpu(p),top_const,top_reg) and
  8421. GetNextInstruction(p, hp1) and
  8422. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8423. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8424. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8425. (
  8426. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8427. not (cs_opt_size in current_settings.optimizerswitches) or
  8428. (
  8429. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8430. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8431. )
  8432. ) then
  8433. begin
  8434. { Change the MOV instruction to a LEA instruction, and update the
  8435. first operand }
  8436. reference_reset(NewRef, 1, []);
  8437. NewRef.base := taicpu(p).oper[1]^.reg;
  8438. NewRef.scalefactor := 1;
  8439. NewRef.offset := -taicpu(p).oper[0]^.val;
  8440. taicpu(hp1).opcode := A_LEA;
  8441. taicpu(hp1).loadref(0, NewRef);
  8442. TransferUsedRegs(TmpUsedRegs);
  8443. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8444. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8445. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8446. begin
  8447. { Move what is now the LEA instruction to before the SUB instruction }
  8448. Asml.Remove(hp1);
  8449. Asml.InsertBefore(hp1, p);
  8450. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8451. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8452. p := hp1;
  8453. end
  8454. else
  8455. begin
  8456. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8457. RemoveCurrentP(p, hp1);
  8458. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8459. end;
  8460. Result := True;
  8461. end;
  8462. end;
  8463. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8464. begin
  8465. { we can skip all instructions not messing with the stack pointer }
  8466. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8467. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8468. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8469. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8470. ({(taicpu(hp1).ops=0) or }
  8471. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8472. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8473. ) and }
  8474. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8475. )
  8476. ) do
  8477. GetNextInstruction(hp1,hp1);
  8478. Result:=assigned(hp1);
  8479. end;
  8480. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8481. var
  8482. hp1, hp2, hp3, hp4, hp5: tai;
  8483. begin
  8484. Result:=false;
  8485. hp5:=nil;
  8486. { replace
  8487. leal(q) x(<stackpointer>),<stackpointer>
  8488. call procname
  8489. leal(q) -x(<stackpointer>),<stackpointer>
  8490. ret
  8491. by
  8492. jmp procname
  8493. but do it only on level 4 because it destroys stack back traces
  8494. }
  8495. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8496. MatchOpType(taicpu(p),top_ref,top_reg) and
  8497. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8498. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8499. { the -8 or -24 are not required, but bail out early if possible,
  8500. higher values are unlikely }
  8501. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8502. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8503. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8504. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8505. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8506. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8507. GetNextInstruction(p, hp1) and
  8508. { Take a copy of hp1 }
  8509. SetAndTest(hp1, hp4) and
  8510. { trick to skip label }
  8511. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8512. SkipSimpleInstructions(hp1) and
  8513. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8514. GetNextInstruction(hp1, hp2) and
  8515. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8516. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8517. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8518. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8519. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8520. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8521. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8522. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8523. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8524. GetNextInstruction(hp2, hp3) and
  8525. { trick to skip label }
  8526. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8527. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8528. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8529. SetAndTest(hp3,hp5) and
  8530. GetNextInstruction(hp3,hp3) and
  8531. MatchInstruction(hp3,A_RET,[S_NO])
  8532. )
  8533. ) and
  8534. (taicpu(hp3).ops=0) then
  8535. begin
  8536. taicpu(hp1).opcode := A_JMP;
  8537. taicpu(hp1).is_jmp := true;
  8538. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8539. RemoveCurrentP(p, hp4);
  8540. RemoveInstruction(hp2);
  8541. RemoveInstruction(hp3);
  8542. if Assigned(hp5) then
  8543. begin
  8544. AsmL.Remove(hp5);
  8545. ASmL.InsertBefore(hp5,hp1)
  8546. end;
  8547. Result:=true;
  8548. end;
  8549. end;
  8550. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8551. {$ifdef x86_64}
  8552. var
  8553. hp1, hp2, hp3, hp4, hp5: tai;
  8554. {$endif x86_64}
  8555. begin
  8556. Result:=false;
  8557. {$ifdef x86_64}
  8558. hp5:=nil;
  8559. { replace
  8560. push %rax
  8561. call procname
  8562. pop %rcx
  8563. ret
  8564. by
  8565. jmp procname
  8566. but do it only on level 4 because it destroys stack back traces
  8567. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8568. for all supported calling conventions
  8569. }
  8570. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8571. MatchOpType(taicpu(p),top_reg) and
  8572. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8573. GetNextInstruction(p, hp1) and
  8574. { Take a copy of hp1 }
  8575. SetAndTest(hp1, hp4) and
  8576. { trick to skip label }
  8577. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8578. SkipSimpleInstructions(hp1) and
  8579. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8580. GetNextInstruction(hp1, hp2) and
  8581. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8582. MatchOpType(taicpu(hp2),top_reg) and
  8583. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8584. GetNextInstruction(hp2, hp3) and
  8585. { trick to skip label }
  8586. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8587. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8588. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8589. SetAndTest(hp3,hp5) and
  8590. GetNextInstruction(hp3,hp3) and
  8591. MatchInstruction(hp3,A_RET,[S_NO])
  8592. )
  8593. ) and
  8594. (taicpu(hp3).ops=0) then
  8595. begin
  8596. taicpu(hp1).opcode := A_JMP;
  8597. taicpu(hp1).is_jmp := true;
  8598. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8599. RemoveCurrentP(p, hp4);
  8600. RemoveInstruction(hp2);
  8601. RemoveInstruction(hp3);
  8602. if Assigned(hp5) then
  8603. begin
  8604. AsmL.Remove(hp5);
  8605. ASmL.InsertBefore(hp5,hp1)
  8606. end;
  8607. Result:=true;
  8608. end;
  8609. {$endif x86_64}
  8610. end;
  8611. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8612. var
  8613. Value, RegName: string;
  8614. begin
  8615. Result:=false;
  8616. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8617. begin
  8618. case taicpu(p).oper[0]^.val of
  8619. 0:
  8620. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8621. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8622. begin
  8623. { change "mov $0,%reg" into "xor %reg,%reg" }
  8624. taicpu(p).opcode := A_XOR;
  8625. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8626. Result := True;
  8627. end;
  8628. $1..$FFFFFFFF:
  8629. begin
  8630. { Code size reduction by J. Gareth "Kit" Moreton }
  8631. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8632. case taicpu(p).opsize of
  8633. S_Q:
  8634. begin
  8635. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8636. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8637. { The actual optimization }
  8638. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8639. taicpu(p).changeopsize(S_L);
  8640. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8641. Result := True;
  8642. end;
  8643. else
  8644. { Do nothing };
  8645. end;
  8646. end;
  8647. -1:
  8648. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8649. if (cs_opt_size in current_settings.optimizerswitches) and
  8650. (taicpu(p).opsize <> S_B) and
  8651. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8652. begin
  8653. { change "mov $-1,%reg" into "or $-1,%reg" }
  8654. { NOTES:
  8655. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8656. - This operation creates a false dependency on the register, so only do it when optimising for size
  8657. - 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
  8658. }
  8659. taicpu(p).opcode := A_OR;
  8660. Result := True;
  8661. end;
  8662. end;
  8663. end;
  8664. end;
  8665. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8666. var
  8667. hp1: tai;
  8668. begin
  8669. { Detect:
  8670. andw x, %ax (0 <= x < $8000)
  8671. ...
  8672. movzwl %ax,%eax
  8673. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8674. }
  8675. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8676. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8677. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8678. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8679. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8680. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8681. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8682. begin
  8683. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8684. taicpu(hp1).opcode := A_CWDE;
  8685. taicpu(hp1).clearop(0);
  8686. taicpu(hp1).clearop(1);
  8687. taicpu(hp1).ops := 0;
  8688. { A change was made, but not with p, so move forward 1 }
  8689. p := tai(p.Next);
  8690. Result := True;
  8691. end;
  8692. end;
  8693. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8694. begin
  8695. Result := False;
  8696. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8697. Exit;
  8698. { Convert:
  8699. movswl %ax,%eax -> cwtl
  8700. movslq %eax,%rax -> cdqe
  8701. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8702. refer to the same opcode and depends only on the assembler's
  8703. current operand-size attribute. [Kit]
  8704. }
  8705. with taicpu(p) do
  8706. case opsize of
  8707. S_WL:
  8708. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8709. begin
  8710. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8711. opcode := A_CWDE;
  8712. clearop(0);
  8713. clearop(1);
  8714. ops := 0;
  8715. Result := True;
  8716. end;
  8717. {$ifdef x86_64}
  8718. S_LQ:
  8719. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8720. begin
  8721. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8722. opcode := A_CDQE;
  8723. clearop(0);
  8724. clearop(1);
  8725. ops := 0;
  8726. Result := True;
  8727. end;
  8728. {$endif x86_64}
  8729. else
  8730. ;
  8731. end;
  8732. end;
  8733. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8734. var
  8735. hp1: tai;
  8736. begin
  8737. { Detect:
  8738. shr x, %ax (x > 0)
  8739. ...
  8740. movzwl %ax,%eax
  8741. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8742. }
  8743. Result := False;
  8744. if MatchOpType(taicpu(p), top_const, top_reg) and
  8745. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8746. (taicpu(p).oper[0]^.val > 0) and
  8747. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8748. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8749. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8750. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8751. begin
  8752. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8753. taicpu(hp1).opcode := A_CWDE;
  8754. taicpu(hp1).clearop(0);
  8755. taicpu(hp1).clearop(1);
  8756. taicpu(hp1).ops := 0;
  8757. { A change was made, but not with p, so move forward 1 }
  8758. p := tai(p.Next);
  8759. Result := True;
  8760. end;
  8761. end;
  8762. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8763. begin
  8764. Result:=false;
  8765. { change "cmp $0, %reg" to "test %reg, %reg" }
  8766. if MatchOpType(taicpu(p),top_const,top_reg) and
  8767. (taicpu(p).oper[0]^.val = 0) then
  8768. begin
  8769. taicpu(p).opcode := A_TEST;
  8770. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8771. Result:=true;
  8772. end;
  8773. end;
  8774. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8775. var
  8776. IsTestConstX : Boolean;
  8777. hp1,hp2 : tai;
  8778. begin
  8779. Result:=false;
  8780. { removes the line marked with (x) from the sequence
  8781. and/or/xor/add/sub/... $x, %y
  8782. test/or %y, %y | test $-1, %y (x)
  8783. j(n)z _Label
  8784. as the first instruction already adjusts the ZF
  8785. %y operand may also be a reference }
  8786. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8787. MatchOperand(taicpu(p).oper[0]^,-1);
  8788. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8789. GetLastInstruction(p, hp1) and
  8790. (tai(hp1).typ = ait_instruction) and
  8791. GetNextInstruction(p,hp2) and
  8792. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8793. case taicpu(hp1).opcode Of
  8794. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8795. begin
  8796. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8797. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8798. { and in case of carry for A(E)/B(E)/C/NC }
  8799. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8800. ((taicpu(hp1).opcode <> A_ADD) and
  8801. (taicpu(hp1).opcode <> A_SUB))) then
  8802. begin
  8803. RemoveCurrentP(p, hp2);
  8804. Result:=true;
  8805. Exit;
  8806. end;
  8807. end;
  8808. A_SHL, A_SAL, A_SHR, A_SAR:
  8809. begin
  8810. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8811. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8812. { therefore, it's only safe to do this optimization for }
  8813. { shifts by a (nonzero) constant }
  8814. (taicpu(hp1).oper[0]^.typ = top_const) and
  8815. (taicpu(hp1).oper[0]^.val <> 0) and
  8816. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8817. { and in case of carry for A(E)/B(E)/C/NC }
  8818. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8819. begin
  8820. RemoveCurrentP(p, hp2);
  8821. Result:=true;
  8822. Exit;
  8823. end;
  8824. end;
  8825. A_DEC, A_INC, A_NEG:
  8826. begin
  8827. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8828. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8829. { and in case of carry for A(E)/B(E)/C/NC }
  8830. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8831. begin
  8832. RemoveCurrentP(p, hp2);
  8833. Result:=true;
  8834. Exit;
  8835. end;
  8836. end
  8837. else
  8838. ;
  8839. end; { case }
  8840. { change "test $-1,%reg" into "test %reg,%reg" }
  8841. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8842. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8843. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8844. if MatchInstruction(p, A_OR, []) and
  8845. { Can only match if they're both registers }
  8846. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8847. begin
  8848. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8849. taicpu(p).opcode := A_TEST;
  8850. { No need to set Result to True, as we've done all the optimisations we can }
  8851. end;
  8852. end;
  8853. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8854. var
  8855. hp1,hp3 : tai;
  8856. {$ifndef x86_64}
  8857. hp2 : taicpu;
  8858. {$endif x86_64}
  8859. begin
  8860. Result:=false;
  8861. hp3:=nil;
  8862. {$ifndef x86_64}
  8863. { don't do this on modern CPUs, this really hurts them due to
  8864. broken call/ret pairing }
  8865. if (current_settings.optimizecputype < cpu_Pentium2) and
  8866. not(cs_create_pic in current_settings.moduleswitches) and
  8867. GetNextInstruction(p, hp1) and
  8868. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8869. MatchOpType(taicpu(hp1),top_ref) and
  8870. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8871. begin
  8872. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8873. InsertLLItem(p.previous, p, hp2);
  8874. taicpu(p).opcode := A_JMP;
  8875. taicpu(p).is_jmp := true;
  8876. RemoveInstruction(hp1);
  8877. Result:=true;
  8878. end
  8879. else
  8880. {$endif x86_64}
  8881. { replace
  8882. call procname
  8883. ret
  8884. by
  8885. jmp procname
  8886. but do it only on level 4 because it destroys stack back traces
  8887. else if the subroutine is marked as no return, remove the ret
  8888. }
  8889. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8890. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8891. GetNextInstruction(p, hp1) and
  8892. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8893. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8894. SetAndTest(hp1,hp3) and
  8895. GetNextInstruction(hp1,hp1) and
  8896. MatchInstruction(hp1,A_RET,[S_NO])
  8897. )
  8898. ) and
  8899. (taicpu(hp1).ops=0) then
  8900. begin
  8901. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8902. { we might destroy stack alignment here if we do not do a call }
  8903. (target_info.stackalign<=sizeof(SizeUInt)) then
  8904. begin
  8905. taicpu(p).opcode := A_JMP;
  8906. taicpu(p).is_jmp := true;
  8907. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8908. end
  8909. else
  8910. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8911. RemoveInstruction(hp1);
  8912. if Assigned(hp3) then
  8913. begin
  8914. AsmL.Remove(hp3);
  8915. AsmL.InsertBefore(hp3,p)
  8916. end;
  8917. Result:=true;
  8918. end;
  8919. end;
  8920. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8921. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8922. begin
  8923. case OpSize of
  8924. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8925. Result := (Val <= $FF) and (Val >= -128);
  8926. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8927. Result := (Val <= $FFFF) and (Val >= -32768);
  8928. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8929. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8930. else
  8931. Result := True;
  8932. end;
  8933. end;
  8934. var
  8935. hp1, hp2 : tai;
  8936. SizeChange: Boolean;
  8937. PreMessage: string;
  8938. begin
  8939. Result := False;
  8940. if (taicpu(p).oper[0]^.typ = top_reg) and
  8941. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8942. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8943. begin
  8944. { Change (using movzbl %al,%eax as an example):
  8945. movzbl %al, %eax movzbl %al, %eax
  8946. cmpl x, %eax testl %eax,%eax
  8947. To:
  8948. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8949. movzbl %al, %eax movzbl %al, %eax
  8950. Smaller instruction and minimises pipeline stall as the CPU
  8951. doesn't have to wait for the register to get zero-extended. [Kit]
  8952. Also allow if the smaller of the two registers is being checked,
  8953. as this still removes the false dependency.
  8954. }
  8955. if
  8956. (
  8957. (
  8958. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8959. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8960. ) or (
  8961. { If MatchOperand returns True, they must both be registers }
  8962. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8963. )
  8964. ) and
  8965. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8966. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8967. begin
  8968. 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);
  8969. asml.Remove(hp1);
  8970. asml.InsertBefore(hp1, p);
  8971. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8972. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8973. begin
  8974. taicpu(hp1).opcode := A_TEST;
  8975. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8976. end;
  8977. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8978. case taicpu(p).opsize of
  8979. S_BW, S_BL:
  8980. begin
  8981. SizeChange := taicpu(hp1).opsize <> S_B;
  8982. taicpu(hp1).changeopsize(S_B);
  8983. end;
  8984. S_WL:
  8985. begin
  8986. SizeChange := taicpu(hp1).opsize <> S_W;
  8987. taicpu(hp1).changeopsize(S_W);
  8988. end
  8989. else
  8990. InternalError(2020112701);
  8991. end;
  8992. UpdateUsedRegs(tai(p.Next));
  8993. { Check if the register is used aferwards - if not, we can
  8994. remove the movzx instruction completely }
  8995. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8996. begin
  8997. { Hp1 is a better position than p for debugging purposes }
  8998. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8999. RemoveCurrentp(p, hp1);
  9000. Result := True;
  9001. end;
  9002. if SizeChange then
  9003. DebugMsg(SPeepholeOptimization + PreMessage +
  9004. 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)
  9005. else
  9006. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9007. Exit;
  9008. end;
  9009. { Change (using movzwl %ax,%eax as an example):
  9010. movzwl %ax, %eax
  9011. movb %al, (dest) (Register is smaller than read register in movz)
  9012. To:
  9013. movb %al, (dest) (Move one back to avoid a false dependency)
  9014. movzwl %ax, %eax
  9015. }
  9016. if (taicpu(hp1).opcode = A_MOV) and
  9017. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9018. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9019. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9020. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9021. begin
  9022. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9023. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9024. asml.Remove(hp1);
  9025. asml.InsertBefore(hp1, p);
  9026. if taicpu(hp1).oper[1]^.typ = top_reg then
  9027. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9028. { Check if the register is used aferwards - if not, we can
  9029. remove the movzx instruction completely }
  9030. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9031. begin
  9032. { Hp1 is a better position than p for debugging purposes }
  9033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9034. RemoveCurrentp(p, hp1);
  9035. Result := True;
  9036. end;
  9037. Exit;
  9038. end;
  9039. end;
  9040. {$ifdef x86_64}
  9041. { Code size reduction by J. Gareth "Kit" Moreton }
  9042. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  9043. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  9044. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  9045. then
  9046. begin
  9047. { Has 64-bit register name and opcode suffix }
  9048. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  9049. { The actual optimization }
  9050. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9051. if taicpu(p).opsize = S_BQ then
  9052. taicpu(p).changeopsize(S_BL)
  9053. else
  9054. taicpu(p).changeopsize(S_WL);
  9055. DebugMsg(SPeepholeOptimization + PreMessage +
  9056. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  9057. end;
  9058. {$endif}
  9059. end;
  9060. {$ifdef x86_64}
  9061. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9062. var
  9063. PreMessage, RegName: string;
  9064. begin
  9065. { Code size reduction by J. Gareth "Kit" Moreton }
  9066. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9067. as this removes the REX prefix }
  9068. Result := False;
  9069. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9070. Exit;
  9071. if taicpu(p).oper[0]^.typ <> top_reg then
  9072. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9073. InternalError(2018011500);
  9074. case taicpu(p).opsize of
  9075. S_Q:
  9076. begin
  9077. 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
  9078. begin
  9079. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9080. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9081. { The actual optimization }
  9082. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9083. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9084. taicpu(p).changeopsize(S_L);
  9085. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9086. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  9087. end;
  9088. end;
  9089. else
  9090. ;
  9091. end;
  9092. end;
  9093. {$endif}
  9094. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9095. var
  9096. OperIdx: Integer;
  9097. begin
  9098. for OperIdx := 0 to p.ops - 1 do
  9099. if p.oper[OperIdx]^.typ = top_ref then
  9100. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9101. end;
  9102. end.