rgobj.pas 98 KB

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