aoptobj.pas 92 KB

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