aoptobj.pas 92 KB

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