rgobj.pas 106 KB

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