rgobj.pas 105 KB

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