rgobj.pas 109 KB

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