aoptobj.pas 106 KB

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