aoptobj.pas 97 KB

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