rgobj.pas 102 KB

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