rgobj.pas 108 KB

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