rgobj.pas 101 KB

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