aoptobj.pas 94 KB

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