rgobj.pas 109 KB

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