aoptobj.pas 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878
  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. {$ifndef JVM}
  331. function OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  332. {$endif JVM}
  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; inline;
  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 (tai_regalloc(StartPai).ratype=ra_alloc) and
  1187. SuperRegistersEqual(tai_regalloc(StartPai).Reg,Reg) then
  1188. begin
  1189. Result:=tai_regalloc(StartPai);
  1190. exit;
  1191. end;
  1192. StartPai := Tai(StartPai.Previous);
  1193. End
  1194. else
  1195. exit;
  1196. Until false;
  1197. End;
  1198. class function TAOptObj.FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  1199. Begin
  1200. Result:=nil;
  1201. Repeat
  1202. While Assigned(StartPai) And
  1203. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  1204. ((StartPai.typ = ait_label) and
  1205. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1206. StartPai := Tai(StartPai.Next);
  1207. If Assigned(StartPai) And
  1208. (StartPai.typ = ait_regAlloc) Then
  1209. Begin
  1210. if (tai_regalloc(StartPai).ratype=ra_dealloc) and
  1211. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  1212. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  1213. begin
  1214. Result:=tai_regalloc(StartPai);
  1215. exit;
  1216. end;
  1217. StartPai := Tai(StartPai.Next);
  1218. End
  1219. else
  1220. exit;
  1221. Until false;
  1222. End;
  1223. class function TAOptObj.FindTempDeAlloc(Offset: ASizeInt; StartPai: Tai): tai_tempalloc;
  1224. Begin
  1225. Result:=nil;
  1226. Repeat
  1227. While Assigned(StartPai) And
  1228. ((StartPai.typ in (SkipInstr - [ait_tempalloc])) Or
  1229. ((StartPai.typ = ait_label) and
  1230. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  1231. StartPai := Tai(StartPai.Next);
  1232. If Assigned(StartPai) And
  1233. (StartPai.typ = ait_tempalloc) Then
  1234. Begin
  1235. if not(tai_tempalloc(StartPai).allocation) and
  1236. (tai_tempalloc(StartPai).temppos = Offset) then
  1237. begin
  1238. Result:=tai_tempalloc(StartPai);
  1239. exit;
  1240. end;
  1241. StartPai := Tai(StartPai.Next);
  1242. End
  1243. else
  1244. exit;
  1245. Until false;
  1246. End;
  1247. { allocates register reg between (and including) instructions p1 and p2
  1248. the type of p1 and p2 must not be in SkipInstr }
  1249. procedure TAOptObj.AllocRegBetween(reg: tregister; p1, p2: tai; var initialusedregs: TAllUsedRegs);
  1250. var
  1251. hp, start: tai;
  1252. Po: PInteger;
  1253. removedsomething,
  1254. firstRemovedWasAlloc,
  1255. lastRemovedWasDealloc: boolean;
  1256. begin
  1257. {$ifdef EXTDEBUG}
  1258. { if assigned(p1.optinfo) and
  1259. (ptaiprop(p1.optinfo)^.usedregs <> initialusedregs) then
  1260. internalerror(2004101010); }
  1261. {$endif EXTDEBUG}
  1262. if not Assigned(p2) then
  1263. { We need a valid final instruction }
  1264. InternalError(2022010401);
  1265. start := p1;
  1266. if (reg = NR_STACK_POINTER_REG) or
  1267. (reg = current_procinfo.framepointer) or
  1268. not(assigned(p1)) then
  1269. { this happens with registers which are loaded implicitely, outside the }
  1270. { current block (e.g. esi with self) }
  1271. exit;
  1272. {$ifdef allocregdebug}
  1273. insertllitem(p1.previous,p1,tai_comment.Create(strpnew('allocating '+std_regname(reg)+' from here...')));
  1274. insertllitem(p2,p2.next,tai_comment.Create(strpnew('allocated '+std_regname(reg)+' till here...')));
  1275. {$endif allocregdebug}
  1276. { make sure we allocate it for this instruction }
  1277. getnextinstruction(p2,p2);
  1278. lastRemovedWasDealloc := false;
  1279. removedSomething := false;
  1280. firstRemovedWasAlloc := false;
  1281. { do it the safe way: always allocate the full super register,
  1282. as we do no register re-allocation in the peephole optimizer,
  1283. this does not hurt
  1284. }
  1285. case getregtype(reg) of
  1286. R_MMREGISTER:
  1287. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1288. R_INTREGISTER:
  1289. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1290. R_FPUREGISTER:
  1291. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1292. R_ADDRESSREGISTER:
  1293. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1294. R_SPECIALREGISTER:
  1295. reg:=newreg(R_SPECIALREGISTER,getsupreg(reg),R_SUBWHOLE);
  1296. else
  1297. Internalerror(2018030701);
  1298. end;
  1299. if not(RegInUsedRegs(reg,initialusedregs)) then
  1300. begin
  1301. hp := tai_regalloc.alloc(reg,nil);
  1302. insertllItem(p1.previous,p1,hp);
  1303. IncludeRegInUsedRegs(reg,initialusedregs);
  1304. lastRemovedWasDealloc := True; { If no tai_regallocs are found at all, treat as if the last one was a deallocation }
  1305. end;
  1306. while assigned(p1) and
  1307. (p1 <> p2) do
  1308. begin
  1309. if assigned(p1.optinfo) then
  1310. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1311. p1 := tai(p1.next);
  1312. repeat
  1313. while assigned(p1) and
  1314. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1315. p1 := tai(p1.next);
  1316. { remove all allocation/deallocation info about the register in between }
  1317. if assigned(p1) and
  1318. (p1.typ = ait_regalloc) then
  1319. begin
  1320. { same super register, different sub register? }
  1321. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1322. begin
  1323. if (getsubreg(reg)<>R_SUBMMWHOLE) and { R_SUBMMWHOLE is below R_SUBMMX, R_SUBMMY and R_SUBMMZ }
  1324. ((getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH)) then
  1325. internalerror(2016101501);
  1326. tai_regalloc(p1).reg:=reg;
  1327. end;
  1328. if tai_regalloc(p1).reg=reg then
  1329. begin
  1330. if not removedSomething then
  1331. begin
  1332. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1333. removedSomething := true;
  1334. end;
  1335. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1336. hp := tai(p1.Next);
  1337. asml.Remove(p1);
  1338. p1.free;
  1339. p1 := hp;
  1340. end
  1341. else
  1342. p1 := tai(p1.next);
  1343. end;
  1344. until not(assigned(p1)) or
  1345. not(p1.typ in SkipInstr);
  1346. end;
  1347. if assigned(p1) then
  1348. begin
  1349. if firstRemovedWasAlloc then
  1350. begin
  1351. hp := tai_regalloc.Alloc(reg,nil);
  1352. insertLLItem(start.previous,start,hp);
  1353. end;
  1354. if lastRemovedWasDealloc then
  1355. begin
  1356. hp := tai_regalloc.DeAlloc(reg,nil);
  1357. insertLLItem(p1.previous,p1,hp);
  1358. end;
  1359. end;
  1360. end;
  1361. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1362. begin
  1363. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1364. RegUsedAfterInstruction :=
  1365. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1366. not(regLoadedWithNewValue(reg,p)) and
  1367. (
  1368. not(GetNextInstruction(p,p)) or
  1369. InstructionLoadsFromReg(reg,p) or
  1370. not(regLoadedWithNewValue(reg,p))
  1371. );
  1372. end;
  1373. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1374. begin
  1375. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1376. RegLoadedWithNewValue(reg,p);
  1377. end;
  1378. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1379. var
  1380. hp1 : tai;
  1381. begin
  1382. result:=GetNextInstruction(p,hp1);
  1383. { p will be removed, update used register as we continue
  1384. with the next instruction after p }
  1385. UpdateUsedRegs(tai(p.Next));
  1386. AsmL.Remove(p);
  1387. p.Free;
  1388. p:=hp1;
  1389. end;
  1390. procedure TAOptObj.RemoveCurrentP(var p: tai; const hp1: tai); inline;
  1391. begin
  1392. if (p=hp1) then
  1393. internalerror(2020120501);
  1394. UpdateUsedRegs(tai(p.Next));
  1395. AsmL.Remove(p);
  1396. p.Free;
  1397. p := hp1;
  1398. end;
  1399. procedure TAOptObj.RemoveInstruction(const hp: tai); inline;
  1400. begin
  1401. AsmL.Remove(hp);
  1402. hp.Free;
  1403. end;
  1404. function FindLiveLabel(hp: tai; var l: tasmlabel): Boolean;
  1405. var
  1406. next: tai;
  1407. begin
  1408. FindLiveLabel := false;
  1409. while True do
  1410. begin
  1411. while assigned(hp.next) and
  1412. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1413. hp := tai(hp.next);
  1414. next := tai(hp.next);
  1415. if assigned(next) and
  1416. (tai(next).typ = ait_label) then
  1417. begin
  1418. l := tai_label(next).labsym;
  1419. if not l.is_used then
  1420. begin
  1421. { Unsafe label }
  1422. hp := next;
  1423. Continue;
  1424. end;
  1425. FindLiveLabel := true;
  1426. end;
  1427. Exit;
  1428. end;
  1429. end;
  1430. {$push}
  1431. {$r-}
  1432. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1433. begin
  1434. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1435. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1436. getlabelwithsym := labelinfo^.labeltable^[sym.labelnr-labelinfo^.lowlabel].paiobj
  1437. else
  1438. getlabelwithsym := nil;
  1439. end;
  1440. {$pop}
  1441. { Returns True if hp is an unconditional jump to a label }
  1442. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1443. begin
  1444. {$if defined(avr) or defined(z80)}
  1445. result:=(hp.opcode in aopt_uncondjmp) and
  1446. {$else}
  1447. result:=(hp.opcode=aopt_uncondjmp) and
  1448. {$endif}
  1449. {$if defined(arm) or defined(aarch64) or defined(z80)}
  1450. (hp.condition=c_None) and
  1451. {$endif arm or aarch64 or z80}
  1452. (hp.ops>0) and
  1453. {$if defined(riscv32) or defined(riscv64)}
  1454. (hp.oper[0]^.reg=NR_X0) and
  1455. {$endif riscv}
  1456. (JumpTargetOp(hp)^.typ = top_ref) and
  1457. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1458. end;
  1459. { Returns True if hp is any jump to a label }
  1460. function IsJumpToLabel(hp: taicpu): boolean;
  1461. begin
  1462. result:=hp.is_jmp and
  1463. (hp.ops>0) and
  1464. (JumpTargetOp(hp)^.typ = top_ref) and
  1465. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1466. end;
  1467. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1468. var
  1469. hp2: tai;
  1470. begin
  1471. hp2:=tai(hp1.next);
  1472. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1473. hp2:=tai(hp2.next);
  1474. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1475. (taicpu(hp2).opcode=A_NOP) then
  1476. begin
  1477. asml.remove(hp2);
  1478. hp2.free;
  1479. end;
  1480. { Anything except A_NOP must be left in place: these instructions
  1481. execute before branch, so code stays correct if branch is removed. }
  1482. end;
  1483. { Output debug message to console - null function if EXTDEBUG is not defined }
  1484. class procedure TAOptObj.DebugWrite(Message: string); inline;
  1485. begin
  1486. {$ifdef DEBUG_JUMP}
  1487. WriteLn(Message);
  1488. {$else DEBUG_JUMP}
  1489. { Do nothing }
  1490. {$endif DEBUG_JUMP}
  1491. end;
  1492. { Converts a conditional jump into an unconditional jump. Only call this
  1493. procedure on an instruction that you already know is a conditional jump }
  1494. procedure TAOptObj.MakeUnconditional(p: taicpu);
  1495. begin
  1496. { TODO: If anyone can improve this particular optimisation to work on
  1497. AVR, please do (it's currently not called at all). [Kit] }
  1498. {$if not defined(avr)}
  1499. {$if defined(powerpc) or defined(powerpc64)}
  1500. p.condition.cond := C_None;
  1501. p.condition.simple := True;
  1502. {$else powerpc}
  1503. p.condition := C_None;
  1504. {$endif powerpc}
  1505. {$ifndef z80}
  1506. p.opcode := aopt_uncondjmp;
  1507. {$endif not z80}
  1508. {$ifdef RISCV}
  1509. p.loadoper(1, p.oper[p.ops-1]^);
  1510. p.loadreg(0, NR_X0);
  1511. p.ops:=2;
  1512. {$endif}
  1513. {$ifdef xtensa}
  1514. p.opcode := aopt_uncondjmp;
  1515. p.loadoper(0, p.oper[p.ops-1]^);
  1516. p.ops:=1;
  1517. {$endif}
  1518. {$endif not avr}
  1519. {$ifdef mips}
  1520. { MIPS conditional jump instructions also conntain register
  1521. operands. A proper implementation is needed here. }
  1522. internalerror(2020071301);
  1523. {$endif}
  1524. end;
  1525. { Removes all instructions between an unconditional jump and the next label.
  1526. Returns True if a jump in between was removed (as it may open up new
  1527. optimisations if the label appeared earlier in the stream) }
  1528. function TAOptObj.RemoveDeadCodeAfterJump(p: tai): Boolean;
  1529. const
  1530. {$ifdef JVM}
  1531. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_jcatch];
  1532. {$else JVM}
  1533. { Stop if it reaches SEH directive information in the form of
  1534. consts, which may occur if RemoveDeadCodeAfterJump is called on
  1535. the final RET instruction on x86, for example }
  1536. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label];
  1537. {$endif JVM}
  1538. var
  1539. hp1, hp2: tai;
  1540. begin
  1541. { the following code removes all code between a jmp and the next label,
  1542. because it can never be executed
  1543. }
  1544. Result := False;
  1545. while GetNextInstruction(p, hp1) and
  1546. (hp1 <> BlockEnd) and
  1547. not (hp1.typ in TaiFence) do
  1548. begin
  1549. if (hp1.typ = ait_instruction) and
  1550. taicpu(hp1).is_jmp and
  1551. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1552. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1553. begin
  1554. { If the destination label appears earlier, it may permit
  1555. further optimisations, so signal this in the Result }
  1556. Result := True;
  1557. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1558. end;
  1559. { don't kill start/end of assembler block,
  1560. no-line-info-start/end etc }
  1561. if (hp1.typ<>ait_marker) and
  1562. ((hp1.typ<>ait_cfi) or
  1563. (tai_cfi_base(hp1).cfityp<>cfi_endproc)) then
  1564. begin
  1565. {$ifdef cpudelayslot}
  1566. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1567. RemoveDelaySlot(hp1);
  1568. {$endif cpudelayslot}
  1569. hp2 := hp1;
  1570. while (hp2.typ = ait_align) do
  1571. begin
  1572. { Only remove the align if a label doesn't immediately follow }
  1573. if GetNextInstruction(hp2, hp2) and (hp2.typ = ait_label) then
  1574. { The label is unskippable }
  1575. Exit;
  1576. { Check again in case there's more than one adjacent alignment entry
  1577. (a frequent construct under x86, for example). [Kit] }
  1578. end;
  1579. asml.remove(hp1);
  1580. hp1.free;
  1581. end
  1582. else
  1583. p:=hp1;
  1584. end;
  1585. end;
  1586. { If hp is a label, strip it if its reference count is zero. Repeat until
  1587. a non-label is found, or a label with a non-zero reference count.
  1588. True is returned if something was stripped }
  1589. function TAOptObj.StripDeadLabels(hp: tai; var NextValid: tai): Boolean;
  1590. var
  1591. tmp, tmpNext: tai;
  1592. hp1: tai;
  1593. CurrentAlign: tai;
  1594. FoundLabels: Boolean;
  1595. begin
  1596. CurrentAlign := nil;
  1597. Result := False;
  1598. hp1 := hp;
  1599. NextValid := hp;
  1600. { Stop if hp is an instruction, for example }
  1601. while (hp1 <> BlockEnd) and (hp1.typ in [ait_label,ait_align]) do
  1602. begin
  1603. prefetch(pointer(hp1.Next)^);
  1604. case hp1.typ of
  1605. ait_label:
  1606. begin
  1607. { Set tmp to the next valid entry }
  1608. tmp := tai(hp1.Next);
  1609. with tai_label(hp1).labsym do
  1610. begin
  1611. if (labeltype <> alt_jump) then
  1612. begin
  1613. { Non-jump label - skip over }
  1614. hp1 := tmp;
  1615. Continue;
  1616. end;
  1617. if is_used or (bind <> AB_LOCAL) then
  1618. begin
  1619. { Valid label }
  1620. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1621. Exit;
  1622. end;
  1623. end;
  1624. DebugWrite('JUMP DEBUG: Removed label ' + tostr(TAsmLabel(tai_label(hp1).labsym).labelnr));
  1625. { Remove label }
  1626. if (NextValid = hp1) then
  1627. NextValid := tmp;
  1628. RemoveInstruction(hp1);
  1629. hp1 := tmp;
  1630. Result := True;
  1631. Continue;
  1632. end;
  1633. { Also remove the align if it comes before an unused label }
  1634. ait_align:
  1635. begin
  1636. { Signal that we can possibly delete this align entry }
  1637. CurrentAlign := hp1;
  1638. tmp := tai(hp1.Next);
  1639. if tmp = BlockEnd then
  1640. { End of block }
  1641. Exit;
  1642. repeat
  1643. case tmp.typ of
  1644. ait_align: { Merge the aligns if permissible }
  1645. begin
  1646. { Check the maxbytes field though, since this may result in the
  1647. alignment being ignored }
  1648. if ((tai_align_abstract(hp1).maxbytes = 0) and (tai_align_abstract(tmp).maxbytes = 0)) or
  1649. { If a maxbytes field is present, only merge if the aligns have the same granularity }
  1650. ((tai_align_abstract(hp1).aligntype = tai_align_abstract(tmp).aligntype)) then
  1651. begin
  1652. with tai_align_abstract(hp1) do
  1653. begin
  1654. aligntype := max(aligntype, tai_align_abstract(tmp).aligntype);
  1655. maxbytes := max(maxbytes, tai_align_abstract(tmp).maxbytes);
  1656. fillsize := max(fillsize, tai_align_abstract(tmp).fillsize);
  1657. use_op := use_op or tai_align_abstract(tmp).use_op;
  1658. if use_op and (tai_align_abstract(tmp).fillop <> 0) then
  1659. fillop := tai_align_abstract(tmp).fillop;
  1660. end;
  1661. tmpNext := tai(tmp.Next);
  1662. RemoveInstruction(tmp);
  1663. Result := True;
  1664. tmp := tmpNext;
  1665. end
  1666. else
  1667. tmp := tai(tmp.Next);
  1668. Continue;
  1669. end;
  1670. ait_label:
  1671. begin
  1672. repeat
  1673. with tai_label(tmp).labsym do
  1674. begin
  1675. if (labeltype <> alt_jump) then
  1676. begin
  1677. { Non-jump label - skip over }
  1678. tmp := tai(tmp.Next);
  1679. Continue;
  1680. end;
  1681. if is_used or (bind <> AB_LOCAL) then
  1682. begin
  1683. { Valid label }
  1684. DebugWrite('JUMP DEBUG: Last label in cluster:' + tostr(labelnr));
  1685. Exit;
  1686. end;
  1687. end;
  1688. DebugWrite('JUMP DEBUG: Removed label ' + tai_label(tmp).labsym.name);
  1689. { Remove label }
  1690. tmpNext := tai(tmp.Next);
  1691. RemoveInstruction(tmp);
  1692. Result := True;
  1693. tmp := tmpNext;
  1694. { Loop here for a minor performance gain }
  1695. until (tmp = BlockEnd) or (tmp.typ <> ait_label);
  1696. { Re-evaluate the align and see what follows }
  1697. Continue;
  1698. end
  1699. else
  1700. begin
  1701. if tmp.typ in SkipInstr then
  1702. begin
  1703. tmp := tai(tmp.Next);
  1704. Continue;
  1705. end;
  1706. { Set hp1 to the instruction after the align, because the
  1707. align might get deleted later and hence set NextValid
  1708. to a dangling pointer. [Kit] }
  1709. hp1 := tmp;
  1710. Break;
  1711. end;
  1712. end;
  1713. until (tmp = BlockEnd);
  1714. { Break out of the outer loop if the above Break is called }
  1715. if (hp1 = tmp) then
  1716. Break;
  1717. end
  1718. else
  1719. Break;
  1720. end;
  1721. hp1 := tai(hp1.Next);
  1722. end;
  1723. if Assigned(CurrentAlign) then
  1724. begin
  1725. { Remember what the first one was }
  1726. tmpNext := CurrentAlign;
  1727. { Remove the alignment field (but only if the next valid entry is not a live label) }
  1728. repeat
  1729. tmp := tai(CurrentAlign.next);
  1730. { Any labels found are non-jump labels and will be skipped over }
  1731. if CurrentAlign.typ = ait_align then
  1732. begin
  1733. DebugWrite('JUMP DEBUG: Alignment field removed');
  1734. RemoveInstruction(CurrentAlign);
  1735. end;
  1736. CurrentAlign := tmp;
  1737. until not Assigned(CurrentAlign) or not (CurrentAlign.typ in [ait_align, ait_label]);
  1738. if (NextValid = tmpNext) then
  1739. NextValid := tmp;
  1740. end;
  1741. end;
  1742. { Strips a label and any aligns that appear before it (if hp points to
  1743. them rather than the label). Only call this procedure on a label that
  1744. you already know is no longer referenced }
  1745. procedure TAOptObj.StripLabelFast(hp: tai);
  1746. var
  1747. tmp: tai;
  1748. begin
  1749. repeat
  1750. case hp.typ of
  1751. ait_align:
  1752. begin
  1753. tmp := tai(hp.Next);
  1754. asml.Remove(hp);
  1755. hp.Free;
  1756. hp := tmp;
  1757. { Control flow will now return to 'repeat' }
  1758. end;
  1759. ait_label:
  1760. begin
  1761. {$ifdef EXTDEBUG}
  1762. { When not in debug mode, deleting a live label will cause an
  1763. access violation later on. [Kit] }
  1764. if tai_label(hp).labsym.getrefs <> 0 then
  1765. InternalError(2019110802);
  1766. {$endif EXTDEBUG}
  1767. asml.Remove(hp);
  1768. hp.Free;
  1769. Exit;
  1770. end;
  1771. else
  1772. begin
  1773. { Might be a comment or temporary allocation entry }
  1774. if not (hp.typ in SkipInstr) then
  1775. InternalError(2019110801);
  1776. hp := tai(hp.Next);
  1777. end;
  1778. end;
  1779. until False;
  1780. end;
  1781. { If a group of labels are clustered, change the jump to point to the last one
  1782. that is still referenced }
  1783. function TAOptObj.CollapseLabelCluster(jump: tai; var lbltai: tai): TAsmLabel;
  1784. var
  1785. LastLabel: TAsmLabel;
  1786. hp2: tai;
  1787. begin
  1788. Result := tai_label(lbltai).labsym;
  1789. LastLabel := Result;
  1790. hp2 := tai(lbltai.next);
  1791. while (hp2 <> BlockEnd) and (hp2.typ in SkipInstr + [ait_align, ait_label]) do
  1792. begin
  1793. if (hp2.typ = ait_label) and
  1794. (tai_label(hp2).labsym.is_used) and
  1795. (tai_label(hp2).labsym.labeltype = alt_jump) then
  1796. LastLabel := tai_label(hp2).labsym;
  1797. hp2 := tai(hp2.next);
  1798. end;
  1799. if (Result <> LastLabel) then
  1800. begin
  1801. Result.decrefs;
  1802. JumpTargetOp(taicpu(jump))^.ref^.symbol := LastLabel;
  1803. LastLabel.increfs;
  1804. Result := LastLabel;
  1805. lbltai := hp2;
  1806. end;
  1807. end;
  1808. {$ifndef JVM}
  1809. function TAOptObj.OptimizeConditionalJump(CJLabel: TAsmLabel; var p: tai; hp1: tai; var stoploop: Boolean): Boolean;
  1810. var
  1811. hp2: tai;
  1812. NCJLabel: TAsmLabel;
  1813. begin
  1814. Result := False;
  1815. while (hp1 <> BlockEnd) do
  1816. begin
  1817. StripDeadLabels(hp1, hp1);
  1818. if (hp1 <> BlockEnd) and
  1819. (tai(hp1).typ=ait_instruction) and
  1820. IsJumpToLabel(taicpu(hp1)) then
  1821. begin
  1822. NCJLabel := TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol);
  1823. if IsJumpToLabelUncond(taicpu(hp1)) then
  1824. begin
  1825. { Do it now to get it out of the way and to aid optimisations
  1826. later on in this method }
  1827. if RemoveDeadCodeAfterJump(taicpu(hp1)) then
  1828. stoploop := False;
  1829. hp2 := getlabelwithsym(NCJLabel);
  1830. if Assigned(hp2) then
  1831. { Collapse the cluster now to aid optimisation and potentially
  1832. cut down on the number of iterations required }
  1833. NCJLabel := CollapseLabelCluster(hp1, hp2);
  1834. { GetNextInstruction could be factored out, but hp2 might be
  1835. different after "RemoveDeadCodeAfterJump" }
  1836. GetNextInstruction(hp1, hp2);
  1837. { Check for:
  1838. jmp<cond> @Lbl
  1839. jmp @Lbl
  1840. }
  1841. if (CJLabel = NCJLabel) then
  1842. begin
  1843. DebugMsg(SPeepholeOptimization+'Short-circuited conditional jump',p);
  1844. { Both jumps go to the same label }
  1845. CJLabel.decrefs;
  1846. {$ifdef cpudelayslot}
  1847. RemoveDelaySlot(p);
  1848. {$endif cpudelayslot}
  1849. RemoveCurrentP(p, hp1);
  1850. Result := True;
  1851. Exit;
  1852. end;
  1853. if FindLabel(CJLabel, hp2) then
  1854. begin
  1855. { change the following jumps:
  1856. jmp<cond> CJLabel jmp<inv_cond> NCJLabel
  1857. jmp NCJLabel >>> <code>
  1858. CJLabel: NCJLabel:
  1859. <code>
  1860. NCJLabel:
  1861. }
  1862. {$if defined(arm) or defined(aarch64)}
  1863. if (taicpu(p).condition<>C_None)
  1864. {$if defined(aarch64)}
  1865. { can't have conditional branches to
  1866. global labels on AArch64, because the
  1867. offset may become too big }
  1868. and (NCJLabel.bind=AB_LOCAL)
  1869. {$endif aarch64}
  1870. then
  1871. begin
  1872. {$endif arm or aarch64}
  1873. DebugMsg(SPeepholeOptimization+'Conditional jump inversion',p);
  1874. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1875. CJLabel.decrefs;
  1876. JumpTargetOp(taicpu(p))^.ref^.symbol := NCJLabel;
  1877. { when freeing hp1, the reference count
  1878. isn't decreased, so don't increase }
  1879. {$ifdef cpudelayslot}
  1880. RemoveDelaySlot(hp1);
  1881. {$endif cpudelayslot}
  1882. RemoveInstruction(hp1);
  1883. stoploop := False;
  1884. if not CJLabel.is_used then
  1885. begin
  1886. CJLabel := NCJLabel;
  1887. StripDeadLabels(tai(p.Next), hp1);
  1888. if (hp1 = BlockEnd) then
  1889. Exit;
  1890. { Attempt another iteration in case more jumps follow }
  1891. if (hp1.typ in SkipInstr) then
  1892. GetNextInstruction(hp1, hp1);
  1893. Continue;
  1894. end;
  1895. {$if defined(arm) or defined(aarch64)}
  1896. end;
  1897. {$endif arm or aarch64}
  1898. end
  1899. else if CollapseZeroDistJump(hp1, NCJLabel) then
  1900. begin
  1901. if (hp1 = BlockEnd) then
  1902. Exit;
  1903. { Attempt another iteration in case more jumps follow }
  1904. if (hp1.typ in SkipInstr) then
  1905. GetNextInstruction(hp1, hp1);
  1906. Continue;
  1907. end;
  1908. end
  1909. else
  1910. begin
  1911. { Do not try to optimize if the test generating the condition
  1912. is the same instruction, like 'bne $v0,$zero,.Lj3' for MIPS }
  1913. if (taicpu(p).ops>1) or (taicpu(hp1).ops>1) then
  1914. exit;
  1915. { Check for:
  1916. jmp<cond1> @Lbl1
  1917. jmp<cond2> @Lbl2
  1918. Remove 2nd jump if conditions are equal or cond2 is a subset of cond1
  1919. (as if the first jump didn't branch, then neither will the 2nd)
  1920. }
  1921. if condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  1922. begin
  1923. DebugMsg(SPeepholeOptimization+'Dominated conditional jump',p);
  1924. NCJLabel.decrefs;
  1925. GetNextInstruction(hp1, hp2);
  1926. {$ifdef cpudelayslot}
  1927. RemoveDelaySlot(hp1);
  1928. {$endif cpudelayslot}
  1929. RemoveInstruction(hp1);
  1930. hp1 := hp2;
  1931. { Flag another pass in case @Lbl2 appeared earlier in the procedure and is now a dead label }
  1932. stoploop := False;
  1933. { Attempt another iteration in case more jumps follow }
  1934. Continue;
  1935. end;
  1936. { Check for:
  1937. jmp<cond1> @Lbl1
  1938. jmp<cond2> @Lbl2
  1939. And inv(cond1) is a subset of cond2 (e.g. je followed by jne, or jae followed by jbe) )
  1940. }
  1941. if condition_in(inverse_cond(taicpu(p).condition), taicpu(hp1).condition) then
  1942. begin
  1943. GetNextInstruction(hp1, hp2);
  1944. { If @lbl1 immediately follows jmp<cond2>, we can remove
  1945. the first jump completely }
  1946. if FindLabel(CJLabel, hp2) then
  1947. begin
  1948. { However, to be absolutely correct, cond2 must be changed to inv(cond1) }
  1949. taicpu(hp1).condition := inverse_cond(taicpu(p).condition);
  1950. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - removed first jump',p);
  1951. CJLabel.decrefs;
  1952. {$ifdef cpudelayslot}
  1953. RemoveDelaySlot(p);
  1954. {$endif cpudelayslot}
  1955. RemoveCurrentP(p, hp1);
  1956. Result := True;
  1957. Exit;
  1958. {$if not defined(avr)}
  1959. end
  1960. else
  1961. { NOTE: There is currently no watertight, cross-platform way to create
  1962. an unconditional jump without access to the cg object. If anyone can
  1963. improve this particular optimisation to work on AVR,
  1964. please do. [Kit] }
  1965. begin
  1966. { Since inv(cond1) is a subset of cond2, jmp<cond2> will always branch if
  1967. jmp<cond1> does not, so change jmp<cond2> to an unconditional jump. }
  1968. DebugMsg(SPeepholeOptimization+'jmp<cond> before jmp<inv_cond> - made second jump unconditional',p);
  1969. MakeUnconditional(taicpu(hp1));
  1970. { NOTE: Changing the jump to unconditional won't open up new opportunities
  1971. for GetFinalDestination on earlier jumps because there's no live label
  1972. between the two jump instructions, so setting 'stoploop' to False only
  1973. wastes time. [Kit] }
  1974. { See if more optimisations are possible }
  1975. Continue;
  1976. {$endif}
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. if GetFinalDestination(taicpu(p),0) then
  1982. stoploop := False;
  1983. Exit;
  1984. end;
  1985. end;
  1986. {$endif JVM}
  1987. function TAOptObj.CollapseZeroDistJump(var p: tai; ThisLabel: TAsmLabel): Boolean;
  1988. var
  1989. hp1: tai;
  1990. begin
  1991. Result := False;
  1992. if not GetNextInstruction(p,hp1) then
  1993. exit;
  1994. if (hp1 = BlockEnd) then
  1995. Exit;
  1996. { remove jumps to labels coming right after them }
  1997. if FindLabel(ThisLabel, hp1) and
  1998. { Cannot remove the first instruction }
  1999. (p<>StartPoint) then
  2000. begin
  2001. ThisLabel.decrefs;
  2002. {$ifdef cpudelayslot}
  2003. RemoveDelaySlot(p);
  2004. {$endif cpudelayslot}
  2005. hp1 := tai(p.Next);
  2006. { Use RemoveInstruction, not RemoveCurrentP, since the latter also
  2007. updates the registers }
  2008. RemoveInstruction(p);
  2009. p := hp1;
  2010. Result := True;
  2011. end;
  2012. end;
  2013. function TAOptObj.CanDoJumpOpts: Boolean;
  2014. begin
  2015. { Always allow by default }
  2016. Result := True;
  2017. end;
  2018. function TAOptObj.DoJumpOptimizations(var p: tai; var stoploop: Boolean): Boolean;
  2019. var
  2020. hp1, hp2: tai;
  2021. ThisLabel: TAsmLabel;
  2022. ThisPassResult: Boolean;
  2023. begin
  2024. Result := False;
  2025. if (p.typ <> ait_instruction) or not IsJumpToLabel(taicpu(p)) then
  2026. Exit;
  2027. repeat
  2028. ThisPassResult := False;
  2029. if GetNextInstruction(p, hp1) and (hp1 <> BlockEnd) then
  2030. begin
  2031. SkipEntryExitMarker(hp1,hp1);
  2032. if (hp1 = BlockEnd) then
  2033. Exit;
  2034. ThisLabel := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  2035. hp2 := getlabelwithsym(ThisLabel);
  2036. { getlabelwithsym returning nil occurs if a label is in a
  2037. different block (e.g. on the other side of an asm...end pair). }
  2038. if Assigned(hp2) then
  2039. begin
  2040. { If there are multiple labels in a row, change the destination to the last one
  2041. in order to aid optimisation later }
  2042. ThisLabel := CollapseLabelCluster(p, hp2);
  2043. if CollapseZeroDistJump(p, ThisLabel) then
  2044. begin
  2045. stoploop := False;
  2046. Result := True;
  2047. Exit;
  2048. end;
  2049. if IsJumpToLabelUncond(taicpu(p)) then
  2050. begin
  2051. { Remove unreachable code between the jump and the next label }
  2052. ThisPassResult := RemoveDeadCodeAfterJump(taicpu(p));
  2053. if GetFinalDestination(taicpu(p), 0) or ThisPassResult then
  2054. { Might have caused some earlier labels to become dead }
  2055. stoploop := False;
  2056. end
  2057. {$ifndef JVM}
  2058. else if (taicpu(p).opcode {$ifdef z80}in{$else}={$endif} aopt_condjmp) then
  2059. ThisPassResult := OptimizeConditionalJump(ThisLabel, p, hp1, stoploop)
  2060. {$endif JVM}
  2061. ;
  2062. end;
  2063. end;
  2064. Result := Result or ThisPassResult;
  2065. until not (ThisPassResult and (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)));
  2066. end;
  2067. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  2068. {traces sucessive jumps to their final destination and sets it, e.g.
  2069. je l1 je l3 <code> <code>
  2070. l1: becomes l1:
  2071. je l2 je l3
  2072. <code> <code>
  2073. l2: l2:
  2074. jmp l3 jmp l3
  2075. the level parameter denotes how deep we have already followed the jump,
  2076. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  2077. var p1: tai;
  2078. p2: tai;
  2079. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64)}
  2080. p3: tai;
  2081. {$endif}
  2082. ThisLabel, l: tasmlabel;
  2083. begin
  2084. GetFinalDestination := false;
  2085. if level > 20 then
  2086. exit;
  2087. ThisLabel := TAsmLabel(JumpTargetOp(hp)^.ref^.symbol);
  2088. p1 := getlabelwithsym(ThisLabel);
  2089. if assigned(p1) then
  2090. begin
  2091. SkipLabels(p1,p1);
  2092. if (p1.typ = ait_instruction) and
  2093. (taicpu(p1).is_jmp) then
  2094. begin
  2095. p2 := tai(p1.Next);
  2096. if p2 = BlockEnd then
  2097. Exit;
  2098. { Collapse any zero distance jumps we stumble across }
  2099. while (p1<>StartPoint) and CollapseZeroDistJump(p1, TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol)) do
  2100. begin
  2101. { Note: Cannot remove the first instruction }
  2102. if (p1.typ in [ait_align, ait_label]) then
  2103. SkipLabels(p1, p1);
  2104. if not Assigned(p1) then
  2105. { No more valid commands }
  2106. Exit;
  2107. { Check to see that we are actually still at a jump }
  2108. if not ((tai(p1).typ = ait_instruction) and (taicpu(p1).is_jmp)) then
  2109. begin
  2110. { Required to ensure recursion works properly, but to also
  2111. return false if a jump isn't modified. [Kit] }
  2112. if level > 0 then GetFinalDestination := True;
  2113. Exit;
  2114. end;
  2115. p2 := tai(p1.Next);
  2116. if p2 = BlockEnd then
  2117. Exit;
  2118. end;
  2119. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64)}
  2120. p3 := p2;
  2121. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64}
  2122. if { the next instruction after the label where the jump hp arrives}
  2123. { is unconditional or of the same type as hp, so continue }
  2124. IsJumpToLabelUncond(taicpu(p1))
  2125. { TODO: For anyone with experience with MIPS or RISC-V, please add support for tracing
  2126. conditional jumps. [Kit] }
  2127. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64)}
  2128. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  2129. or
  2130. condition_in(hp.condition, taicpu(p1).condition) or
  2131. { the next instruction after the label where the jump hp arrives
  2132. is the opposite of hp (so this one is never taken), but after
  2133. that one there is a branch that will be taken, so perform a
  2134. little hack: set p1 equal to this instruction }
  2135. (condition_in(hp.condition, inverse_cond(taicpu(p1).condition)) and
  2136. SkipLabels(p3,p2) and
  2137. (p2.typ = ait_instruction) and
  2138. (taicpu(p2).is_jmp) and
  2139. (IsJumpToLabelUncond(taicpu(p2)) or
  2140. (condition_in(hp.condition, taicpu(p2).condition))
  2141. ) and
  2142. SetAndTest(p2,p1)
  2143. )
  2144. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64}
  2145. then
  2146. begin
  2147. { quick check for loops of the form "l5: ; jmp l5" }
  2148. if (TAsmLabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr = ThisLabel.labelnr) then
  2149. exit;
  2150. if not GetFinalDestination(taicpu(p1),succ(level)) then
  2151. exit;
  2152. { NOTE: Do not move this before the "l5: ; jmp l5" check,
  2153. because GetFinalDestination may change the destination
  2154. label of p1. [Kit] }
  2155. l := tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol);
  2156. {$if defined(aarch64)}
  2157. { can't have conditional branches to
  2158. global labels on AArch64, because the
  2159. offset may become too big }
  2160. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  2161. (l.bind<>AB_LOCAL) then
  2162. exit;
  2163. {$endif aarch64}
  2164. ThisLabel.decrefs;
  2165. JumpTargetOp(hp)^.ref^.symbol:=l;
  2166. l.increfs;
  2167. GetFinalDestination := True;
  2168. Exit;
  2169. end
  2170. {$if not defined(MIPS) and not defined(riscv64) and not defined(riscv32) and not defined(JVM) and not defined(loongarch64)}
  2171. else
  2172. if condition_in(inverse_cond(hp.condition), taicpu(p1).condition) then
  2173. begin
  2174. if not FindLiveLabel(p1,l) then
  2175. begin
  2176. {$ifdef finaldestdebug}
  2177. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2178. strpnew('previous label inserted'))));
  2179. {$endif finaldestdebug}
  2180. current_asmdata.getjumplabel(l);
  2181. insertllitem(p1,p1.next,tai_label.Create(l));
  2182. ThisLabel.decrefs;
  2183. JumpTargetOp(hp)^.ref^.symbol := l;
  2184. l.increfs;
  2185. GetFinalDestination := True;
  2186. { this won't work, since the new label isn't in the labeltable }
  2187. { so it will fail the rangecheck. Labeltable should become a }
  2188. { hashtable to support this: }
  2189. { GetFinalDestination(asml, hp); }
  2190. end
  2191. else
  2192. begin
  2193. {$ifdef finaldestdebug}
  2194. insertllitem(asml,p1,p1.next,tai_comment.Create(
  2195. strpnew('next label reused'))));
  2196. {$endif finaldestdebug}
  2197. l.increfs;
  2198. ThisLabel.decrefs;
  2199. JumpTargetOp(hp)^.ref^.symbol := l;
  2200. if not GetFinalDestination(hp,succ(level)) then
  2201. exit;
  2202. end;
  2203. GetFinalDestination := True;
  2204. Exit;
  2205. end;
  2206. {$endif not MIPS and not RV64 and not RV32 and not JVM and not loongarch64}
  2207. end;
  2208. end;
  2209. { Required to ensure recursion works properly, but to also
  2210. return false if a jump isn't modified. [Kit] }
  2211. if level > 0 then GetFinalDestination := True;
  2212. end;
  2213. { Attempts to reconfigure the Regallocs and Regdeallocs before p1 and
  2214. after p2 so Reg is no longer allocated between them. Returns True if the
  2215. register is no longer allocated at p1 }
  2216. function TAOptObj.TryRemoveRegAlloc(const Reg: TRegister; p1, p2: tai): Boolean;
  2217. var
  2218. CurrentAlloc: tai;
  2219. begin
  2220. Result := False;
  2221. if RegInInstruction(Reg, p1) then
  2222. { Register is definitely in use }
  2223. Exit;
  2224. { Search for the first de/alloc before p1 that relates to Reg }
  2225. CurrentAlloc := tai(p1.Previous);
  2226. repeat
  2227. while Assigned(CurrentAlloc) and
  2228. ((CurrentAlloc.typ in (SkipInstr - [ait_regAlloc])) or
  2229. ((CurrentAlloc.typ = ait_label) and
  2230. not(Tai_Label(CurrentAlloc).labsym.Is_Used))) do
  2231. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2232. if Assigned(CurrentAlloc) and
  2233. (CurrentAlloc.typ = ait_regalloc) then
  2234. begin
  2235. if (getregtype(tai_regalloc(CurrentAlloc).Reg) = getregtype(Reg)) and
  2236. (getsupreg(tai_regalloc(CurrentAlloc).Reg) = getsupreg(Reg)) then
  2237. begin
  2238. Break;
  2239. end;
  2240. CurrentAlloc := Tai(CurrentAlloc.Previous);
  2241. end
  2242. else
  2243. begin
  2244. CurrentAlloc := nil;
  2245. Break;
  2246. end;
  2247. until false;
  2248. { Remove any register allocation prior to p1 }
  2249. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2250. (tai_regalloc(CurrentAlloc).ratype = ra_alloc) then
  2251. begin
  2252. RemoveInstruction(CurrentAlloc);
  2253. Result := True;
  2254. end
  2255. else if not Assigned(CurrentAlloc) or (CurrentAlloc.typ <> ait_regalloc) or
  2256. (tai_regalloc(CurrentAlloc).ratype <> ra_dealloc) then
  2257. begin
  2258. AsmL.InsertBefore(tai_regalloc.dealloc(Reg, nil), p1);
  2259. Result := True;
  2260. end;
  2261. if (p1 <> p2) and RegInInstruction(Reg, p2) then
  2262. begin
  2263. { Reg is in use, so insert allocation before it }
  2264. AsmL.InsertBefore(tai_regalloc.alloc(Reg, nil), p2);
  2265. Exit;
  2266. end;
  2267. { If a deallocation exists, remove it since the register will no longer be allocated by this time }
  2268. CurrentAlloc := FindRegDealloc(Reg, tai(p2.Next));
  2269. if Assigned(CurrentAlloc) and (CurrentAlloc.typ = ait_regalloc) and
  2270. (tai_regalloc(CurrentAlloc).ratype = ra_dealloc) then
  2271. begin
  2272. RemoveInstruction(CurrentAlloc);
  2273. end
  2274. else
  2275. begin
  2276. { Since no deallocation was found, Register may end up being used afterwards, so add a new alloc to play safe }
  2277. AsmL.InsertAfter(tai_regalloc.alloc(Reg, nil), p2);
  2278. end;
  2279. end;
  2280. procedure TAOptObj.PrePeepHoleOpts;
  2281. var
  2282. p: tai;
  2283. begin
  2284. p := BlockStart;
  2285. ClearUsedRegs;
  2286. while (p <> BlockEnd) Do
  2287. begin
  2288. prefetch(pointer(p.Next)^);
  2289. if PrePeepHoleOptsCpu(p) then
  2290. continue;
  2291. if assigned(p) then
  2292. begin
  2293. p:=tai(p.next);
  2294. UpdateUsedRegs(p);
  2295. end;
  2296. end;
  2297. end;
  2298. procedure TAOptObj.PeepHoleOptPass1;
  2299. const
  2300. MaxPasses_Pass1: array[1..3] of Cardinal = (1, 2, 8);
  2301. var
  2302. p : tai;
  2303. stoploop, FirstInstruction, JumpOptsAvailable: boolean;
  2304. PassCount, MaxCount: Cardinal;
  2305. begin
  2306. JumpOptsAvailable := CanDoJumpOpts();
  2307. StartPoint := BlockStart;
  2308. PassCount := 0;
  2309. { Determine the maximum number of passes allowed based on the compiler switches }
  2310. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2311. { it should never take more than 8 passes, but the limit is finite to protect against faulty optimisations }
  2312. MaxCount := MaxPasses_Pass1[3]
  2313. else if (cs_opt_level2 in current_settings.optimizerswitches) then
  2314. MaxCount := MaxPasses_Pass1[2] { The original double run of Pass 1 }
  2315. else
  2316. MaxCount := MaxPasses_Pass1[1];
  2317. NotFirstIteration := False;
  2318. repeat
  2319. stoploop:=true;
  2320. p := StartPoint;
  2321. FirstInstruction := True;
  2322. ClearUsedRegs;
  2323. while Assigned(p) and (p <> BlockEnd) Do
  2324. begin
  2325. prefetch(pointer(p.Next)^);
  2326. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  2327. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  2328. UpdateUsedRegs(tai(p.next));
  2329. }
  2330. {$ifdef DEBUG_OPTALLOC}
  2331. if p.Typ=ait_instruction then
  2332. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  2333. {$endif DEBUG_OPTALLOC}
  2334. { Handle jump optimizations first }
  2335. if JumpOptsAvailable and DoJumpOptimizations(p, stoploop) then
  2336. begin
  2337. if FirstInstruction then
  2338. { Update StartPoint, since the old p was removed;
  2339. don't set FirstInstruction to False though, as
  2340. the new p might get removed too. }
  2341. StartPoint := p;
  2342. if (p.typ = ait_instruction) and IsJumpToLabel(taicpu(p)) then
  2343. Continue;
  2344. end;
  2345. if PeepHoleOptPass1Cpu(p) then
  2346. begin
  2347. stoploop:=false;
  2348. UpdateUsedRegs(p);
  2349. if FirstInstruction then
  2350. { Update StartPoint, since the old p was modified;
  2351. don't set FirstInstruction to False though, as
  2352. the new p might get modified too. }
  2353. StartPoint := p;
  2354. continue;
  2355. end;
  2356. FirstInstruction := False;
  2357. if assigned(p) then
  2358. begin
  2359. p:=tai(p.next);
  2360. UpdateUsedRegs(p);
  2361. end;
  2362. end;
  2363. Inc(PassCount);
  2364. if not stoploop then
  2365. NotFirstIteration := True;
  2366. until stoploop or (PassCount >= MaxCount);
  2367. end;
  2368. procedure TAOptObj.PeepHoleOptPass2;
  2369. const
  2370. MaxPasses_Pass2 = 8;
  2371. var
  2372. p: tai;
  2373. stoploop: Boolean;
  2374. PassCount: Cardinal;
  2375. begin
  2376. PassCount := 0;
  2377. { Pass 2 is only executed multiple times under -O3 and above }
  2378. repeat
  2379. stoploop := True;
  2380. p := BlockStart;
  2381. ClearUsedRegs;
  2382. while (p <> BlockEnd) Do
  2383. begin
  2384. prefetch(pointer(p.Next)^);
  2385. if PeepHoleOptPass2Cpu(p) then
  2386. begin
  2387. stoploop := False;
  2388. continue;
  2389. end;
  2390. if assigned(p) then
  2391. begin
  2392. p:=tai(p.next);
  2393. UpdateUsedRegs(p);
  2394. end;
  2395. end;
  2396. Inc(PassCount);
  2397. until stoploop or not (cs_opt_level3 in current_settings.optimizerswitches) or (PassCount >= MaxPasses_Pass2);
  2398. end;
  2399. procedure TAOptObj.PostPeepHoleOpts;
  2400. var
  2401. p: tai;
  2402. begin
  2403. p := BlockStart;
  2404. ClearUsedRegs;
  2405. while (p <> BlockEnd) Do
  2406. begin
  2407. prefetch(pointer(p.Next)^);
  2408. if PostPeepHoleOptsCpu(p) then
  2409. continue;
  2410. if assigned(p) then
  2411. p := tai(UpdateUsedRegsAndOptimize(p).Next);
  2412. end;
  2413. end;
  2414. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  2415. begin
  2416. result := false;
  2417. end;
  2418. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  2419. begin
  2420. result := false;
  2421. end;
  2422. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  2423. begin
  2424. result := false;
  2425. end;
  2426. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  2427. begin
  2428. result := false;
  2429. end;
  2430. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  2431. var
  2432. p: tai;
  2433. ri: tregisterindex;
  2434. reg: TRegister;
  2435. commentstr: AnsiString;
  2436. registers_found: Boolean;
  2437. begin
  2438. p:=tai(AsmL.First);
  2439. while (p<>AsmL.Last) Do
  2440. begin
  2441. if p.typ=ait_instruction then
  2442. begin
  2443. {$ifdef x86}
  2444. taicpu(p).SetOperandOrder(op_att);
  2445. {$endif x86}
  2446. commentstr:='Instruction reads';
  2447. registers_found:=false;
  2448. for ri in tregisterindex do
  2449. begin
  2450. reg:=regnumber_table[ri];
  2451. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) then
  2452. begin
  2453. commentstr:=commentstr+' '+std_regname(reg);
  2454. registers_found:=true;
  2455. end;
  2456. end;
  2457. if not registers_found then
  2458. commentstr:=commentstr+' no registers';
  2459. commentstr:=commentstr+' and writes new values in';
  2460. registers_found:=false;
  2461. for ri in tregisterindex do
  2462. begin
  2463. reg:=regnumber_table[ri];
  2464. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  2465. begin
  2466. commentstr:=commentstr+' '+std_regname(reg);
  2467. registers_found:=true;
  2468. end;
  2469. end;
  2470. if not registers_found then
  2471. commentstr:=commentstr+' no registers';
  2472. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  2473. end;
  2474. p:=tai(p.next);
  2475. end;
  2476. end;
  2477. End.