aoptobj.pas 98 KB

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