2
0

aoptobj.pas 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  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. {$i fpcdefs.inc}
  22. { general, processor independent objects for use by the assembler optimizer }
  23. Interface
  24. uses
  25. globtype,
  26. aasmbase,aasmcpu,aasmtai,aasmdata,
  27. cclasses,
  28. cgbase,cgutils,
  29. cpubase,
  30. aoptbase,aoptcpub,aoptda;
  31. { ************************************************************************* }
  32. { ********************************* Constants ***************************** }
  33. { ************************************************************************* }
  34. Const
  35. {Possible register content types}
  36. con_Unknown = 0;
  37. con_ref = 1;
  38. con_const = 2;
  39. {***************** Types ****************}
  40. Type
  41. { ************************************************************************* }
  42. { ************************* Some general type definitions ***************** }
  43. { ************************************************************************* }
  44. TRefCompare = Function(const r1, r2: TReference): Boolean;
  45. //!!! FIXME
  46. TRegArray = Array[byte] of tsuperregister;
  47. TRegSet = tcpuregisterset;
  48. { possible actions on an operand: read, write or modify (= read & write) }
  49. TOpAction = (OpAct_Read, OpAct_Write, OpAct_Modify, OpAct_Unknown);
  50. { ************************************************************************* }
  51. { * Object to hold information on which regiters are in use and which not * }
  52. { ************************************************************************* }
  53. { TUsedRegs }
  54. TUsedRegs = class
  55. Constructor create(aTyp : TRegisterType);
  56. Constructor create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  57. Destructor Destroy;override;
  58. Procedure Clear;
  59. { update the info with the pairegalloc objects coming after
  60. p }
  61. procedure Update(p: Tai; IgnoreNewAllocs: Boolean=false);
  62. { is Reg currently in use }
  63. Function IsUsed(Reg: TRegister): Boolean;
  64. { get all the currently used registers }
  65. Function GetUsedRegs: TRegSet;
  66. { outputs the current set }
  67. Procedure Dump(var t : text);
  68. Private
  69. Typ : TRegisterType;
  70. UsedRegs: TRegSet;
  71. End;
  72. { ************************************************************************* }
  73. { ******************* Contents of the integer registers ******************* }
  74. { ************************************************************************* }
  75. { size of the integer that holds the state number of a register. Can be any }
  76. { integer type, so it can be changed to reduce the size of the TContent }
  77. { structure or to improve alignment }
  78. TStateInt = Byte;
  79. TContent = Record
  80. { start and end of block instructions that defines the }
  81. { content of this register. If Typ = con_const, then }
  82. { Longint(StartMod) = value of the constant) }
  83. StartMod: Tai;
  84. { starts at 0, gets increased everytime the register is }
  85. { written to }
  86. WState: TStateInt;
  87. { starts at 0, gets increased everytime the register is read }
  88. { from }
  89. RState: TStateInt;
  90. { how many instructions starting with StarMod does the block }
  91. { consist of }
  92. NrOfMods: Byte;
  93. { the type of the content of the register: unknown, memory }
  94. { (variable) or constant }
  95. Typ: Byte;
  96. End;
  97. //!!! FIXME
  98. TRegContent = Array[byte] Of TContent;
  99. { ************************************************************************** }
  100. { information object with the contents of every register. Every Tai object }
  101. { gets one of these assigned: a pointer to it is stored in the OptInfo field }
  102. { ************************************************************************** }
  103. { TPaiProp }
  104. TPaiProp = class(TAoptBaseCpu)
  105. Regs: TRegContent;
  106. { can this instruction be removed? }
  107. CanBeRemoved: Boolean;
  108. Constructor create; reintroduce;
  109. { checks the whole sequence of which (so regs[which].StartMod and and }
  110. { the next NrOfMods Tai objects) to see whether Reg is used somewhere, }
  111. { without it being loaded with something else first }
  112. Function RegInSequence(Reg, which: TRegister): Boolean;
  113. { destroy the contents of a register, as well as those whose contents }
  114. { are based on those of that register }
  115. Procedure DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  116. TInstrSinceLastMod);
  117. { if the contents of WhichReg (can be R_NO in case of a constant) are }
  118. { written to memory at the location Ref, the contents of the registers }
  119. { that depend on Ref have to be destroyed }
  120. Procedure DestroyRefs(Const Ref: TReference; WhichReg: TRegister; var
  121. InstrSinceLastMod: TInstrSinceLastMod);
  122. { an instruction reads from operand o }
  123. Procedure ReadOp(const o:toper);
  124. { an instruction reads from reference Ref }
  125. Procedure ReadRef(Ref: PReference);
  126. { an instruction reads from register Reg }
  127. Procedure ReadReg(Reg: TRegister);
  128. { an instruction writes/modifies operand o and this has special }
  129. { side-effects or modifies the contents in such a way that we can't }
  130. { simply add this instruction to the sequence of instructions that }
  131. { describe the contents of the operand, so destroy it }
  132. Procedure DestroyOp(const o:Toper; var InstrSinceLastMod:
  133. TInstrSinceLastMod);
  134. { destroy the contents of all registers }
  135. Procedure DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  136. { a register's contents are modified, but not destroyed (the new value
  137. depends on the old one) }
  138. Procedure ModifyReg(reg: TRegister; var InstrSinceLastMod:
  139. TInstrSinceLastMod);
  140. { an operand's contents are modified, but not destroyed (the new value
  141. depends on the old one) }
  142. Procedure ModifyOp(const oper: TOper; var InstrSinceLastMod:
  143. TInstrSinceLastMod);
  144. { increase the write state of a register (call every time a register is
  145. written to) }
  146. Procedure IncWState(Reg: TRegister);
  147. { increase the read state of a register (call every time a register is }
  148. { read from) }
  149. Procedure IncRState(Reg: TRegister);
  150. { get the write state of a register }
  151. Function GetWState(Reg: TRegister): TStateInt;
  152. { get the read state of a register }
  153. Function GetRState(Reg: TRegister): TStateInt;
  154. { get the type of contents of a register }
  155. Function GetRegContentType(Reg: TRegister): Byte;
  156. Destructor Done;
  157. Private
  158. Procedure IncState(var s: TStateInt);
  159. { returns whether the reference Ref is used somewhere in the loading }
  160. { sequence Content }
  161. Function RefInSequence(Const Ref: TReference; Content: TContent;
  162. RefsEq: TRefCompare): Boolean;
  163. { returns whether the instruction P reads from and/or writes }
  164. { to Reg }
  165. Function RefInInstruction(Const Ref: TReference; p: Tai;
  166. RefsEq: TRefCompare): Boolean;
  167. { returns whether two references with at least one pointing to an array }
  168. { may point to the same memory location }
  169. End;
  170. { ************************************************************************* }
  171. { ************************ Label information ****************************** }
  172. { ************************************************************************* }
  173. TLabelTableItem = Record
  174. PaiObj: Tai;
  175. End;
  176. TLabelTable = Array[0..2500000] Of TLabelTableItem;
  177. PLabelTable = ^TLabelTable;
  178. PLabelInfo = ^TLabelInfo;
  179. TLabelInfo = Record
  180. { the highest and lowest label number occurring in the current code }
  181. { fragment }
  182. LowLabel, HighLabel: longint;
  183. LabelDif: cardinal;
  184. { table that contains the addresses of the Pai_Label objects associated
  185. with each label number }
  186. LabelTable: PLabelTable;
  187. End;
  188. { ************************************************************************* }
  189. { ********** General optimizer object, used to derive others from ********* }
  190. { ************************************************************************* }
  191. TAllUsedRegs = array[TRegisterType] of TUsedRegs;
  192. { TAOptObj }
  193. TAOptObj = class(TAoptBaseCpu)
  194. { the PAasmOutput list this optimizer instance works on }
  195. AsmL: TAsmList;
  196. { The labelinfo record contains the addresses of the Tai objects }
  197. { that are labels, how many labels there are and the min and max }
  198. { label numbers }
  199. LabelInfo: PLabelInfo;
  200. { Start and end of the block that is currently being optimized }
  201. BlockStart, BlockEnd: Tai;
  202. DFA: TAOptDFA;
  203. UsedRegs: TAllUsedRegs;
  204. { _AsmL is the PAasmOutpout list that has to be optimized, }
  205. { _BlockStart and _BlockEnd the start and the end of the block }
  206. { that has to be optimized and _LabelInfo a pointer to a }
  207. { TLabelInfo record }
  208. Constructor create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  209. _LabelInfo: PLabelInfo); virtual; reintroduce;
  210. Destructor Destroy;override;
  211. { processor independent methods }
  212. Procedure CreateUsedRegs(var regs: TAllUsedRegs);
  213. Procedure ClearUsedRegs;
  214. Procedure UpdateUsedRegs(p : Tai);
  215. class procedure UpdateUsedRegs(var Regs: TAllUsedRegs; p: Tai);
  216. Function CopyUsedRegs(var dest : TAllUsedRegs) : boolean;
  217. class Procedure ReleaseUsedRegs(const regs : TAllUsedRegs);
  218. class Function RegInUsedRegs(reg : TRegister;regs : TAllUsedRegs) : boolean;
  219. class Procedure IncludeRegInUsedRegs(reg : TRegister;var regs : TAllUsedRegs);
  220. class Procedure ExcludeRegFromUsedRegs(reg: TRegister;var regs : TAllUsedRegs);
  221. Function GetAllocationString(const regs : TAllUsedRegs) : string;
  222. { returns true if the label L is found between hp and the next }
  223. { instruction }
  224. Function FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  225. { inserts new_one between prev and foll in AsmL }
  226. Procedure InsertLLItem(prev, foll, new_one: TLinkedListItem);
  227. { If P is a Tai object releveant to the optimizer, P is returned
  228. If it is not relevant tot he optimizer, the first object after P
  229. that is relevant is returned }
  230. Function SkipHead(P: Tai): Tai;
  231. { returns true if the operands o1 and o2 are completely equal }
  232. Function OpsEqual(const o1,o2:toper): Boolean;
  233. { Returns the next ait_alloc object with ratype ra_alloc for
  234. Reg is found in the block
  235. of Tai's starting with StartPai and ending with the next "real"
  236. instruction. If none is found, it returns
  237. nil
  238. }
  239. Function FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  240. { Returns the last ait_alloc object with ratype ra_alloc for
  241. Reg is found in the block
  242. of Tai's starting with StartPai and ending with the next "real"
  243. instruction. If none is found, it returns
  244. nil
  245. }
  246. Function FindRegAllocBackward(Reg : TRegister; StartPai : Tai) : tai_regalloc;
  247. { Returns the next ait_alloc object with ratype ra_dealloc
  248. for Reg which is found in the block of Tai's starting with StartPai
  249. and ending with the next "real" instruction. If none is found, it returns
  250. nil }
  251. Function FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  252. { allocates register reg between (and including) instructions p1 and p2
  253. the type of p1 and p2 must not be in SkipInstr }
  254. procedure AllocRegBetween(reg : tregister; p1,p2 : tai; var initialusedregs : TAllUsedRegs);
  255. { reg used after p? }
  256. function RegUsedAfterInstruction(reg: Tregister; p: tai; var AllUsedRegs: TAllUsedRegs): Boolean;
  257. { returns true if reg reaches it's end of life at p, this means it is either
  258. reloaded with a new value or it is deallocated afterwards }
  259. function RegEndOfLife(reg: TRegister;p: taicpu): boolean;
  260. { removes p from asml, updates registers and replaces it by a valid value, if this is the case true is returned }
  261. function RemoveCurrentP(var p : tai): boolean;
  262. { traces sucessive jumps to their final destination and sets it, e.g.
  263. je l1 je l3
  264. <code> <code>
  265. l1: becomes l1:
  266. je l2 je l3
  267. <code> <code>
  268. l2: l2:
  269. jmp l3 jmp l3
  270. the level parameter denotes how deeep we have already followed the jump,
  271. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  272. function GetFinalDestination(hp: taicpu; level: longint): boolean;
  273. function getlabelwithsym(sym: tasmlabel): tai;
  274. { Removes an instruction following hp1 (possibly with reg.deallocations in between),
  275. if its opcode is A_NOP. }
  276. procedure RemoveDelaySlot(hp1: tai);
  277. { peephole optimizer }
  278. procedure PrePeepHoleOpts; virtual;
  279. procedure PeepHoleOptPass1; virtual;
  280. procedure PeepHoleOptPass2; virtual;
  281. procedure PostPeepHoleOpts; virtual;
  282. { processor dependent methods }
  283. // if it returns true, perform a "continue"
  284. function PrePeepHoleOptsCpu(var p: tai): boolean; virtual;
  285. function PeepHoleOptPass1Cpu(var p: tai): boolean; virtual;
  286. function PeepHoleOptPass2Cpu(var p: tai): boolean; virtual;
  287. function PostPeepHoleOptsCpu(var p: tai): boolean; virtual;
  288. { insert debug comments about which registers are read and written by
  289. each instruction. Useful for debugging the InstructionLoadsFromReg and
  290. other similar functions. }
  291. procedure Debug_InsertInstrRegisterDependencyInfo; virtual;
  292. End;
  293. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  294. { ***************************** Implementation **************************** }
  295. Implementation
  296. uses
  297. cutils,
  298. globals,
  299. verbose,
  300. aoptutils,
  301. aasmcfi,
  302. procinfo;
  303. function JumpTargetOp(ai: taicpu): poper; inline;
  304. begin
  305. {$if defined(MIPS)}
  306. { MIPS branches can have 1,2 or 3 operands, target label is the last one. }
  307. result:=ai.oper[ai.ops-1];
  308. {$elseif defined(SPARC64)}
  309. if ai.ops=2 then
  310. result:=ai.oper[1]
  311. else
  312. result:=ai.oper[0];
  313. {$else MIPS}
  314. result:=ai.oper[0];
  315. {$endif}
  316. end;
  317. { ************************************************************************* }
  318. { ******************************** TUsedRegs ****************************** }
  319. { ************************************************************************* }
  320. Constructor TUsedRegs.create(aTyp : TRegisterType);
  321. Begin
  322. Typ:=aTyp;
  323. UsedRegs := [];
  324. End;
  325. Constructor TUsedRegs.create_regset(aTyp : TRegisterType;Const _RegSet: TRegSet);
  326. Begin
  327. Typ:=aTyp;
  328. UsedRegs := _RegSet;
  329. End;
  330. {
  331. updates UsedRegs with the RegAlloc Information coming after P
  332. }
  333. Procedure TUsedRegs.Update(p: Tai;IgnoreNewAllocs : Boolean = false);
  334. Begin
  335. { this code is normally not used because updating the register allocation information is done in
  336. TAOptObj.UpdateUsedRegs for speed reasons }
  337. repeat
  338. while assigned(p) and
  339. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  340. (p.typ = ait_label) or
  341. ((p.typ = ait_marker) and
  342. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  343. p := tai(p.next);
  344. while assigned(p) and
  345. (p.typ=ait_RegAlloc) Do
  346. begin
  347. if (getregtype(tai_regalloc(p).reg) = typ) then
  348. begin
  349. case tai_regalloc(p).ratype of
  350. ra_alloc :
  351. if not(IgnoreNewAllocs) then
  352. Include(UsedRegs, getsupreg(tai_regalloc(p).reg));
  353. ra_dealloc :
  354. Exclude(UsedRegs, getsupreg(tai_regalloc(p).reg));
  355. end;
  356. end;
  357. p := tai(p.next);
  358. end;
  359. until not(assigned(p)) or
  360. (not(p.typ in SkipInstr) and
  361. not((p.typ = ait_label) and
  362. labelCanBeSkipped(tai_label(p))));
  363. End;
  364. Function TUsedRegs.IsUsed(Reg: TRegister): Boolean;
  365. Begin
  366. IsUsed := (getregtype(Reg)=Typ) and (getsupreg(Reg) in UsedRegs);
  367. End;
  368. Function TUsedRegs.GetUsedRegs: TRegSet;
  369. Begin
  370. GetUsedRegs := UsedRegs;
  371. End;
  372. procedure TUsedRegs.Dump(var t: text);
  373. var
  374. i: dword;
  375. begin
  376. write(t,Typ,' ');
  377. for i:=low(TRegSet) to high(TRegSet) do
  378. if i in UsedRegs then
  379. write(t,i,' ');
  380. writeln(t);
  381. end;
  382. Destructor TUsedRegs.Destroy;
  383. Begin
  384. inherited destroy;
  385. end;
  386. procedure TUsedRegs.Clear;
  387. begin
  388. UsedRegs := [];
  389. end;
  390. { ************************************************************************* }
  391. { **************************** TPaiProp *********************************** }
  392. { ************************************************************************* }
  393. Constructor TPaiProp.Create;
  394. Begin
  395. {!!!!!!
  396. UsedRegs.Init;
  397. CondRegs.init;
  398. }
  399. { DirFlag: TFlagContents; I386 specific}
  400. End;
  401. Function TPaiProp.RegInSequence(Reg, which: TRegister): Boolean;
  402. {
  403. Var p: Tai;
  404. RegsChecked: TRegSet;
  405. content: TContent;
  406. Counter: Byte;
  407. TmpResult: Boolean;
  408. }
  409. begin
  410. Result:=False; { unimplemented }
  411. (*!!!!!!!!!!1
  412. RegsChecked := [];
  413. content := regs[which];
  414. p := content.StartMod;
  415. TmpResult := False;
  416. Counter := 1;
  417. While Not(TmpResult) And
  418. (Counter <= Content.NrOfMods) Do
  419. Begin
  420. If IsLoadMemReg(p) Then
  421. With PInstr(p)^.oper[LoadSrc]^.ref^ Do
  422. If (Base = ProcInfo.FramePointer)
  423. {$ifdef cpurefshaveindexreg}
  424. And (Index = R_NO)
  425. {$endif cpurefshaveindexreg} Then
  426. Begin
  427. RegsChecked := RegsChecked +
  428. [RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg)];
  429. If Reg = RegMaxSize(PInstr(p)^.oper[LoadDst]^.reg) Then
  430. Break;
  431. End
  432. Else
  433. Begin
  434. If (Base = Reg) And
  435. Not(Base In RegsChecked)
  436. Then TmpResult := True;
  437. {$ifdef cpurefshaveindexreg}
  438. If Not(TmpResult) And
  439. (Index = Reg) And
  440. Not(Index In RegsChecked)
  441. Then TmpResult := True;
  442. {$Endif cpurefshaveindexreg}
  443. End
  444. Else TmpResult := RegInInstruction(Reg, p);
  445. Inc(Counter);
  446. GetNextInstruction(p,p)
  447. End;
  448. RegInSequence := TmpResult
  449. *)
  450. End;
  451. Procedure TPaiProp.DestroyReg(Reg: TRegister; var InstrSinceLastMod:
  452. TInstrSinceLastMod);
  453. { Destroys the contents of the register Reg in the PPaiProp p1, as well as }
  454. { the contents of registers are loaded with a memory location based on Reg }
  455. {
  456. Var TmpWState, TmpRState: Byte;
  457. Counter: TRegister;
  458. }
  459. Begin
  460. {!!!!!!!
  461. Reg := RegMaxSize(Reg);
  462. If (Reg in [LoGPReg..HiGPReg]) Then
  463. For Counter := LoGPReg to HiGPReg Do
  464. With Regs[Counter] Do
  465. If (Counter = reg) Or
  466. ((Typ = Con_Ref) And
  467. RegInSequence(Reg, Counter)) Then
  468. Begin
  469. InstrSinceLastMod[Counter] := 0;
  470. IncWState(Counter);
  471. TmpWState := GetWState(Counter);
  472. TmpRState := GetRState(Counter);
  473. FillChar(Regs[Counter], SizeOf(TContent), 0);
  474. WState := TmpWState;
  475. RState := TmpRState
  476. End
  477. }
  478. End;
  479. Function ArrayRefsEq(const r1, r2: TReference): Boolean;
  480. Begin
  481. Result:=False; { unimplemented }
  482. (*!!!!!!!!!!
  483. ArrayRefsEq := (R1.Offset+R1.OffsetFixup = R2.Offset+R2.OffsetFixup) And
  484. {$ifdef refsHaveSegmentReg}
  485. (R1.Segment = R2.Segment) And
  486. {$endif}
  487. (R1.Base = R2.Base) And
  488. (R1.Symbol=R2.Symbol);
  489. *)
  490. End;
  491. Procedure TPaiProp.DestroyRefs(Const Ref: TReference; WhichReg: TRegister;
  492. var InstrSinceLastMod: TInstrSinceLastMod);
  493. { destroys all registers which possibly contain a reference to Ref, WhichReg }
  494. { is the register whose contents are being written to memory (if this proc }
  495. { is called because of a "mov?? %reg, (mem)" instruction) }
  496. {
  497. Var RefsEq: TRefCompare;
  498. Counter: TRegister;
  499. }
  500. Begin
  501. (*!!!!!!!!!!!
  502. WhichReg := RegMaxSize(WhichReg);
  503. If (Ref.base = procinfo.FramePointer) or
  504. Assigned(Ref.Symbol) Then
  505. Begin
  506. If
  507. {$ifdef cpurefshaveindexreg}
  508. (Ref.Index = R_NO) And
  509. {$endif cpurefshaveindexreg}
  510. (Not(Assigned(Ref.Symbol)) or
  511. (Ref.base = R_NO)) Then
  512. { local variable which is not an array }
  513. RefsEq := @RefsEqual
  514. Else
  515. { local variable which is an array }
  516. RefsEq := @ArrayRefsEq;
  517. {write something to a parameter, a local or global variable, so
  518. * with uncertain optimizations on:
  519. - destroy the contents of registers whose contents have somewhere a
  520. "mov?? (Ref), %reg". WhichReg (this is the register whose contents
  521. are being written to memory) is not destroyed if it's StartMod is
  522. of that form and NrOfMods = 1 (so if it holds ref, but is not a
  523. pointer or value based on Ref)
  524. * with uncertain optimizations off:
  525. - also destroy registers that contain any pointer}
  526. For Counter := LoGPReg to HiGPReg Do
  527. With Regs[Counter] Do
  528. Begin
  529. If (typ = Con_Ref) And
  530. ((Not(cs_opt_size in current_settings.optimizerswitches) And
  531. (NrOfMods <> 1)
  532. ) Or
  533. (RefInSequence(Ref,Regs[Counter], RefsEq) And
  534. ((Counter <> WhichReg) Or
  535. ((NrOfMods <> 1) And
  536. {StarMod is always of the type ait_instruction}
  537. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  538. RefsEq(PInstr(StartMod)^.oper[0].ref^, Ref)
  539. )
  540. )
  541. )
  542. )
  543. Then
  544. DestroyReg(Counter, InstrSinceLastMod)
  545. End
  546. End
  547. Else
  548. {write something to a pointer location, so
  549. * with uncertain optimzations on:
  550. - do not destroy registers which contain a local/global variable or a
  551. parameter, except if DestroyRefs is called because of a "movsl"
  552. * with uncertain optimzations off:
  553. - destroy every register which contains a memory location
  554. }
  555. For Counter := LoGPReg to HiGPReg Do
  556. With Regs[Counter] Do
  557. If (typ = Con_Ref) And
  558. (Not(cs_opt_size in current_settings.optimizerswitches) Or
  559. {$ifdef x86}
  560. {for movsl}
  561. (Ref.Base = R_EDI) Or
  562. {$endif}
  563. {don't destroy if reg contains a parameter, local or global variable}
  564. Not((NrOfMods = 1) And
  565. (PInstr(StartMod)^.oper[0].typ = top_ref) And
  566. ((PInstr(StartMod)^.oper[0].ref^.base = ProcInfo.FramePointer) Or
  567. Assigned(PInstr(StartMod)^.oper[0].ref^.Symbol)
  568. )
  569. )
  570. )
  571. Then DestroyReg(Counter, InstrSinceLastMod)
  572. *)
  573. End;
  574. Procedure TPaiProp.DestroyAllRegs(var InstrSinceLastMod: TInstrSinceLastMod);
  575. {Var Counter: TRegister;}
  576. Begin {initializes/desrtoys all registers}
  577. (*!!!!!!!!!
  578. For Counter := LoGPReg To HiGPReg Do
  579. Begin
  580. ReadReg(Counter);
  581. DestroyReg(Counter, InstrSinceLastMod);
  582. End;
  583. CondRegs.Init;
  584. { FPURegs.Init; }
  585. *)
  586. End;
  587. Procedure TPaiProp.DestroyOp(const o:Toper; var InstrSinceLastMod:
  588. TInstrSinceLastMod);
  589. Begin
  590. {!!!!!!!
  591. Case o.typ Of
  592. top_reg: DestroyReg(o.reg, InstrSinceLastMod);
  593. top_ref:
  594. Begin
  595. ReadRef(o.ref);
  596. DestroyRefs(o.ref^, R_NO, InstrSinceLastMod);
  597. End;
  598. top_symbol:;
  599. End;
  600. }
  601. End;
  602. Procedure TPaiProp.ReadReg(Reg: TRegister);
  603. Begin
  604. {!!!!!!!
  605. Reg := RegMaxSize(Reg);
  606. If Reg in General_Registers Then
  607. IncRState(RegMaxSize(Reg))
  608. }
  609. End;
  610. Procedure TPaiProp.ReadRef(Ref: PReference);
  611. Begin
  612. (*!!!!!!
  613. If Ref^.Base <> R_NO Then
  614. ReadReg(Ref^.Base);
  615. {$ifdef cpurefshaveindexreg}
  616. If Ref^.Index <> R_NO Then
  617. ReadReg(Ref^.Index);
  618. {$endif cpurefshaveindexreg}
  619. *)
  620. End;
  621. Procedure TPaiProp.ReadOp(const o:toper);
  622. Begin
  623. Case o.typ Of
  624. top_reg: ReadReg(o.reg);
  625. top_ref: ReadRef(o.ref);
  626. else
  627. internalerror(200410241);
  628. End;
  629. End;
  630. Procedure TPaiProp.ModifyReg(reg: TRegister; Var InstrSinceLastMod:
  631. TInstrSinceLastMod);
  632. Begin
  633. (*!!!!!!!
  634. With Regs[reg] Do
  635. If (Typ = Con_Ref)
  636. Then
  637. Begin
  638. IncState(WState);
  639. {also store how many instructions are part of the sequence in the first
  640. instructions PPaiProp, so it can be easily accessed from within
  641. CheckSequence}
  642. Inc(NrOfMods, InstrSinceLastMod[Reg]);
  643. PPaiProp(StartMod.OptInfo)^.Regs[Reg].NrOfMods := NrOfMods;
  644. InstrSinceLastMod[Reg] := 0;
  645. End
  646. Else
  647. DestroyReg(Reg, InstrSinceLastMod);
  648. *)
  649. End;
  650. Procedure TPaiProp.ModifyOp(const oper: TOper; var InstrSinceLastMod:
  651. TInstrSinceLastMod);
  652. Begin
  653. If oper.typ = top_reg Then
  654. ModifyReg(RegMaxSize(oper.reg),InstrSinceLastMod)
  655. Else
  656. Begin
  657. ReadOp(oper);
  658. DestroyOp(oper, InstrSinceLastMod);
  659. End
  660. End;
  661. Procedure TPaiProp.IncWState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  662. Begin
  663. //!!!! IncState(Regs[Reg].WState);
  664. End;
  665. Procedure TPaiProp.IncRState(Reg: TRegister);{$ifdef inl} inline;{$endif inl}
  666. Begin
  667. //!!!! IncState(Regs[Reg].RState);
  668. End;
  669. Function TPaiProp.GetWState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  670. Begin
  671. Result:=0; { unimplemented }
  672. //!!!! GetWState := Regs[Reg].WState
  673. End;
  674. Function TPaiProp.GetRState(Reg: TRegister): TStateInt; {$ifdef inl} inline;{$endif inl}
  675. Begin
  676. Result:=0; { unimplemented }
  677. //!!!! GetRState := Regs[Reg].RState
  678. End;
  679. Function TPaiProp.GetRegContentType(Reg: TRegister): Byte; {$ifdef inl} inline;{$endif inl}
  680. Begin
  681. Result:=0; { unimplemented }
  682. //!!!! GetRegContentType := Regs[Reg].typ
  683. End;
  684. Destructor TPaiProp.Done;
  685. Begin
  686. //!!!! UsedRegs.Done;
  687. //!!!! CondRegs.Done;
  688. { DirFlag: TFlagContents; I386 specific}
  689. End;
  690. { ************************ private TPaiProp stuff ************************* }
  691. Procedure TPaiProp.IncState(Var s: TStateInt); {$ifdef inl} inline;{$endif inl}
  692. Begin
  693. If s <> High(TStateInt) Then Inc(s)
  694. Else s := 0
  695. End;
  696. Function TPaiProp.RefInInstruction(Const Ref: TReference; p: Tai;
  697. RefsEq: TRefCompare): Boolean;
  698. Var Count: AWord;
  699. TmpResult: Boolean;
  700. Begin
  701. TmpResult := False;
  702. If (p.typ = ait_instruction) Then
  703. Begin
  704. Count := 0;
  705. Repeat
  706. If (TInstr(p).oper[Count]^.typ = Top_Ref) Then
  707. TmpResult := RefsEq(Ref, PInstr(p)^.oper[Count]^.ref^);
  708. Inc(Count);
  709. Until (Count = MaxOps) or TmpResult;
  710. End;
  711. RefInInstruction := TmpResult;
  712. End;
  713. Function TPaiProp.RefInSequence(Const Ref: TReference; Content: TContent;
  714. RefsEq: TRefCompare): Boolean;
  715. Var p: Tai;
  716. Counter: Byte;
  717. TmpResult: Boolean;
  718. Begin
  719. p := Content.StartMod;
  720. TmpResult := False;
  721. Counter := 1;
  722. While Not(TmpResult) And
  723. (Counter <= Content.NrOfMods) Do
  724. Begin
  725. If (p.typ = ait_instruction) And
  726. RefInInstruction(Ref, p, @references_equal)
  727. Then TmpResult := True;
  728. Inc(Counter);
  729. GetNextInstruction(p,p)
  730. End;
  731. RefInSequence := TmpResult
  732. End;
  733. { ************************************************************************* }
  734. { ***************************** TAoptObj ********************************** }
  735. { ************************************************************************* }
  736. Constructor TAoptObj.create(_AsmL: TAsmList; _BlockStart, _BlockEnd: Tai;
  737. _LabelInfo: PLabelInfo);
  738. Begin
  739. AsmL := _AsmL;
  740. BlockStart := _BlockStart;
  741. BlockEnd := _BlockEnd;
  742. LabelInfo := _LabelInfo;
  743. CreateUsedRegs(UsedRegs);
  744. End;
  745. destructor TAOptObj.Destroy;
  746. var
  747. i : TRegisterType;
  748. begin
  749. for i:=low(TRegisterType) to high(TRegisterType) do
  750. UsedRegs[i].Destroy;
  751. inherited Destroy;
  752. end;
  753. procedure TAOptObj.CreateUsedRegs(var regs: TAllUsedRegs);
  754. var
  755. i : TRegisterType;
  756. begin
  757. for i:=low(TRegisterType) to high(TRegisterType) do
  758. Regs[i]:=TUsedRegs.Create(i);
  759. end;
  760. procedure TAOptObj.ClearUsedRegs;
  761. var
  762. i : TRegisterType;
  763. begin
  764. for i:=low(TRegisterType) to high(TRegisterType) do
  765. UsedRegs[i].Clear;
  766. end;
  767. procedure TAOptObj.UpdateUsedRegs(p : Tai);
  768. begin
  769. { this code is based on TUsedRegs.Update to avoid multiple passes through the asmlist,
  770. the code is duplicated here }
  771. repeat
  772. while assigned(p) and
  773. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  774. ((p.typ = ait_label) and
  775. labelCanBeSkipped(tai_label(p))) or
  776. ((p.typ = ait_marker) and
  777. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  778. p := tai(p.next);
  779. while assigned(p) and
  780. (p.typ=ait_RegAlloc) Do
  781. begin
  782. case tai_regalloc(p).ratype of
  783. ra_alloc :
  784. Include(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  785. ra_dealloc :
  786. Exclude(UsedRegs[getregtype(tai_regalloc(p).reg)].UsedRegs, getsupreg(tai_regalloc(p).reg));
  787. end;
  788. p := tai(p.next);
  789. end;
  790. until not(assigned(p)) or
  791. (not(p.typ in SkipInstr) and
  792. not((p.typ = ait_label) and
  793. labelCanBeSkipped(tai_label(p))));
  794. end;
  795. class procedure TAOptObj.UpdateUsedRegs(var Regs : TAllUsedRegs;p : Tai);
  796. var
  797. i : TRegisterType;
  798. begin
  799. for i:=low(TRegisterType) to high(TRegisterType) do
  800. Regs[i].Update(p);
  801. end;
  802. function TAOptObj.CopyUsedRegs(var dest: TAllUsedRegs): boolean;
  803. var
  804. i : TRegisterType;
  805. begin
  806. Result:=true;
  807. for i:=low(TRegisterType) to high(TRegisterType) do
  808. dest[i]:=TUsedRegs.Create_Regset(i,UsedRegs[i].GetUsedRegs);
  809. end;
  810. class procedure TAOptObj.ReleaseUsedRegs(const regs: TAllUsedRegs);
  811. var
  812. i : TRegisterType;
  813. begin
  814. for i:=low(TRegisterType) to high(TRegisterType) do
  815. regs[i].Free;
  816. end;
  817. class Function TAOptObj.RegInUsedRegs(reg : TRegister;regs : TAllUsedRegs) : boolean;
  818. begin
  819. result:=regs[getregtype(reg)].IsUsed(reg);
  820. end;
  821. class procedure TAOptObj.IncludeRegInUsedRegs(reg: TRegister;
  822. var regs: TAllUsedRegs);
  823. begin
  824. include(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  825. end;
  826. class procedure TAOptObj.ExcludeRegFromUsedRegs(reg: TRegister;
  827. var regs: TAllUsedRegs);
  828. begin
  829. exclude(regs[getregtype(reg)].UsedRegs,getsupreg(Reg));
  830. end;
  831. function TAOptObj.GetAllocationString(const regs: TAllUsedRegs): string;
  832. var
  833. i : TRegisterType;
  834. j : TSuperRegister;
  835. begin
  836. Result:='';
  837. for i:=low(TRegisterType) to high(TRegisterType) do
  838. for j in regs[i].UsedRegs do
  839. Result:=Result+std_regname(newreg(i,j,R_SUBWHOLE))+' ';
  840. end;
  841. Function TAOptObj.FindLabel(L: TasmLabel; Var hp: Tai): Boolean;
  842. Var TempP: Tai;
  843. Begin
  844. TempP := hp;
  845. While Assigned(TempP) and
  846. (TempP.typ In SkipInstr + [ait_label,ait_align]) Do
  847. If (TempP.typ <> ait_Label) Or
  848. (Tai_label(TempP).labsym <> L)
  849. Then GetNextInstruction(TempP, TempP)
  850. Else
  851. Begin
  852. hp := TempP;
  853. FindLabel := True;
  854. exit
  855. End;
  856. FindLabel := False;
  857. End;
  858. Procedure TAOptObj.InsertLLItem(prev, foll, new_one : TLinkedListItem);
  859. Begin
  860. If Assigned(prev) Then
  861. If Assigned(foll) Then
  862. Begin
  863. If Assigned(new_one) Then
  864. Begin
  865. new_one.previous := prev;
  866. new_one.next := foll;
  867. prev.next := new_one;
  868. foll.previous := new_one;
  869. { should we update line information? }
  870. if (not (tai(new_one).typ in SkipLineInfo)) and
  871. (not (tai(foll).typ in SkipLineInfo)) then
  872. Tailineinfo(new_one).fileinfo := Tailineinfo(foll).fileinfo
  873. End
  874. End
  875. Else AsmL.Concat(new_one)
  876. Else If Assigned(Foll) Then AsmL.Insert(new_one)
  877. End;
  878. Function TAOptObj.SkipHead(P: Tai): Tai;
  879. Var OldP: Tai;
  880. Begin
  881. Repeat
  882. OldP := P;
  883. If (P.typ in SkipInstr) Or
  884. ((P.typ = ait_marker) And
  885. (Tai_Marker(P).Kind = mark_AsmBlockEnd)) Then
  886. GetNextInstruction(P, P)
  887. Else If ((P.Typ = Ait_Marker) And
  888. (Tai_Marker(P).Kind = mark_NoPropInfoStart)) Then
  889. { a marker of the type mark_NoPropInfoStart can't be the first instruction of a }
  890. { paasmoutput list }
  891. GetNextInstruction(Tai(P.Previous),P);
  892. If (P.Typ = Ait_Marker) And
  893. (Tai_Marker(P).Kind = mark_AsmBlockStart) Then
  894. Begin
  895. P := Tai(P.Next);
  896. While (P.typ <> Ait_Marker) Or
  897. (Tai_Marker(P).Kind <> mark_AsmBlockEnd) Do
  898. P := Tai(P.Next)
  899. End;
  900. Until P = OldP;
  901. SkipHead := P;
  902. End;
  903. Function TAOptObj.OpsEqual(const o1,o2:toper): Boolean;
  904. Begin
  905. if o1.typ=o2.typ then
  906. Case o1.typ Of
  907. Top_Reg :
  908. OpsEqual:=o1.reg=o2.reg;
  909. Top_Ref :
  910. OpsEqual := references_equal(o1.ref^, o2.ref^);
  911. Top_Const :
  912. OpsEqual:=o1.val=o2.val;
  913. Top_None :
  914. OpsEqual := True
  915. else OpsEqual := False
  916. End
  917. else
  918. OpsEqual := False;
  919. End;
  920. Function TAOptObj.FindRegAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  921. Begin
  922. Result:=nil;
  923. Repeat
  924. While Assigned(StartPai) And
  925. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  926. {$ifdef cpudelayslot}
  927. ((startpai.typ=ait_instruction) and (taicpu(startpai).opcode=A_NOP)) or
  928. {$endif cpudelayslot}
  929. ((StartPai.typ = ait_label) and
  930. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  931. StartPai := Tai(StartPai.Next);
  932. If Assigned(StartPai) And
  933. (StartPai.typ = ait_regAlloc) Then
  934. Begin
  935. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  936. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  937. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  938. begin
  939. Result:=tai_regalloc(StartPai);
  940. exit;
  941. end;
  942. StartPai := Tai(StartPai.Next);
  943. End
  944. else
  945. exit;
  946. Until false;
  947. End;
  948. Function TAOptObj.FindRegAllocBackward(Reg: TRegister; StartPai: Tai): tai_regalloc;
  949. Begin
  950. Result:=nil;
  951. Repeat
  952. While Assigned(StartPai) And
  953. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  954. ((StartPai.typ = ait_label) and
  955. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  956. StartPai := Tai(StartPai.Previous);
  957. If Assigned(StartPai) And
  958. (StartPai.typ = ait_regAlloc) Then
  959. Begin
  960. if (tai_regalloc(StartPai).ratype=ra_alloc) and
  961. SuperRegistersEqual(tai_regalloc(StartPai).Reg,Reg) then
  962. begin
  963. Result:=tai_regalloc(StartPai);
  964. exit;
  965. end;
  966. StartPai := Tai(StartPai.Previous);
  967. End
  968. else
  969. exit;
  970. Until false;
  971. End;
  972. function TAOptObj.FindRegDeAlloc(Reg: TRegister; StartPai: Tai): tai_regalloc;
  973. Begin
  974. Result:=nil;
  975. Repeat
  976. While Assigned(StartPai) And
  977. ((StartPai.typ in (SkipInstr - [ait_regAlloc])) Or
  978. ((StartPai.typ = ait_label) and
  979. Not(Tai_Label(StartPai).labsym.Is_Used))) Do
  980. StartPai := Tai(StartPai.Next);
  981. If Assigned(StartPai) And
  982. (StartPai.typ = ait_regAlloc) Then
  983. Begin
  984. if (tai_regalloc(StartPai).ratype=ra_dealloc) and
  985. (getregtype(tai_regalloc(StartPai).Reg) = getregtype(Reg)) and
  986. (getsupreg(tai_regalloc(StartPai).Reg) = getsupreg(Reg)) then
  987. begin
  988. Result:=tai_regalloc(StartPai);
  989. exit;
  990. end;
  991. StartPai := Tai(StartPai.Next);
  992. End
  993. else
  994. exit;
  995. Until false;
  996. End;
  997. { allocates register reg between (and including) instructions p1 and p2
  998. the type of p1 and p2 must not be in SkipInstr }
  999. procedure TAOptObj.AllocRegBetween(reg: tregister; p1, p2: tai; var initialusedregs: TAllUsedRegs);
  1000. var
  1001. hp, start: tai;
  1002. removedsomething,
  1003. firstRemovedWasAlloc,
  1004. lastRemovedWasDealloc: boolean;
  1005. begin
  1006. {$ifdef EXTDEBUG}
  1007. { if assigned(p1.optinfo) and
  1008. (ptaiprop(p1.optinfo)^.usedregs <> initialusedregs) then
  1009. internalerror(2004101010); }
  1010. {$endif EXTDEBUG}
  1011. start := p1;
  1012. if (reg = NR_STACK_POINTER_REG) or
  1013. (reg = current_procinfo.framepointer) or
  1014. not(assigned(p1)) then
  1015. { this happens with registers which are loaded implicitely, outside the }
  1016. { current block (e.g. esi with self) }
  1017. exit;
  1018. { make sure we allocate it for this instruction }
  1019. getnextinstruction(p2,p2);
  1020. lastRemovedWasDealloc := false;
  1021. removedSomething := false;
  1022. firstRemovedWasAlloc := false;
  1023. {$ifdef allocregdebug}
  1024. hp := tai_comment.Create(strpnew('allocating '+std_regname(reg)+' from here...'));
  1025. insertllitem(p1.previous,p1,hp);
  1026. hp := tai_comment.Create(strpnew('allocated '+std_regname(reg)+' till here...'));
  1027. insertllitem(p2,p2.next,hp);
  1028. {$endif allocregdebug}
  1029. { do it the safe way: always allocate the full super register,
  1030. as we do no register re-allocation in the peephole optimizer,
  1031. this does not hurt
  1032. }
  1033. case getregtype(reg) of
  1034. R_MMREGISTER:
  1035. reg:=newreg(R_MMREGISTER,getsupreg(reg),R_SUBMMWHOLE);
  1036. R_INTREGISTER:
  1037. reg:=newreg(R_INTREGISTER,getsupreg(reg),R_SUBWHOLE);
  1038. R_FPUREGISTER:
  1039. reg:=newreg(R_FPUREGISTER,getsupreg(reg),R_SUBWHOLE);
  1040. R_ADDRESSREGISTER:
  1041. reg:=newreg(R_ADDRESSREGISTER,getsupreg(reg),R_SUBWHOLE);
  1042. else
  1043. Internalerror(2018030701);
  1044. end;
  1045. if not(RegInUsedRegs(reg,initialusedregs)) then
  1046. begin
  1047. hp := tai_regalloc.alloc(reg,nil);
  1048. insertllItem(p1.previous,p1,hp);
  1049. IncludeRegInUsedRegs(reg,initialusedregs);
  1050. end;
  1051. while assigned(p1) and
  1052. (p1 <> p2) do
  1053. begin
  1054. if assigned(p1.optinfo) then
  1055. internalerror(2014022301); // IncludeRegInUsedRegs(reg,ptaiprop(p1.optinfo)^.usedregs);
  1056. p1 := tai(p1.next);
  1057. repeat
  1058. while assigned(p1) and
  1059. (p1.typ in (SkipInstr-[ait_regalloc])) Do
  1060. p1 := tai(p1.next);
  1061. { remove all allocation/deallocation info about the register in between }
  1062. if assigned(p1) and
  1063. (p1.typ = ait_regalloc) then
  1064. begin
  1065. { same super register, different sub register? }
  1066. if SuperRegistersEqual(reg,tai_regalloc(p1).reg) and (tai_regalloc(p1).reg<>reg) then
  1067. begin
  1068. if (getsubreg(tai_regalloc(p1).reg)>getsubreg(reg)) or (getsubreg(reg)=R_SUBH) then
  1069. internalerror(2016101501);
  1070. tai_regalloc(p1).reg:=reg;
  1071. end;
  1072. if tai_regalloc(p1).reg=reg then
  1073. begin
  1074. if not removedSomething then
  1075. begin
  1076. firstRemovedWasAlloc := tai_regalloc(p1).ratype=ra_alloc;
  1077. removedSomething := true;
  1078. end;
  1079. lastRemovedWasDealloc := (tai_regalloc(p1).ratype=ra_dealloc);
  1080. hp := tai(p1.Next);
  1081. asml.Remove(p1);
  1082. p1.free;
  1083. p1 := hp;
  1084. end
  1085. else
  1086. p1 := tai(p1.next);
  1087. end;
  1088. until not(assigned(p1)) or
  1089. not(p1.typ in SkipInstr);
  1090. end;
  1091. if assigned(p1) then
  1092. begin
  1093. if firstRemovedWasAlloc then
  1094. begin
  1095. hp := tai_regalloc.Alloc(reg,nil);
  1096. insertLLItem(start.previous,start,hp);
  1097. end;
  1098. if lastRemovedWasDealloc then
  1099. begin
  1100. hp := tai_regalloc.DeAlloc(reg,nil);
  1101. insertLLItem(p1.previous,p1,hp);
  1102. end;
  1103. end;
  1104. end;
  1105. function TAOptObj.RegUsedAfterInstruction(reg: Tregister; p: tai;var AllUsedRegs: TAllUsedRegs): Boolean;
  1106. begin
  1107. AllUsedRegs[getregtype(reg)].Update(tai(p.Next),true);
  1108. RegUsedAfterInstruction :=
  1109. AllUsedRegs[getregtype(reg)].IsUsed(reg) and
  1110. not(regLoadedWithNewValue(reg,p)) and
  1111. (
  1112. not(GetNextInstruction(p,p)) or
  1113. InstructionLoadsFromReg(reg,p) or
  1114. not(regLoadedWithNewValue(reg,p))
  1115. );
  1116. end;
  1117. function TAOptObj.RegEndOfLife(reg : TRegister;p : taicpu) : boolean;
  1118. begin
  1119. Result:=assigned(FindRegDealloc(reg,tai(p.Next))) or
  1120. RegLoadedWithNewValue(reg,p);
  1121. end;
  1122. function TAOptObj.RemoveCurrentP(var p : tai) : boolean;
  1123. var
  1124. hp1 : tai;
  1125. begin
  1126. result:=GetNextInstruction(p,hp1);
  1127. { p will be removed, update used register as we continue
  1128. with the next instruction after p }
  1129. UpdateUsedRegs(tai(p.Next));
  1130. AsmL.Remove(p);
  1131. p.Free;
  1132. p:=hp1;
  1133. end;
  1134. function FindAnyLabel(hp: tai; var l: tasmlabel): Boolean;
  1135. begin
  1136. FindAnyLabel := false;
  1137. while assigned(hp.next) and
  1138. (tai(hp.next).typ in (SkipInstr+[ait_align])) Do
  1139. hp := tai(hp.next);
  1140. if assigned(hp.next) and
  1141. (tai(hp.next).typ = ait_label) then
  1142. begin
  1143. FindAnyLabel := true;
  1144. l := tai_label(hp.next).labsym;
  1145. end
  1146. end;
  1147. {$push}
  1148. {$r-}
  1149. function TAOptObj.getlabelwithsym(sym: tasmlabel): tai;
  1150. begin
  1151. if (int64(sym.labelnr) >= int64(labelinfo^.lowlabel)) and
  1152. (int64(sym.labelnr) <= int64(labelinfo^.highlabel)) then { range check, a jump can go past an assembler block! }
  1153. getlabelwithsym := labelinfo^.labeltable^[sym.labelnr-labelinfo^.lowlabel].paiobj
  1154. else
  1155. getlabelwithsym := nil;
  1156. end;
  1157. {$pop}
  1158. { Returns True if hp is an unconditional jump to a label }
  1159. function IsJumpToLabelUncond(hp: taicpu): boolean;
  1160. begin
  1161. {$if defined(avr)}
  1162. result:=(hp.opcode in aopt_uncondjmp) and
  1163. {$else avr}
  1164. result:=(hp.opcode=aopt_uncondjmp) and
  1165. {$endif avr}
  1166. {$if defined(arm) or defined(aarch64)}
  1167. (hp.condition=c_None) and
  1168. {$endif arm or aarch64}
  1169. (hp.ops>0) and
  1170. (JumpTargetOp(hp)^.typ = top_ref) and
  1171. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1172. end;
  1173. { Returns True if hp is any jump to a label }
  1174. function IsJumpToLabel(hp: taicpu): boolean;
  1175. begin
  1176. result:=hp.is_jmp and
  1177. (hp.ops>0) and
  1178. (JumpTargetOp(hp)^.typ = top_ref) and
  1179. (JumpTargetOp(hp)^.ref^.symbol is TAsmLabel);
  1180. end;
  1181. procedure TAOptObj.RemoveDelaySlot(hp1:tai);
  1182. var
  1183. hp2: tai;
  1184. begin
  1185. hp2:=tai(hp1.next);
  1186. while assigned(hp2) and (hp2.typ in SkipInstr) do
  1187. hp2:=tai(hp2.next);
  1188. if assigned(hp2) and (hp2.typ=ait_instruction) and
  1189. (taicpu(hp2).opcode=A_NOP) then
  1190. begin
  1191. asml.remove(hp2);
  1192. hp2.free;
  1193. end;
  1194. { Anything except A_NOP must be left in place: these instructions
  1195. execute before branch, so code stays correct if branch is removed. }
  1196. end;
  1197. function TAOptObj.GetFinalDestination(hp: taicpu; level: longint): boolean;
  1198. {traces sucessive jumps to their final destination and sets it, e.g.
  1199. je l1 je l3
  1200. <code> <code>
  1201. l1: becomes l1:
  1202. je l2 je l3
  1203. <code> <code>
  1204. l2: l2:
  1205. jmp l3 jmp l3
  1206. the level parameter denotes how deeep we have already followed the jump,
  1207. to avoid endless loops with constructs such as "l5: ; jmp l5" }
  1208. var p1: tai;
  1209. {$if not defined(MIPS) and not defined(JVM)}
  1210. p2: tai;
  1211. l: tasmlabel;
  1212. {$endif}
  1213. begin
  1214. GetfinalDestination := false;
  1215. if level > 20 then
  1216. exit;
  1217. p1 := getlabelwithsym(tasmlabel(JumpTargetOp(hp)^.ref^.symbol));
  1218. if assigned(p1) then
  1219. begin
  1220. SkipLabels(p1,p1);
  1221. if (tai(p1).typ = ait_instruction) and
  1222. (taicpu(p1).is_jmp) then
  1223. if { the next instruction after the label where the jump hp arrives}
  1224. { is unconditional or of the same type as hp, so continue }
  1225. IsJumpToLabelUncond(taicpu(p1))
  1226. {$if not defined(MIPS) and not defined(JVM)}
  1227. { for MIPS, it isn't enough to check the condition; first operands must be same, too. }
  1228. or
  1229. conditions_equal(taicpu(p1).condition,hp.condition) or
  1230. { the next instruction after the label where the jump hp arrives
  1231. is the opposite of hp (so this one is never taken), but after
  1232. that one there is a branch that will be taken, so perform a
  1233. little hack: set p1 equal to this instruction (that's what the
  1234. last SkipLabels is for, only works with short bool evaluation)}
  1235. (conditions_equal(taicpu(p1).condition,inverse_cond(hp.condition)) and
  1236. SkipLabels(p1,p2) and
  1237. (p2.typ = ait_instruction) and
  1238. (taicpu(p2).is_jmp) and
  1239. (IsJumpToLabelUncond(taicpu(p2)) or
  1240. (conditions_equal(taicpu(p2).condition,hp.condition))) and
  1241. SkipLabels(p1,p1))
  1242. {$endif not MIPS and not JVM}
  1243. then
  1244. begin
  1245. { quick check for loops of the form "l5: ; jmp l5 }
  1246. if (tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).labelnr =
  1247. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).labelnr) then
  1248. exit;
  1249. if not GetFinalDestination(taicpu(p1),succ(level)) then
  1250. exit;
  1251. {$if defined(aarch64)}
  1252. { can't have conditional branches to
  1253. global labels on AArch64, because the
  1254. offset may become too big }
  1255. if not(taicpu(hp).condition in [C_None,C_AL,C_NV]) and
  1256. (tasmlabel(JumpTargetOp(taicpu(p1))^.ref^.symbol).bind<>AB_LOCAL) then
  1257. exit;
  1258. {$endif aarch64}
  1259. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1260. JumpTargetOp(hp)^.ref^.symbol:=JumpTargetOp(taicpu(p1))^.ref^.symbol;
  1261. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).increfs;
  1262. end
  1263. {$if not defined(MIPS) and not defined(JVM)}
  1264. else
  1265. if conditions_equal(taicpu(p1).condition,inverse_cond(hp.condition)) then
  1266. if not FindAnyLabel(p1,l) then
  1267. begin
  1268. {$ifdef finaldestdebug}
  1269. insertllitem(asml,p1,p1.next,tai_comment.Create(
  1270. strpnew('previous label inserted'))));
  1271. {$endif finaldestdebug}
  1272. current_asmdata.getjumplabel(l);
  1273. insertllitem(p1,p1.next,tai_label.Create(l));
  1274. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1275. JumpTargetOp(hp)^.ref^.symbol := l;
  1276. l.increfs;
  1277. { this won't work, since the new label isn't in the labeltable }
  1278. { so it will fail the rangecheck. Labeltable should become a }
  1279. { hashtable to support this: }
  1280. { GetFinalDestination(asml, hp); }
  1281. end
  1282. else
  1283. begin
  1284. {$ifdef finaldestdebug}
  1285. insertllitem(asml,p1,p1.next,tai_comment.Create(
  1286. strpnew('next label reused'))));
  1287. {$endif finaldestdebug}
  1288. l.increfs;
  1289. tasmlabel(JumpTargetOp(hp)^.ref^.symbol).decrefs;
  1290. JumpTargetOp(hp)^.ref^.symbol := l;
  1291. if not GetFinalDestination(hp,succ(level)) then
  1292. exit;
  1293. end;
  1294. {$endif not MIPS and not JVM}
  1295. end;
  1296. GetFinalDestination := true;
  1297. end;
  1298. procedure TAOptObj.PrePeepHoleOpts;
  1299. var
  1300. p: tai;
  1301. begin
  1302. p := BlockStart;
  1303. ClearUsedRegs;
  1304. while (p <> BlockEnd) Do
  1305. begin
  1306. UpdateUsedRegs(tai(p.next));
  1307. if PrePeepHoleOptsCpu(p) then
  1308. continue;
  1309. if assigned(p) then
  1310. begin
  1311. UpdateUsedRegs(p);
  1312. p:=tai(p.next);
  1313. end;
  1314. end;
  1315. end;
  1316. procedure TAOptObj.PeepHoleOptPass1;
  1317. var
  1318. p,hp1,hp2 : tai;
  1319. stoploop:boolean;
  1320. const
  1321. {$ifdef JVM}
  1322. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_jcatch];
  1323. {$else JVM}
  1324. { Stop if it reaches SEH directive information in the form of
  1325. consts, which may occur if RemoveDeadCodeAfterJump is called on
  1326. the final RET instruction on x86, for example }
  1327. TaiFence = SkipInstr + [ait_const, ait_realconst, ait_typedconst, ait_label, ait_align];
  1328. {$endif JVM} begin
  1329. repeat
  1330. stoploop:=true;
  1331. p := BlockStart;
  1332. ClearUsedRegs;
  1333. while (p <> BlockEnd) Do
  1334. begin
  1335. { I'am not sure why this is done, UsedRegs should reflect the register usage before the instruction
  1336. If an instruction needs the information of this, it can easily create a TempUsedRegs (FK)
  1337. UpdateUsedRegs(tai(p.next));
  1338. }
  1339. {$ifdef DEBUG_OPTALLOC}
  1340. if p.Typ=ait_instruction then
  1341. InsertLLItem(tai(p.Previous),p,tai_comment.create(strpnew(GetAllocationString(UsedRegs))));
  1342. {$endif DEBUG_OPTALLOC}
  1343. if PeepHoleOptPass1Cpu(p) then
  1344. begin
  1345. stoploop:=false;
  1346. UpdateUsedRegs(p);
  1347. continue;
  1348. end;
  1349. case p.Typ Of
  1350. ait_instruction:
  1351. begin
  1352. { Handle Jmp Optimizations }
  1353. if taicpu(p).is_jmp then
  1354. begin
  1355. { the following if-block removes all code between a jmp and the next label,
  1356. because it can never be executed
  1357. }
  1358. if IsJumpToLabelUncond(taicpu(p)) then
  1359. begin
  1360. hp2:=p;
  1361. while GetNextInstruction(hp2, hp1) and
  1362. (hp1.typ <> ait_label)
  1363. {$ifdef JVM}
  1364. and (hp1.typ <> ait_jcatch)
  1365. {$endif}
  1366. do
  1367. if not(hp1.typ in TaiFence) then
  1368. begin
  1369. if (hp1.typ = ait_instruction) and
  1370. taicpu(hp1).is_jmp and
  1371. (JumpTargetOp(taicpu(hp1))^.typ = top_ref) and
  1372. (JumpTargetOp(taicpu(hp1))^.ref^.symbol is TAsmLabel) then
  1373. TAsmLabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).decrefs;
  1374. { don't kill start/end of assembler block,
  1375. no-line-info-start/end, cfi end, etc }
  1376. if not(hp1.typ in [ait_align,ait_marker]) and
  1377. ((hp1.typ<>ait_cfi) or
  1378. (tai_cfi_base(hp1).cfityp<>cfi_endproc)) then
  1379. begin
  1380. {$ifdef cpudelayslot}
  1381. if (hp1.typ=ait_instruction) and (taicpu(hp1).is_jmp) then
  1382. RemoveDelaySlot(hp1);
  1383. {$endif cpudelayslot}
  1384. asml.remove(hp1);
  1385. hp1.free;
  1386. stoploop:=false;
  1387. end
  1388. else
  1389. hp2:=hp1;
  1390. end
  1391. else break;
  1392. end;
  1393. if GetNextInstruction(p, hp1) then
  1394. begin
  1395. SkipEntryExitMarker(hp1,hp1);
  1396. { remove unconditional jumps to a label coming right after them }
  1397. if IsJumpToLabelUncond(taicpu(p)) and
  1398. FindLabel(tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol), hp1) and
  1399. { TODO: FIXME removing the first instruction fails}
  1400. (p<>blockstart) then
  1401. begin
  1402. tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol).decrefs;
  1403. {$ifdef cpudelayslot}
  1404. RemoveDelaySlot(p);
  1405. {$endif cpudelayslot}
  1406. hp2:=tai(hp1.next);
  1407. asml.remove(p);
  1408. p.free;
  1409. p:=hp2;
  1410. stoploop:=false;
  1411. continue;
  1412. end
  1413. else if assigned(hp1) then
  1414. begin
  1415. { change the following jumps:
  1416. jmp<cond> lab_1 jmp<cond_inverted> lab_2
  1417. jmp lab_2 >>> <code>
  1418. lab_1: lab_2:
  1419. <code>
  1420. lab_2:
  1421. }
  1422. if hp1.typ = ait_label then
  1423. SkipLabels(hp1,hp1);
  1424. if (tai(hp1).typ=ait_instruction) and
  1425. IsJumpToLabelUncond(taicpu(hp1)) and
  1426. GetNextInstruction(hp1, hp2) and
  1427. IsJumpToLabel(taicpu(p)) and
  1428. FindLabel(tasmlabel(JumpTargetOp(taicpu(p))^.ref^.symbol), hp2) then
  1429. begin
  1430. if (taicpu(p).opcode=aopt_condjmp)
  1431. {$if defined(arm) or defined(aarch64)}
  1432. and (taicpu(p).condition<>C_None)
  1433. {$endif arm or aarch64}
  1434. {$if defined(aarch64)}
  1435. { can't have conditional branches to
  1436. global labels on AArch64, because the
  1437. offset may become too big }
  1438. and (tasmlabel(JumpTargetOp(taicpu(hp1))^.ref^.symbol).bind=AB_LOCAL)
  1439. {$endif aarch64}
  1440. then
  1441. begin
  1442. taicpu(p).condition:=inverse_cond(taicpu(p).condition);
  1443. tai_label(hp2).labsym.decrefs;
  1444. JumpTargetOp(taicpu(p))^.ref^.symbol:=JumpTargetOp(taicpu(hp1))^.ref^.symbol;
  1445. { when freeing hp1, the reference count
  1446. isn't decreased, so don't increase
  1447. taicpu(p).oper[0]^.ref^.symbol.increfs;
  1448. }
  1449. {$ifdef cpudelayslot}
  1450. RemoveDelaySlot(hp1);
  1451. {$endif cpudelayslot}
  1452. asml.remove(hp1);
  1453. hp1.free;
  1454. stoploop:=false;
  1455. GetFinalDestination(taicpu(p),0);
  1456. end
  1457. else
  1458. begin
  1459. GetFinalDestination(taicpu(p),0);
  1460. p:=tai(p.next);
  1461. continue;
  1462. end;
  1463. end
  1464. else if IsJumpToLabel(taicpu(p)) then
  1465. GetFinalDestination(taicpu(p),0);
  1466. end;
  1467. end;
  1468. end
  1469. else
  1470. { All other optimizes }
  1471. begin
  1472. end; { if is_jmp }
  1473. end;
  1474. end;
  1475. if assigned(p) then
  1476. begin
  1477. UpdateUsedRegs(p);
  1478. p:=tai(p.next);
  1479. end;
  1480. end;
  1481. until stoploop or not(cs_opt_level3 in current_settings.optimizerswitches);
  1482. end;
  1483. procedure TAOptObj.PeepHoleOptPass2;
  1484. var
  1485. p: tai;
  1486. begin
  1487. p := BlockStart;
  1488. ClearUsedRegs;
  1489. while (p <> BlockEnd) Do
  1490. begin
  1491. if PeepHoleOptPass2Cpu(p) then
  1492. continue;
  1493. if assigned(p) then
  1494. begin
  1495. UpdateUsedRegs(p);
  1496. p:=tai(p.next);
  1497. end;
  1498. end;
  1499. end;
  1500. procedure TAOptObj.PostPeepHoleOpts;
  1501. var
  1502. p: tai;
  1503. begin
  1504. p := BlockStart;
  1505. ClearUsedRegs;
  1506. while (p <> BlockEnd) Do
  1507. begin
  1508. UpdateUsedRegs(tai(p.next));
  1509. if PostPeepHoleOptsCpu(p) then
  1510. continue;
  1511. if assigned(p) then
  1512. begin
  1513. UpdateUsedRegs(p);
  1514. p:=tai(p.next);
  1515. end;
  1516. end;
  1517. end;
  1518. function TAOptObj.PrePeepHoleOptsCpu(var p : tai) : boolean;
  1519. begin
  1520. result := false;
  1521. end;
  1522. function TAOptObj.PeepHoleOptPass1Cpu(var p: tai): boolean;
  1523. begin
  1524. result := false;
  1525. end;
  1526. function TAOptObj.PeepHoleOptPass2Cpu(var p : tai) : boolean;
  1527. begin
  1528. result := false;
  1529. end;
  1530. function TAOptObj.PostPeepHoleOptsCpu(var p: tai): boolean;
  1531. begin
  1532. result := false;
  1533. end;
  1534. procedure TAOptObj.Debug_InsertInstrRegisterDependencyInfo;
  1535. var
  1536. p: tai;
  1537. ri: tregisterindex;
  1538. reg: TRegister;
  1539. commentstr: AnsiString;
  1540. registers_found: Boolean;
  1541. begin
  1542. p:=tai(AsmL.First);
  1543. while (p<>AsmL.Last) Do
  1544. begin
  1545. if p.typ=ait_instruction then
  1546. begin
  1547. {$ifdef x86}
  1548. taicpu(p).SetOperandOrder(op_att);
  1549. {$endif x86}
  1550. commentstr:='Instruction reads';
  1551. registers_found:=false;
  1552. for ri in tregisterindex do
  1553. begin
  1554. reg:=regnumber_table[ri];
  1555. if (reg<>NR_NO) and InstructionLoadsFromReg(reg,p) then
  1556. begin
  1557. commentstr:=commentstr+' '+std_regname(reg);
  1558. registers_found:=true;
  1559. end;
  1560. end;
  1561. if not registers_found then
  1562. commentstr:=commentstr+' no registers';
  1563. commentstr:=commentstr+' and writes new values in';
  1564. registers_found:=false;
  1565. for ri in tregisterindex do
  1566. begin
  1567. reg:=regnumber_table[ri];
  1568. if (reg<>NR_NO) and RegLoadedWithNewValue(reg,p) then
  1569. begin
  1570. commentstr:=commentstr+' '+std_regname(reg);
  1571. registers_found:=true;
  1572. end;
  1573. end;
  1574. if not registers_found then
  1575. commentstr:=commentstr+' no registers';
  1576. AsmL.InsertAfter(tai_comment.Create(strpnew(commentstr)),p);
  1577. end;
  1578. p:=tai(p.next);
  1579. end;
  1580. end;
  1581. End.