aoptobj.pas 96 KB

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