aoptobj.pas 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  1. {
  2. Copyright (c) 1998-2004 by Jonas Maebe, member of the Free Pascal
  3. Development Team
  4. This unit contains the processor independent assembler optimizer
  5. object, base for the dataflow analyzer, peepholeoptimizer and
  6. common subexpression elimination objects.
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2 of the License, or
  10. (at your option) any later version.
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with this program; if not, write to the Free Software
  17. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. ****************************************************************************
  19. }
  20. Unit AoptObj;
  21. { $define DEBUG_AOPTOBJ}
  22. { $define DEBUG_JUMP}
  23. {$i fpcdefs.inc}
  24. {$if not defined(JVM) and not defined(WASM)}
  25. {$define CPU_SUPPORTS_OPT_COND_JUMP}
  26. {$endif}
  27. { general, processor independent objects for use by the assembler optimizer }
  28. Interface
  29. uses
  30. globtype,
  31. aasmbase,aasmcpu,aasmtai,aasmdata,
  32. cclasses,
  33. cgbase,cgutils,
  34. cpubase,
  35. aoptbase,aoptcpub,aoptda;
  36. { ************************************************************************* }
  37. { ********************************* Constants ***************************** }
  38. { ************************************************************************* }
  39. Const
  40. {Possible register content types}
  41. con_Unknown = 0;
  42. con_ref = 1;
  43. con_const = 2;
  44. {***************** Types ****************}
  45. Type
  46. { ************************************************************************* }
  47. { ************************* Some general type definitions ***************** }
  48. { ************************************************************************* }
  49. TRefCompare = Function(const r1, r2: TReference): Boolean;
  50. //!!! FIXME
  51. TRegArray = Array[byte] of tsuperregister;
  52. TRegSet = tcpuregisterset;
  53. { possible actions on an operand: read, write or modify (= read & write) }
  54. TOpAction = (OpAct_Read, OpAct_Write, OpAct_Modify, OpAct_Unknown);
  55. { ************************************************************************* }
  56. { * Object to hold information on which regiters are in use and which not * }
  57. { ************************************************************************* }
  58. { TUsedRegs }
  59. TUsedRegs = class
  60. Constructor create(aTyp : TRegisterType);
  61. Constructor create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  62. Destructor Destroy;override;
  63. Procedure Clear;
  64. { update the info with the pairegalloc objects coming after
  65. p }
  66. procedure Update(p: Tai; IgnoreNewAllocs: Boolean=false);
  67. { is Reg currently in use }
  68. Function IsUsed(Reg: TRegister): Boolean; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  69. { get all the currently used registers }
  70. Function GetUsedRegs: TRegSet; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  71. { outputs the current set }
  72. Procedure Dump(var t : text);
  73. Private
  74. Typ : TRegisterType;
  75. UsedRegs: TRegSet;
  76. End;
  77. { ************************************************************************* }
  78. { ******************* Contents of the integer registers ******************* }
  79. { ************************************************************************* }
  80. { size of the integer that holds the state number of a register. Can be any }
  81. { integer type, so it can be changed to reduce the size of the TContent }
  82. { structure or to improve alignment }
  83. TStateInt = Byte;
  84. TContent = Record
  85. { start and end of block instructions that defines the }
  86. { content of this register. If Typ = con_const, then }
  87. { Longint(StartMod) = value of the constant) }
  88. StartMod: Tai;
  89. { starts at 0, gets increased everytime the register is }
  90. { written to }
  91. WState: TStateInt;
  92. { starts at 0, gets increased everytime the register is read }
  93. { from }
  94. RState: TStateInt;
  95. { how many instructions starting with StarMod does the block }
  96. { consist of }
  97. NrOfMods: Byte;
  98. { the type of the content of the register: unknown, memory }
  99. { (variable) or constant }
  100. Typ: Byte;
  101. End;
  102. //!!! FIXME
  103. TRegContent = Array[byte] Of TContent;
  104. { ************************************************************************** }
  105. { information object with the contents of every register. Every Tai object }
  106. { gets one of these assigned: a pointer to it is stored in the OptInfo field }
  107. { ************************************************************************** }
  108. { TPaiProp }
  109. TPaiProp = class(TAoptBaseCpu)
  110. Regs: TRegContent;
  111. { can this instruction be removed? }
  112. CanBeRemoved: Boolean;
  113. Constructor create; reintroduce;
  114. { checks the whole sequence of which (so regs[which].StartMod and and }
  115. { the next NrOfMods Tai objects) to see whether Reg is used somewhere, }
  116. { without it being loaded with something else first }
  117. Function RegInSequence(Reg, which: TRegister): Boolean;
  118. { destroy the contents of a register, as well as those whose contents }
  119. { are based on those of that register }
  120. Procedure DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  121. TInstrSinceLastMod);
  122. { if the contents of WhichReg (can be R_NO in case of a constant) are }
  123. { written to memory at the location Ref, the contents of the registers }
  124. { that depend on Ref have to be destroyed }
  125. Procedure DestroyRefs(Const Ref: TReference; WhichReg: TRegister; var
  126. InstrSinceLastMod: TInstrSinceLastMod);
  127. { an instruction reads from operand o }
  128. Procedure ReadOp(const o:toper);
  129. { an instruction reads from reference Ref }
  130. Procedure ReadRef(Ref: PReference);
  131. { an instruction reads from register Reg }
  132. Procedure ReadReg(Reg: TRegister);
  133. { an instruction writes/modifies operand o and this has special }
  134. { side-effects or modifies the contents in such a way that we can't }
  135. { simply add this instruction to the sequence of instructions that }
  136. { describe the contents of the operand, so destroy it }
  137. Procedure DestroyOp(const o:Toper; var InstrSinceLastMod:
  138. TInstrSinceLastMod);
  139. { destroy the contents of all registers }
  140. Procedure DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  141. { a register's contents are modified, but not destroyed (the new value
  142. depends on the old one) }
  143. Procedure ModifyReg(reg: TRegister; var InstrSinceLastMod:
  144. TInstrSinceLastMod);
  145. { an operand's contents are modified, but not destroyed (the new value
  146. depends on the old one) }
  147. Procedure ModifyOp(const oper: TOper; var InstrSinceLastMod:
  148. TInstrSinceLastMod);
  149. { increase the write state of a register (call every time a register is
  150. written to) }
  151. Procedure IncWState(Reg: TRegister);
  152. { increase the read state of a register (call every time a register is }
  153. { read from) }
  154. Procedure IncRState(Reg: TRegister);
  155. { get the write state of a register }
  156. Function GetWState(Reg: TRegister): TStateInt;
  157. { get the read state of a register }
  158. Function GetRState(Reg: TRegister): TStateInt;
  159. { get the type of contents of a register }
  160. Function GetRegContentType(Reg: TRegister): Byte;
  161. Destructor Done;
  162. Private
  163. Procedure IncState(var s: TStateInt);
  164. { returns whether the reference Ref is used somewhere in the loading }
  165. { sequence Content }
  166. class function RefInSequence(Const Ref: TReference; Content: TContent;
  167. RefsEq: TRefCompare): Boolean; static;
  168. { returns whether the instruction P reads from and/or writes }
  169. { to Reg }
  170. class function RefInInstruction(Const Ref: TReference; p: Tai;
  171. RefsEq: TRefCompare): Boolean; static;
  172. { returns whether two references with at least one pointing to an array }
  173. { may point to the same memory location }
  174. End;
  175. { ************************************************************************* }
  176. { ************************ Label information ****************************** }
  177. { ************************************************************************* }
  178. TLabelTableItem = Record
  179. PaiObj: Tai;
  180. End;
  181. TLabelTable = Array Of TLabelTableItem;
  182. PLabelInfo = ^TLabelInfo;
  183. TLabelInfo = Record
  184. { the highest and lowest label number occurring in the current code }
  185. { fragment }
  186. LowLabel, HighLabel: longint;
  187. LabelDif: cardinal;
  188. { table that contains the addresses of the Pai_Label objects associated
  189. with each label number }
  190. LabelTable: TLabelTable;
  191. End;
  192. { ************************************************************************* }
  193. { ********** General optimizer object, used to derive others from ********* }
  194. { ************************************************************************* }
  195. TAllUsedRegs = array[TRegisterType] of TUsedRegs;
  196. { TAOptObj }
  197. TAOptObj = class(TAoptBaseCpu)
  198. { the PAasmOutput list this optimizer instance works on }
  199. AsmL: TAsmList;
  200. { The labelinfo record contains the addresses of the Tai objects }
  201. { that are labels, how many labels there are and the min and max }
  202. { label numbers }
  203. LabelInfo: PLabelInfo;
  204. { Start and end of the block that is currently being optimized, and
  205. a selected start point after the start of the block }
  206. BlockStart, BlockEnd, StartPoint: Tai;
  207. DFA: TAOptDFA;
  208. UsedRegs: TAllUsedRegs;
  209. { _AsmL is the PAasmOutpout list that has to be optimized, }
  210. { _BlockStart and _BlockEnd the start and the end of the block }
  211. { that has to be optimized and _LabelInfo a pointer to a }
  212. { TLabelInfo record }
  213. Constructor create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  214. _LabelInfo: PLabelInfo); virtual; reintroduce;
  215. Destructor Destroy;override;
  216. { processor independent methods }
  217. Procedure CreateUsedRegs(var regs: TAllUsedRegs);
  218. Procedure ClearUsedRegs;
  219. Procedure UpdateUsedRegs(p : Tai); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  220. class procedure UpdateUsedRegs(var Regs: TAllUsedRegs; p: Tai); static;
  221. { UpdateUsedRegsBetween updates the given TUsedRegs from p1 to p2 exclusive, calling GetNextInstruction
  222. to move between instructions and sending p1.Next to UpdateUsedRegs }
  223. class procedure UpdateUsedRegsBetween(var Regs: TAllUsedRegs; p1, p2: Tai); static;
  224. { If UpdateUsedRegsAndOptimize has read ahead, the result is one before
  225. the next valid entry (so "p.Next" returns what's expected). If no
  226. reading ahead happened, then the result is equal to p. }
  227. function UpdateUsedRegsAndOptimize(p : Tai): Tai;
  228. Function CopyUsedRegs(var dest : TAllUsedRegs) : boolean;
  229. procedure RestoreUsedRegs(const Regs : TAllUsedRegs);
  230. procedure TransferUsedRegs(var dest: TAllUsedRegs);
  231. class procedure ReleaseUsedRegs(const regs : TAllUsedRegs); static;
  232. class function RegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs) : boolean; static;
  233. class procedure IncludeRegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  234. class procedure ExcludeRegFromUsedRegs(reg: TRegister;var regs : TAllUsedRegs); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  235. class function GetAllocationString(const regs : TAllUsedRegs) : string; static;
  236. { returns true if the label L is found between hp and the next }
  237. { instruction }
  238. class function FindLabel(L: TasmLabel; Var hp: Tai): Boolean; static;
  239. { returns true if p is after p2 or before }
  240. { and the number of instructions between p and p2 in out variable count }
  241. function GetInstructionDistance(p,p2: Tai; out count: ASizeInt) : boolean;
  242. { inserts new_one between prev and foll in AsmL }
  243. Procedure InsertLLItem(prev, foll, new_one: TLinkedListItem);
  244. { If P is a Tai object releveant to the optimizer, P is returned
  245. If it is not relevant tot he optimizer, the first object after P
  246. that is relevant is returned }
  247. class function SkipHead(P: Tai): Tai; static;
  248. { returns true if the operands o1 and o2 are completely equal }
  249. class function OpsEqual(const o1,o2:toper): Boolean; static;
  250. { Returns the next ait_alloc object with ratype ra_alloc for
  251. Reg is found in the block
  252. of Tai's starting with StartPai and ending with the next "real"
  253. instruction. If none is found, it returns
  254. nil
  255. }
  256. class function FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc; static;
  257. { Returns the last ait_alloc object with ratype ra_alloc for
  258. Reg is found in the block
  259. of Tai's starting with StartPai and ending with the next "real"
  260. instruction. If none is found, it returns
  261. nil
  262. }
  263. class function FindRegAllocBackward(Reg : TRegister; StartPai : Tai) : tai_regalloc; static;
  264. { Returns the next ait_alloc object with ratype ra_dealloc
  265. for Reg which is found in the block of Tai's starting with StartPai
  266. and ending with the next "real" instruction. If none is found, it returns
  267. nil }
  268. class function FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc; static;
  269. { allocates register reg between (and including) instructions p1 and p2
  270. the type of p1 and p2 must not be in SkipInstr }
  271. procedure AllocRegBetween(reg : tregister; p1,p2 : tai; var initialusedregs : TAllUsedRegs);
  272. { reg used after p? }
  273. function RegUsedAfterInstruction(reg: Tregister; p: tai; var AllUsedRegs: TAllUsedRegs): Boolean;
  274. { returns true if reg reaches it's end of life at p, this means it is either
  275. reloaded with a new value or it is deallocated afterwards }
  276. function RegEndOfLife(reg: TRegister;p: taicpu): boolean;
  277. { Returns the next ait_tempalloc object with allocation=false
  278. for Offset which is found in the block of Tai's starting with StartPai
  279. and ending with the next "real" instruction. If none is found, it returns
  280. nil }
  281. class function FindTempDeAlloc(Offset: ASizeInt; StartPai: Tai): tai_tempalloc;
  282. { removes p from asml, updates registers and replaces it by a valid value, if this is the case true is returned }
  283. function RemoveCurrentP(var p : tai): boolean;
  284. { removes p from asml, updates registers and replaces p with hp1 (if the next instruction was known beforehand) }
  285. procedure RemoveCurrentP(var p: tai; const hp1: tai); inline;
  286. { removes hp from asml then frees it }
  287. procedure RemoveInstruction(const hp: tai); inline;
  288. { traces sucessive jumps to their final destination and sets it, e.g.
  289. je l1 je l3
  290. <code> <code>
  291. l1: becomes l1:
  292. je l2 je l3
  293. <code> <code>
  294. l2: l2:
  295. jmp l3 jmp l3
  296. the level parameter denotes how deeep we have already followed the jump,
  297. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  298. function GetFinalDestination(hp: taicpu; level: longint): boolean;
  299. function getlabelwithsym(sym: tasmlabel): tai;
  300. { Removes an instruction following hp1 (possibly with reg.deallocations in between),
  301. if its opcode is A_NOP. }
  302. procedure RemoveDelaySlot(hp1: tai);
  303. { peephole optimizer }
  304. procedure PrePeepHoleOpts; virtual;
  305. procedure PeepHoleOptPass1; virtual;
  306. procedure PeepHoleOptPass2; virtual;
  307. procedure PostPeepHoleOpts; virtual;
  308. { processor dependent methods }
  309. // if it returns true, perform a "continue"
  310. function PrePeepHoleOptsCpu(var p: tai): boolean; virtual;
  311. function PeepHoleOptPass1Cpu(var p: tai): boolean; virtual;
  312. function PeepHoleOptPass2Cpu(var p: tai): boolean; virtual;
  313. function PostPeepHoleOptsCpu(var p: tai): boolean; virtual;
  314. { Output debug message to console - null function if EXTDEBUG is not defined }
  315. class procedure DebugWrite(Message: string); static; inline;
  316. { Converts a conditional jump into an unconditional jump. Only call this
  317. procedure on an instruction that you already know is a conditional jump }
  318. procedure MakeUnconditional(p: taicpu); virtual;
  319. { Removes all instructions between an unconditional jump and the next label.
  320. Returns True if a jump in between was removed (as it may open up new
  321. optimisations if the label appeared earlier in the stream) }
  322. function RemoveDeadCodeAfterJump(p: tai): Boolean;
  323. { If hp is a label, strip it if its reference count is zero. Repeat until
  324. a non-label is found, or a label with a non-zero reference count.
  325. True is returned if something was stripped }
  326. function StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  327. { Strips a label and any aligns that appear before it (if hp points to
  328. them rather than the label). Only call this procedure on a label that
  329. you already know is no longer referenced }
  330. procedure StripLabelFast(hp: tai);
  331. { Checks and removes "jmp @@lbl; @lbl". Returns True if the jump was removed }
  332. function CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  333. { If a group of labels are clustered, change the jump to point to the last one that is still referenced }
  334. function CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  335. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  336. function OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  337. {$endif}
  338. { Function to determine if the jump optimisations can be performed }
  339. function CanDoJumpOpts: Boolean; virtual;
  340. { Jump/label optimisation entry method }
  341. function DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  342. { Attempts to reconfigure the Regallocs and Regdeallocs before p1 and
  343. after p2 so Reg is no longer allocated between them. Returns True if
  344. the register is no longer allocated at p1 }
  345. function TryRemoveRegAlloc(const Reg: TRegister; p1, p2: tai): Boolean;
  346. { insert debug comments about which registers are read and written by
  347. each instruction. Useful for debugging the InstructionLoadsFromReg and
  348. other similar functions. }
  349. procedure Debug_InsertInstrRegisterDependencyInfo; virtual;
  350. protected
  351. { Set to True if this is the second time that Pass 1 is being run }
  352. NotFirstIteration: Boolean;
  353. { Actually updates a used register }
  354. class procedure UpdateReg(var Regs : TAllUsedRegs; p: tai_regalloc); static; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  355. private
  356. procedure DebugMsg(const s: string; p: tai);
  357. { Utilty function for the UpdateUsedRegs family of methods }
  358. class function GetNextRegUpdatePoint(var p : Tai; pTerm: tai): Boolean; static;
  359. End;
  360. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  361. { Returns a pointer to the operand that contains the destination label }
  362. function JumpTargetOp(ai: taicpu): poper;
  363. { Returns True if hp is any jump to a label }
  364. function IsJumpToLabel(hp: taicpu): boolean;
  365. { Returns True if hp is an unconditional jump to a label }
  366. function IsJumpToLabelUncond(hp: taicpu): boolean;
  367. { ***************************** Implementation **************************** }
  368. Implementation
  369. uses
  370. cutils,
  371. globals,
  372. verbose,
  373. aoptutils,
  374. aasmcfi,
  375. {$if defined(ARM)}
  376. cpuinfo,
  377. {$endif defined(ARM)}
  378. procinfo;
  379. {$ifdef DEBUG_AOPTOBJ}
  380. const
  381. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  382. {$else DEBUG_AOPTOBJ}
  383. { Empty strings help the optimizer to remove string concatenations that won't
  384. ever appear to the user on release builds. [Kit] }
  385. const
  386. SPeepholeOptimization = '';
  387. {$endif DEBUG_AOPTOBJ}
  388. function JumpTargetOp(ai: taicpu): poper; {$IFDEF USEINLINE}inline;{$ENDIF}
  389. begin
  390. {$if defined(MIPS) or defined(riscv64) or defined(riscv32) or defined(xtensa) or defined(loongarch64)}
  391. { Branches of above archs can have 1,2 or 3 operands, target label is the last one. }
  392. result:=ai.oper[ai.ops-1];
  393. {$elseif defined(SPARC64)}
  394. if ai.ops=2 then
  395. result:=ai.oper[1]
  396. else
  397. result:=ai.oper[0];
  398. {$else MIPS}
  399. result:=ai.oper[0];
  400. {$endif}
  401. end;
  402. { ************************************************************************* }
  403. { ******************************** TUsedRegs ****************************** }
  404. { ************************************************************************* }
  405. Constructor TUsedRegs.create(aTyp : TRegisterType);
  406. Begin
  407. Typ:=aTyp;
  408. UsedRegs := [];
  409. End;
  410. Constructor TUsedRegs.create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  411. Begin
  412. Typ:=aTyp;
  413. UsedRegs := _RegSet;
  414. End;
  415. {
  416. updates UsedRegs with the RegAlloc Information coming after P
  417. }
  418. Procedure TUsedRegs.Update(p: Tai;IgnoreNewAllocs : Boolean = false);
  419. Begin
  420. { this code is normally not used because updating the register allocation information is done in
  421. TAOptObj.UpdateUsedRegs for speed reasons }
  422. repeat
  423. while assigned(p) and
  424. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  425. (p.typ = ait_label) or
  426. ((p.typ = ait_marker) and
  427. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  428. p := tai(p.next);
  429. while assigned(p) and
  430. (p.typ=ait_RegAlloc) Do
  431. begin
  432. if (getregtype(tai_regalloc(p).reg) = typ) then
  433. begin
  434. case tai_regalloc(p).ratype of
  435. ra_alloc :
  436. if not(IgnoreNewAllocs) then
  437. Include(UsedRegs, getsupreg(tai_regalloc(p).reg));
  438. ra_dealloc :
  439. Exclude(UsedRegs, getsupreg(tai_regalloc(p).reg));
  440. else
  441. ;
  442. end;
  443. end;
  444. p := tai(p.next);
  445. end;
  446. until not(assigned(p)) or
  447. (not(p.typ in SkipInstr) and
  448. not((p.typ = ait_label) and
  449. labelCanBeSkipped(tai_label(p))));
  450. End;
  451. Function TUsedRegs.IsUsed(Reg: TRegister): Boolean; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  452. Begin
  453. IsUsed := (getregtype(Reg)=Typ) and (getsupreg(Reg) in UsedRegs);
  454. End;
  455. Function TUsedRegs.GetUsedRegs: TRegSet; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  456. Begin
  457. GetUsedRegs := UsedRegs;
  458. End;
  459. procedure TUsedRegs.Dump(var t: text);
  460. var
  461. i: dword;
  462. begin
  463. write(t,Typ,' ');
  464. for i:=low(TRegSet) to high(TRegSet) do
  465. if i in UsedRegs then
  466. write(t,i,' ');
  467. writeln(t);
  468. end;
  469. Destructor TUsedRegs.Destroy;
  470. Begin
  471. inherited destroy;
  472. end;
  473. procedure TUsedRegs.Clear;
  474. begin
  475. UsedRegs := [];
  476. end;
  477. { ************************************************************************* }
  478. { **************************** TPaiProp *********************************** }
  479. { ************************************************************************* }
  480. Constructor TPaiProp.Create;
  481. Begin
  482. {!!!!!!
  483. UsedRegs.Init;
  484. CondRegs.init;
  485. }
  486. { DirFlag: TFlagContents; I386 specific}
  487. End;
  488. Function TPaiProp.RegInSequence(Reg, which: TRegister): Boolean;
  489. {
  490. Var p: Tai;
  491. RegsChecked: TRegSet;
  492. content: TContent;
  493. Counter: Byte;
  494. TmpResult: Boolean;
  495. }
  496. begin
  497. Result:=False; { unimplemented }
  498. (*!!!!!!!!!!1
  499. RegsChecked := [];
  500. content := regs[which];
  501. p := content.StartMod;
  502. TmpResult := False;
  503. Counter := 1;
  504. While Not(TmpResult) And
  505. (Counter <= Content.NrOfMods) Do
  506. Begin
  507. If IsLoadMemReg(p) Then
  508. With PInstr(p)^.oper[LoadSrc]^.ref^ Do
  509. If (Base = ProcInfo.FramePointer)
  510. {$ifdef cpurefshaveindexreg}
  511. And (Index = R_NO)
  512. {$endif cpurefshaveindexreg} Then
  513. Begin
  514. RegsChecked := RegsChecked +
  515. [RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg)];
  516. If Reg = RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg) Then
  517. Break;
  518. End
  519. Else
  520. Begin
  521. If (Base = Reg) And
  522. Not(Base In RegsChecked)
  523. Then TmpResult := True;
  524. {$ifdef cpurefshaveindexreg}
  525. If Not(TmpResult) And
  526. (Index = Reg) And
  527. Not(Index In RegsChecked)
  528. Then TmpResult := True;
  529. {$Endif cpurefshaveindexreg}
  530. End
  531. Else TmpResult := RegInInstruction(Reg, p);
  532. Inc(Counter);
  533. GetNextInstruction(p,p)
  534. End;
  535. RegInSequence := TmpResult
  536. *)
  537. End;
  538. Procedure TPaiProp.DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  539. TInstrSinceLastMod);
  540. { Destroys the contents of the register Reg in the PPaiProp p1, as well as }
  541. { the contents of registers are loaded with a memory location based on Reg }
  542. {
  543. Var TmpWState, TmpRState: Byte;
  544. Counter: TRegister;
  545. }
  546. Begin
  547. {!!!!!!!
  548. Reg := RegMaxSize(Reg);
  549. If (Reg in [LoGPReg..HiGPReg]) Then
  550. For Counter := LoGPReg to HiGPReg Do
  551. With Regs[Counter] Do
  552. If (Counter = reg) Or
  553. ((Typ = Con_Ref) And
  554. RegInSequence(Reg, Counter)) Then
  555. Begin
  556. InstrSinceLastMod[Counter] := 0;
  557. IncWState(Counter);
  558. TmpWState := GetWState(Counter);
  559. TmpRState := GetRState(Counter);
  560. FillChar(Regs[Counter], SizeOf(TContent), 0);
  561. WState := TmpWState;
  562. RState := TmpRState
  563. End
  564. }
  565. End;
  566. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  567. Begin
  568. Result:=False; { unimplemented }
  569. (*!!!!!!!!!!
  570. ArrayRefsEq := (R1.Offset+R1.OffsetFixup = R2.Offset+R2.OffsetFixup) And
  571. {$ifdef refsHaveSegmentReg}
  572. (R1.Segment = R2.Segment) And
  573. {$endif}
  574. (R1.Base = R2.Base) And
  575. (R1.Symbol=R2.Symbol);
  576. *)
  577. End;
  578. Procedure TPaiProp.DestroyRefs(Const Ref: TReference; WhichReg: TRegister;
  579. var InstrSinceLastMod: TInstrSinceLastMod);
  580. { destroys all registers which possibly contain a reference to Ref, WhichReg }
  581. { is the register whose contents are being written to memory (if this proc }
  582. { is called because of a "mov?? %reg, (mem)" instruction) }
  583. {
  584. Var RefsEq: TRefCompare;
  585. Counter: TRegister;
  586. }
  587. Begin
  588. (*!!!!!!!!!!!
  589. WhichReg := RegMaxSize(WhichReg);
  590. If (Ref.base = procinfo.FramePointer) or
  591. Assigned(Ref.Symbol) Then
  592. Begin
  593. If
  594. {$ifdef cpurefshaveindexreg}
  595. (Ref.Index = R_NO) And
  596. {$endif cpurefshaveindexreg}
  597. (Not(Assigned(Ref.Symbol)) or
  598. (Ref.base = R_NO)) Then
  599. { local variable which is not an array }
  600. RefsEq := @RefsEqual
  601. Else
  602. { local variable which is an array }
  603. RefsEq := @ArrayRefsEq;
  604. {write something to a parameter, a local or global variable, so
  605. * with uncertain optimizations on:
  606. - destroy the contents of registers whose contents have somewhere a
  607. "mov?? (Ref), %reg". WhichReg (this is the register whose contents
  608. are being written to memory) is not destroyed if it's StartMod is
  609. of that form and NrOfMods = 1 (so if it holds ref, but is not a
  610. pointer or value based on Ref)
  611. * with uncertain optimizations off:
  612. - also destroy registers that contain any pointer}
  613. For Counter := LoGPReg to HiGPReg Do
  614. With Regs[Counter] Do
  615. Begin
  616. If (typ = Con_Ref) And
  617. ((Not(cs_opt_size in current_settings.optimizerswitches) And
  618. (NrOfMods <> 1)
  619. ) Or
  620. (RefInSequence(Ref,Regs[Counter], RefsEq) And
  621. ((Counter <> WhichReg) Or
  622. ((NrOfMods <> 1) And
  623. {StarMod is always of the type ait_instruction}
  624. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  625. RefsEq(PInstr(StartMod)^.oper[0].ref^, Ref)
  626. )
  627. )
  628. )
  629. )
  630. Then
  631. DestroyReg(Counter, InstrSinceLastMod)
  632. End
  633. End
  634. Else
  635. {write something to a pointer location, so
  636. * with uncertain optimzations on:
  637. - do not destroy registers which contain a local/global variable or a
  638. parameter, except if DestroyRefs is called because of a "movsl"
  639. * with uncertain optimzations off:
  640. - destroy every register which contains a memory location
  641. }
  642. For Counter := LoGPReg to HiGPReg Do
  643. With Regs[Counter] Do
  644. If (typ = Con_Ref) And
  645. (Not(cs_opt_size in current_settings.optimizerswitches) Or
  646. {$ifdef x86}
  647. {for movsl}
  648. (Ref.Base = R_EDI) Or
  649. {$endif}
  650. {don't destroy if reg contains a parameter, local or global variable}
  651. Not((NrOfMods = 1) And
  652. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  653. ((PInstr(StartMod)^.oper[0].ref^.base = ProcInfo.FramePointer) Or
  654. Assigned(PInstr(StartMod)^.oper[0].ref^.Symbol)
  655. )
  656. )
  657. )
  658. Then DestroyReg(Counter, InstrSinceLastMod)
  659. *)
  660. End;
  661. Procedure TPaiProp.DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  662. {Var Counter: TRegister;}
  663. Begin {initializes/desrtoys all registers}
  664. (*!!!!!!!!!
  665. For Counter := LoGPReg To HiGPReg Do
  666. Begin
  667. ReadReg(Counter);
  668. DestroyReg(Counter, InstrSinceLastMod);
  669. End;
  670. CondRegs.Init;
  671. { FPURegs.Init; }
  672. *)
  673. End;
  674. Procedure TPaiProp.DestroyOp(const o:Toper; var InstrSinceLastMod:
  675. TInstrSinceLastMod);
  676. Begin
  677. {!!!!!!!
  678. Case o.typ Of
  679. top_reg: DestroyReg(o.reg, InstrSinceLastMod);
  680. top_ref:
  681. Begin
  682. ReadRef(o.ref);
  683. DestroyRefs(o.ref^, R_NO, InstrSinceLastMod);
  684. End;
  685. top_symbol:;
  686. End;
  687. }
  688. End;
  689. Procedure TPaiProp.ReadReg(Reg: TRegister);
  690. Begin
  691. {!!!!!!!
  692. Reg := RegMaxSize(Reg);
  693. If Reg in General_Registers Then
  694. IncRState(RegMaxSize(Reg))
  695. }
  696. End;
  697. Procedure TPaiProp.ReadRef(Ref: PReference);
  698. Begin
  699. (*!!!!!!
  700. If Ref^.Base <> R_NO Then
  701. ReadReg(Ref^.Base);
  702. {$ifdef cpurefshaveindexreg}
  703. If Ref^.Index <> R_NO Then
  704. ReadReg(Ref^.Index);
  705. {$endif cpurefshaveindexreg}
  706. *)
  707. End;
  708. Procedure TPaiProp.ReadOp(const o:toper);
  709. Begin
  710. Case o.typ Of
  711. top_reg: ReadReg(o.reg);
  712. top_ref: ReadRef(o.ref);
  713. else
  714. internalerror(200410241);
  715. End;
  716. End;
  717. Procedure TPaiProp.ModifyReg(reg: TRegister; Var InstrSinceLastMod:
  718. TInstrSinceLastMod);
  719. Begin
  720. (*!!!!!!!
  721. With Regs[reg] Do
  722. If (Typ = Con_Ref)
  723. Then
  724. Begin
  725. IncState(WState);
  726. {also store how many instructions are part of the sequence in the first
  727. instructions PPaiProp, so it can be easily accessed from within
  728. CheckSequence}
  729. Inc(NrOfMods, InstrSinceLastMod[Reg]);
  730. PPaiProp(StartMod.OptInfo)^.Regs[Reg].NrOfMods := NrOfMods;
  731. InstrSinceLastMod[Reg] := 0;
  732. End
  733. Else
  734. DestroyReg(Reg, InstrSinceLastMod);
  735. *)
  736. End;
  737. Procedure TPaiProp.ModifyOp(const oper: TOper; var InstrSinceLastMod:
  738. TInstrSinceLastMod);
  739. Begin
  740. If oper.typ = top_reg Then
  741. ModifyReg(RegMaxSize(oper.reg),InstrSinceLastMod)
  742. Else
  743. Begin
  744. ReadOp(oper);
  745. DestroyOp(oper, InstrSinceLastMod);
  746. End
  747. End;
  748. Procedure TPaiProp.IncWState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  749. Begin
  750. //!!!! IncState(Regs[Reg].WState);
  751. End;
  752. Procedure TPaiProp.IncRState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  753. Begin
  754. //!!!! IncState(Regs[Reg].RState);
  755. End;
  756. Function TPaiProp.GetWState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  757. Begin
  758. Result:=0; { unimplemented }
  759. //!!!! GetWState := Regs[Reg].WState
  760. End;
  761. Function TPaiProp.GetRState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  762. Begin
  763. Result:=0; { unimplemented }
  764. //!!!! GetRState := Regs[Reg].RState
  765. End;
  766. Function TPaiProp.GetRegContentType(Reg: TRegister): Byte; {$ifdef inl} inline;{$endif inl}
  767. Begin
  768. Result:=0; { unimplemented }
  769. //!!!! GetRegContentType := Regs[Reg].typ
  770. End;
  771. Destructor TPaiProp.Done;
  772. Begin
  773. //!!!! UsedRegs.Done;
  774. //!!!! CondRegs.Done;
  775. { DirFlag: TFlagContents; I386 specific}
  776. End;
  777. { ************************ private TPaiProp stuff ************************* }
  778. Procedure TPaiProp.IncState(Var s: TStateInt); {$ifdef inl} inline;{$endif inl}
  779. Begin
  780. If s <> High(TStateInt) Then Inc(s)
  781. Else s := 0
  782. End;
  783. class Function TPaiProp.RefInInstruction(Const Ref: TReference; p: Tai;
  784. RefsEq: TRefCompare): Boolean;
  785. Var Count: AWord;
  786. TmpResult: Boolean;
  787. Begin
  788. TmpResult := False;
  789. If (p.typ = ait_instruction) Then
  790. Begin
  791. Count := 0;
  792. Repeat
  793. If (TInstr(p).oper[Count]^.typ = Top_Ref) Then
  794. TmpResult := RefsEq(Ref, PInstr(p)^.oper[Count]^.ref^);
  795. Inc(Count);
  796. Until (Count = max_operands) or TmpResult;
  797. End;
  798. RefInInstruction := TmpResult;
  799. End;
  800. class function TPaiProp.RefInSequence(Const Ref: TReference; Content: TContent;
  801. RefsEq: TRefCompare): Boolean;
  802. Var p: Tai;
  803. Counter: Byte;
  804. TmpResult: Boolean;
  805. Begin
  806. p := Content.StartMod;
  807. TmpResult := False;
  808. Counter := 1;
  809. While Not(TmpResult) And
  810. (Counter <= Content.NrOfMods) Do
  811. Begin
  812. If (p.typ = ait_instruction) And
  813. RefInInstruction(Ref, p, @references_equal)
  814. Then TmpResult := True;
  815. Inc(Counter);
  816. GetNextInstruction(p,p)
  817. End;
  818. RefInSequence := TmpResult
  819. End;
  820. { ************************************************************************* }
  821. { ***************************** TAoptObj ********************************** }
  822. { ************************************************************************* }
  823. Constructor TAoptObj.create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  824. _LabelInfo: PLabelInfo);
  825. Begin
  826. AsmL := _AsmL;
  827. BlockStart := _BlockStart;
  828. BlockEnd := _BlockEnd;
  829. LabelInfo := _LabelInfo;
  830. CreateUsedRegs(UsedRegs);
  831. End;
  832. destructor TAOptObj.Destroy;
  833. var
  834. i : TRegisterType;
  835. begin
  836. for i:=low(TRegisterType) to high(TRegisterType) do
  837. UsedRegs[i].Destroy;
  838. inherited Destroy;
  839. end;
  840. {$ifdef DEBUG_AOPTOBJ}
  841. procedure TAOptObj.DebugMsg(const s: string;p : tai);
  842. begin
  843. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  844. end;
  845. {$else DEBUG_AOPTOBJ}
  846. procedure TAOptObj.DebugMsg(const s: string;p : tai);inline;
  847. begin
  848. end;
  849. {$endif DEBUG_AOPTOBJ}
  850. procedure TAOptObj.CreateUsedRegs(var regs: TAllUsedRegs);
  851. var
  852. i : TRegisterType;
  853. begin
  854. for i:=low(TRegisterType) to high(TRegisterType) do
  855. Regs[i]:=TUsedRegs.Create(i);
  856. end;
  857. procedure TAOptObj.ClearUsedRegs;
  858. var
  859. i : TRegisterType;
  860. begin
  861. for i:=low(TRegisterType) to high(TRegisterType) do
  862. UsedRegs[i].Clear;
  863. end;
  864. { If UpdateUsedRegsAndOptimize has read ahead, the result is one before
  865. the next valid entry (so "p.Next" returns what's expected). If no
  866. reading ahead happened, then the result is equal to p. }
  867. function TAOptObj.UpdateUsedRegsAndOptimize(p : Tai): Tai;
  868. var
  869. NotFirst: Boolean;
  870. begin
  871. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  872. the code is duplicated here }
  873. Result := p;
  874. if (p.typ in [ait_instruction, ait_label]) then
  875. begin
  876. if (p.next <> BlockEnd) and (tai(p.next).typ <> ait_instruction) then
  877. begin
  878. { Advance one, otherwise the routine exits immediately and wastes time }
  879. p := tai(p.Next);
  880. NotFirst := True;
  881. end
  882. else
  883. { If the next entry is an instruction, nothing will be updated or
  884. optimised here, so exit now to save time }
  885. Exit;
  886. end
  887. else
  888. NotFirst := False;
  889. repeat
  890. while assigned(p) and
  891. ((p.typ in (SkipInstr + [ait_label] - [ait_RegAlloc])) or
  892. ((p.typ = ait_marker) and
  893. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  894. begin
  895. prefetch(pointer(p.Next)^);
  896. { Here's the optimise part }
  897. if (p.typ in [ait_align, ait_label]) then
  898. begin
  899. if StripDeadLabels(p, p) then
  900. begin
  901. { Note, if the first instruction is stripped and is
  902. the only one that gets removed, Result will now
  903. contain a dangling pointer, so compensate for this. }
  904. if not NotFirst then
  905. Result := tai(p.Previous);
  906. Continue;
  907. end;
  908. if ((p.typ = ait_label) and not labelCanBeSkipped(tai_label(p))) then
  909. Break;
  910. end;
  911. Result := p;
  912. p := tai(p.next);
  913. end;
  914. while assigned(p) and
  915. (p.typ=ait_RegAlloc) Do
  916. begin
  917. prefetch(pointer(p.Next)^);
  918. case tai_regalloc(p).ratype of
  919. ra_alloc :
  920. Include(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  921. ra_dealloc :
  922. Exclude(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  923. else
  924. { Do nothing };
  925. end;
  926. Result := p;
  927. p := tai(p.next);
  928. end;
  929. NotFirst := True;
  930. until not(assigned(p)) or
  931. (not(p.typ in SkipInstr) and
  932. not((p.typ = ait_label) and
  933. labelCanBeSkipped(tai_label(p))));
  934. end;
  935. procedure TAOptObj.UpdateUsedRegs(p : Tai); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  936. begin
  937. UpdateUsedRegs(UsedRegs, p);
  938. end;
  939. class function TAOptObj.GetNextRegUpdatePoint(var p : Tai; pTerm: tai): Boolean;
  940. begin
  941. Result := False; { Needed to suppress compiler warning }
  942. while SetAndTest(Assigned(p) and (p <> pTerm), Result) and
  943. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  944. ((p.typ = ait_label) and
  945. labelCanBeSkipped(tai_label(p))) or
  946. ((p.typ = ait_marker) and
  947. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd])) or
  948. (
  949. Assigned(pTerm) and { Causes p to stop on any live label or instruction if pTerm is nil }
  950. (p.typ in [ait_label, ait_instruction])
  951. )
  952. ) do
  953. p := tai(p.next);
  954. end;
  955. class procedure TAOptObj.UpdateReg(var Regs : TAllUsedRegs; p: tai_regalloc);
  956. begin
  957. case tai_regalloc(p).ratype of
  958. ra_alloc :
  959. Include(Regs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  960. ra_dealloc :
  961. Exclude(Regs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  962. else
  963. ;
  964. end;
  965. end;
  966. class procedure TAOptObj.UpdateUsedRegs(var Regs : TAllUsedRegs;p : Tai);
  967. begin
  968. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  969. the code is duplicated here }
  970. repeat
  971. if not GetNextRegUpdatePoint(p, nil) then
  972. Exit;
  973. while assigned(p) and
  974. (p.typ=ait_RegAlloc) Do
  975. begin
  976. prefetch(pointer(p.Next)^);
  977. UpdateReg(Regs, tai_regalloc(p));
  978. p := tai(p.next);
  979. end;
  980. until not(assigned(p)) or
  981. (not(p.typ in SkipInstr) and
  982. not((p.typ = ait_label) and
  983. labelCanBeSkipped(tai_label(p))));
  984. end;
  985. class procedure TAOptObj.UpdateUsedRegsBetween(var Regs: TAllUsedRegs; p1, p2: Tai);
  986. begin
  987. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  988. the code is duplicated here }
  989. repeat
  990. if not GetNextRegUpdatePoint(p1, p2) then
  991. Exit;
  992. while assigned(p1) and (p1 <> p2) and
  993. (p1.typ=ait_RegAlloc) Do
  994. begin
  995. prefetch(pointer(p1.Next)^);
  996. UpdateReg(Regs, tai_regalloc(p1));
  997. p1 := tai(p1.next);
  998. end;
  999. { Only stop if either p2 or a terminating marker is reached }
  1000. until not Assigned(p1) or (p1 = p2) or
  1001. not (p1.typ in (SkipInstr + [ait_label, ait_instruction])) or
  1002. (
  1003. (p1.typ = ait_marker) and
  1004. not (tai_Marker(p1).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd])
  1005. );
  1006. if (p1 <> p2) then
  1007. { Reached the end of the procedure or a terminating marker that wasn't p2 }
  1008. InternalError(2022010701);
  1009. end;
  1010. function TAOptObj.CopyUsedRegs(var dest: TAllUsedRegs): boolean;
  1011. var
  1012. i : TRegisterType;
  1013. begin
  1014. Result:=true;
  1015. for i:=low(TRegisterType) to high(TRegisterType) do
  1016. dest[i]:=TUsedRegs.Create_Regset(i,UsedRegs[i].GetUsedRegs);
  1017. end;
  1018. procedure TAOptObj.RestoreUsedRegs(const Regs: TAllUsedRegs);
  1019. var
  1020. i : TRegisterType;
  1021. begin
  1022. { Note that the constructor Create_Regset is being called as a regular
  1023. method - it is not instantiating a new object. This is because it is
  1024. the only published means to modify the internal state en-masse. [Kit] }
  1025. for i:=low(TRegisterType) to high(TRegisterType) do
  1026. UsedRegs[i].Create_Regset(i,Regs[i].GetUsedRegs);
  1027. end;
  1028. procedure TAOptObj.TransferUsedRegs(var dest: TAllUsedRegs);
  1029. var
  1030. i : TRegisterType;
  1031. begin
  1032. { Note that the constructor Create_Regset is being called as a regular
  1033. method - it is not instantiating a new object. This is because it is
  1034. the only published means to modify the internal state en-masse. [Kit] }
  1035. for i:=low(TRegisterType) to high(TRegisterType) do
  1036. dest[i].Create_Regset(i, UsedRegs[i].GetUsedRegs);
  1037. end;
  1038. class procedure TAOptObj.ReleaseUsedRegs(const regs: TAllUsedRegs);
  1039. var
  1040. i : TRegisterType;
  1041. begin
  1042. for i:=low(TRegisterType) to high(TRegisterType) do
  1043. regs[i].Free;
  1044. end;
  1045. class Function TAOptObj.RegInUsedRegs(reg : TRegister; var regs : TAllUsedRegs) : boolean;
  1046. begin
  1047. result:=regs[getregtype(reg)].IsUsed(reg);
  1048. end;
  1049. class procedure TAOptObj.IncludeRegInUsedRegs(reg: TRegister;
  1050. var regs: TAllUsedRegs); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  1051. begin
  1052. include(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  1053. end;
  1054. class procedure TAOptObj.ExcludeRegFromUsedRegs(reg: TRegister;
  1055. var regs: TAllUsedRegs); {$ifdef USEINLINE}inline;{$endif USEINLINE}
  1056. begin
  1057. exclude(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  1058. end;
  1059. class function TAOptObj.GetAllocationString(const regs: TAllUsedRegs): string;
  1060. var
  1061. i : TRegisterType;
  1062. j : TSuperRegister;
  1063. begin
  1064. Result:='';
  1065. for i:=low(TRegisterType) to high(TRegisterType) do
  1066. for j in regs[i].UsedRegs do
  1067. Result:=Result+std_regname(newreg(i,j,R_SUBWHOLE))+' ';
  1068. end;
  1069. class function TAOptObj.FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  1070. Var TempP: Tai;
  1071. Begin
  1072. TempP := hp;
  1073. While Assigned(TempP) and
  1074. (TempP.typ In SkipInstr + [ait_label,ait_align]) Do
  1075. If (TempP.typ <> ait_Label) Or
  1076. (Tai_label(TempP).labsym <> L)
  1077. Then
  1078. begin
  1079. GetNextInstruction(TempP, TempP);
  1080. end
  1081. Else
  1082. Begin
  1083. hp := TempP;
  1084. FindLabel := True;
  1085. exit
  1086. End;
  1087. FindLabel := False;
  1088. End;
  1089. function TAOptObj.GetInstructionDistance(p,p2: Tai; out count: ASizeInt) : boolean;
  1090. Var TempP: Tai;
  1091. Begin
  1092. { Forward search }
  1093. TempP := p;
  1094. count:=0;
  1095. While Assigned(TempP) Do
  1096. Begin
  1097. if TempP.typ=ait_instruction then
  1098. inc(count);
  1099. If (TempP<>p2) then
  1100. TempP:=tai(TempP.Next)
  1101. Else
  1102. Begin
  1103. GetInstructionDistance := true;
  1104. exit
  1105. End;
  1106. End;
  1107. { Search p after p2 }
  1108. TempP := p2;
  1109. count:=0;
  1110. While Assigned(TempP) Do
  1111. Begin
  1112. If TempP.typ=ait_instruction then
  1113. dec(count);
  1114. If (TempP<>p) then
  1115. TempP:=tai(TempP.Next)
  1116. Else
  1117. Begin
  1118. GetInstructionDistance := true;
  1119. exit
  1120. End;
  1121. End;
  1122. GetInstructionDistance := false;
  1123. End;
  1124. Procedure TAOptObj.InsertLLItem(prev, foll, new_one : TLinkedListItem);
  1125. Begin
  1126. If Assigned(prev) Then
  1127. If Assigned(foll) Then
  1128. Begin
  1129. If Assigned(new_one) Then
  1130. Begin
  1131. new_one.previous := prev;
  1132. new_one.next := foll;
  1133. prev.next := new_one;
  1134. foll.previous := new_one;
  1135. { should we update line information? }
  1136. if (not (tai(new_one).typ in SkipLineInfo)) and
  1137. (not (tai(foll).typ in SkipLineInfo)) then
  1138. Tailineinfo(new_one).fileinfo := Tailineinfo(foll).fileinfo
  1139. End
  1140. End
  1141. Else AsmL.Concat(new_one)
  1142. Else If Assigned(Foll) Then AsmL.Insert(new_one)
  1143. End;
  1144. class function TAOptObj.SkipHead(P: Tai): Tai;
  1145. Var OldP: Tai;
  1146. Begin
  1147. Repeat
  1148. OldP := P;
  1149. If (P.typ in SkipInstr) Or
  1150. ((P.typ = ait_marker) And
  1151. (Tai_Marker(P).Kind = mark_AsmBlockEnd)) Then
  1152. GetNextInstruction(P, P)
  1153. Else If ((P.Typ = Ait_Marker) And
  1154. (Tai_Marker(P).Kind = mark_NoPropInfoStart)) Then
  1155. { a marker of the type mark_NoPropInfoStart can't be the first instruction of a }
  1156. { paasmoutput list }
  1157. GetNextInstruction(Tai(P.Previous),P);
  1158. If (P.Typ = Ait_Marker) And
  1159. (Tai_Marker(P).Kind = mark_AsmBlockStart) Then
  1160. Begin
  1161. P := Tai(P.Next);
  1162. While (P.typ <> Ait_Marker) Or
  1163. (Tai_Marker(P).Kind <> mark_AsmBlockEnd) Do
  1164. P := Tai(P.Next)
  1165. End;
  1166. Until P = OldP;
  1167. SkipHead := P;
  1168. End;
  1169. class function TAOptObj.OpsEqual(const o1,o2:toper): Boolean;
  1170. Begin
  1171. if o1.typ=o2.typ then
  1172. Case o1.typ Of
  1173. Top_Reg :
  1174. OpsEqual:=o1.reg=o2.reg;
  1175. Top_Ref :
  1176. OpsEqual:=
  1177. references_equal(o1.ref^, o2.ref^) and
  1178. (o1.ref^.volatility=[]) and
  1179. (o2.ref^.volatility=[]);
  1180. Top_Const :
  1181. OpsEqual:=o1.val=o2.val;
  1182. Top_None :
  1183. OpsEqual := True
  1184. else OpsEqual := False
  1185. End
  1186. else
  1187. OpsEqual := False;
  1188. End;
  1189. class function TAOptObj.FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1190. Begin
  1191. Result:=nil;
  1192. Repeat
  1193. While Assigned(StartPai) And
  1194. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1195. {$ifdef cpudelayslot}
  1196. ((startpai.typ=ait_instruction) and (taicpu(startpai).opcode=A_NOP)) or
  1197. {$endif cpudelayslot}
  1198. ((StartPai.typ = ait_label) and
  1199. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1200. StartPai := Tai(StartPai.Next);
  1201. If Assigned(StartPai) And
  1202. (StartPai.typ = ait_regAlloc) Then
  1203. Begin
  1204. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  1205. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  1206. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  1207. begin
  1208. Result:=tai_regalloc(StartPai);
  1209. exit;
  1210. end;
  1211. StartPai := Tai(StartPai.Next);
  1212. End
  1213. else
  1214. exit;
  1215. Until false;
  1216. End;
  1217. class function TAOptObj.FindRegAllocBackward(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1218. Begin
  1219. Result:=nil;
  1220. Repeat
  1221. While Assigned(StartPai) And
  1222. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1223. ((StartPai.typ = ait_label) and
  1224. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1225. StartPai := Tai(StartPai.Previous);
  1226. If Assigned(StartPai) And
  1227. (StartPai.typ = ait_regAlloc) Then
  1228. Begin
  1229. if SuperRegistersEqual(tai_regalloc(StartPai).Reg,Reg) then
  1230. begin
  1231. { If we find a dealloc first, say, return nil }
  1232. if (tai_regalloc(StartPai).ratype<>ra_dealloc) then
  1233. Result:=tai_regalloc(StartPai);
  1234. exit;
  1235. end;
  1236. StartPai := Tai(StartPai.Previous);
  1237. End
  1238. else
  1239. exit;
  1240. Until false;
  1241. End;
  1242. class function TAOptObj.FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1243. Begin
  1244. Result:=nil;
  1245. Repeat
  1246. While Assigned(StartPai) And
  1247. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1248. ((StartPai.typ = ait_label) and
  1249. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1250. StartPai := Tai(StartPai.Next);
  1251. If Assigned(StartPai) And
  1252. (StartPai.typ = ait_regAlloc) Then
  1253. Begin
  1254. if (tai_regalloc(StartPai).ratype=ra_dealloc) and
  1255. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  1256. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  1257. begin
  1258. Result:=tai_regalloc(StartPai);
  1259. exit;
  1260. end;
  1261. StartPai := Tai(StartPai.Next);
  1262. End
  1263. else
  1264. exit;
  1265. Until false;
  1266. End;
  1267. class function TAOptObj.FindTempDeAlloc(Offset: ASizeInt; StartPai: Tai): tai_tempalloc;
  1268. Begin
  1269. Result:=nil;
  1270. Repeat
  1271. While Assigned(StartPai) And
  1272. ((StartPai.typ in (SkipInstr - [ait_tempalloc])) Or
  1273. ((StartPai.typ = ait_label) and
  1274. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1275. StartPai := Tai(StartPai.Next);
  1276. If Assigned(StartPai) And
  1277. (StartPai.typ = ait_tempalloc) Then
  1278. Begin
  1279. if not(tai_tempalloc(StartPai).allocation) and
  1280. (tai_tempalloc(StartPai).temppos = Offset) then
  1281. begin
  1282. Result:=tai_tempalloc(StartPai);
  1283. exit;
  1284. end;
  1285. StartPai := Tai(StartPai.Next);
  1286. End
  1287. else
  1288. exit;
  1289. Until false;
  1290. End;
  1291. { allocates register reg between (and including) instructions p1 and p2
  1292. the type of p1 and p2 must not be in SkipInstr }
  1293. procedure TAOptObj.AllocRegBetween(reg: tregister; p1, p2: tai; var initialusedregs: TAllUsedRegs);
  1294. var
  1295. hp, start: tai;
  1296. Po: PInteger;
  1297. removedsomething,
  1298. firstRemovedWasAlloc,
  1299. lastRemovedWasDealloc: boolean;
  1300. begin
  1301. {$ifdef EXTDEBUG}
  1302. { if assigned(p1.optinfo) and
  1303. (ptaiprop(p1.optinfo)^.usedregs <> initialusedregs) then
  1304. internalerror(2004101010); }
  1305. {$endif EXTDEBUG}
  1306. if not Assigned(p2) then
  1307. { We need a valid final instruction }
  1308. InternalError(2022010401);
  1309. start := p1;
  1310. if (reg = NR_STACK_POINTER_REG) or
  1311. (reg = current_procinfo.framepointer) or
  1312. not(assigned(p1)) then
  1313. { this happens with registers which are loaded implicitely, outside the }
  1314. { current block (e.g. esi with self) }
  1315. exit;
  1316. {$ifdef allocregdebug}
  1317. insertllitem(p1.previous,p1,tai_comment.Create(strpnew('allocating '+std_regname(reg)+' from here...')));
  1318. insertllitem(p2,p2.next,tai_comment.Create(strpnew('allocated '+std_regname(reg)+' till here...')));
  1319. {$endif allocregdebug}
  1320. { make sure we allocate it for this instruction }
  1321. getnextinstruction(p2,p2);
  1322. lastRemovedWasDealloc := false;
  1323. removedSomething := false;
  1324. firstRemovedWasAlloc := false;
  1325. { do it the safe way: always allocate the full super register,
  1326. as we do no register re-allocation in the peephole optimizer,
  1327. this does not hurt
  1328. }
  1329. case getregtype(reg) of
  1330. R_MMREGISTER:
  1331. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1332. R_INTREGISTER:
  1333. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1334. R_FPUREGISTER:
  1335. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1336. R_ADDRESSREGISTER:
  1337. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1338. R_SPECIALREGISTER:
  1339. reg:=newreg(R_SPECIALREGISTER,getsupreg(reg),R_SUBWHOLE);
  1340. else
  1341. Internalerror(2018030701);
  1342. end;
  1343. if not(RegInUsedRegs(reg,initialusedregs)) then
  1344. begin
  1345. hp := tai_regalloc.alloc(reg,nil);
  1346. insertllItem(p1.previous,p1,hp);
  1347. IncludeRegInUsedRegs(reg,initialusedregs);
  1348. lastRemovedWasDealloc := True; { If no tai_regallocs are found at all, treat as if the last one was a deallocation }
  1349. end;
  1350. while assigned(p1) and
  1351. (p1 <> p2) do
  1352. begin
  1353. if assigned(p1.optinfo) then
  1354. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1355. p1 := tai(p1.next);
  1356. repeat
  1357. while assigned(p1) and
  1358. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1359. p1 := tai(p1.next);
  1360. { remove all allocation/deallocation info about the register in between }
  1361. if assigned(p1) and
  1362. (p1.typ = ait_regalloc) then
  1363. begin
  1364. { same super register, different sub register? }
  1365. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1366. begin
  1367. if (getsubreg(reg)<>R_SUBMMWHOLE) and { R_SUBMMWHOLE is below R_SUBMMX, R_SUBMMY and R_SUBMMZ }
  1368. ((getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH)) then
  1369. internalerror(2016101501);
  1370. tai_regalloc(p1).reg:=reg;
  1371. end;
  1372. if tai_regalloc(p1).reg=reg then
  1373. begin
  1374. if not removedSomething then
  1375. begin
  1376. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1377. removedSomething := true;
  1378. end;
  1379. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1380. hp := tai(p1.Next);
  1381. asml.Remove(p1);
  1382. p1.free;
  1383. p1 := hp;
  1384. end
  1385. else
  1386. p1 := tai(p1.next);
  1387. end;
  1388. until not(assigned(p1)) or
  1389. not(p1.typ in SkipInstr);
  1390. end;
  1391. if assigned(p1) then
  1392. begin
  1393. if firstRemovedWasAlloc then
  1394. begin
  1395. hp := tai_regalloc.Alloc(reg,nil);
  1396. insertLLItem(start.previous,start,hp);
  1397. end;
  1398. if lastRemovedWasDealloc then
  1399. begin
  1400. hp := tai_regalloc.DeAlloc(reg,nil);
  1401. insertLLItem(p1.previous,p1,hp);
  1402. end;
  1403. end;
  1404. end;
  1405. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1406. begin
  1407. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1408. RegUsedAfterInstruction :=
  1409. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1410. not(regLoadedWithNewValue(reg,p)) and
  1411. (
  1412. not(GetNextInstruction(p,p)) or
  1413. InstructionLoadsFromReg(reg,p) or
  1414. not(regLoadedWithNewValue(reg,p))
  1415. );
  1416. end;
  1417. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1418. begin
  1419. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1420. RegLoadedWithNewValue(reg,p);
  1421. end;
  1422. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1423. var
  1424. hp1 : tai;
  1425. begin
  1426. result:=GetNextInstruction(p,hp1);
  1427. { p will be removed, update used register as we continue
  1428. with the next instruction after p }
  1429. UpdateUsedRegs(tai(p.Next));
  1430. AsmL.Remove(p);
  1431. p.Free;
  1432. p:=hp1;
  1433. end;
  1434. procedure TAOptObj.RemoveCurrentP(var p: tai; const hp1: tai); inline;
  1435. begin
  1436. if (p=hp1) then
  1437. internalerror(2020120501);
  1438. UpdateUsedRegs(tai(p.Next));
  1439. AsmL.Remove(p);
  1440. p.Free;
  1441. p := hp1;
  1442. end;
  1443. procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
  1444. begin
  1445. AsmL.Remove(hp);
  1446. hp.Free;
  1447. end;
  1448. function FindLiveLabel(hp: tai; var l: tasmlabel): Boolean;
  1449. var
  1450. next: tai;
  1451. begin
  1452. FindLiveLabel := false;
  1453. while True do
  1454. begin
  1455. while assigned(hp.next) and
  1456. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1457. hp := tai(hp.next);
  1458. next := tai(hp.next);
  1459. if assigned(next) and
  1460. (tai(next).typ = ait_label) then
  1461. begin
  1462. l := tai_label(next).labsym;
  1463. if not l.is_used then
  1464. begin
  1465. { Unsafe label }
  1466. hp := next;
  1467. Continue;
  1468. end;
  1469. FindLiveLabel := true;
  1470. end;
  1471. Exit;
  1472. end;
  1473. end;
  1474. {$push}
  1475. {$r-}
  1476. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1477. begin
  1478. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1479. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1480. getlabelwithsym := labelinfo^.labeltable[sym.labelnr-labelinfo^.lowlabel].paiobj
  1481. else
  1482. getlabelwithsym := nil;
  1483. end;
  1484. {$pop}
  1485. { Returns True if hp is an unconditional jump to a label }
  1486. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1487. begin
  1488. {$if defined(avr) or defined(z80)}
  1489. result:=(hp.opcode in aopt_uncondjmp) and
  1490. {$else}
  1491. result:=(hp.opcode=aopt_uncondjmp) and
  1492. {$endif}
  1493. {$if defined(arm) or defined(aarch64) or defined(z80)}
  1494. (hp.condition=c_None) and
  1495. {$endif arm or aarch64 or z80}
  1496. (hp.ops>0) and
  1497. {$if defined(riscv32) or defined(riscv64)}
  1498. (hp.oper[0]^.reg=NR_X0) and
  1499. {$endif riscv}
  1500. (JumpTargetOp(hp)^.typ = top_ref) and
  1501. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1502. end;
  1503. { Returns True if hp is any jump to a label }
  1504. function IsJumpToLabel(hp: taicpu): boolean;
  1505. begin
  1506. result:=hp.is_jmp and
  1507. (hp.ops>0) and
  1508. (JumpTargetOp(hp)^.typ = top_ref) and
  1509. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1510. end;
  1511. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1512. var
  1513. hp2: tai;
  1514. begin
  1515. hp2:=tai(hp1.next);
  1516. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1517. hp2:=tai(hp2.next);
  1518. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1519. (taicpu(hp2).opcode=A_NOP) then
  1520. begin
  1521. asml.remove(hp2);
  1522. hp2.free;
  1523. end;
  1524. { Anything except A_NOP must be left in place: these instructions
  1525. execute before branch, so code stays correct if branch is removed. }
  1526. end;
  1527. { Output debug message to console - null function if EXTDEBUG is not defined }
  1528. class procedure TAOptObj.DebugWrite(Message: string); inline;
  1529. begin
  1530. {$ifdef DEBUG_JUMP}
  1531. WriteLn(Message);
  1532. {$else DEBUG_JUMP}
  1533. { Do nothing }
  1534. {$endif DEBUG_JUMP}
  1535. end;
  1536. { Converts a conditional jump into an unconditional jump. Only call this
  1537. procedure on an instruction that you already know is a conditional jump }
  1538. procedure TAOptObj.MakeUnconditional(p: taicpu);
  1539. begin
  1540. { TODO: If anyone can improve this particular optimisation to work on
  1541. AVR, please do (it's currently not called at all). [Kit] }
  1542. {$if not defined(avr)}
  1543. {$if defined(powerpc) or defined(powerpc64)}
  1544. p.condition.cond := C_None;
  1545. p.condition.simple := True;
  1546. {$else powerpc}
  1547. p.condition := C_None;
  1548. {$endif powerpc}
  1549. {$ifndef z80}
  1550. p.opcode := aopt_uncondjmp;
  1551. {$endif not z80}
  1552. {$ifdef RISCV}
  1553. p.loadoper(1, p.oper[p.ops-1]^);
  1554. p.loadreg(0, NR_X0);
  1555. p.ops:=2;
  1556. {$endif}
  1557. {$ifdef xtensa}
  1558. p.opcode := aopt_uncondjmp;
  1559. p.loadoper(0, p.oper[p.ops-1]^);
  1560. p.ops:=1;
  1561. {$endif}
  1562. {$endif not avr}
  1563. {$ifdef mips}
  1564. { MIPS conditional jump instructions also conntain register
  1565. operands. A proper implementation is needed here. }
  1566. internalerror(2020071301);
  1567. {$endif}
  1568. end;
  1569. { Removes all instructions between an unconditional jump and the next label.
  1570. Returns True if a jump in between was removed (as it may open up new
  1571. optimisations if the label appeared earlier in the stream) }
  1572. function TAOptObj.RemoveDeadCodeAfterJump(p: tai): Boolean;
  1573. const
  1574. {$ifdef JVM}
  1575. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_jcatch];
  1576. {$else JVM}
  1577. { Stop if it reaches SEH directive information in the form of
  1578. consts, which may occur if RemoveDeadCodeAfterJump is called on
  1579. the final RET instruction on x86, for example }
  1580. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label];
  1581. {$endif JVM}
  1582. var
  1583. hp1, hp2: tai;
  1584. begin
  1585. { the following code removes all code between a jmp and the next label,
  1586. because it can never be executed
  1587. }
  1588. Result := False;
  1589. while GetNextInstruction(p, hp1) and
  1590. (hp1 <> BlockEnd) and
  1591. not (hp1.typ in TaiFence) do
  1592. begin
  1593. if (hp1.typ = ait_instruction) and
  1594. taicpu(hp1).is_jmp and
  1595. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1596. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1597. begin
  1598. { If the destination label appears earlier, it may permit
  1599. further optimisations, so signal this in the Result }
  1600. Result := True;
  1601. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1602. end;
  1603. { don't kill start/end of assembler block,
  1604. no-line-info-start/end etc }
  1605. if (hp1.typ<>ait_marker) and
  1606. ((hp1.typ<>ait_cfi) or
  1607. (tai_cfi_base(hp1).cfityp<>cfi_endproc)) then
  1608. begin
  1609. {$ifdef cpudelayslot}
  1610. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1611. RemoveDelaySlot(hp1);
  1612. {$endif cpudelayslot}
  1613. hp2 := hp1;
  1614. while (hp2.typ = ait_align) do
  1615. begin
  1616. { Only remove the align if a label doesn't immediately follow }
  1617. if GetNextInstruction(hp2, hp2) and (hp2.typ = ait_label) then
  1618. { The label is unskippable }
  1619. Exit;
  1620. { Check again in case there's more than one adjacent alignment entry
  1621. (a frequent construct under x86, for example). [Kit] }
  1622. end;
  1623. asml.remove(hp1);
  1624. hp1.free;
  1625. end
  1626. else
  1627. p:=hp1;
  1628. end;
  1629. end;
  1630. { If hp is a label, strip it if its reference count is zero. Repeat until
  1631. a non-label is found, or a label with a non-zero reference count.
  1632. True is returned if something was stripped }
  1633. function TAOptObj.StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  1634. var
  1635. tmp, tmpNext: tai;
  1636. hp1: tai;
  1637. CurrentAlign: tai;
  1638. FoundLabels: Boolean;
  1639. begin
  1640. CurrentAlign := nil;
  1641. Result := False;
  1642. hp1 := hp;
  1643. NextValid := hp;
  1644. { Stop if hp is an instruction, for example }
  1645. while (hp1 <> BlockEnd) and (hp1.typ in [ait_label,ait_align]) do
  1646. begin
  1647. prefetch(pointer(hp1.Next)^);
  1648. case hp1.typ of
  1649. ait_label:
  1650. begin
  1651. { Set tmp to the next valid entry }
  1652. tmp := tai(hp1.Next);
  1653. with tai_label(hp1).labsym do
  1654. begin
  1655. if (labeltype <> alt_jump) then
  1656. begin
  1657. { Non-jump label - skip over }
  1658. hp1 := tmp;
  1659. Continue;
  1660. end;
  1661. if is_used or (bind <> AB_LOCAL) then
  1662. begin
  1663. { Valid label }
  1664. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1665. Exit;
  1666. end;
  1667. end;
  1668. DebugWrite('JUMP DEBUG: Removed label ' + tostr(TAsmLabel(tai_label(hp1).labsym).labelnr));
  1669. { Remove label }
  1670. if (NextValid = hp1) then
  1671. NextValid := tmp;
  1672. RemoveInstruction(hp1);
  1673. hp1 := tmp;
  1674. Result := True;
  1675. Continue;
  1676. end;
  1677. { Also remove the align if it comes before an unused label }
  1678. ait_align:
  1679. begin
  1680. { Signal that we can possibly delete this align entry }
  1681. CurrentAlign := hp1;
  1682. tmp := tai(hp1.Next);
  1683. if tmp = BlockEnd then
  1684. { End of block }
  1685. Exit;
  1686. repeat
  1687. case tmp.typ of
  1688. ait_align: { Merge the aligns if permissible }
  1689. begin
  1690. { Check the maxbytes field though, since this may result in the
  1691. alignment being ignored }
  1692. if ((tai_align_abstract(hp1).maxbytes = 0) and (tai_align_abstract(tmp).maxbytes = 0)) or
  1693. { If a maxbytes field is present, only merge if the aligns have the same granularity }
  1694. ((tai_align_abstract(hp1).aligntype = tai_align_abstract(tmp).aligntype)) then
  1695. begin
  1696. with tai_align_abstract(hp1) do
  1697. begin
  1698. aligntype := max(aligntype, tai_align_abstract(tmp).aligntype);
  1699. maxbytes := max(maxbytes, tai_align_abstract(tmp).maxbytes);
  1700. fillsize := max(fillsize, tai_align_abstract(tmp).fillsize);
  1701. use_op := use_op or tai_align_abstract(tmp).use_op;
  1702. if use_op and (tai_align_abstract(tmp).fillop <> 0) then
  1703. fillop := tai_align_abstract(tmp).fillop;
  1704. end;
  1705. tmpNext := tai(tmp.Next);
  1706. RemoveInstruction(tmp);
  1707. Result := True;
  1708. tmp := tmpNext;
  1709. end
  1710. else
  1711. tmp := tai(tmp.Next);
  1712. Continue;
  1713. end;
  1714. ait_label:
  1715. begin
  1716. repeat
  1717. with tai_label(tmp).labsym do
  1718. begin
  1719. { alt_addr is needed so alignment directives before
  1720. jump tables e.g. for arm thumb are not removed }
  1721. if not(labeltype in [alt_addr,alt_jump]) then
  1722. begin
  1723. { Non-jump label - skip over }
  1724. tmp := tai(tmp.Next);
  1725. Continue;
  1726. end;
  1727. if is_used or (bind <> AB_LOCAL) then
  1728. begin
  1729. { Valid label }
  1730. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1731. Exit;
  1732. end;
  1733. end;
  1734. DebugWrite('JUMP DEBUG: Removed label ' + tai_label(tmp).labsym.name);
  1735. { Remove label }
  1736. tmpNext := tai(tmp.Next);
  1737. RemoveInstruction(tmp);
  1738. Result := True;
  1739. tmp := tmpNext;
  1740. { Loop here for a minor performance gain }
  1741. until (tmp = BlockEnd) or (tmp.typ <> ait_label);
  1742. { Re-evaluate the align and see what follows }
  1743. Continue;
  1744. end
  1745. else
  1746. begin
  1747. if tmp.typ in SkipInstr then
  1748. begin
  1749. tmp := tai(tmp.Next);
  1750. Continue;
  1751. end;
  1752. { Set hp1 to the instruction after the align, because the
  1753. align might get deleted later and hence set NextValid
  1754. to a dangling pointer. [Kit] }
  1755. hp1 := tmp;
  1756. Break;
  1757. end;
  1758. end;
  1759. until (tmp = BlockEnd);
  1760. { Break out of the outer loop if the above Break is called }
  1761. if (hp1 = tmp) then
  1762. Break;
  1763. end
  1764. else
  1765. Break;
  1766. end;
  1767. hp1 := tai(hp1.Next);
  1768. end;
  1769. if Assigned(CurrentAlign) then
  1770. begin
  1771. { Remember what the first one was }
  1772. tmpNext := CurrentAlign;
  1773. { Remove the alignment field (but only if the next valid entry is not a live label) }
  1774. repeat
  1775. tmp := tai(CurrentAlign.next);
  1776. { Any labels found are non-jump labels and will be skipped over }
  1777. if CurrentAlign.typ = ait_align then
  1778. begin
  1779. DebugWrite('JUMP DEBUG: Alignment field removed');
  1780. RemoveInstruction(CurrentAlign);
  1781. end;
  1782. CurrentAlign := tmp;
  1783. until not Assigned(CurrentAlign) or not (CurrentAlign.typ in [ait_align, ait_label]);
  1784. if (NextValid = tmpNext) then
  1785. NextValid := tmp;
  1786. end;
  1787. end;
  1788. { Strips a label and any aligns that appear before it (if hp points to
  1789. them rather than the label). Only call this procedure on a label that
  1790. you already know is no longer referenced }
  1791. procedure TAOptObj.StripLabelFast(hp: tai);
  1792. var
  1793. tmp: tai;
  1794. begin
  1795. repeat
  1796. case hp.typ of
  1797. ait_align:
  1798. begin
  1799. tmp := tai(hp.Next);
  1800. asml.Remove(hp);
  1801. hp.Free;
  1802. hp := tmp;
  1803. { Control flow will now return to 'repeat' }
  1804. end;
  1805. ait_label:
  1806. begin
  1807. {$ifdef EXTDEBUG}
  1808. { When not in debug mode, deleting a live label will cause an
  1809. access violation later on. [Kit] }
  1810. if tai_label(hp).labsym.getrefs <> 0 then
  1811. InternalError(2019110802);
  1812. {$endif EXTDEBUG}
  1813. asml.Remove(hp);
  1814. hp.Free;
  1815. Exit;
  1816. end;
  1817. else
  1818. begin
  1819. { Might be a comment or temporary allocation entry }
  1820. if not (hp.typ in SkipInstr) then
  1821. InternalError(2019110801);
  1822. hp := tai(hp.Next);
  1823. end;
  1824. end;
  1825. until False;
  1826. end;
  1827. { If a group of labels are clustered, change the jump to point to the last one
  1828. that is still referenced }
  1829. function TAOptObj.CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  1830. var
  1831. LastLabel: TAsmLabel;
  1832. hp2: tai;
  1833. begin
  1834. Result := tai_label(lbltai).labsym;
  1835. LastLabel := Result;
  1836. hp2 := tai(lbltai.next);
  1837. while (hp2 <> BlockEnd) and (hp2.typ in SkipInstr + [ait_align, ait_label]) do
  1838. begin
  1839. if (hp2.typ = ait_label) and
  1840. (tai_label(hp2).labsym.is_used) and
  1841. (tai_label(hp2).labsym.labeltype = alt_jump) then
  1842. LastLabel := tai_label(hp2).labsym;
  1843. hp2 := tai(hp2.next);
  1844. end;
  1845. if (Result <> LastLabel) then
  1846. begin
  1847. Result.decrefs;
  1848. JumpTargetOp(taicpu(jump))^.ref^.symbol := LastLabel;
  1849. LastLabel.increfs;
  1850. Result := LastLabel;
  1851. lbltai := hp2;
  1852. end;
  1853. end;
  1854. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  1855. function TAOptObj.OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  1856. var
  1857. hp2: tai;
  1858. NCJLabel: TAsmLabel;
  1859. {$ifdef CPU_BC_HAS_SIZE_LIMIT}
  1860. hpncg : tai;
  1861. count : ASizeInt;
  1862. {$endif CPU_BC_HAS_SIZE_LIMIT}
  1863. begin
  1864. Result := False;
  1865. while (hp1 <> BlockEnd) do
  1866. begin
  1867. StripDeadLabels(hp1, hp1);
  1868. if (hp1 <> BlockEnd) and
  1869. (tai(hp1).typ=ait_instruction) and
  1870. IsJumpToLabel(taicpu(hp1)) then
  1871. begin
  1872. NCJLabel := TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol);
  1873. if IsJumpToLabelUncond(taicpu(hp1)) then
  1874. begin
  1875. { Do it now to get it out of the way and to aid optimisations
  1876. later on in this method }
  1877. if RemoveDeadCodeAfterJump(taicpu(hp1)) then
  1878. stoploop := False;
  1879. hp2 := getlabelwithsym(NCJLabel);
  1880. {$ifdef CPU_BC_HAS_SIZE_LIMIT}
  1881. hpncg :=hp2;
  1882. {$endif CPU_BC_HAS_SIZE_LIMIT}
  1883. if Assigned(hp2) then
  1884. { Collapse the cluster now to aid optimisation and potentially
  1885. cut down on the number of iterations required }
  1886. NCJLabel := CollapseLabelCluster(hp1, hp2);
  1887. { GetNextInstruction could be factored out, but hp2 might be
  1888. different after "RemoveDeadCodeAfterJump" }
  1889. GetNextInstruction(hp1, hp2);
  1890. { Check for:
  1891. jmp<cond> @Lbl
  1892. jmp @Lbl
  1893. }
  1894. if (CJLabel = NCJLabel) then
  1895. begin
  1896. DebugMsg(SPeepholeOptimization+'Short-circuited conditional jump',p);
  1897. { Both jumps go to the same label }
  1898. CJLabel.decrefs;
  1899. {$ifdef cpudelayslot}
  1900. RemoveDelaySlot(p);
  1901. {$endif cpudelayslot}
  1902. RemoveCurrentP(p, hp1);
  1903. Result := True;
  1904. Exit;
  1905. end;
  1906. if FindLabel(CJLabel, hp2)
  1907. {$ifdef CPU_BC_HAS_SIZE_LIMIT}
  1908. and assigned(hpncg) and GetInstructionDistance(p, hpncg, count) and
  1909. (abs(count) < BC_max_distance)
  1910. {$endif CPU_BC_HAS_SIZE_LIMIT}
  1911. then
  1912. begin
  1913. { change the following jumps:
  1914. jmp<cond> CJLabel jmp<inv_cond> NCJLabel
  1915. jmp NCJLabel >>> <code>
  1916. CJLabel: NCJLabel:
  1917. <code>
  1918. NCJLabel:
  1919. }
  1920. {$if defined(arm) or defined(aarch64)}
  1921. if (taicpu(p).condition<>C_None)
  1922. {$if defined(aarch64)}
  1923. { can't have conditional branches to
  1924. global labels on AArch64, because the
  1925. offset may become too big }
  1926. and (NCJLabel.bind=AB_LOCAL)
  1927. {$endif aarch64}
  1928. then
  1929. begin
  1930. {$endif arm or aarch64}
  1931. DebugMsg(SPeepholeOptimization+'Conditional jump inversion',p);
  1932. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1933. CJLabel.decrefs;
  1934. JumpTargetOp(taicpu(p))^.ref^.symbol := NCJLabel;
  1935. { when freeing hp1, the reference count
  1936. isn't decreased, so don't increase }
  1937. {$ifdef cpudelayslot}
  1938. RemoveDelaySlot(hp1);
  1939. {$endif cpudelayslot}
  1940. RemoveInstruction(hp1);
  1941. stoploop := False;
  1942. if not CJLabel.is_used then
  1943. begin
  1944. CJLabel := NCJLabel;
  1945. StripDeadLabels(tai(p.Next), hp1);
  1946. if (hp1 = BlockEnd) then
  1947. Exit;
  1948. { Attempt another iteration in case more jumps follow }
  1949. if (hp1.typ in SkipInstr) then
  1950. GetNextInstruction(hp1, hp1);
  1951. Continue;
  1952. end;
  1953. {$if defined(arm) or defined(aarch64)}
  1954. end;
  1955. {$endif arm or aarch64}
  1956. end
  1957. else if CollapseZeroDistJump(hp1, NCJLabel) then
  1958. begin
  1959. if (hp1 = BlockEnd) then
  1960. Exit;
  1961. { Attempt another iteration in case more jumps follow }
  1962. if (hp1.typ in SkipInstr) then
  1963. GetNextInstruction(hp1, hp1);
  1964. Continue;
  1965. end;
  1966. end
  1967. else
  1968. begin
  1969. { Do not try to optimize if the test generating the condition
  1970. is the same instruction, like 'bne $v0,$zero,.Lj3' for MIPS }
  1971. if (taicpu(p).ops>1) or (taicpu(hp1).ops>1) then
  1972. exit;
  1973. { Check for:
  1974. jmp<cond1> @Lbl1
  1975. jmp<cond2> @Lbl2
  1976. Remove 2nd jump if conditions are equal or cond2 is a subset of cond1
  1977. (as if the first jump didn't branch, then neither will the 2nd)
  1978. }
  1979. if condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  1980. begin
  1981. DebugMsg(SPeepholeOptimization+'Dominated conditional jump',p);
  1982. NCJLabel.decrefs;
  1983. GetNextInstruction(hp1, hp2);
  1984. {$ifdef cpudelayslot}
  1985. RemoveDelaySlot(hp1);
  1986. {$endif cpudelayslot}
  1987. RemoveInstruction(hp1);
  1988. hp1 := hp2;
  1989. { Flag another pass in case @Lbl2 appeared earlier in the procedure and is now a dead label }
  1990. stoploop := False;
  1991. { Attempt another iteration in case more jumps follow }
  1992. Continue;
  1993. end;
  1994. { Check for:
  1995. jmp<cond1> @Lbl1
  1996. jmp<cond2> @Lbl2
  1997. And inv(cond1) is a subset of cond2 (e.g. je followed by jne, or jae followed by jbe) )
  1998. }
  1999. if condition_in(inverse_cond(taicpu(p).condition), taicpu(hp1).condition) then
  2000. begin
  2001. GetNextInstruction(hp1, hp2);
  2002. { If @lbl1 immediately follows jmp<cond2>, we can remove
  2003. the first jump completely }
  2004. if FindLabel(CJLabel, hp2) then
  2005. begin
  2006. { However, to be absolutely correct, cond2 must be changed to inv(cond1) }
  2007. taicpu(hp1).condition := inverse_cond(taicpu(p).condition);
  2008. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - removed first jump',p);
  2009. CJLabel.decrefs;
  2010. {$ifdef cpudelayslot}
  2011. RemoveDelaySlot(p);
  2012. {$endif cpudelayslot}
  2013. RemoveCurrentP(p, hp1);
  2014. Result := True;
  2015. Exit;
  2016. {$if not defined(avr)}
  2017. end
  2018. else
  2019. { NOTE: There is currently no watertight, cross-platform way to create
  2020. an unconditional jump without access to the cg object. If anyone can
  2021. improve this particular optimisation to work on AVR,
  2022. please do. [Kit] }
  2023. begin
  2024. { Since inv(cond1) is a subset of cond2, jmp<cond2> will always branch if
  2025. jmp<cond1> does not, so change jmp<cond2> to an unconditional jump. }
  2026. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - made second jump unconditional',p);
  2027. MakeUnconditional(taicpu(hp1));
  2028. { NOTE: Changing the jump to unconditional won't open up new opportunities
  2029. for GetFinalDestination on earlier jumps because there's no live label
  2030. between the two jump instructions, so setting 'stoploop' to False only
  2031. wastes time. [Kit] }
  2032. { See if more optimisations are possible }
  2033. Continue;
  2034. {$endif}
  2035. end;
  2036. end;
  2037. end;
  2038. end;
  2039. if GetFinalDestination(taicpu(p),0) then
  2040. stoploop := False;
  2041. Exit;
  2042. end;
  2043. end;
  2044. {$endif CPU_SUPPORTS_OPT_COND_JUMP}
  2045. function TAOptObj.CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  2046. var
  2047. hp1: tai;
  2048. begin
  2049. Result := False;
  2050. if not GetNextInstruction(p,hp1) then
  2051. exit;
  2052. if (hp1 = BlockEnd) then
  2053. Exit;
  2054. { remove jumps to labels coming right after them }
  2055. if FindLabel(ThisLabel, hp1) and
  2056. { Cannot remove the first instruction }
  2057. (p<>StartPoint) then
  2058. begin
  2059. ThisLabel.decrefs;
  2060. {$ifdef cpudelayslot}
  2061. RemoveDelaySlot(p);
  2062. {$endif cpudelayslot}
  2063. hp1 := tai(p.Next);
  2064. { Use RemoveInstruction, not RemoveCurrentP, since the latter also
  2065. updates the registers }
  2066. RemoveInstruction(p);
  2067. p := hp1;
  2068. Result := True;
  2069. end;
  2070. end;
  2071. function TAOptObj.CanDoJumpOpts: Boolean;
  2072. begin
  2073. { Always allow by default }
  2074. Result := True;
  2075. end;
  2076. function TAOptObj.DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  2077. var
  2078. hp1, hp2: tai;
  2079. ThisLabel: TAsmLabel;
  2080. ThisPassResult: Boolean;
  2081. begin
  2082. Result := False;
  2083. if (p.typ <> ait_instruction) or not IsJumpToLabel(taicpu(p)) then
  2084. Exit;
  2085. repeat
  2086. ThisPassResult := False;
  2087. if GetNextInstruction(p, hp1) and (hp1 <> BlockEnd) then
  2088. begin
  2089. SkipEntryExitMarker(hp1,hp1);
  2090. if (hp1 = BlockEnd) then
  2091. Exit;
  2092. ThisLabel := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  2093. hp2 := getlabelwithsym(ThisLabel);
  2094. { getlabelwithsym returning nil occurs if a label is in a
  2095. different block (e.g. on the other side of an asm...end pair). }
  2096. if Assigned(hp2) then
  2097. begin
  2098. { If there are multiple labels in a row, change the destination to the last one
  2099. in order to aid optimisation later }
  2100. ThisLabel := CollapseLabelCluster(p, hp2);
  2101. if CollapseZeroDistJump(p, ThisLabel) then
  2102. begin
  2103. stoploop := False;
  2104. Result := True;
  2105. Exit;
  2106. end;
  2107. if IsJumpToLabelUncond(taicpu(p)) then
  2108. begin
  2109. { Remove unreachable code between the jump and the next label }
  2110. ThisPassResult := RemoveDeadCodeAfterJump(taicpu(p));
  2111. if GetFinalDestination(taicpu(p), 0) or ThisPassResult then
  2112. { Might have caused some earlier labels to become dead }
  2113. stoploop := False;
  2114. end
  2115. {$ifdef CPU_SUPPORTS_OPT_COND_JUMP}
  2116. else if (taicpu(p).opcode {$ifdef z80}in{$else}={$endif} aopt_condjmp) then
  2117. ThisPassResult := OptimizeConditionalJump(ThisLabel, p, hp1, stoploop)
  2118. {$endif CPU_SUPPORTS_OPT_COND_JUMP}
  2119. ;
  2120. end;
  2121. end;
  2122. Result := Result or ThisPassResult;
  2123. until not (ThisPassResult and (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)));
  2124. end;
  2125. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  2126. {traces sucessive jumps to their final destination and sets it, e.g.
  2127. je l1 je l3 <code> <code>
  2128. l1: becomes l1:
  2129. je l2 je l3
  2130. <code> <code>
  2131. l2: l2:
  2132. jmp l3 jmp l3
  2133. the level parameter denotes how deep we have already followed the jump,
  2134. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  2135. var p1: tai;
  2136. p2: tai;
  2137. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2138. p3: tai;
  2139. {$endif}
  2140. ThisLabel, l: tasmlabel;
  2141. begin
  2142. GetFinalDestination := false;
  2143. if level > 20 then
  2144. exit;
  2145. ThisLabel := TAsmLabel(JumpTargetOp(hp)^.ref^.symbol);
  2146. p1 := getlabelwithsym(ThisLabel);
  2147. if assigned(p1) then
  2148. begin
  2149. SkipLabels(p1,p1);
  2150. if (p1.typ = ait_instruction) and
  2151. (taicpu(p1).is_jmp) then
  2152. begin
  2153. p2 := tai(p1.Next);
  2154. if p2 = BlockEnd then
  2155. Exit;
  2156. { Collapse any zero distance jumps we stumble across }
  2157. while (p1<>StartPoint) and CollapseZeroDistJump(p1, TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol)) do
  2158. begin
  2159. { Note: Cannot remove the first instruction }
  2160. if (p1.typ in [ait_align, ait_label]) then
  2161. SkipLabels(p1, p1);
  2162. if not Assigned(p1) then
  2163. { No more valid commands }
  2164. Exit;
  2165. { Check to see that we are actually still at a jump }
  2166. if not ((tai(p1).typ = ait_instruction) and (taicpu(p1).is_jmp)) then
  2167. begin
  2168. { Required to ensure recursion works properly, but to also
  2169. return false if a jump isn't modified. [Kit] }
  2170. if level > 0 then GetFinalDestination := True;
  2171. Exit;
  2172. end;
  2173. p2 := tai(p1.Next);
  2174. if p2 = BlockEnd then
  2175. Exit;
  2176. end;
  2177. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2178. p3 := p2;
  2179. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2180. if { the next instruction after the label where the jump hp arrives}
  2181. { is unconditional or of the same type as hp, so continue }
  2182. IsJumpToLabelUncond(taicpu(p1))
  2183. { TODO: For anyone with experience with MIPS or RISC-V, please add support for tracing
  2184. conditional jumps. [Kit] }
  2185. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2186. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  2187. or
  2188. condition_in(hp.condition, taicpu(p1).condition) or
  2189. { the next instruction after the label where the jump hp arrives
  2190. is the opposite of hp (so this one is never taken), but after
  2191. that one there is a branch that will be taken, so perform a
  2192. little hack: set p1 equal to this instruction }
  2193. (condition_in(hp.condition, inverse_cond(taicpu(p1).condition)) and
  2194. SkipLabels(p3,p2) and
  2195. (p2.typ = ait_instruction) and
  2196. (taicpu(p2).is_jmp) and
  2197. (IsJumpToLabelUncond(taicpu(p2)) or
  2198. (condition_in(hp.condition, taicpu(p2).condition))
  2199. ) and
  2200. SetAndTest(p2,p1)
  2201. )
  2202. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2203. then
  2204. begin
  2205. { quick check for loops of the form "l5: ; jmp l5" }
  2206. if (TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr = ThisLabel.labelnr) then
  2207. exit;
  2208. if not GetFinalDestination(taicpu(p1),succ(level)) then
  2209. exit;
  2210. { NOTE: Do not move this before the "l5: ; jmp l5" check,
  2211. because GetFinalDestination may change the destination
  2212. label of p1. [Kit] }
  2213. l := tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol);
  2214. {$if defined(aarch64)}
  2215. { can't have conditional branches to
  2216. global labels on AArch64, because the
  2217. offset may become too big }
  2218. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  2219. (l.bind<>AB_LOCAL) then
  2220. exit;
  2221. {$endif aarch64}
  2222. ThisLabel.decrefs;
  2223. JumpTargetOp(hp)^.ref^.symbol:=l;
  2224. l.increfs;
  2225. GetFinalDestination := True;
  2226. Exit;
  2227. end
  2228. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64) and not defined(WASM)}
  2229. else
  2230. if condition_in(inverse_cond(hp.condition), taicpu(p1).condition) then
  2231. begin
  2232. if not FindLiveLabel(p1,l) then
  2233. begin
  2234. {$ifdef finaldestdebug}
  2235. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2236. strpnew('previous label inserted'))));
  2237. {$endif finaldestdebug}
  2238. current_asmdata.getjumplabel(l);
  2239. insertllitem(p1,p1.next,tai_label.Create(l));
  2240. ThisLabel.decrefs;
  2241. JumpTargetOp(hp)^.ref^.symbol := l;
  2242. l.increfs;
  2243. GetFinalDestination := True;
  2244. { this won't work, since the new label isn't in the labeltable }
  2245. { so it will fail the rangecheck. Labeltable should become a }
  2246. { hashtable to support this: }
  2247. { GetFinalDestination(asml, hp); }
  2248. end
  2249. else
  2250. begin
  2251. {$ifdef finaldestdebug}
  2252. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2253. strpnew('next label reused'))));
  2254. {$endif finaldestdebug}
  2255. l.increfs;
  2256. ThisLabel.decrefs;
  2257. JumpTargetOp(hp)^.ref^.symbol := l;
  2258. if not GetFinalDestination(hp,succ(level)) then
  2259. exit;
  2260. end;
  2261. GetFinalDestination := True;
  2262. Exit;
  2263. end;
  2264. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64 and not WASM}
  2265. end;
  2266. end;
  2267. { Required to ensure recursion works properly, but to also
  2268. return false if a jump isn't modified. [Kit] }
  2269. if level > 0 then GetFinalDestination := True;
  2270. end;
  2271. { Attempts to reconfigure the Regallocs and Regdeallocs before p1 and
  2272. after p2 so Reg is no longer allocated between them. Returns True if the
  2273. register is no longer allocated at p1 }
  2274. function TAOptObj.TryRemoveRegAlloc(const Reg: TRegister; p1, p2: tai): Boolean;
  2275. var
  2276. CurrentAlloc: tai;
  2277. begin
  2278. Result := False;
  2279. if RegInInstruction(Reg, p1) then
  2280. { Register is definitely in use }
  2281. Exit;
  2282. { Search for the first de/alloc before p1 that relates to Reg }
  2283. CurrentAlloc := tai(p1.Previous);
  2284. repeat
  2285. while Assigned(CurrentAlloc) and
  2286. ((CurrentAlloc.typ in (SkipInstr - [ait_regAlloc])) or
  2287. ((CurrentAlloc.typ = ait_label) and
  2288. not(Tai_Label(CurrentAlloc).labsym.Is_Used))) do
  2289. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2290. if Assigned(CurrentAlloc) and
  2291. (CurrentAlloc.typ = ait_regalloc) then
  2292. begin
  2293. if (getregtype(tai_regalloc(CurrentAlloc).Reg) = getregtype(Reg)) and
  2294. (getsupreg(tai_regalloc(CurrentAlloc).Reg) = getsupreg(Reg)) then
  2295. begin
  2296. Break;
  2297. end;
  2298. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2299. end
  2300. else
  2301. begin
  2302. CurrentAlloc := nil;
  2303. Break;
  2304. end;
  2305. until false;
  2306. { Remove any register allocation prior to p1 }
  2307. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2308. (tai_regalloc(CurrentAlloc).ratype = ra_alloc) then
  2309. begin
  2310. RemoveInstruction(CurrentAlloc);
  2311. Result := True;
  2312. end
  2313. else if not Assigned(CurrentAlloc) or (CurrentAlloc.typ <> ait_regalloc) or
  2314. (tai_regalloc(CurrentAlloc).ratype <> ra_dealloc) then
  2315. begin
  2316. AsmL.InsertBefore(tai_regalloc.dealloc(Reg, nil), p1);
  2317. Result := True;
  2318. end;
  2319. if (p1 <> p2) and RegInInstruction(Reg, p2) then
  2320. begin
  2321. { Reg is in use, so insert allocation before it }
  2322. AsmL.InsertBefore(tai_regalloc.alloc(Reg, nil), p2);
  2323. Exit;
  2324. end;
  2325. { If a deallocation exists, remove it since the register will no longer be allocated by this time }
  2326. CurrentAlloc := FindRegDealloc(Reg, tai(p2.Next));
  2327. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2328. (tai_regalloc(CurrentAlloc).ratype = ra_dealloc) then
  2329. begin
  2330. RemoveInstruction(CurrentAlloc);
  2331. end
  2332. else
  2333. begin
  2334. { Since no deallocation was found, Register may end up being used afterwards, so add a new alloc to play safe }
  2335. AsmL.InsertAfter(tai_regalloc.alloc(Reg, nil), p2);
  2336. end;
  2337. end;
  2338. procedure TAOptObj.PrePeepHoleOpts;
  2339. var
  2340. p: tai;
  2341. begin
  2342. p := BlockStart;
  2343. ClearUsedRegs;
  2344. while (p <> BlockEnd) Do
  2345. begin
  2346. prefetch(pointer(p.Next)^);
  2347. if PrePeepHoleOptsCpu(p) then
  2348. continue;
  2349. if assigned(p) then
  2350. begin
  2351. p:=tai(p.next);
  2352. UpdateUsedRegs(p);
  2353. end;
  2354. end;
  2355. end;
  2356. procedure TAOptObj.PeepHoleOptPass1;
  2357. const
  2358. MaxPasses_Pass1: array[1..3] of Cardinal = (1, 2, 8);
  2359. var
  2360. p : tai;
  2361. stoploop, FirstInstruction, JumpOptsAvailable: boolean;
  2362. PassCount, MaxCount: Cardinal;
  2363. begin
  2364. JumpOptsAvailable := CanDoJumpOpts();
  2365. StartPoint := BlockStart;
  2366. PassCount := 0;
  2367. { Determine the maximum number of passes allowed based on the compiler switches }
  2368. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2369. { it should never take more than 8 passes, but the limit is finite to protect against faulty optimisations }
  2370. MaxCount := MaxPasses_Pass1[3]
  2371. else if (cs_opt_level2 in current_settings.optimizerswitches) then
  2372. MaxCount := MaxPasses_Pass1[2] { The original double run of Pass 1 }
  2373. else
  2374. MaxCount := MaxPasses_Pass1[1];
  2375. NotFirstIteration := False;
  2376. repeat
  2377. stoploop:=true;
  2378. p := StartPoint;
  2379. FirstInstruction := True;
  2380. ClearUsedRegs;
  2381. while Assigned(p) and (p <> BlockEnd) Do
  2382. begin
  2383. prefetch(pointer(p.Next)^);
  2384. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  2385. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  2386. UpdateUsedRegs(tai(p.next));
  2387. }
  2388. {$ifdef DEBUG_OPTALLOC}
  2389. if p.Typ=ait_instruction then
  2390. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  2391. {$endif DEBUG_OPTALLOC}
  2392. { Handle jump optimizations first }
  2393. if JumpOptsAvailable and DoJumpOptimizations(p, stoploop) then
  2394. begin
  2395. if FirstInstruction then
  2396. { Update StartPoint, since the old p was removed;
  2397. don't set FirstInstruction to False though, as
  2398. the new p might get removed too. }
  2399. StartPoint := p;
  2400. if (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)) then
  2401. Continue;
  2402. end;
  2403. if PeepHoleOptPass1Cpu(p) then
  2404. begin
  2405. stoploop:=false;
  2406. UpdateUsedRegs(p);
  2407. if FirstInstruction then
  2408. { Update StartPoint, since the old p was modified;
  2409. don't set FirstInstruction to False though, as
  2410. the new p might get modified too. }
  2411. StartPoint := p;
  2412. continue;
  2413. end;
  2414. FirstInstruction := False;
  2415. if assigned(p) then
  2416. begin
  2417. p:=tai(p.next);
  2418. UpdateUsedRegs(p);
  2419. end;
  2420. end;
  2421. Inc(PassCount);
  2422. if not stoploop then
  2423. NotFirstIteration := True;
  2424. until stoploop or (PassCount >= MaxCount);
  2425. end;
  2426. procedure TAOptObj.PeepHoleOptPass2;
  2427. const
  2428. MaxPasses_Pass2 = 8;
  2429. var
  2430. p: tai;
  2431. stoploop: Boolean;
  2432. PassCount: Cardinal;
  2433. begin
  2434. PassCount := 0;
  2435. { Pass 2 is only executed multiple times under -O3 and above }
  2436. NotFirstIteration := False;
  2437. repeat
  2438. stoploop := True;
  2439. p := BlockStart;
  2440. ClearUsedRegs;
  2441. while (p <> BlockEnd) Do
  2442. begin
  2443. prefetch(pointer(p.Next)^);
  2444. if PeepHoleOptPass2Cpu(p) then
  2445. begin
  2446. stoploop := False;
  2447. continue;
  2448. end;
  2449. if assigned(p) then
  2450. begin
  2451. p:=tai(p.next);
  2452. UpdateUsedRegs(p);
  2453. end;
  2454. end;
  2455. Inc(PassCount);
  2456. if not stoploop then
  2457. NotFirstIteration := True;
  2458. until stoploop or not (cs_opt_level3 in current_settings.optimizerswitches) or (PassCount >= MaxPasses_Pass2);
  2459. end;
  2460. procedure TAOptObj.PostPeepHoleOpts;
  2461. var
  2462. p: tai;
  2463. begin
  2464. p := BlockStart;
  2465. ClearUsedRegs;
  2466. while (p <> BlockEnd) Do
  2467. begin
  2468. prefetch(pointer(p.Next)^);
  2469. if PostPeepHoleOptsCpu(p) then
  2470. continue;
  2471. if assigned(p) then
  2472. p := tai(UpdateUsedRegsAndOptimize(p).Next);
  2473. end;
  2474. end;
  2475. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  2476. begin
  2477. result := false;
  2478. end;
  2479. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  2480. begin
  2481. result := false;
  2482. end;
  2483. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  2484. begin
  2485. result := false;
  2486. end;
  2487. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  2488. begin
  2489. result := false;
  2490. end;
  2491. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  2492. var
  2493. p: tai;
  2494. ri: tregisterindex;
  2495. reg: TRegister;
  2496. commentstr: AnsiString;
  2497. registers_found: Boolean;
  2498. begin
  2499. p:=tai(AsmL.First);
  2500. while (p<>AsmL.Last) Do
  2501. begin
  2502. if p.typ=ait_instruction then
  2503. begin
  2504. {$ifdef x86}
  2505. taicpu(p).SetOperandOrder(op_att);
  2506. {$endif x86}
  2507. commentstr:='Instruction reads from';
  2508. registers_found:=false;
  2509. for ri in tregisterindex do
  2510. begin
  2511. reg:=regnumber_table[ri];
  2512. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) and
  2513. { Modified registers are handled below }
  2514. not RegModifiedByInstruction(reg,p) then
  2515. begin
  2516. commentstr:=commentstr+' '+std_regname(reg);
  2517. registers_found:=true;
  2518. end;
  2519. end;
  2520. if not registers_found then
  2521. commentstr:=commentstr+' no registers';
  2522. commentstr:=commentstr+', modifies';
  2523. registers_found:=false;
  2524. for ri in tregisterindex do
  2525. begin
  2526. reg:=regnumber_table[ri];
  2527. if (reg<>NR_NO) and RegModifiedByInstruction(reg,p) and
  2528. { Pure writes are handled below }
  2529. not RegLoadedWithNewValue(reg,p) then
  2530. begin
  2531. commentstr:=commentstr+' '+std_regname(reg);
  2532. registers_found:=true;
  2533. end;
  2534. end;
  2535. if not registers_found then
  2536. commentstr:=commentstr+' no registers';
  2537. commentstr:=commentstr+' and writes new values to';
  2538. registers_found:=false;
  2539. for ri in tregisterindex do
  2540. begin
  2541. reg:=regnumber_table[ri];
  2542. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  2543. begin
  2544. commentstr:=commentstr+' '+std_regname(reg);
  2545. registers_found:=true;
  2546. end;
  2547. end;
  2548. if not registers_found then
  2549. commentstr:=commentstr+' no registers';
  2550. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  2551. end;
  2552. p:=tai(p.next);
  2553. end;
  2554. end;
  2555. End.