rgobj.pas 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085
  1. {
  2. Copyright (c) 1998-2012 by the Free Pascal team
  3. This unit implements the base class for the register allocator
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. {$i fpcdefs.inc}
  18. { $define DEBUG_REGALLOC}
  19. { $define DEBUG_SPILLCOALESCE}
  20. { $define DEBUG_REGISTERLIFE}
  21. { Allow duplicate allocations, can be used to get the .s file written }
  22. { $define ALLOWDUPREG}
  23. {$ifdef DEBUG_REGALLOC}
  24. {$define EXTDEBUG}
  25. {$endif DEBUG_REGALLOC}
  26. unit rgobj;
  27. interface
  28. uses
  29. cutils, cpubase,
  30. aasmtai,aasmdata,aasmsym,aasmcpu,
  31. cclasses,globtype,cgbase,cgutils;
  32. const
  33. interferenceBitmap2Size = 256;
  34. type
  35. {
  36. The interference bitmap contains of 2 layers:
  37. layer 1 - 256*256 blocks with pointers to layer 2 blocks
  38. layer 2 - blocks of 32*256 (32 bytes = 256 bits)
  39. }
  40. Tinterferencebitmap2 = array of set of byte;
  41. Tinterferencebitmap1 = array[byte] of Tinterferencebitmap2;
  42. tinterferencebitmap1Array = array of tinterferencebitmap1;
  43. Tinterferencebitmap=class
  44. private
  45. maxx1,
  46. maxy1 : byte;
  47. fbitmap : tinterferencebitmap1Array;
  48. function getbitmap(x,y:tsuperregister):boolean;
  49. procedure setbitmap(x,y:tsuperregister;b:boolean);
  50. public
  51. constructor create;
  52. destructor destroy;override;
  53. property bitmap[x,y:tsuperregister]:boolean read getbitmap write setbitmap;default;
  54. end;
  55. {In the register allocator we keep track of move instructions.
  56. These instructions are moved between five linked lists. There
  57. is also a linked list per register to keep track about the moves
  58. it is associated with. Because we need to determine quickly in
  59. which of the five lists it is we add anu enumeradtion to each
  60. move instruction.}
  61. Tmoveset=(ms_coalesced_moves,ms_constrained_moves,ms_frozen_moves,
  62. ms_worklist_moves,ms_active_moves);
  63. Tmoveins=class(Tlinkedlistitem)
  64. moveset:Tmoveset;
  65. x,y:Tsuperregister;
  66. id:longint;
  67. end;
  68. Tmovelistheader=record
  69. count,
  70. maxcount,
  71. sorted_until : cardinal;
  72. end;
  73. Tmovelist=record
  74. header : Tmovelistheader;
  75. data : array[tsuperregister] of Tmoveins;
  76. end;
  77. Pmovelist=^Tmovelist;
  78. Treginfoflag=(
  79. ri_coalesced, { the register is coalesced with other register }
  80. ri_selected, { the register is put to selectstack }
  81. ri_spill_helper, { the register contains a value of a previously spilled register }
  82. ri_has_initial_loc { the register has the initial memory location (e.g. a parameter in the stack) }
  83. );
  84. Treginfoflagset=set of Treginfoflag;
  85. Treginfo=record
  86. live_start,
  87. live_end : Tai;
  88. subreg : tsubregister;
  89. alias : Tsuperregister;
  90. { The register allocator assigns each register a colour }
  91. colour : Tsuperregister;
  92. movelist : Pmovelist;
  93. adjlist : Psuperregisterworklist;
  94. degree : TSuperregister;
  95. flags : Treginfoflagset;
  96. weight : longint;
  97. {$ifdef llvm}
  98. def : pointer;
  99. {$endif llvm}
  100. count_uses : longint;
  101. total_interferences : longint;
  102. real_reg_interferences: word;
  103. end;
  104. // Preginfo=^TReginfo;
  105. TReginfoArray = Array of TReginfo;
  106. tspillreginfo = record
  107. { a single register may appear more than once in an instruction,
  108. but with different subregister types -> store all subregister types
  109. that occur, so we can add the necessary constraints for the inline
  110. register that will have to replace it }
  111. spillregconstraints : set of TSubRegister;
  112. orgreg : tsuperregister;
  113. loadreg,
  114. storereg: tregister;
  115. regread, regwritten, mustbespilled: boolean;
  116. end;
  117. tspillregsinfo = record
  118. spillreginfocount: longint;
  119. spillreginfo: array[0..3] of tspillreginfo;
  120. end;
  121. // Pspill_temp_list=^Tspill_temp_list;
  122. Tspill_temp_list = array of Treference;
  123. { used to store where a register is spilled and what interferences it has at the point of being spilled }
  124. tspillinfo = record
  125. spilllocation : treference;
  126. spilled : boolean;
  127. interferences : Tinterferencebitmap;
  128. end;
  129. {#------------------------------------------------------------------
  130. This class implements the default register allocator. It is used by the
  131. code generator to allocate and free registers which might be valid
  132. across nodes. It also contains utility routines related to registers.
  133. Some of the methods in this class should be overridden
  134. by cpu-specific implementations.
  135. --------------------------------------------------------------------}
  136. trgobj=class
  137. preserved_by_proc : tcpuregisterset;
  138. used_in_proc : tcpuregisterset;
  139. { generate SSA code? }
  140. ssa_safe: boolean;
  141. constructor create(Aregtype:Tregistertype;
  142. Adefaultsub:Tsubregister;
  143. const Ausable:array of tsuperregister;
  144. Afirst_imaginary:Tsuperregister;
  145. Apreserved_by_proc:Tcpuregisterset);
  146. destructor destroy;override;
  147. { Allocate a register. An internalerror will be generated if there is
  148. no more free registers which can be allocated.}
  149. function getregister(list:TAsmList;subreg:Tsubregister):Tregister;virtual;
  150. { Get the register specified.}
  151. procedure getcpuregister(list:TAsmList;r:Tregister);virtual;
  152. procedure ungetcpuregister(list:TAsmList;r:Tregister);virtual;
  153. { Get multiple registers specified.}
  154. procedure alloccpuregisters(list:TAsmList;const r:Tcpuregisterset);virtual;
  155. { Free multiple registers specified.}
  156. procedure dealloccpuregisters(list:TAsmList;const r:Tcpuregisterset);virtual;
  157. function uses_registers:boolean;virtual;
  158. procedure add_reg_instruction(instr:Tai;r:tregister;aweight:longint);
  159. procedure add_move_instruction(instr:Taicpu);
  160. { Do the register allocation.}
  161. procedure do_register_allocation(list:TAsmList;headertai:tai);virtual;
  162. { Adds an interference edge.
  163. don't move this to the protected section, the arm cg requires to access this (FK) }
  164. procedure add_edge(u,v:Tsuperregister);
  165. { translates a single given imaginary register to it's real register }
  166. procedure translate_register(var reg : tregister);
  167. { sets the initial memory location of the register }
  168. procedure set_reg_initial_location(reg: tregister; const ref: treference);
  169. protected
  170. maxreginfo,
  171. maxreginfoinc,
  172. maxreg : Tsuperregister;
  173. regtype : Tregistertype;
  174. { default subregister used }
  175. defaultsub : tsubregister;
  176. live_registers:Tsuperregisterworklist;
  177. spillednodes: tsuperregisterworklist;
  178. { can be overridden to add cpu specific interferences }
  179. procedure add_cpu_interferences(p : tai);virtual;
  180. procedure add_constraints(reg:Tregister);virtual;
  181. function getregisterinline(list:TAsmList;const subregconstraints:Tsubregisterset):Tregister;
  182. procedure ungetregisterinline(list:TAsmList;r:Tregister);
  183. function get_spill_subreg(r : tregister) : tsubregister;virtual;
  184. function do_spill_replace(list:TAsmList;instr:tai_cpu_abstract_sym;orgreg:tsuperregister;const spilltemp:treference):boolean;virtual;
  185. { the orgrsupeg parameter is only here for the llvm target, so it can
  186. discover the def to use for the load }
  187. procedure do_spill_read(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);virtual;
  188. procedure do_spill_written(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);virtual;
  189. function addreginfo(var spregs: tspillregsinfo; const r: tsuperregisterset; reg: tregister; operation: topertype): boolean;
  190. function instr_get_oper_spilling_info(var spregs: tspillregsinfo; const r: tsuperregisterset; instr: tai_cpu_abstract_sym; opidx: longint): boolean; virtual;
  191. procedure substitute_spilled_registers(const spregs: tspillregsinfo; instr: tai_cpu_abstract_sym; opidx: longint); virtual;
  192. procedure try_replace_reg(const spregs: tspillregsinfo; var reg: tregister; useloadreg: boolean);
  193. function instr_spill_register(list:TAsmList;
  194. instr:tai_cpu_abstract_sym;
  195. const r:Tsuperregisterset;
  196. const spilltemplist:Tspill_temp_list): boolean;virtual;
  197. procedure insert_regalloc_info_all(list:TAsmList);
  198. procedure determine_spill_registers(list:TAsmList;headertail:tai); virtual;
  199. procedure get_spill_temp(list:TAsmlist;spill_temps: Tspill_temp_list; supreg: tsuperregister);virtual;
  200. strict protected
  201. { Highest register allocated until now.}
  202. reginfo : TReginfoArray;
  203. usable_registers_cnt : word;
  204. private
  205. int_live_range_direction: TRADirection;
  206. { First imaginary register.}
  207. first_imaginary : Tsuperregister;
  208. usable_registers : array[0..maxcpuregister] of tsuperregister;
  209. usable_register_set : tcpuregisterset;
  210. ibitmap : Tinterferencebitmap;
  211. simplifyworklist,
  212. freezeworklist,
  213. spillworklist,
  214. coalescednodes,
  215. selectstack : tsuperregisterworklist;
  216. worklist_moves,
  217. active_moves,
  218. frozen_moves,
  219. coalesced_moves,
  220. constrained_moves,
  221. { in this list we collect all moveins which should be disposed after register allocation finishes,
  222. we still need the moves for spill coalesce for the whole register allocation process, so they cannot be
  223. released as soon as they are frozen or whatever }
  224. move_garbage : Tlinkedlist;
  225. extended_backwards,
  226. backwards_was_first : tbitset;
  227. has_usedmarks: boolean;
  228. has_directalloc: boolean;
  229. spillinfo : array of tspillinfo;
  230. moveins_id_counter: longint;
  231. { Disposes of the reginfo array.}
  232. procedure dispose_reginfo;
  233. { Prepare the register colouring.}
  234. procedure prepare_colouring;
  235. { Clean up after register colouring.}
  236. procedure epilogue_colouring;
  237. { Colour the registers; that is do the register allocation.}
  238. procedure colour_registers;
  239. procedure insert_regalloc_info(list:TAsmList;u:tsuperregister);
  240. procedure generate_interference_graph(list:TAsmList;headertai:tai);
  241. { sort spilled nodes by increasing number of interferences }
  242. procedure sort_spillednodes;
  243. { translates the registers in the given assembler list }
  244. procedure translate_registers(list:TAsmList);
  245. function spill_registers(list:TAsmList;headertai:tai):boolean;virtual;
  246. function getnewreg(subreg:tsubregister):tsuperregister;
  247. procedure add_edges_used(u:Tsuperregister);
  248. procedure add_to_movelist(u:Tsuperregister;ins:Tmoveins);
  249. function move_related(n:Tsuperregister):boolean;
  250. procedure make_work_list;
  251. procedure sort_simplify_worklist;
  252. procedure enable_moves(n:Tsuperregister);
  253. procedure decrement_degree(m:Tsuperregister);
  254. procedure simplify;
  255. procedure add_worklist(u:Tsuperregister);
  256. function adjacent_ok(u,v:Tsuperregister):boolean;
  257. function conservative(u,v:Tsuperregister):boolean;
  258. procedure coalesce;
  259. procedure freeze_moves(u:Tsuperregister);
  260. procedure freeze;
  261. procedure select_spill;
  262. procedure assign_colours;
  263. procedure clear_interferences(u:Tsuperregister);
  264. procedure set_live_range_direction(dir: TRADirection);
  265. procedure set_live_start(reg : tsuperregister;t : tai);
  266. function get_live_start(reg : tsuperregister) : tai;
  267. procedure set_live_end(reg : tsuperregister;t : tai);
  268. function get_live_end(reg : tsuperregister) : tai;
  269. procedure alloc_spillinfo(max_reg: Tsuperregister);
  270. { Remove p from the list and set p to the next element in the list }
  271. procedure remove_ai(list:TAsmList; var p:Tai);
  272. {$ifdef DEBUG_SPILLCOALESCE}
  273. procedure write_spill_stats;
  274. {$endif DEBUG_SPILLCOALESCE}
  275. public
  276. {$ifdef EXTDEBUG}
  277. procedure writegraph(loopidx:longint);
  278. {$endif EXTDEBUG}
  279. procedure combine(u,v:Tsuperregister);
  280. { set v as an alias for u }
  281. procedure set_alias(u,v:Tsuperregister);
  282. function get_alias(n:Tsuperregister):Tsuperregister;
  283. property live_range_direction: TRADirection read int_live_range_direction write set_live_range_direction;
  284. property live_start[reg : tsuperregister]: tai read get_live_start write set_live_start;
  285. property live_end[reg : tsuperregister]: tai read get_live_end write set_live_end;
  286. end;
  287. const
  288. first_reg = 0;
  289. last_reg = high(tsuperregister)-1;
  290. maxspillingcounter = 20;
  291. implementation
  292. uses
  293. sysutils,
  294. globals,
  295. verbose,tgobj,procinfo,cgobj;
  296. procedure sort_movelist(ml:Pmovelist);
  297. var h,i,p:longword;
  298. t:Tmoveins;
  299. begin
  300. with ml^ do
  301. begin
  302. if header.count<2 then
  303. exit;
  304. p:=longword(1) shl BsrDWord(header.count-1);
  305. repeat
  306. for h:=p to header.count-1 do
  307. begin
  308. i:=h;
  309. t:=data[i];
  310. repeat
  311. if data[i-p].id<=t.id then
  312. break;
  313. data[i]:=data[i-p];
  314. dec(i,p);
  315. until i<p;
  316. data[i]:=t;
  317. end;
  318. p:=p shr 1;
  319. until p=0;
  320. header.sorted_until:=header.count-1;
  321. end;
  322. end;
  323. {******************************************************************************
  324. tinterferencebitmap
  325. ******************************************************************************}
  326. constructor tinterferencebitmap.create;
  327. begin
  328. inherited create;
  329. maxx1:=1;
  330. SetLength(fbitmap,2);
  331. end;
  332. destructor tinterferencebitmap.destroy;
  333. var i,j:byte;
  334. begin
  335. for i:=0 to maxx1 do
  336. for j:=0 to maxy1 do
  337. if assigned(fbitmap[i,j]) then
  338. fbitmap[i,j]:=nil;
  339. fbitmap:=nil;
  340. end;
  341. function tinterferencebitmap.getbitmap(x,y:tsuperregister):boolean;
  342. var
  343. page : TInterferencebitmap2;
  344. begin
  345. result:=false;
  346. if (x shr 8>maxx1) then
  347. exit;
  348. page:=fbitmap[x shr 8,y shr 8];
  349. result:=assigned(page) and
  350. ((x and $ff) in page[y and $ff]);
  351. end;
  352. procedure tinterferencebitmap.setbitmap(x,y:tsuperregister;b:boolean);
  353. var
  354. x1,y1 : byte;
  355. begin
  356. x1:=x shr 8;
  357. y1:=y shr 8;
  358. if x1>maxx1 then
  359. begin
  360. Setlength(fbitmap,x1+1);
  361. maxx1:=x1;
  362. end;
  363. if not assigned(fbitmap[x1,y1]) then
  364. begin
  365. if y1>maxy1 then
  366. maxy1:=y1;
  367. SetLength(fbitmap[x1,y1],interferenceBitmap2Size);
  368. end;
  369. if b then
  370. include(fbitmap[x1,y1][y and $ff],(x and $ff))
  371. else
  372. exclude(fbitmap[x1,y1][y and $ff],(x and $ff));
  373. end;
  374. {******************************************************************************
  375. trgobj
  376. ******************************************************************************}
  377. constructor trgobj.create(Aregtype:Tregistertype;
  378. Adefaultsub:Tsubregister;
  379. const Ausable:array of tsuperregister;
  380. Afirst_imaginary:Tsuperregister;
  381. Apreserved_by_proc:Tcpuregisterset);
  382. var
  383. i : cardinal;
  384. begin
  385. { empty super register sets can cause very strange problems }
  386. if high(Ausable)=-1 then
  387. internalerror(200210181);
  388. live_range_direction:=rad_forward;
  389. first_imaginary:=Afirst_imaginary;
  390. maxreg:=Afirst_imaginary;
  391. regtype:=Aregtype;
  392. defaultsub:=Adefaultsub;
  393. preserved_by_proc:=Apreserved_by_proc;
  394. // default values set by newinstance
  395. // used_in_proc:=[];
  396. // ssa_safe:=false;
  397. live_registers.init;
  398. { Get reginfo for CPU registers }
  399. maxreginfo:=first_imaginary;
  400. maxreginfoinc:=16;
  401. moveins_id_counter:=0;
  402. worklist_moves:=Tlinkedlist.create;
  403. move_garbage:=TLinkedList.Create;
  404. SetLength(reginfo,first_imaginary);
  405. for i:=0 to first_imaginary-1 do
  406. begin
  407. reginfo[i].degree:=high(tsuperregister);
  408. reginfo[i].alias:=RS_INVALID;
  409. end;
  410. { Usable registers }
  411. // default value set by constructor
  412. // fillchar(usable_registers,sizeof(usable_registers),0);
  413. for i:=low(Ausable) to high(Ausable) do
  414. begin
  415. usable_registers[i]:=Ausable[i];
  416. include(usable_register_set,Ausable[i]);
  417. end;
  418. usable_registers_cnt:=high(Ausable)+1;
  419. { Initialize Worklists }
  420. spillednodes.init;
  421. simplifyworklist.init;
  422. freezeworklist.init;
  423. spillworklist.init;
  424. coalescednodes.init;
  425. selectstack.init;
  426. end;
  427. destructor trgobj.destroy;
  428. begin
  429. spillednodes.done;
  430. simplifyworklist.done;
  431. freezeworklist.done;
  432. spillworklist.done;
  433. coalescednodes.done;
  434. selectstack.done;
  435. live_registers.done;
  436. move_garbage.free;
  437. worklist_moves.free;
  438. dispose_reginfo;
  439. extended_backwards.free;
  440. backwards_was_first.free;
  441. end;
  442. procedure Trgobj.dispose_reginfo;
  443. var
  444. i : cardinal;
  445. begin
  446. if reginfo<>nil then
  447. begin
  448. for i:=0 to maxreg-1 do
  449. with reginfo[i] do
  450. begin
  451. if adjlist<>nil then
  452. dispose(adjlist,done);
  453. if movelist<>nil then
  454. dispose(movelist);
  455. end;
  456. reginfo:=nil;
  457. end;
  458. end;
  459. function trgobj.getnewreg(subreg:tsubregister):tsuperregister;
  460. var
  461. oldmaxreginfo : tsuperregister;
  462. begin
  463. result:=maxreg;
  464. inc(maxreg);
  465. if maxreg>=last_reg then
  466. Message(parser_f_too_complex_proc);
  467. if maxreg>=maxreginfo then
  468. begin
  469. oldmaxreginfo:=maxreginfo;
  470. { Prevent overflow }
  471. if maxreginfoinc>last_reg-maxreginfo then
  472. maxreginfo:=last_reg
  473. else
  474. begin
  475. inc(maxreginfo,maxreginfoinc);
  476. if maxreginfoinc<256 then
  477. maxreginfoinc:=maxreginfoinc*2;
  478. end;
  479. SetLength(reginfo,maxreginfo);
  480. end;
  481. reginfo[result].subreg:=subreg;
  482. end;
  483. function trgobj.getregister(list:TAsmList;subreg:Tsubregister):Tregister;
  484. begin
  485. {$ifdef EXTDEBUG}
  486. if reginfo=nil then
  487. InternalError(2004020901);
  488. {$endif EXTDEBUG}
  489. if defaultsub=R_SUBNONE then
  490. result:=newreg(regtype,getnewreg(R_SUBNONE),R_SUBNONE)
  491. else
  492. result:=newreg(regtype,getnewreg(subreg),subreg);
  493. end;
  494. function trgobj.uses_registers:boolean;
  495. begin
  496. result:=(maxreg>first_imaginary) or has_usedmarks or has_directalloc;
  497. end;
  498. procedure trgobj.ungetcpuregister(list:TAsmList;r:Tregister);
  499. begin
  500. if (getsupreg(r)>=first_imaginary) then
  501. InternalError(2004020902);
  502. list.concat(Tai_regalloc.dealloc(r,nil));
  503. end;
  504. procedure trgobj.getcpuregister(list:TAsmList;r:Tregister);
  505. var
  506. supreg:Tsuperregister;
  507. begin
  508. supreg:=getsupreg(r);
  509. if supreg>=first_imaginary then
  510. internalerror(2003121503);
  511. include(used_in_proc,supreg);
  512. has_directalloc:=true;
  513. list.concat(Tai_regalloc.alloc(r,nil));
  514. end;
  515. procedure trgobj.alloccpuregisters(list:TAsmList;const r:Tcpuregisterset);
  516. var i:cardinal;
  517. begin
  518. for i:=0 to first_imaginary-1 do
  519. if i in r then
  520. getcpuregister(list,newreg(regtype,i,defaultsub));
  521. end;
  522. procedure trgobj.dealloccpuregisters(list:TAsmList;const r:Tcpuregisterset);
  523. var i:cardinal;
  524. begin
  525. for i:=0 to first_imaginary-1 do
  526. if i in r then
  527. ungetcpuregister(list,newreg(regtype,i,defaultsub));
  528. end;
  529. const
  530. rtindex : longint = 0;
  531. procedure trgobj.do_register_allocation(list:TAsmList;headertai:tai);
  532. var
  533. spillingcounter:longint;
  534. endspill:boolean;
  535. i : Longint;
  536. begin
  537. { Insert regalloc info for imaginary registers }
  538. insert_regalloc_info_all(list);
  539. ibitmap:=tinterferencebitmap.create;
  540. generate_interference_graph(list,headertai);
  541. {$ifdef DEBUG_SPILLCOALESCE}
  542. if maxreg>first_imaginary then
  543. writeln(current_procinfo.procdef.mangledname, ': register allocation [',regtype,']');
  544. {$endif DEBUG_SPILLCOALESCE}
  545. {$ifdef DEBUG_REGALLOC}
  546. if maxreg>first_imaginary then
  547. writegraph(rtindex);
  548. {$endif DEBUG_REGALLOC}
  549. inc(rtindex);
  550. { Don't do the real allocation when -sr is passed }
  551. if (cs_no_regalloc in current_settings.globalswitches) then
  552. exit;
  553. { Spill registers which interfere with all usable real registers.
  554. It is pointless to keep them for further processing. Also it may
  555. cause endless spilling.
  556. This can happen when compiling for very constrained CPUs such as
  557. i8086 where indexed memory access instructions allow only
  558. few registers as arguments and additionally the calling convention
  559. provides no general purpose volatile registers.
  560. Also spill registers which have the initial memory location
  561. and are used only once. This allows to access the memory location
  562. directly, without preloading it to a register.
  563. }
  564. for i:=first_imaginary to maxreg-1 do
  565. with reginfo[i] do
  566. if (real_reg_interferences>=usable_registers_cnt) or
  567. { also spill registers which have the initial memory location
  568. and are used only once }
  569. ((ri_has_initial_loc in flags) and (weight<=200)) then
  570. spillednodes.add(i);
  571. if spillednodes.length<>0 then
  572. begin
  573. spill_registers(list,headertai);
  574. spillednodes.clear;
  575. end;
  576. {Do register allocation.}
  577. spillingcounter:=0;
  578. repeat
  579. determine_spill_registers(list,headertai);
  580. endspill:=true;
  581. if spillednodes.length<>0 then
  582. begin
  583. inc(spillingcounter);
  584. if spillingcounter>maxspillingcounter then
  585. begin
  586. {$ifdef EXTDEBUG}
  587. { Only exit here so the .s file is still generated. Assembling
  588. the file will still trigger an error }
  589. exit;
  590. {$else}
  591. internalerror(200309041);
  592. {$endif}
  593. end;
  594. endspill:=not spill_registers(list,headertai);
  595. end;
  596. until endspill;
  597. ibitmap.free;
  598. translate_registers(list);
  599. {$ifdef DEBUG_SPILLCOALESCE}
  600. write_spill_stats;
  601. {$endif DEBUG_SPILLCOALESCE}
  602. { we need the translation table for debugging info and verbose assembler output,
  603. so not dispose them yet (FK)
  604. }
  605. for i:=0 to High(spillinfo) do
  606. spillinfo[i].interferences.Free;
  607. spillinfo:=nil;
  608. end;
  609. procedure trgobj.add_constraints(reg:Tregister);
  610. begin
  611. end;
  612. procedure trgobj.add_edge(u,v:Tsuperregister);
  613. {This procedure will add an edge to the virtual interference graph.}
  614. procedure addadj(u,v:Tsuperregister);
  615. begin
  616. {$ifdef EXTDEBUG}
  617. if (u>=maxreginfo) then
  618. internalerror(2012101901);
  619. {$endif}
  620. with reginfo[u] do
  621. begin
  622. if adjlist=nil then
  623. new(adjlist,init);
  624. adjlist^.add(v);
  625. if (v<first_imaginary) and
  626. (v in usable_register_set) then
  627. inc(real_reg_interferences);
  628. end;
  629. end;
  630. begin
  631. if (u<>v) and not(ibitmap[v,u]) then
  632. begin
  633. ibitmap[v,u]:=true;
  634. ibitmap[u,v]:=true;
  635. {Precoloured nodes are not stored in the interference graph.}
  636. if (u>=first_imaginary) then
  637. addadj(u,v);
  638. if (v>=first_imaginary) then
  639. addadj(v,u);
  640. end;
  641. end;
  642. procedure trgobj.add_edges_used(u:Tsuperregister);
  643. var i:cardinal;
  644. begin
  645. with live_registers do
  646. if length>0 then
  647. for i:=0 to length-1 do
  648. add_edge(u,get_alias(buf[i]));
  649. end;
  650. {$ifdef EXTDEBUG}
  651. procedure trgobj.writegraph(loopidx:longint);
  652. {This procedure writes out the current interference graph in the
  653. register allocator.}
  654. var f:text;
  655. i,j:cardinal;
  656. begin
  657. assign(f,outputunitdir+current_procinfo.procdef.mangledname+'_igraph'+tostr(loopidx));
  658. rewrite(f);
  659. writeln(f,'Interference graph of ',current_procinfo.procdef.fullprocname(true));
  660. writeln(f,'Register type: ',regtype,', First imaginary register is ',first_imaginary,' ($',hexstr(first_imaginary,2),')');
  661. writeln(f);
  662. write(f,' ');
  663. for i:=0 to maxreg div 16 do
  664. for j:=0 to 15 do
  665. write(f,hexstr(i,1));
  666. writeln(f);
  667. write(f,'Weight Degree Uses IntfCnt ');
  668. for i:=0 to maxreg div 16 do
  669. write(f,'0123456789ABCDEF');
  670. writeln(f);
  671. for i:=0 to maxreg-1 do
  672. begin
  673. write(f,reginfo[i].weight:5,' ',reginfo[i].degree:5,' ',reginfo[i].count_uses:5,' ',reginfo[i].total_interferences:5,' ');
  674. if (i<first_imaginary) and
  675. (findreg_by_number(newreg(regtype,TSuperRegister(i),defaultsub))<>0) then
  676. write(f,std_regname(newreg(regtype,TSuperRegister(i),defaultsub))+':'+hexstr(i,2):7)
  677. else
  678. write(f,' ',hexstr(i,2):4);
  679. for j:=0 to maxreg-1 do
  680. if ibitmap[i,j] then
  681. write(f,'*')
  682. else
  683. write(f,'-');
  684. writeln(f);
  685. end;
  686. close(f);
  687. end;
  688. {$endif EXTDEBUG}
  689. procedure trgobj.add_to_movelist(u:Tsuperregister;ins:Tmoveins);
  690. begin
  691. {$ifdef EXTDEBUG}
  692. if (u>=maxreginfo) then
  693. internalerror(2012101902);
  694. {$endif}
  695. with reginfo[u] do
  696. begin
  697. if movelist=nil then
  698. begin
  699. { don't use sizeof(tmovelistheader), because that ignores alignment }
  700. getmem(movelist,ptruint(@movelist^.data)-ptruint(movelist)+16*sizeof(pointer));
  701. movelist^.header.maxcount:=16;
  702. movelist^.header.count:=0;
  703. movelist^.header.sorted_until:=0;
  704. end
  705. else
  706. begin
  707. if movelist^.header.count>=movelist^.header.maxcount then
  708. begin
  709. movelist^.header.maxcount:=movelist^.header.maxcount*2;
  710. { don't use sizeof(tmovelistheader), because that ignores alignment }
  711. reallocmem(movelist,ptruint(@movelist^.data)-ptruint(movelist)+movelist^.header.maxcount*sizeof(pointer));
  712. end;
  713. end;
  714. movelist^.data[movelist^.header.count]:=ins;
  715. inc(movelist^.header.count);
  716. end;
  717. end;
  718. procedure trgobj.set_live_range_direction(dir: TRADirection);
  719. begin
  720. if (dir in [rad_backwards,rad_backwards_reinit]) then
  721. begin
  722. if not assigned(extended_backwards) then
  723. begin
  724. { create expects a "size", not a "max bit" parameter -> +1 }
  725. backwards_was_first:=tbitset.create(maxreg+1);
  726. extended_backwards:=tbitset.create(maxreg+1);
  727. end
  728. else
  729. begin
  730. if (dir=rad_backwards_reinit) then
  731. extended_backwards.clear;
  732. backwards_was_first.clear;
  733. end;
  734. int_live_range_direction:=rad_backwards;
  735. end
  736. else
  737. int_live_range_direction:=rad_forward;
  738. end;
  739. procedure trgobj.set_live_start(reg: tsuperregister; t: tai);
  740. begin
  741. reginfo[reg].live_start:=t;
  742. end;
  743. function trgobj.get_live_start(reg: tsuperregister): tai;
  744. begin
  745. result:=reginfo[reg].live_start;
  746. end;
  747. procedure trgobj.set_live_end(reg: tsuperregister; t: tai);
  748. begin
  749. reginfo[reg].live_end:=t;
  750. end;
  751. function trgobj.get_live_end(reg: tsuperregister): tai;
  752. begin
  753. result:=reginfo[reg].live_end;
  754. end;
  755. procedure trgobj.alloc_spillinfo(max_reg: Tsuperregister);
  756. var
  757. j: longint;
  758. begin
  759. if Length(spillinfo)<max_reg then
  760. begin
  761. j:=Length(spillinfo);
  762. SetLength(spillinfo,max_reg);
  763. fillchar(spillinfo[j],sizeof(spillinfo[0])*(Length(spillinfo)-j),0);
  764. end;
  765. end;
  766. procedure trgobj.add_reg_instruction(instr:Tai;r:tregister;aweight:longint);
  767. var
  768. supreg : tsuperregister;
  769. begin
  770. supreg:=getsupreg(r);
  771. {$ifdef extdebug}
  772. if not (cs_no_regalloc in current_settings.globalswitches) and
  773. (supreg>=maxreginfo) then
  774. internalerror(200411061);
  775. {$endif extdebug}
  776. if supreg>=first_imaginary then
  777. with reginfo[supreg] do
  778. begin
  779. { avoid overflow }
  780. if high(weight)-aweight<weight then
  781. weight:=high(weight)
  782. else
  783. inc(weight,aweight);
  784. if (live_range_direction=rad_forward) then
  785. begin
  786. if not assigned(live_start) then
  787. live_start:=instr;
  788. live_end:=instr;
  789. end
  790. else
  791. begin
  792. if not extended_backwards.isset(supreg) then
  793. begin
  794. extended_backwards.include(supreg);
  795. live_start := instr;
  796. if not assigned(live_end) then
  797. begin
  798. backwards_was_first.include(supreg);
  799. live_end := instr;
  800. end;
  801. end
  802. else
  803. begin
  804. if backwards_was_first.isset(supreg) then
  805. live_end := instr;
  806. end
  807. end
  808. end;
  809. end;
  810. procedure trgobj.add_move_instruction(instr:Taicpu);
  811. {This procedure notifies a certain as a move instruction so the
  812. register allocator can try to eliminate it.}
  813. var i:Tmoveins;
  814. sreg, dreg : Tregister;
  815. ssupreg,dsupreg:Tsuperregister;
  816. begin
  817. {$ifdef extdebug}
  818. if (instr.oper[O_MOV_SOURCE]^.typ<>top_reg) or
  819. (instr.oper[O_MOV_DEST]^.typ<>top_reg) then
  820. internalerror(200311291);
  821. {$endif}
  822. sreg:=instr.oper[O_MOV_SOURCE]^.reg;
  823. dreg:=instr.oper[O_MOV_DEST]^.reg;
  824. { How should we handle m68k move %d0,%a0? }
  825. if (getregtype(sreg)<>getregtype(dreg)) then
  826. exit;
  827. if moveins_id_counter=high(moveins_id_counter) then
  828. internalerror(2021112701);
  829. inc(moveins_id_counter);
  830. i:=Tmoveins.create;
  831. i.id:=moveins_id_counter;
  832. i.moveset:=ms_worklist_moves;
  833. worklist_moves.insert(i);
  834. ssupreg:=getsupreg(sreg);
  835. add_to_movelist(ssupreg,i);
  836. dsupreg:=getsupreg(dreg);
  837. { On m68k move can mix address and integer registers,
  838. this leads to problems ... PM }
  839. if (ssupreg<>dsupreg) {and (getregtype(sreg)=getregtype(dreg))} then
  840. {Avoid adding the same move instruction twice to a single register.}
  841. add_to_movelist(dsupreg,i);
  842. i.x:=ssupreg;
  843. i.y:=dsupreg;
  844. end;
  845. function trgobj.move_related(n:Tsuperregister):boolean;
  846. var i:cardinal;
  847. begin
  848. move_related:=false;
  849. with reginfo[n] do
  850. if movelist<>nil then
  851. with movelist^ do
  852. for i:=0 to header.count-1 do
  853. if Tmoveins(data[i]).moveset in [ms_worklist_moves,ms_active_moves] then
  854. begin
  855. move_related:=true;
  856. break;
  857. end;
  858. end;
  859. procedure Trgobj.sort_simplify_worklist;
  860. {Sorts the simplifyworklist by the number of interferences the
  861. registers in it cause. This allows simplify to execute in
  862. constant time.
  863. Sort the list in the descending order, since items of simplifyworklist
  864. are retrieved from end to start and then items are added to selectstack.
  865. The selectstack list is also processed from end to start.
  866. Such way nodes with most interferences will get their colors first.
  867. Since degree of nodes in simplifyworklist before sorting is always
  868. less than the number of usable registers this should not trigger spilling
  869. and should lead to a better register allocation in some cases.
  870. }
  871. var p,h,i,leni,lent:longword;
  872. t:Tsuperregister;
  873. adji,adjt:Psuperregisterworklist;
  874. begin
  875. with simplifyworklist do
  876. begin
  877. if length<2 then
  878. exit;
  879. p:=longword(1) shl BsrDWord(length-1);
  880. repeat
  881. for h:=p to length-1 do
  882. begin
  883. i:=h;
  884. t:=buf[i];
  885. adjt:=reginfo[buf[i]].adjlist;
  886. lent:=0;
  887. if adjt<>nil then
  888. lent:=adjt^.length;
  889. repeat
  890. adji:=reginfo[buf[i-p]].adjlist;
  891. leni:=0;
  892. if adji<>nil then
  893. leni:=adji^.length;
  894. if leni>=lent then
  895. break;
  896. buf[i]:=buf[i-p];
  897. dec(i,p)
  898. until i<p;
  899. buf[i]:=t;
  900. end;
  901. p:=p shr 1;
  902. until p=0;
  903. end;
  904. end;
  905. { sort spilled nodes by increasing number of interferences }
  906. procedure Trgobj.sort_spillednodes;
  907. var
  908. p,h,i,leni,lent:longword;
  909. t:Tsuperregister;
  910. adji,adjt:Psuperregisterworklist;
  911. begin
  912. with spillednodes do
  913. begin
  914. if length<2 then
  915. exit;
  916. p:=longword(1) shl BsrDWord(length-1);
  917. repeat
  918. for h:=p to length-1 do
  919. begin
  920. i:=h;
  921. t:=buf[i];
  922. adjt:=reginfo[buf[i]].adjlist;
  923. lent:=0;
  924. if adjt<>nil then
  925. lent:=adjt^.length;
  926. repeat
  927. adji:=reginfo[buf[i-p]].adjlist;
  928. leni:=0;
  929. if adji<>nil then
  930. leni:=adji^.length;
  931. if leni<=lent then
  932. break;
  933. buf[i]:=buf[i-p];
  934. dec(i,p)
  935. until i<p;
  936. buf[i]:=t;
  937. end;
  938. p:=p shr 1;
  939. until p=0;
  940. end;
  941. end;
  942. procedure trgobj.make_work_list;
  943. var n:cardinal;
  944. begin
  945. {If we have 7 cpu registers, and the degree of a node >= 7, we cannot
  946. assign it to any of the registers, thus it is significant.}
  947. for n:=first_imaginary to maxreg-1 do
  948. with reginfo[n] do
  949. begin
  950. if adjlist=nil then
  951. degree:=0
  952. else
  953. degree:=adjlist^.length;
  954. if degree>=usable_registers_cnt then
  955. spillworklist.add(n)
  956. else if move_related(n) then
  957. freezeworklist.add(n)
  958. else if not(ri_coalesced in flags) then
  959. simplifyworklist.add(n);
  960. end;
  961. sort_simplify_worklist;
  962. end;
  963. procedure trgobj.prepare_colouring;
  964. begin
  965. make_work_list;
  966. active_moves:=Tlinkedlist.create;
  967. frozen_moves:=Tlinkedlist.create;
  968. coalesced_moves:=Tlinkedlist.create;
  969. constrained_moves:=Tlinkedlist.create;
  970. selectstack.clear;
  971. end;
  972. procedure trgobj.enable_moves(n:Tsuperregister);
  973. var m:Tlinkedlistitem;
  974. i:cardinal;
  975. begin
  976. with reginfo[n] do
  977. if movelist<>nil then
  978. for i:=0 to movelist^.header.count-1 do
  979. begin
  980. m:=movelist^.data[i];
  981. if Tmoveins(m).moveset=ms_active_moves then
  982. begin
  983. {Move m from the set active_moves to the set worklist_moves.}
  984. active_moves.remove(m);
  985. Tmoveins(m).moveset:=ms_worklist_moves;
  986. worklist_moves.concat(m);
  987. end;
  988. end;
  989. end;
  990. procedure Trgobj.decrement_degree(m:Tsuperregister);
  991. var adj : Psuperregisterworklist;
  992. n : tsuperregister;
  993. d,i : cardinal;
  994. begin
  995. with reginfo[m] do
  996. begin
  997. d:=degree;
  998. if d=0 then
  999. internalerror(200312151);
  1000. dec(degree);
  1001. if d=usable_registers_cnt then
  1002. begin
  1003. {Enable moves for m.}
  1004. enable_moves(m);
  1005. {Enable moves for adjacent.}
  1006. adj:=adjlist;
  1007. if adj<>nil then
  1008. for i:=1 to adj^.length do
  1009. begin
  1010. n:=adj^.buf[i-1];
  1011. if reginfo[n].flags*[ri_selected,ri_coalesced]<>[] then
  1012. enable_moves(n);
  1013. end;
  1014. {Remove the node from the spillworklist.}
  1015. if not spillworklist.delete(m) then
  1016. internalerror(200310145);
  1017. if move_related(m) then
  1018. freezeworklist.add(m)
  1019. else
  1020. simplifyworklist.add(m);
  1021. end;
  1022. end;
  1023. end;
  1024. procedure trgobj.simplify;
  1025. var adj : Psuperregisterworklist;
  1026. m,n : Tsuperregister;
  1027. i : cardinal;
  1028. begin
  1029. {We take the element with the least interferences out of the
  1030. simplifyworklist. Since the simplifyworklist is now sorted, we
  1031. no longer need to search, but we can simply take the first element.}
  1032. m:=simplifyworklist.get;
  1033. {Push it on the selectstack.}
  1034. selectstack.add(m);
  1035. with reginfo[m] do
  1036. begin
  1037. include(flags,ri_selected);
  1038. adj:=adjlist;
  1039. end;
  1040. if adj<>nil then
  1041. for i:=1 to adj^.length do
  1042. begin
  1043. n:=adj^.buf[i-1];
  1044. if (n>=first_imaginary) and
  1045. (reginfo[n].flags*[ri_selected,ri_coalesced]=[]) then
  1046. decrement_degree(n);
  1047. end;
  1048. end;
  1049. function trgobj.get_alias(n:Tsuperregister):Tsuperregister;
  1050. begin
  1051. if n>=maxreg then
  1052. internalerror(2021121201);
  1053. while ri_coalesced in reginfo[n].flags do
  1054. n:=reginfo[n].alias;
  1055. get_alias:=n;
  1056. end;
  1057. procedure trgobj.add_worklist(u:Tsuperregister);
  1058. begin
  1059. if (u>=first_imaginary) and
  1060. (not move_related(u)) and
  1061. (reginfo[u].degree<usable_registers_cnt) then
  1062. begin
  1063. if not freezeworklist.delete(u) then
  1064. internalerror(200308161); {must be found}
  1065. simplifyworklist.add(u);
  1066. end;
  1067. end;
  1068. function trgobj.adjacent_ok(u,v:Tsuperregister):boolean;
  1069. {Check wether u and v should be coalesced. u is precoloured.}
  1070. function ok(t,r:Tsuperregister):boolean;
  1071. begin
  1072. ok:=(t<first_imaginary) or
  1073. (reginfo[t].degree<usable_registers_cnt) or
  1074. ibitmap[r,t];
  1075. end;
  1076. var adj : Psuperregisterworklist;
  1077. i : cardinal;
  1078. n : tsuperregister;
  1079. begin
  1080. with reginfo[v] do
  1081. begin
  1082. adjacent_ok:=true;
  1083. adj:=adjlist;
  1084. if adj<>nil then
  1085. for i:=1 to adj^.length do
  1086. begin
  1087. n:=adj^.buf[i-1];
  1088. if (reginfo[n].flags*[ri_coalesced]=[]) and not ok(n,u) then
  1089. begin
  1090. adjacent_ok:=false;
  1091. break;
  1092. end;
  1093. end;
  1094. end;
  1095. end;
  1096. function trgobj.conservative(u,v:Tsuperregister):boolean;
  1097. var adj : Psuperregisterworklist;
  1098. done : Tsuperregisterset; {To prevent that we count nodes twice.}
  1099. i,k:cardinal;
  1100. n : tsuperregister;
  1101. begin
  1102. k:=0;
  1103. supregset_reset(done,false,maxreg);
  1104. with reginfo[u] do
  1105. begin
  1106. adj:=adjlist;
  1107. if adj<>nil then
  1108. for i:=1 to adj^.length do
  1109. begin
  1110. n:=adj^.buf[i-1];
  1111. if reginfo[n].flags*[ri_coalesced,ri_selected]=[] then
  1112. begin
  1113. supregset_include(done,n);
  1114. if reginfo[n].degree>=usable_registers_cnt then
  1115. inc(k);
  1116. end;
  1117. end;
  1118. end;
  1119. adj:=reginfo[v].adjlist;
  1120. if adj<>nil then
  1121. for i:=1 to adj^.length do
  1122. begin
  1123. n:=adj^.buf[i-1];
  1124. if (u<first_imaginary) and
  1125. (n>=first_imaginary) and
  1126. not ibitmap[u,n] and
  1127. (usable_registers_cnt-reginfo[n].real_reg_interferences<=1) then
  1128. begin
  1129. { Do not coalesce if 'u' is the last usable real register available
  1130. for imaginary register 'n'. }
  1131. conservative:=false;
  1132. exit;
  1133. end;
  1134. if not supregset_in(done,n) and
  1135. (reginfo[n].degree>=usable_registers_cnt) and
  1136. (reginfo[n].flags*[ri_coalesced,ri_selected]=[]) then
  1137. inc(k);
  1138. end;
  1139. conservative:=(k<usable_registers_cnt);
  1140. end;
  1141. procedure trgobj.set_alias(u,v:Tsuperregister);
  1142. begin
  1143. { don't make registers that the register allocator shouldn't touch (such
  1144. as stack and frame pointers) be aliases for other registers, because
  1145. then it can propagate them and even start changing them if the aliased
  1146. register gets changed }
  1147. if ((u<first_imaginary) and
  1148. not(u in usable_register_set)) or
  1149. ((v<first_imaginary) and
  1150. not(v in usable_register_set)) then
  1151. exit;
  1152. include(reginfo[v].flags,ri_coalesced);
  1153. if reginfo[v].alias<>0 then
  1154. internalerror(200712291);
  1155. reginfo[v].alias:=get_alias(u);
  1156. coalescednodes.add(v);
  1157. end;
  1158. procedure trgobj.combine(u,v:Tsuperregister);
  1159. var adj : Psuperregisterworklist;
  1160. original_u_count, i,n,p,q:cardinal;
  1161. t : tsuperregister;
  1162. searched:Tmoveins;
  1163. found : boolean;
  1164. begin
  1165. if not freezeworklist.delete(v) then
  1166. spillworklist.delete(v);
  1167. coalescednodes.add(v);
  1168. include(reginfo[v].flags,ri_coalesced);
  1169. reginfo[v].alias:=u;
  1170. {Combine both movelists. Since the movelists are sets, only add
  1171. elements that are not already present. The movelists cannot be
  1172. empty by definition; nodes are only coalesced if there is a move
  1173. between them. To prevent quadratic time blowup (movelists of
  1174. especially machine registers can get very large because of moves
  1175. generated during calls) we need to go into disgusting complexity.
  1176. (See webtbs/tw2242 for an example that stresses this.)
  1177. We want to sort the movelist to be able to search logarithmically.
  1178. Unfortunately, sorting the movelist every time before searching
  1179. is counter-productive, since the movelist usually grows with a few
  1180. items at a time. Therefore, we split the movelist into a sorted
  1181. and an unsorted part and search through both. If the unsorted part
  1182. becomes too large, we sort.}
  1183. if assigned(reginfo[u].movelist) then
  1184. begin
  1185. {We have to weigh the cost of sorting the list against searching
  1186. the cost of the unsorted part. I use factor of 8 here; if the
  1187. number of items is less than 8 times the numer of unsorted items,
  1188. we'll sort the list.}
  1189. with reginfo[u].movelist^ do
  1190. if header.count<8*(header.count-header.sorted_until) then
  1191. sort_movelist(reginfo[u].movelist);
  1192. if assigned(reginfo[v].movelist) then
  1193. begin
  1194. original_u_count:=reginfo[u].movelist^.header.count;
  1195. for n:=0 to reginfo[v].movelist^.header.count-1 do
  1196. begin
  1197. {Binary search the sorted part of the list.}
  1198. searched:=reginfo[v].movelist^.data[n];
  1199. p:=0;
  1200. q:=reginfo[u].movelist^.header.sorted_until;
  1201. i:=0;
  1202. if q<>0 then
  1203. repeat
  1204. i:=(p+q) shr 1;
  1205. if searched.id>reginfo[u].movelist^.data[i].id then
  1206. p:=i+1
  1207. else
  1208. q:=i;
  1209. until p=q;
  1210. with reginfo[u].movelist^ do
  1211. if searched<>data[i] then
  1212. begin
  1213. {Linear search the unsorted part of the list.}
  1214. found:=false;
  1215. { no need to search the instructions we've already added
  1216. from v, we know we won't find a match there }
  1217. for i:=header.sorted_until+1 to original_u_count-1 do
  1218. if searched.id=data[i].id then
  1219. begin
  1220. found:=true;
  1221. break;
  1222. end;
  1223. if not found then
  1224. add_to_movelist(u,searched);
  1225. end;
  1226. end;
  1227. end;
  1228. end;
  1229. enable_moves(v);
  1230. adj:=reginfo[v].adjlist;
  1231. if adj<>nil then
  1232. for i:=1 to adj^.length do
  1233. begin
  1234. t:=adj^.buf[i-1];
  1235. with reginfo[t] do
  1236. if not(ri_coalesced in flags) then
  1237. begin
  1238. {t has a connection to v. Since we are adding v to u, we
  1239. need to connect t to u. However, beware if t was already
  1240. connected to u...}
  1241. if (ibitmap[t,u]) and not (ri_selected in flags) then
  1242. begin
  1243. {... because in that case, we are actually removing an edge
  1244. and the degree of t decreases.}
  1245. decrement_degree(t);
  1246. { if v is combined with a real register, retry
  1247. coalescing of interfering nodes since it may succeed now. }
  1248. if (u<first_imaginary) and
  1249. (adj^.length>=usable_registers_cnt) and
  1250. (reginfo[t].degree>usable_registers_cnt) then
  1251. enable_moves(t);
  1252. end
  1253. else
  1254. begin
  1255. add_edge(t,u);
  1256. {We have added an edge to t and u. So their degree increases.
  1257. However, v is added to u. That means its neighbours will
  1258. no longer point to v, but to u instead. Therefore, only the
  1259. degree of u increases.}
  1260. if (u>=first_imaginary) and not (ri_selected in flags) then
  1261. inc(reginfo[u].degree);
  1262. end;
  1263. end;
  1264. end;
  1265. if (reginfo[u].degree>=usable_registers_cnt) and freezeworklist.delete(u) then
  1266. spillworklist.add(u);
  1267. end;
  1268. procedure trgobj.coalesce;
  1269. var m:Tmoveins;
  1270. x,y,u,v:cardinal;
  1271. begin
  1272. m:=Tmoveins(worklist_moves.getfirst);
  1273. x:=get_alias(m.x);
  1274. y:=get_alias(m.y);
  1275. if (y<first_imaginary) then
  1276. begin
  1277. u:=y;
  1278. v:=x;
  1279. end
  1280. else
  1281. begin
  1282. u:=x;
  1283. v:=y;
  1284. end;
  1285. if (u=v) then
  1286. begin
  1287. m.moveset:=ms_coalesced_moves; {Already coalesced.}
  1288. coalesced_moves.insert(m);
  1289. add_worklist(u);
  1290. end
  1291. {Do u and v interfere? In that case the move is constrained. Two
  1292. precoloured nodes interfere allways. If v is precoloured, by the above
  1293. code u is precoloured, thus interference...}
  1294. else if (v<first_imaginary) or ibitmap[u,v] then
  1295. begin
  1296. m.moveset:=ms_constrained_moves; {Cannot coalesce yet...}
  1297. constrained_moves.insert(m);
  1298. add_worklist(u);
  1299. add_worklist(v);
  1300. end
  1301. {Next test: is it possible and a good idea to coalesce?? Note: don't
  1302. coalesce registers that should not be touched by the register allocator,
  1303. such as stack/framepointers, because otherwise they can be changed }
  1304. else if (((u<first_imaginary) and adjacent_ok(u,v)) or
  1305. conservative(u,v)) and
  1306. ((u>=first_imaginary) or
  1307. (u in usable_register_set)) and
  1308. ((v>=first_imaginary) or
  1309. (v in usable_register_set)) then
  1310. begin
  1311. m.moveset:=ms_coalesced_moves; {Move coalesced!}
  1312. coalesced_moves.insert(m);
  1313. combine(u,v);
  1314. add_worklist(u);
  1315. end
  1316. else
  1317. begin
  1318. m.moveset:=ms_active_moves;
  1319. active_moves.insert(m);
  1320. end;
  1321. end;
  1322. procedure trgobj.freeze_moves(u:Tsuperregister);
  1323. var i:cardinal;
  1324. m:Tlinkedlistitem;
  1325. v,x,y:Tsuperregister;
  1326. begin
  1327. if reginfo[u].movelist<>nil then
  1328. for i:=0 to reginfo[u].movelist^.header.count-1 do
  1329. begin
  1330. m:=reginfo[u].movelist^.data[i];
  1331. if Tmoveins(m).moveset in [ms_worklist_moves,ms_active_moves] then
  1332. begin
  1333. x:=Tmoveins(m).x;
  1334. y:=Tmoveins(m).y;
  1335. if get_alias(y)=get_alias(u) then
  1336. v:=get_alias(x)
  1337. else
  1338. v:=get_alias(y);
  1339. {Move m from active_moves/worklist_moves to frozen_moves.}
  1340. if Tmoveins(m).moveset=ms_active_moves then
  1341. active_moves.remove(m)
  1342. else
  1343. worklist_moves.remove(m);
  1344. Tmoveins(m).moveset:=ms_frozen_moves;
  1345. frozen_moves.insert(m);
  1346. if (v>=first_imaginary) and not(move_related(v)) and
  1347. (reginfo[v].degree<usable_registers_cnt) then
  1348. begin
  1349. freezeworklist.delete(v);
  1350. simplifyworklist.add(v);
  1351. end;
  1352. end;
  1353. end;
  1354. end;
  1355. procedure trgobj.freeze;
  1356. var n:Tsuperregister;
  1357. begin
  1358. { We need to take a random element out of the freezeworklist. We take
  1359. the last element. Dirty code! }
  1360. n:=freezeworklist.get;
  1361. {Add it to the simplifyworklist.}
  1362. simplifyworklist.add(n);
  1363. freeze_moves(n);
  1364. end;
  1365. { The spilling approach selected by SPILLING_NEW does not work well for AVR as it eploits apparently the problem of the current
  1366. reg. allocator with AVR. The current reg. allocator is not aware of the fact that r1-r15 and r16-r31 are not equal on AVR }
  1367. {$if defined(AVR)}
  1368. {$define SPILLING_OLD}
  1369. {$else defined(AVR)}
  1370. { $define SPILLING_NEW}
  1371. {$endif defined(AVR)}
  1372. {$ifndef SPILLING_NEW}
  1373. {$define SPILLING_OLD}
  1374. {$endif SPILLING_NEW}
  1375. procedure trgobj.select_spill;
  1376. var
  1377. n : tsuperregister;
  1378. adj : psuperregisterworklist;
  1379. maxlength,minlength,p,i :word;
  1380. minweight: longint;
  1381. {$ifdef SPILLING_NEW}
  1382. dist: Double;
  1383. {$endif}
  1384. begin
  1385. {$ifdef SPILLING_NEW}
  1386. { This new approach for selecting the next spill candidate takes care of the weight of a register:
  1387. It spills the register with the lowest weight but only if it is expected that it results in convergence of
  1388. register allocation. Convergence is expected if a register is spilled where the average of the active interferences
  1389. - active interference means that the register is used in an instruction - is lower than
  1390. the degree.
  1391. Example (modify means read and the write):
  1392. modify reg1
  1393. loop:
  1394. modify reg2
  1395. modify reg3
  1396. modify reg4
  1397. modify reg5
  1398. modify reg6
  1399. modify reg7
  1400. modify reg1
  1401. In this example, all register have the same degree. However, spilling reg1 is most benefical as it is used least. Furthermore,
  1402. spilling reg1 is a step toward solving the coloring problem as the registers used during spilling will have a lower degree
  1403. as no register are in use at the location where reg1 is spilled.
  1404. }
  1405. minweight:=high(longint);
  1406. p:=0;
  1407. with spillworklist do
  1408. begin
  1409. { Safe: This procedure is only called if length<>0 }
  1410. for i:=0 to length-1 do
  1411. begin
  1412. adj:=reginfo[buf^[i]].adjlist;
  1413. dist:=adj^.length-reginfo[buf^[i]].total_interferences/reginfo[buf^[i]].count_uses;
  1414. if assigned(adj) and
  1415. (reginfo[buf^[i]].weight<minweight) and
  1416. (dist>=1) and
  1417. (reginfo[buf^[i]].weight>0) then
  1418. begin
  1419. p:=i;
  1420. minweight:=reginfo[buf^[i]].weight;
  1421. end;
  1422. end;
  1423. n:=buf^[p];
  1424. deleteidx(p);
  1425. end;
  1426. {$endif SPILLING_NEW}
  1427. {$ifdef SPILLING_OLD}
  1428. { We must look for the element with the most interferences in the
  1429. spillworklist. This is required because those registers are creating
  1430. the most conflicts and keeping them in a register will not reduce the
  1431. complexity and even can cause the help registers for the spilling code
  1432. to get too much conflicts with the result that the spilling code
  1433. will never converge (PFV)
  1434. We need a special processing for nodes with the ri_spill_helper flag set.
  1435. These nodes contain a value of a previously spilled node.
  1436. We need to avoid another spilling of ri_spill_helper nodes, since it will
  1437. likely lead to an endless loop and the register allocation will fail.
  1438. }
  1439. maxlength:=0;
  1440. minweight:=high(longint);
  1441. p:=high(p);
  1442. with spillworklist do
  1443. begin
  1444. {Safe: This procedure is only called if length<>0}
  1445. { Search for a candidate to be spilled, ignoring nodes with the ri_spill_helper flag set. }
  1446. for i:=0 to length-1 do
  1447. if not(ri_spill_helper in reginfo[buf[i]].flags) then
  1448. begin
  1449. adj:=reginfo[buf[i]].adjlist;
  1450. if assigned(adj) and
  1451. (
  1452. (adj^.length>maxlength) or
  1453. ((adj^.length=maxlength) and (reginfo[buf[i]].weight<minweight))
  1454. ) then
  1455. begin
  1456. p:=i;
  1457. maxlength:=adj^.length;
  1458. minweight:=reginfo[buf[i]].weight;
  1459. end;
  1460. end;
  1461. if p=high(p) then
  1462. begin
  1463. { If no normal nodes found, then only ri_spill_helper nodes are present
  1464. in the list. Finding the node with the least interferences and
  1465. the least weight.
  1466. This allows us to put the most restricted ri_spill_helper nodes
  1467. to the top of selectstack so they will be the first to get
  1468. a color assigned.
  1469. }
  1470. minlength:=high(maxlength);
  1471. minweight:=high(minweight);
  1472. p:=0;
  1473. for i:=0 to length-1 do
  1474. begin
  1475. adj:=reginfo[buf[i]].adjlist;
  1476. if assigned(adj) and
  1477. (
  1478. (adj^.length<minlength) or
  1479. ((adj^.length=minlength) and (reginfo[buf[i]].weight<minweight))
  1480. ) then
  1481. begin
  1482. p:=i;
  1483. minlength:=adj^.length;
  1484. minweight:=reginfo[buf[i]].weight;
  1485. end;
  1486. end;
  1487. end;
  1488. n:=buf[p];
  1489. deleteidx(p);
  1490. end;
  1491. {$endif SPILLING_OLD}
  1492. simplifyworklist.add(n);
  1493. freeze_moves(n);
  1494. end;
  1495. procedure trgobj.assign_colours;
  1496. {Assign_colours assigns the actual colours to the registers.}
  1497. var
  1498. colourednodes : Tsuperregisterset;
  1499. procedure reset_colours;
  1500. var
  1501. n : Tsuperregister;
  1502. begin
  1503. spillednodes.clear;
  1504. {Reset colours}
  1505. for n:=0 to maxreg-1 do
  1506. reginfo[n].colour:=n;
  1507. {Colour the cpu registers...}
  1508. supregset_reset(colourednodes,false,maxreg);
  1509. for n:=0 to first_imaginary-1 do
  1510. supregset_include(colourednodes,n);
  1511. end;
  1512. function colour_register(n : Tsuperregister) : boolean;
  1513. var
  1514. j,k : cardinal;
  1515. adj : Psuperregisterworklist;
  1516. adj_colours:set of 0..255;
  1517. a,c : Tsuperregister;
  1518. {$if declared(RS_STACK_POINTER_REG) and (RS_STACK_POINTER_REG<>RS_INVALID)}
  1519. tmpr: tregister;
  1520. {$endif}
  1521. begin
  1522. {Create a list of colours that we cannot assign to n.}
  1523. adj_colours:=[];
  1524. adj:=reginfo[n].adjlist;
  1525. if adj<>nil then
  1526. for j:=0 to adj^.length-1 do
  1527. begin
  1528. a:=get_alias(adj^.buf[j]);
  1529. if supregset_in(colourednodes,a) and (reginfo[a].colour<=255) then
  1530. include(adj_colours,reginfo[a].colour);
  1531. end;
  1532. { e.g. AVR does not have a stack pointer register }
  1533. {$if declared(RS_STACK_POINTER_REG) and (RS_STACK_POINTER_REG<>RS_INVALID)}
  1534. { FIXME: temp variable r is needed here to avoid Internal error 20060521 }
  1535. { while compiling the compiler. }
  1536. tmpr:=NR_STACK_POINTER_REG;
  1537. if (regtype=getregtype(tmpr)) then
  1538. include(adj_colours,RS_STACK_POINTER_REG);
  1539. {$ifend}
  1540. {Assume a spill by default...}
  1541. result:=false;
  1542. {Search for a colour not in this list.}
  1543. for k:=0 to usable_registers_cnt-1 do
  1544. begin
  1545. c:=usable_registers[k];
  1546. if not(c in adj_colours) then
  1547. begin
  1548. reginfo[n].colour:=c;
  1549. result:=true;
  1550. supregset_include(colourednodes,n);
  1551. break;
  1552. end;
  1553. end;
  1554. if not result then
  1555. spillednodes.add(n);
  1556. end;
  1557. var
  1558. i,k : cardinal;
  1559. n : Tsuperregister;
  1560. spill_loop : boolean;
  1561. begin
  1562. reset_colours;
  1563. {Now colour the imaginary registers on the select-stack.}
  1564. spill_loop:=false;
  1565. for i:=selectstack.length downto 1 do
  1566. begin
  1567. n:=selectstack.buf[i-1];
  1568. if not colour_register(n) and
  1569. (ri_spill_helper in reginfo[n].flags) then
  1570. begin
  1571. { Register n is a helper register which holds the value
  1572. of a previously spilled register. Register n must never
  1573. be spilled. Report the spilling loop and break. }
  1574. spill_loop:=true;
  1575. break;
  1576. end;
  1577. end;
  1578. if spill_loop then
  1579. begin
  1580. { Spilling loop is detected when colouring registers using the select-stack order.
  1581. Trying to eliminte this by using a different colouring order. }
  1582. reset_colours;
  1583. { To prevent spilling of helper registers it is needed to assign colours to them first. }
  1584. for i:=selectstack.length downto 1 do
  1585. begin
  1586. n:=selectstack.buf[i-1];
  1587. if ri_spill_helper in reginfo[n].flags then
  1588. if not colour_register(n) then
  1589. { Can't colour the spill helper register n.
  1590. This can happen only when the code generator produces invalid code
  1591. or sue to incorrect node coalescing. }
  1592. internalerror(2021091001);
  1593. end;
  1594. { Assign colours for the rest of the registers }
  1595. for i:=selectstack.length downto 1 do
  1596. begin
  1597. n:=selectstack.buf[i-1];
  1598. if not (ri_spill_helper in reginfo[n].flags) then
  1599. colour_register(n);
  1600. end;
  1601. end;
  1602. {Finally colour the nodes that were coalesced.}
  1603. for i:=1 to coalescednodes.length do
  1604. begin
  1605. n:=coalescednodes.buf[i-1];
  1606. k:=get_alias(n);
  1607. reginfo[n].colour:=reginfo[k].colour;
  1608. end;
  1609. end;
  1610. procedure trgobj.colour_registers;
  1611. begin
  1612. repeat
  1613. if simplifyworklist.length<>0 then
  1614. simplify
  1615. else if not(worklist_moves.empty) then
  1616. coalesce
  1617. else if freezeworklist.length<>0 then
  1618. freeze
  1619. else if spillworklist.length<>0 then
  1620. select_spill;
  1621. until (simplifyworklist.length=0) and
  1622. worklist_moves.empty and
  1623. (freezeworklist.length=0) and
  1624. (spillworklist.length=0);
  1625. assign_colours;
  1626. end;
  1627. procedure trgobj.epilogue_colouring;
  1628. begin
  1629. { remove all items from the worklists, but do not free them, they are still needed for spill coalesce }
  1630. move_garbage.concatList(worklist_moves);
  1631. move_garbage.concatList(active_moves);
  1632. active_moves.Free;
  1633. active_moves:=nil;
  1634. move_garbage.concatList(frozen_moves);
  1635. frozen_moves.Free;
  1636. frozen_moves:=nil;
  1637. move_garbage.concatList(coalesced_moves);
  1638. coalesced_moves.Free;
  1639. coalesced_moves:=nil;
  1640. move_garbage.concatList(constrained_moves);
  1641. constrained_moves.Free;
  1642. constrained_moves:=nil;
  1643. end;
  1644. procedure trgobj.clear_interferences(u:Tsuperregister);
  1645. {Remove node u from the interference graph and remove all collected
  1646. move instructions it is associated with.}
  1647. var i : word;
  1648. v : Tsuperregister;
  1649. adj,adj2 : Psuperregisterworklist;
  1650. begin
  1651. adj:=reginfo[u].adjlist;
  1652. if adj<>nil then
  1653. begin
  1654. for i:=1 to adj^.length do
  1655. begin
  1656. v:=adj^.buf[i-1];
  1657. {Remove (u,v) and (v,u) from bitmap.}
  1658. ibitmap[u,v]:=false;
  1659. ibitmap[v,u]:=false;
  1660. {Remove (v,u) from adjacency list.}
  1661. adj2:=reginfo[v].adjlist;
  1662. if adj2<>nil then
  1663. begin
  1664. adj2^.delete(u);
  1665. if adj2^.length=0 then
  1666. begin
  1667. dispose(adj2,done);
  1668. reginfo[v].adjlist:=nil;
  1669. end;
  1670. end;
  1671. end;
  1672. {Remove ( u,* ) from adjacency list.}
  1673. dispose(adj,done);
  1674. reginfo[u].adjlist:=nil;
  1675. end;
  1676. end;
  1677. function trgobj.getregisterinline(list:TAsmList;const subregconstraints:Tsubregisterset):Tregister;
  1678. var
  1679. p : Tsuperregister;
  1680. subreg: tsubregister;
  1681. begin
  1682. for subreg:=high(tsubregister) downto low(tsubregister) do
  1683. if subreg in subregconstraints then
  1684. break;
  1685. p:=getnewreg(subreg);
  1686. live_registers.add(p);
  1687. result:=newreg(regtype,p,subreg);
  1688. add_edges_used(p);
  1689. add_constraints(result);
  1690. { also add constraints for other sizes used for this register }
  1691. if subreg<>low(tsubregister) then
  1692. for subreg:=pred(subreg) downto low(tsubregister) do
  1693. if subreg in subregconstraints then
  1694. add_constraints(newreg(regtype,getsupreg(result),subreg));
  1695. end;
  1696. procedure trgobj.ungetregisterinline(list:TAsmList;r:Tregister);
  1697. var
  1698. supreg:Tsuperregister;
  1699. begin
  1700. supreg:=getsupreg(r);
  1701. live_registers.delete(supreg);
  1702. insert_regalloc_info(list,supreg);
  1703. end;
  1704. procedure trgobj.insert_regalloc_info(list:TAsmList;u:tsuperregister);
  1705. var
  1706. p : tai;
  1707. r : tregister;
  1708. palloc,
  1709. pdealloc : tai_regalloc;
  1710. begin
  1711. { Insert regallocs for all imaginary registers }
  1712. with reginfo[u] do
  1713. begin
  1714. r:=newreg(regtype,u,subreg);
  1715. if assigned(live_start) then
  1716. begin
  1717. { Generate regalloc and bind it to an instruction, this
  1718. is needed to find all live registers belonging to an
  1719. instruction during the spilling }
  1720. if live_start.typ=ait_instruction then
  1721. palloc:=tai_regalloc.alloc(r,live_start)
  1722. else
  1723. palloc:=tai_regalloc.alloc(r,nil);
  1724. if assigned(live_end) and (live_end.typ=ait_instruction) then
  1725. pdealloc:=tai_regalloc.dealloc(r,live_end)
  1726. else
  1727. pdealloc:=tai_regalloc.dealloc(r,nil);
  1728. { Insert live start allocation before the instruction/reg_a_sync }
  1729. list.insertbefore(palloc,live_start);
  1730. { Insert live end deallocation before reg allocations
  1731. to reduce conflicts }
  1732. p:=live_end;
  1733. while assigned(p) and
  1734. assigned(p.previous) and
  1735. (
  1736. (tai(p.previous).typ in [ait_comment,ait_tempalloc,ait_varloc]) or
  1737. (
  1738. (tai(p.previous).typ=ait_regalloc) and
  1739. (tai_regalloc(p.previous).ratype=ra_alloc) and
  1740. (tai_regalloc(p.previous).reg<>r)
  1741. )
  1742. ) do
  1743. p:=tai(p.previous);
  1744. { , but add release after a reg_a_sync }
  1745. if assigned(p) and
  1746. (p.typ=ait_regalloc) and
  1747. (tai_regalloc(p).ratype=ra_sync) then
  1748. p:=tai(p.next);
  1749. if assigned(p) then
  1750. list.insertbefore(pdealloc,p)
  1751. else
  1752. list.concat(pdealloc);
  1753. end;
  1754. end;
  1755. end;
  1756. procedure trgobj.insert_regalloc_info_all(list:TAsmList);
  1757. var
  1758. supreg : tsuperregister;
  1759. begin
  1760. { Insert regallocs for all imaginary registers }
  1761. for supreg:=first_imaginary to maxreg-1 do
  1762. insert_regalloc_info(list,supreg);
  1763. end;
  1764. procedure trgobj.determine_spill_registers(list: TAsmList; headertail: tai);
  1765. begin
  1766. prepare_colouring;
  1767. colour_registers;
  1768. epilogue_colouring;
  1769. end;
  1770. procedure trgobj.get_spill_temp(list: TAsmlist; spill_temps: Tspill_temp_list; supreg: tsuperregister);
  1771. var
  1772. size: ptrint;
  1773. begin
  1774. {Get a temp for the spilled register, the size must at least equal a complete register,
  1775. take also care of the fact that subreg can be larger than a single register like doubles
  1776. that occupy 2 registers }
  1777. { only force the whole register in case of integers. Storing a register that contains
  1778. a single precision value as a double can cause conversion errors on e.g. ARM VFP }
  1779. if (regtype=R_INTREGISTER) then
  1780. size:=max(tcgsize2size[reg_cgsize(newreg(regtype,supreg,R_SUBWHOLE))],
  1781. tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))])
  1782. else
  1783. size:=tcgsize2size[reg_cgsize(newreg(regtype,supreg,reginfo[supreg].subreg))];
  1784. tg.gettemp(list,
  1785. size,size,
  1786. tt_noreuse,spill_temps[supreg]);
  1787. end;
  1788. procedure trgobj.add_cpu_interferences(p : tai);
  1789. begin
  1790. end;
  1791. procedure trgobj.generate_interference_graph(list:TAsmList;headertai:tai);
  1792. procedure RecordUse(var r : Treginfo);
  1793. begin
  1794. inc(r.total_interferences,live_registers.length);
  1795. inc(r.count_uses);
  1796. end;
  1797. var
  1798. p : tai;
  1799. i : integer;
  1800. supreg, u: tsuperregister;
  1801. {$ifdef arm}
  1802. so: pshifterop;
  1803. {$endif arm}
  1804. begin
  1805. { All allocations are available. Now we can generate the
  1806. interference graph. Walk through all instructions, we can
  1807. start with the headertai, because before the header tai is
  1808. only symbols. }
  1809. live_registers.clear;
  1810. p:=headertai;
  1811. while assigned(p) do
  1812. begin
  1813. prefetch(pointer(p.next)^);
  1814. case p.typ of
  1815. ait_instruction:
  1816. with Taicpu(p) do
  1817. begin
  1818. current_filepos:=fileinfo;
  1819. {For speed reasons, get_alias isn't used here, instead,
  1820. assign_colours will also set the colour of coalesced nodes.
  1821. If there are registers with colour=0, then the coalescednodes
  1822. list probably doesn't contain these registers, causing
  1823. assign_colours not to do this properly.}
  1824. for i:=0 to ops-1 do
  1825. with oper[i]^ do
  1826. case typ of
  1827. top_reg:
  1828. if (getregtype(reg)=regtype) then
  1829. begin
  1830. u:=getsupreg(reg);
  1831. {$ifdef EXTDEBUG}
  1832. if (u>=maxreginfo) then
  1833. internalerror(2018111701);
  1834. {$endif}
  1835. RecordUse(reginfo[u]);
  1836. end;
  1837. top_ref:
  1838. begin
  1839. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  1840. with ref^ do
  1841. begin
  1842. if (base<>NR_NO) and
  1843. (getregtype(base)=regtype) then
  1844. begin
  1845. u:=getsupreg(base);
  1846. {$ifdef EXTDEBUG}
  1847. if (u>=maxreginfo) then
  1848. internalerror(2018111702);
  1849. {$endif}
  1850. RecordUse(reginfo[u]);
  1851. end;
  1852. if (index<>NR_NO) and
  1853. (getregtype(index)=regtype) then
  1854. begin
  1855. u:=getsupreg(index);
  1856. {$ifdef EXTDEBUG}
  1857. if (u>=maxreginfo) then
  1858. internalerror(2018111703);
  1859. {$endif}
  1860. RecordUse(reginfo[u]);
  1861. end;
  1862. {$if defined(x86)}
  1863. if (segment<>NR_NO) and
  1864. (getregtype(segment)=regtype) then
  1865. begin
  1866. u:=getsupreg(segment);
  1867. {$ifdef EXTDEBUG}
  1868. if (u>=maxreginfo) then
  1869. internalerror(2018111704);
  1870. {$endif}
  1871. RecordUse(reginfo[u]);
  1872. end;
  1873. {$endif defined(x86)}
  1874. end;
  1875. end;
  1876. {$ifdef arm}
  1877. Top_shifterop:
  1878. begin
  1879. if regtype=R_INTREGISTER then
  1880. begin
  1881. so:=shifterop;
  1882. if (so^.rs<>NR_NO) and
  1883. (getregtype(so^.rs)=regtype) then
  1884. RecordUse(reginfo[getsupreg(so^.rs)]);
  1885. end;
  1886. end;
  1887. {$endif arm}
  1888. else
  1889. ;
  1890. end;
  1891. end;
  1892. ait_regalloc:
  1893. with Tai_regalloc(p) do
  1894. begin
  1895. if (getregtype(reg)=regtype) then
  1896. begin
  1897. supreg:=getsupreg(reg);
  1898. case ratype of
  1899. ra_alloc :
  1900. begin
  1901. live_registers.add(supreg);
  1902. {$ifdef DEBUG_REGISTERLIFE}
  1903. write(live_registers.length,' ');
  1904. for i:=0 to live_registers.length-1 do
  1905. write(std_regname(newreg(regtype,live_registers.buf[i],defaultsub)),' ');
  1906. writeln;
  1907. {$endif DEBUG_REGISTERLIFE}
  1908. add_edges_used(supreg);
  1909. end;
  1910. ra_dealloc :
  1911. begin
  1912. live_registers.delete(supreg);
  1913. {$ifdef DEBUG_REGISTERLIFE}
  1914. write(live_registers.length,' ');
  1915. for i:=0 to live_registers.length-1 do
  1916. write(std_regname(newreg(regtype,live_registers.buf[i],defaultsub)),' ');
  1917. writeln;
  1918. {$endif DEBUG_REGISTERLIFE}
  1919. add_edges_used(supreg);
  1920. end;
  1921. ra_markused :
  1922. if (supreg<first_imaginary) then
  1923. begin
  1924. include(used_in_proc,supreg);
  1925. has_usedmarks:=true;
  1926. end;
  1927. else
  1928. ;
  1929. end;
  1930. { constraints needs always to be updated }
  1931. add_constraints(reg);
  1932. end;
  1933. end;
  1934. else
  1935. ;
  1936. end;
  1937. add_cpu_interferences(p);
  1938. p:=Tai(p.next);
  1939. end;
  1940. {$ifdef EXTDEBUG}
  1941. if live_registers.length>0 then
  1942. begin
  1943. for i:=0 to live_registers.length-1 do
  1944. begin
  1945. { Only report for imaginary registers }
  1946. if live_registers.buf[i]>=first_imaginary then
  1947. Comment(V_Warning,'Register '+std_regname(newreg(regtype,live_registers.buf[i],defaultsub))+' not released');
  1948. end;
  1949. end;
  1950. {$endif}
  1951. end;
  1952. procedure trgobj.translate_register(var reg : tregister);
  1953. begin
  1954. if (getregtype(reg)=regtype) then
  1955. setsupreg(reg,reginfo[getsupreg(reg)].colour)
  1956. else
  1957. internalerror(200602021);
  1958. end;
  1959. procedure trgobj.set_reg_initial_location(reg: tregister; const ref: treference);
  1960. var
  1961. supreg: TSuperRegister;
  1962. begin
  1963. supreg:=getsupreg(reg);
  1964. if (supreg<first_imaginary) or (supreg>=maxreg) then
  1965. internalerror(2020090501);
  1966. alloc_spillinfo(supreg+1);
  1967. spillinfo[supreg].spilllocation:=ref;
  1968. include(reginfo[supreg].flags,ri_has_initial_loc);
  1969. end;
  1970. procedure trgobj.translate_registers(list: TAsmList);
  1971. function get_reg_name_full(r: tregister; include_prefix: boolean): string;
  1972. var
  1973. rr:tregister;
  1974. sr:TSuperRegister;
  1975. begin
  1976. sr:=getsupreg(r);
  1977. if reginfo[sr].live_start=nil then
  1978. begin
  1979. result:='';
  1980. exit;
  1981. end;
  1982. if (sr<length(spillinfo)) and spillinfo[sr].spilled then
  1983. with spillinfo[sr].spilllocation do
  1984. begin
  1985. result:='['+std_regname(base);
  1986. if offset>=0 then
  1987. result:=result+'+';
  1988. result:=result+IntToStr(offset)+']';
  1989. if include_prefix then
  1990. result:='stack '+result;
  1991. end
  1992. else
  1993. begin
  1994. rr:=r;
  1995. setsupreg(rr,reginfo[sr].colour);
  1996. result:=std_regname(rr);
  1997. if include_prefix then
  1998. result:='register '+result;
  1999. end;
  2000. {$if defined(cpu8bitalu) or defined(cpu16bitalu)}
  2001. if (sr>=first_int_imreg) and cg.has_next_reg[sr] then
  2002. result:=result+':'+get_reg_name_full(cg.GetNextReg(r),false);
  2003. {$endif defined(cpu8bitalu) or defined(cpu16bitalu)}
  2004. end;
  2005. var
  2006. hp,p:Tai;
  2007. i:shortint;
  2008. u:longint;
  2009. s:string;
  2010. {$ifdef arm}
  2011. so:pshifterop;
  2012. {$endif arm}
  2013. begin
  2014. { Leave when no imaginary registers are used }
  2015. if maxreg<=first_imaginary then
  2016. exit;
  2017. p:=Tai(list.first);
  2018. while assigned(p) do
  2019. begin
  2020. prefetch(pointer(p.next)^);
  2021. case p.typ of
  2022. ait_regalloc:
  2023. with Tai_regalloc(p) do
  2024. begin
  2025. if (getregtype(reg)=regtype) then
  2026. begin
  2027. { Only alloc/dealloc is needed for the optimizer, remove
  2028. other regalloc }
  2029. if not(ratype in [ra_alloc,ra_dealloc]) then
  2030. begin
  2031. remove_ai(list,p);
  2032. continue;
  2033. end
  2034. else
  2035. begin
  2036. u:=reginfo[getsupreg(reg)].colour;
  2037. include(used_in_proc,u);
  2038. {$ifdef DEBUG_SPILLCOALESCE}
  2039. if (ratype=ra_alloc) and (ri_coalesced in reginfo[getsupreg(reg)].flags) then
  2040. begin
  2041. hp:=Tai_comment.Create(strpnew('Coalesced '+std_regname(reg)+'->'+
  2042. std_regname(newreg(regtype,reginfo[getsupreg(reg)].alias,reginfo[getsupreg(reg)].subreg))+
  2043. ' ('+std_regname(newreg(regtype,u,reginfo[getsupreg(reg)].subreg))+')'));
  2044. list.insertafter(hp,p);
  2045. end;
  2046. {$endif DEBUG_SPILLCOALESCE}
  2047. {$ifdef EXTDEBUG}
  2048. if u>=maxreginfo then
  2049. internalerror(2015040501);
  2050. {$endif}
  2051. setsupreg(reg,u);
  2052. end;
  2053. end;
  2054. end;
  2055. ait_varloc:
  2056. begin
  2057. if (getregtype(tai_varloc(p).newlocation)=regtype) then
  2058. begin
  2059. if (cs_asm_source in current_settings.globalswitches) then
  2060. begin
  2061. s:=get_reg_name_full(tai_varloc(p).newlocation,tai_varloc(p).newlocationhi=NR_NO);
  2062. if s<>'' then
  2063. begin
  2064. if tai_varloc(p).newlocationhi<>NR_NO then
  2065. s:=get_reg_name_full(tai_varloc(p).newlocationhi,true)+':'+s;
  2066. hp:=Tai_comment.Create(strpnew('Var '+tai_varloc(p).varsym.realname+' located in '+s));
  2067. list.insertafter(hp,p);
  2068. end;
  2069. setsupreg(tai_varloc(p).newlocation,reginfo[getsupreg(tai_varloc(p).newlocation)].colour);
  2070. if tai_varloc(p).newlocationhi<>NR_NO then
  2071. setsupreg(tai_varloc(p).newlocationhi,reginfo[getsupreg(tai_varloc(p).newlocationhi)].colour);
  2072. end;
  2073. remove_ai(list,p);
  2074. continue;
  2075. end;
  2076. end;
  2077. ait_instruction:
  2078. with Taicpu(p) do
  2079. begin
  2080. current_filepos:=fileinfo;
  2081. {For speed reasons, get_alias isn't used here, instead,
  2082. assign_colours will also set the colour of coalesced nodes.
  2083. If there are registers with colour=0, then the coalescednodes
  2084. list probably doesn't contain these registers, causing
  2085. assign_colours not to do this properly.}
  2086. for i:=0 to ops-1 do
  2087. with oper[i]^ do
  2088. case typ of
  2089. Top_reg:
  2090. if (getregtype(reg)=regtype) then
  2091. begin
  2092. u:=getsupreg(reg);
  2093. {$ifdef EXTDEBUG}
  2094. if (u>=maxreginfo) then
  2095. internalerror(2012101903);
  2096. {$endif}
  2097. setsupreg(reg,reginfo[u].colour);
  2098. end;
  2099. Top_ref:
  2100. begin
  2101. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2102. with ref^ do
  2103. begin
  2104. if (base<>NR_NO) and
  2105. (getregtype(base)=regtype) then
  2106. begin
  2107. u:=getsupreg(base);
  2108. {$ifdef EXTDEBUG}
  2109. if (u>=maxreginfo) then
  2110. internalerror(2012101904);
  2111. {$endif}
  2112. setsupreg(base,reginfo[u].colour);
  2113. end;
  2114. if (index<>NR_NO) and
  2115. (getregtype(index)=regtype) then
  2116. begin
  2117. u:=getsupreg(index);
  2118. {$ifdef EXTDEBUG}
  2119. if (u>=maxreginfo) then
  2120. internalerror(2012101905);
  2121. {$endif}
  2122. setsupreg(index,reginfo[u].colour);
  2123. end;
  2124. {$if defined(x86)}
  2125. if (segment<>NR_NO) and
  2126. (getregtype(segment)=regtype) then
  2127. begin
  2128. u:=getsupreg(segment);
  2129. {$ifdef EXTDEBUG}
  2130. if (u>=maxreginfo) then
  2131. internalerror(2013052401);
  2132. {$endif}
  2133. setsupreg(segment,reginfo[u].colour);
  2134. end;
  2135. {$endif defined(x86)}
  2136. end;
  2137. end;
  2138. {$ifdef arm}
  2139. Top_shifterop:
  2140. begin
  2141. if regtype=R_INTREGISTER then
  2142. begin
  2143. so:=shifterop;
  2144. if (so^.rs<>NR_NO) and
  2145. (getregtype(so^.rs)=regtype) then
  2146. setsupreg(so^.rs,reginfo[getsupreg(so^.rs)].colour);
  2147. end;
  2148. end;
  2149. {$endif arm}
  2150. else
  2151. ;
  2152. end;
  2153. { Maybe the operation can be removed when
  2154. it is a move and both arguments are the same }
  2155. if is_same_reg_move(regtype) then
  2156. begin
  2157. { Be careful of dangling pointers in previous reg_allocs,
  2158. ss these can confuse the register allocator }
  2159. hp:=tai(p.previous);
  2160. while Assigned(hp) do
  2161. begin
  2162. if (hp.typ in [ait_comment,ait_tempalloc,ait_varloc]) then
  2163. { Do nothing, but pass control flow to
  2164. "hp:=tai(hp.previous)" and continue the loop }
  2165. else if (hp.typ=ait_regalloc) then
  2166. begin
  2167. if tai_regalloc(hp).instr=p then
  2168. tai_regalloc(hp).instr:=nil;
  2169. end
  2170. else
  2171. Break;
  2172. hp:=tai(hp.previous);
  2173. end;
  2174. remove_ai(list,p);
  2175. continue;
  2176. end;
  2177. end;
  2178. else
  2179. ;
  2180. end;
  2181. p:=Tai(p.next);
  2182. end;
  2183. current_filepos:=current_procinfo.exitpos;
  2184. end;
  2185. function trgobj.spill_registers(list:TAsmList;headertai:tai):boolean;
  2186. { Returns true if any help registers have been used }
  2187. var
  2188. i : cardinal;
  2189. t : tsuperregister;
  2190. p : Tai;
  2191. regs_to_spill_set:Tsuperregisterset;
  2192. spill_temps : Tspill_temp_list;
  2193. supreg,x,y : tsuperregister;
  2194. templist : TAsmList;
  2195. j : Longint;
  2196. getnewspillloc : Boolean;
  2197. begin
  2198. spill_registers:=false;
  2199. live_registers.clear;
  2200. { spilling should start with the node with the highest number of interferences, so we can coalesce as
  2201. much as possible spilled nodes (coalesce in case of spilled node means they share the same memory location) }
  2202. sort_spillednodes;
  2203. for i:=first_imaginary to maxreg-1 do
  2204. exclude(reginfo[i].flags,ri_selected);
  2205. SetLength(spill_temps,maxreg);
  2206. supregset_reset(regs_to_spill_set,false,$ffff);
  2207. {$ifdef DEBUG_SPILLCOALESCE}
  2208. writeln('trgobj.spill_registers: Got maxreg ',maxreg);
  2209. writeln('trgobj.spill_registers: Spilling ',spillednodes.length,' nodes');
  2210. {$endif DEBUG_SPILLCOALESCE}
  2211. { after each round of spilling, more registers could be used due to allocations for spilling }
  2212. alloc_spillinfo(maxreg);
  2213. { Allocate temps and insert in front of the list }
  2214. templist:=TAsmList.create;
  2215. { Safe: this procedure is only called if there are spilled nodes. }
  2216. with spillednodes do
  2217. { the node with the highest interferences is the last one }
  2218. for i:=length-1 downto 0 do
  2219. begin
  2220. t:=buf[i];
  2221. {$ifdef DEBUG_SPILLCOALESCE}
  2222. writeln('trgobj.spill_registers: Spilling ',t);
  2223. {$endif DEBUG_SPILLCOALESCE}
  2224. spillinfo[t].interferences:=Tinterferencebitmap.create;
  2225. { copy interferences }
  2226. for j:=0 to maxreg-1 do
  2227. spillinfo[t].interferences[0,j]:=ibitmap[t,j];
  2228. { Alternative representation. }
  2229. supregset_include(regs_to_spill_set,t);
  2230. { Clear all interferences of the spilled register. }
  2231. clear_interferences(t);
  2232. getnewspillloc:=not (ri_has_initial_loc in reginfo[t].flags);
  2233. if not getnewspillloc then
  2234. spill_temps[t]:=spillinfo[t].spilllocation;
  2235. { check if we can "coalesce" spilled nodes. To do so, it is required that they do not
  2236. interfere but are connected by a move instruction
  2237. doing so might save some mem->mem moves }
  2238. if (cs_opt_level3 in current_settings.optimizerswitches) and
  2239. getnewspillloc and
  2240. assigned(reginfo[t].movelist) then
  2241. for j:=0 to reginfo[t].movelist^.header.count-1 do
  2242. begin
  2243. x:=Tmoveins(reginfo[t].movelist^.data[j]).x;
  2244. y:=Tmoveins(reginfo[t].movelist^.data[j]).y;
  2245. if (x=t) and
  2246. (spillinfo[get_alias(y)].spilled) and
  2247. not(spillinfo[get_alias(y)].interferences[0,t]) then
  2248. begin
  2249. spill_temps[t]:=spillinfo[get_alias(y)].spilllocation;
  2250. {$ifdef DEBUG_SPILLCOALESCE}
  2251. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',y);
  2252. {$endif DEBUG_SPILLCOALESCE}
  2253. getnewspillloc:=false;
  2254. break;
  2255. end
  2256. else if (y=t) and
  2257. (spillinfo[get_alias(x)].spilled) and
  2258. not(spillinfo[get_alias(x)].interferences[0,t]) then
  2259. begin
  2260. {$ifdef DEBUG_SPILLCOALESCE}
  2261. writeln('trgobj.spill_registers: Spill coalesce ',t,' to ',x);
  2262. {$endif DEBUG_SPILLCOALESCE}
  2263. spill_temps[t]:=spillinfo[get_alias(x)].spilllocation;
  2264. getnewspillloc:=false;
  2265. break;
  2266. end;
  2267. end;
  2268. if getnewspillloc then
  2269. get_spill_temp(templist,spill_temps,t);
  2270. {$ifdef DEBUG_SPILLCOALESCE}
  2271. writeln('trgobj.spill_registers: Spill temp: ',getsupreg(spill_temps[t].base),'+',spill_temps[t].offset);
  2272. {$endif DEBUG_SPILLCOALESCE}
  2273. { set spilled only as soon as a temp is assigned, else a mov iregX,iregX results in a spill coalesce with itself }
  2274. spillinfo[t].spilled:=true;
  2275. spillinfo[t].spilllocation:=spill_temps[t];
  2276. end;
  2277. list.insertlistafter(headertai,templist);
  2278. templist.free;
  2279. { Walk through all instructions, we can start with the headertai,
  2280. because before the header tai is only symbols }
  2281. p:=headertai;
  2282. while assigned(p) do
  2283. begin
  2284. case p.typ of
  2285. ait_regalloc:
  2286. with Tai_regalloc(p) do
  2287. begin
  2288. if (getregtype(reg)=regtype) then
  2289. begin
  2290. {A register allocation of the spilled register (and all coalesced registers)
  2291. must be removed.}
  2292. supreg:=get_alias(getsupreg(reg));
  2293. if supregset_in(regs_to_spill_set,supreg) then
  2294. begin
  2295. { Remove loading of the register from its initial memory location
  2296. (e.g. load of a stack parameter to the register). }
  2297. if (ratype=ra_alloc) and
  2298. (ri_has_initial_loc in reginfo[supreg].flags) and
  2299. (instr<>nil) then
  2300. begin
  2301. list.remove(instr);
  2302. FreeAndNil(instr);
  2303. dec(reginfo[supreg].weight,100);
  2304. end;
  2305. { Remove the regalloc }
  2306. remove_ai(list,p);
  2307. continue;
  2308. end
  2309. else
  2310. begin
  2311. case ratype of
  2312. ra_alloc :
  2313. live_registers.add(supreg);
  2314. ra_dealloc :
  2315. live_registers.delete(supreg);
  2316. else
  2317. ;
  2318. end;
  2319. end;
  2320. end;
  2321. end;
  2322. {$ifdef llvm}
  2323. ait_llvmins,
  2324. {$endif llvm}
  2325. ait_instruction:
  2326. with tai_cpu_abstract_sym(p) do
  2327. begin
  2328. // writeln(gas_op2str[tai_cpu_abstract_sym(p).opcode]);
  2329. current_filepos:=fileinfo;
  2330. if instr_spill_register(list,tai_cpu_abstract_sym(p),regs_to_spill_set,spill_temps) then
  2331. spill_registers:=true;
  2332. end;
  2333. else
  2334. ;
  2335. end;
  2336. p:=Tai(p.next);
  2337. end;
  2338. current_filepos:=current_procinfo.exitpos;
  2339. {Safe: this procedure is only called if there are spilled nodes.}
  2340. with spillednodes do
  2341. for i:=0 to length-1 do
  2342. begin
  2343. j:=buf[i];
  2344. if tg.istemp(spill_temps[j]) then
  2345. tg.ungettemp(list,spill_temps[j]);
  2346. end;
  2347. spill_temps:=nil;
  2348. end;
  2349. function trgobj.do_spill_replace(list:TAsmList;instr:tai_cpu_abstract_sym;orgreg:tsuperregister;const spilltemp:treference):boolean;
  2350. begin
  2351. result:=false;
  2352. end;
  2353. procedure trgobj.do_spill_read(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2354. var
  2355. ins:tai_cpu_abstract_sym;
  2356. begin
  2357. ins:=spilling_create_load(spilltemp,tempreg);
  2358. add_cpu_interferences(ins);
  2359. list.insertafter(ins,pos);
  2360. {$ifdef DEBUG_SPILLING}
  2361. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Read')),ins);
  2362. {$endif}
  2363. end;
  2364. procedure Trgobj.do_spill_written(list:TAsmList;pos:tai;const spilltemp:treference;tempreg:tregister;orgsupreg:tsuperregister);
  2365. var
  2366. ins:tai_cpu_abstract_sym;
  2367. begin
  2368. ins:=spilling_create_store(tempreg,spilltemp);
  2369. add_cpu_interferences(ins);
  2370. list.insertafter(ins,pos);
  2371. {$ifdef DEBUG_SPILLING}
  2372. list.Insertbefore(tai_comment.Create(strpnew('Spilling: Spill Write')),ins);
  2373. {$endif}
  2374. end;
  2375. function trgobj.get_spill_subreg(r : tregister) : tsubregister;
  2376. begin
  2377. result:=defaultsub;
  2378. end;
  2379. function trgobj.addreginfo(var spregs: tspillregsinfo; const r: tsuperregisterset; reg: tregister; operation: topertype): boolean;
  2380. var
  2381. i, tmpindex: longint;
  2382. supreg: tsuperregister;
  2383. begin
  2384. result:=false;
  2385. tmpindex := spregs.spillreginfocount;
  2386. supreg := get_alias(getsupreg(reg));
  2387. { did we already encounter this register? }
  2388. for i := 0 to pred(spregs.spillreginfocount) do
  2389. if (spregs.spillreginfo[i].orgreg = supreg) then
  2390. begin
  2391. tmpindex := i;
  2392. break;
  2393. end;
  2394. if tmpindex > high(spregs.spillreginfo) then
  2395. internalerror(2003120301);
  2396. spregs.spillreginfo[tmpindex].orgreg := supreg;
  2397. include(spregs.spillreginfo[tmpindex].spillregconstraints,get_spill_subreg(reg));
  2398. if supregset_in(r,supreg) then
  2399. begin
  2400. { add/update info on this register }
  2401. spregs.spillreginfo[tmpindex].mustbespilled := true;
  2402. case operation of
  2403. operand_read:
  2404. spregs.spillreginfo[tmpindex].regread := true;
  2405. operand_write:
  2406. spregs.spillreginfo[tmpindex].regwritten := true;
  2407. operand_readwrite:
  2408. begin
  2409. spregs.spillreginfo[tmpindex].regread := true;
  2410. spregs.spillreginfo[tmpindex].regwritten := true;
  2411. end;
  2412. end;
  2413. result:=true;
  2414. end;
  2415. inc(spregs.spillreginfocount,ord(spregs.spillreginfocount=tmpindex));
  2416. end;
  2417. function trgobj.instr_get_oper_spilling_info(var spregs: tspillregsinfo; const r: tsuperregisterset; instr: tai_cpu_abstract_sym; opidx: longint): boolean;
  2418. begin
  2419. result:=false;
  2420. with instr.oper[opidx]^ do
  2421. begin
  2422. case typ of
  2423. top_reg:
  2424. begin
  2425. if (getregtype(reg) = regtype) then
  2426. result:=addreginfo(spregs,r,reg,instr.spilling_get_operation_type(opidx));
  2427. end;
  2428. top_ref:
  2429. begin
  2430. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2431. with ref^ do
  2432. begin
  2433. if (base <> NR_NO) and
  2434. (getregtype(base)=regtype) then
  2435. result:=addreginfo(spregs,r,base,instr.spilling_get_operation_type_ref(opidx,base));
  2436. if (index <> NR_NO) and
  2437. (getregtype(index)=regtype) then
  2438. result:=addreginfo(spregs,r,index,instr.spilling_get_operation_type_ref(opidx,index)) or result;
  2439. {$if defined(x86)}
  2440. if (segment <> NR_NO) and
  2441. (getregtype(segment)=regtype) then
  2442. result:=addreginfo(spregs,r,segment,instr.spilling_get_operation_type_ref(opidx,segment)) or result;
  2443. {$endif defined(x86)}
  2444. end;
  2445. end;
  2446. {$ifdef ARM}
  2447. top_shifterop:
  2448. begin
  2449. if regtype in [R_INTREGISTER,R_ADDRESSREGISTER] then
  2450. if shifterop^.rs<>NR_NO then
  2451. result:=addreginfo(spregs,r,shifterop^.rs,operand_read);
  2452. end;
  2453. {$endif ARM}
  2454. else
  2455. ;
  2456. end;
  2457. end;
  2458. end;
  2459. procedure trgobj.try_replace_reg(const spregs: tspillregsinfo; var reg: tregister; useloadreg: boolean);
  2460. var
  2461. i: longint;
  2462. supreg: tsuperregister;
  2463. begin
  2464. supreg:=get_alias(getsupreg(reg));
  2465. for i:=0 to pred(spregs.spillreginfocount) do
  2466. if (spregs.spillreginfo[i].mustbespilled) and
  2467. (spregs.spillreginfo[i].orgreg=supreg) then
  2468. begin
  2469. { Only replace supreg }
  2470. if useloadreg then
  2471. setsupreg(reg, getsupreg(spregs.spillreginfo[i].loadreg))
  2472. else
  2473. setsupreg(reg, getsupreg(spregs.spillreginfo[i].storereg));
  2474. break;
  2475. end;
  2476. end;
  2477. procedure trgobj.substitute_spilled_registers(const spregs: tspillregsinfo; instr: tai_cpu_abstract_sym; opidx: longint);
  2478. begin
  2479. with instr.oper[opidx]^ do
  2480. case typ of
  2481. top_reg:
  2482. begin
  2483. if (getregtype(reg) = regtype) then
  2484. try_replace_reg(spregs, reg, not ssa_safe or
  2485. (instr.spilling_get_operation_type(opidx)=operand_read));
  2486. end;
  2487. top_ref:
  2488. begin
  2489. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2490. begin
  2491. if (ref^.base <> NR_NO) and
  2492. (getregtype(ref^.base)=regtype) then
  2493. try_replace_reg(spregs, ref^.base,
  2494. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.base)=operand_read));
  2495. if (ref^.index <> NR_NO) and
  2496. (getregtype(ref^.index)=regtype) then
  2497. try_replace_reg(spregs, ref^.index,
  2498. not ssa_safe or (instr.spilling_get_operation_type_ref(opidx, ref^.index)=operand_read));
  2499. {$if defined(x86)}
  2500. if (ref^.segment <> NR_NO) and
  2501. (getregtype(ref^.segment)=regtype) then
  2502. try_replace_reg(spregs, ref^.segment, true { always read-only });
  2503. {$endif defined(x86)}
  2504. end;
  2505. end;
  2506. {$ifdef ARM}
  2507. top_shifterop:
  2508. begin
  2509. if regtype in [R_INTREGISTER, R_ADDRESSREGISTER] then
  2510. try_replace_reg(spregs, shifterop^.rs, true { always read-only });
  2511. end;
  2512. {$endif ARM}
  2513. else
  2514. ;
  2515. end;
  2516. end;
  2517. function trgobj.instr_spill_register(list:TAsmList;
  2518. instr:tai_cpu_abstract_sym;
  2519. const r:Tsuperregisterset;
  2520. const spilltemplist:Tspill_temp_list): boolean;
  2521. var
  2522. counter: longint;
  2523. spregs: tspillregsinfo;
  2524. spilled: boolean;
  2525. var
  2526. loadpos,
  2527. storepos : tai;
  2528. oldlive_registers : tsuperregisterworklist;
  2529. begin
  2530. result := false;
  2531. fillchar(spregs,sizeof(spregs),0);
  2532. for counter := low(spregs.spillreginfo) to high(spregs.spillreginfo) do
  2533. begin
  2534. spregs.spillreginfo[counter].orgreg := RS_INVALID;
  2535. spregs.spillreginfo[counter].loadreg := NR_INVALID;
  2536. spregs.spillreginfo[counter].storereg := NR_INVALID;
  2537. end;
  2538. spilled := false;
  2539. { check whether and if so which and how (read/written) this instructions contains
  2540. registers that must be spilled }
  2541. for counter := 0 to instr.ops-1 do
  2542. spilled:=instr_get_oper_spilling_info(spregs,r,instr,counter) or spilled;
  2543. { if no spilling for this instruction we can leave }
  2544. if not spilled then
  2545. exit;
  2546. { Check if the instruction is "OP reg1,reg2" and reg1 is coalesced with reg2 }
  2547. if (spregs.spillreginfocount=1) and (instr.ops=2) and
  2548. (instr.oper[0]^.typ=top_reg) and (instr.oper[1]^.typ=top_reg) and
  2549. (getregtype(instr.oper[0]^.reg)=getregtype(instr.oper[1]^.reg)) then
  2550. begin
  2551. { Set both registers in the instruction to the same register }
  2552. setsupreg(instr.oper[0]^.reg, spregs.spillreginfo[0].orgreg);
  2553. setsupreg(instr.oper[1]^.reg, spregs.spillreginfo[0].orgreg);
  2554. { In case of MOV reg,reg no spilling is needed.
  2555. This MOV will be removed later in translate_registers() }
  2556. if instr.is_same_reg_move(regtype) then
  2557. exit;
  2558. end;
  2559. {$if defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2560. { Try replacing the register with the spilltemp. This is useful only
  2561. for the i386,x86_64 that support memory locations for several instructions
  2562. For non-x86 it is nevertheless possible to replace moves to/from the register
  2563. with loads/stores to spilltemp (Sergei) }
  2564. for counter := 0 to pred(spregs.spillreginfocount) do
  2565. with spregs.spillreginfo[counter] do
  2566. begin
  2567. if mustbespilled then
  2568. begin
  2569. if do_spill_replace(list,instr,orgreg,spilltemplist[orgreg]) then
  2570. mustbespilled:=false;
  2571. end;
  2572. end;
  2573. {$endif defined(x86) or defined(mips) or defined(sparcgen) or defined(arm) or defined(m68k)}
  2574. {
  2575. There are registers that need are spilled. We generate the
  2576. following code for it. The used positions where code need
  2577. to be inserted are marked using #. Note that code is always inserted
  2578. before the positions using pos.previous. This way the position is always
  2579. the same since pos doesn't change, but pos.previous is modified everytime
  2580. new code is inserted.
  2581. [
  2582. - reg_allocs load spills
  2583. - load spills
  2584. ]
  2585. [#loadpos
  2586. - reg_deallocs
  2587. - reg_allocs
  2588. ]
  2589. [
  2590. - reg_deallocs for load-only spills
  2591. - reg_allocs for store-only spills
  2592. ]
  2593. [#instr
  2594. - original instruction
  2595. ]
  2596. [
  2597. - store spills
  2598. - reg_deallocs store spills
  2599. ]
  2600. [#storepos
  2601. ]
  2602. }
  2603. result := true;
  2604. oldlive_registers.copyfrom(live_registers);
  2605. { Process all tai_regallocs belonging to this instruction, ignore explicit
  2606. inserted regallocs. These can happend for example in i386:
  2607. mov ref,ireg26
  2608. <regdealloc ireg26, instr=taicpu of lea>
  2609. <regalloc edi, insrt=nil>
  2610. lea [ireg26+ireg17],edi
  2611. All released registers are also added to the live_registers because
  2612. they can't be used during the spilling }
  2613. loadpos:=tai(instr.previous);
  2614. while assigned(loadpos) and
  2615. (
  2616. (loadpos.typ in [ait_comment,ait_tempalloc,ait_varloc]) or
  2617. (
  2618. (loadpos.typ=ait_regalloc) and
  2619. (
  2620. (tai_regalloc(loadpos).instr=nil) or
  2621. (tai_regalloc(loadpos).instr=instr)
  2622. )
  2623. )
  2624. ) do
  2625. begin
  2626. { Only add deallocs belonging to the instruction. Explicit inserted deallocs
  2627. belong to the previous instruction and not the current instruction }
  2628. if (loadpos.typ=ait_regalloc) and
  2629. (tai_regalloc(loadpos).instr=instr) and
  2630. (tai_regalloc(loadpos).ratype=ra_dealloc) then
  2631. live_registers.add(get_alias(getsupreg(tai_regalloc(loadpos).reg)));
  2632. loadpos:=tai(loadpos.previous);
  2633. end;
  2634. loadpos:=tai(loadpos.next);
  2635. { Load the spilled registers }
  2636. for counter := 0 to pred(spregs.spillreginfocount) do
  2637. with spregs.spillreginfo[counter] do
  2638. begin
  2639. if mustbespilled and regread then
  2640. begin
  2641. loadreg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2642. do_spill_read(list,tai(loadpos.previous),spilltemplist[orgreg],loadreg,orgreg);
  2643. include(reginfo[getsupreg(loadreg)].flags,ri_spill_helper);
  2644. end;
  2645. end;
  2646. { Release temp registers of read-only registers, and add reference of the instruction
  2647. to the reginfo }
  2648. for counter := 0 to pred(spregs.spillreginfocount) do
  2649. with spregs.spillreginfo[counter] do
  2650. begin
  2651. if mustbespilled and regread and
  2652. (ssa_safe or
  2653. not regwritten) then
  2654. begin
  2655. { The original instruction will be the next that uses this register
  2656. set weigth of the newly allocated register higher than the old one,
  2657. so it will selected for spilling with a lower priority than
  2658. the original one, this prevents an endless spilling loop if orgreg
  2659. is short living, see e.g. tw25164.pp
  2660. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2661. add_reg_instruction(instr,loadreg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2662. ungetregisterinline(list,loadreg);
  2663. end;
  2664. end;
  2665. { Allocate temp registers of write-only registers, and add reference of the instruction
  2666. to the reginfo }
  2667. for counter := 0 to pred(spregs.spillreginfocount) do
  2668. with spregs.spillreginfo[counter] do
  2669. begin
  2670. if mustbespilled and regwritten then
  2671. begin
  2672. { When the register is also loaded there is already a register assigned }
  2673. if (not regread) or
  2674. ssa_safe then
  2675. begin
  2676. storereg:=getregisterinline(list,spregs.spillreginfo[counter].spillregconstraints);
  2677. include(reginfo[getsupreg(storereg)].flags,ri_spill_helper);
  2678. { we also use loadreg for store replacements in case we
  2679. don't have ensure ssa -> initialise loadreg even if
  2680. there are no reads }
  2681. if not regread then
  2682. loadreg:=storereg;
  2683. end
  2684. else
  2685. storereg:=loadreg;
  2686. { The original instruction will be the next that uses this register, this
  2687. also needs to be done for read-write registers,
  2688. set weigth of the newly allocated register higher than the old one,
  2689. so it will selected for spilling with a lower priority than
  2690. the original one, this prevents an endless spilling loop if orgreg
  2691. is short living, see e.g. tw25164.pp
  2692. the min trick is needed to avoid an overflow in case weight=high(weight which might happen }
  2693. add_reg_instruction(instr,storereg,min(high(reginfo[orgreg].weight)-1,reginfo[orgreg].weight)+1);
  2694. end;
  2695. end;
  2696. { store the spilled registers }
  2697. if not assigned(instr.next) then
  2698. list.concat(tai_marker.Create(mark_Position));
  2699. storepos:=tai(instr.next);
  2700. for counter := 0 to pred(spregs.spillreginfocount) do
  2701. with spregs.spillreginfo[counter] do
  2702. begin
  2703. if mustbespilled and regwritten then
  2704. begin
  2705. do_spill_written(list,tai(storepos.previous),spilltemplist[orgreg],storereg,orgreg);
  2706. ungetregisterinline(list,storereg);
  2707. end;
  2708. end;
  2709. { now all spilling code is generated we can restore the live registers. This
  2710. must be done after the store because the store can need an extra register
  2711. that also needs to conflict with the registers of the instruction }
  2712. live_registers.done;
  2713. live_registers:=oldlive_registers;
  2714. { substitute registers }
  2715. for counter:=0 to instr.ops-1 do
  2716. substitute_spilled_registers(spregs,instr,counter);
  2717. { We have modified the instruction; perhaps the new instruction has
  2718. certain constraints regarding which imaginary registers interfere
  2719. with certain physical registers. }
  2720. add_cpu_interferences(instr);
  2721. end;
  2722. procedure trgobj.remove_ai(list:TAsmList; var p:Tai);
  2723. var
  2724. q:Tai;
  2725. begin
  2726. q:=tai(p.next);
  2727. list.remove(p);
  2728. p.free;
  2729. p:=q;
  2730. end;
  2731. {$ifdef DEBUG_SPILLCOALESCE}
  2732. procedure trgobj.write_spill_stats;
  2733. { This procedure outputs spilling statistincs.
  2734. If no spilling has occurred, no output is provided.
  2735. NUM is the number of spilled registers.
  2736. EFF is efficiency of the spilling which is based on
  2737. weight and usage count of registers. Range 0-100%.
  2738. 0% means all imaginary registers have been spilled.
  2739. 100% means no imaginary registers have been spilled
  2740. (no output in this case).
  2741. Higher value is better.
  2742. }
  2743. var
  2744. i,j,spillingcounter,max_weight:longint;
  2745. all_weight,spill_weight,d: double;
  2746. begin
  2747. max_weight:=1;
  2748. for i:=first_imaginary to maxreg-1 do
  2749. with reginfo[i] do
  2750. if weight>max_weight then
  2751. max_weight:=weight;
  2752. spillingcounter:=0;
  2753. spill_weight:=0;
  2754. all_weight:=0;
  2755. for i:=first_imaginary to maxreg-1 do
  2756. with reginfo[i] do
  2757. if not (ri_spill_helper in flags) then
  2758. begin
  2759. d:=weight/max_weight;
  2760. all_weight:=all_weight+d;
  2761. if (ri_coalesced in flags) and (alias>=first_imaginary) then
  2762. j:=alias
  2763. else
  2764. j:=i;
  2765. if (reginfo[j].weight>100) and
  2766. (j<=high(spillinfo)) and
  2767. spillinfo[j].spilled then
  2768. begin
  2769. inc(spillingcounter);
  2770. spill_weight:=spill_weight+d;
  2771. end;
  2772. end;
  2773. if spillingcounter>0 then
  2774. begin
  2775. d:=(1.0-spill_weight/all_weight)*100.0;
  2776. writeln(current_procinfo.procdef.mangledname,' [',regtype,']: spill stats: NUM: ',spillingcounter, ', EFF: ',d:4:1,'%');
  2777. end;
  2778. end;
  2779. {$endif DEBUG_SPILLCOALESCE}
  2780. end.