HybridAllocator.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using ARMeilleure.IntermediateRepresentation;
  2. using ARMeilleure.Translation;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Numerics;
  6. using System.Runtime.CompilerServices;
  7. using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
  8. using static ARMeilleure.IntermediateRepresentation.Operation.Factory;
  9. namespace ARMeilleure.CodeGen.RegisterAllocators
  10. {
  11. class HybridAllocator : IRegisterAllocator
  12. {
  13. private readonly struct BlockInfo
  14. {
  15. public bool HasCall { get; }
  16. public int IntFixedRegisters { get; }
  17. public int VecFixedRegisters { get; }
  18. public BlockInfo(bool hasCall, int intFixedRegisters, int vecFixedRegisters)
  19. {
  20. HasCall = hasCall;
  21. IntFixedRegisters = intFixedRegisters;
  22. VecFixedRegisters = vecFixedRegisters;
  23. }
  24. }
  25. private struct LocalInfo
  26. {
  27. public int Uses { get; set; }
  28. public int UsesAllocated { get; set; }
  29. public int Sequence { get; set; }
  30. public Operand Temp { get; set; }
  31. public Operand Register { get; set; }
  32. public Operand SpillOffset { get; set; }
  33. public OperandType Type { get; }
  34. private int _first;
  35. private int _last;
  36. public bool IsBlockLocal => _first == _last;
  37. public LocalInfo(OperandType type, int uses, int blkIndex)
  38. {
  39. Uses = uses;
  40. Type = type;
  41. UsesAllocated = 0;
  42. Sequence = 0;
  43. Temp = default;
  44. Register = default;
  45. SpillOffset = default;
  46. _first = -1;
  47. _last = -1;
  48. SetBlockIndex(blkIndex);
  49. }
  50. public void SetBlockIndex(int blkIndex)
  51. {
  52. if (_first == -1 || blkIndex < _first)
  53. {
  54. _first = blkIndex;
  55. }
  56. if (_last == -1 || blkIndex > _last)
  57. {
  58. _last = blkIndex;
  59. }
  60. }
  61. }
  62. private const int MaxIROperands = 4;
  63. // The "visited" state is stored in the MSB of the local's value.
  64. private const ulong VisitedMask = 1ul << 63;
  65. private BlockInfo[] _blockInfo;
  66. private LocalInfo[] _localInfo;
  67. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  68. private static bool IsVisited(Operand local)
  69. {
  70. Debug.Assert(local.Kind == OperandKind.LocalVariable);
  71. return (local.GetValueUnsafe() & VisitedMask) != 0;
  72. }
  73. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  74. private static void SetVisited(Operand local)
  75. {
  76. Debug.Assert(local.Kind == OperandKind.LocalVariable);
  77. local.GetValueUnsafe() |= VisitedMask;
  78. }
  79. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  80. private ref LocalInfo GetLocalInfo(Operand local)
  81. {
  82. Debug.Assert(local.Kind == OperandKind.LocalVariable);
  83. Debug.Assert(IsVisited(local), "Local variable not visited. Used before defined?");
  84. return ref _localInfo[(uint)local.GetValueUnsafe() - 1];
  85. }
  86. public AllocationResult RunPass(ControlFlowGraph cfg, StackAllocator stackAlloc, RegisterMasks regMasks)
  87. {
  88. int intUsedRegisters = 0;
  89. int vecUsedRegisters = 0;
  90. int intFreeRegisters = regMasks.IntAvailableRegisters;
  91. int vecFreeRegisters = regMasks.VecAvailableRegisters;
  92. _blockInfo = new BlockInfo[cfg.Blocks.Count];
  93. _localInfo = new LocalInfo[cfg.Blocks.Count * 3];
  94. int localInfoCount = 0;
  95. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  96. {
  97. BasicBlock block = cfg.PostOrderBlocks[index];
  98. int intFixedRegisters = 0;
  99. int vecFixedRegisters = 0;
  100. bool hasCall = false;
  101. for (Operation node = block.Operations.First; node != default; node = node.ListNext)
  102. {
  103. if (node.Instruction == Instruction.Call)
  104. {
  105. hasCall = true;
  106. }
  107. foreach (Operand source in node.SourcesUnsafe)
  108. {
  109. if (source.Kind == OperandKind.LocalVariable)
  110. {
  111. GetLocalInfo(source).SetBlockIndex(block.Index);
  112. }
  113. else if (source.Kind == OperandKind.Memory)
  114. {
  115. MemoryOperand memOp = source.GetMemory();
  116. if (memOp.BaseAddress != default)
  117. {
  118. GetLocalInfo(memOp.BaseAddress).SetBlockIndex(block.Index);
  119. }
  120. if (memOp.Index != default)
  121. {
  122. GetLocalInfo(memOp.Index).SetBlockIndex(block.Index);
  123. }
  124. }
  125. }
  126. foreach (Operand dest in node.DestinationsUnsafe)
  127. {
  128. if (dest.Kind == OperandKind.LocalVariable)
  129. {
  130. if (IsVisited(dest))
  131. {
  132. GetLocalInfo(dest).SetBlockIndex(block.Index);
  133. }
  134. else
  135. {
  136. dest.NumberLocal(++localInfoCount);
  137. if (localInfoCount > _localInfo.Length)
  138. {
  139. Array.Resize(ref _localInfo, localInfoCount * 2);
  140. }
  141. SetVisited(dest);
  142. GetLocalInfo(dest) = new LocalInfo(dest.Type, UsesCount(dest), block.Index);
  143. }
  144. }
  145. else if (dest.Kind == OperandKind.Register)
  146. {
  147. if (dest.Type.IsInteger())
  148. {
  149. intFixedRegisters |= 1 << dest.GetRegister().Index;
  150. }
  151. else
  152. {
  153. vecFixedRegisters |= 1 << dest.GetRegister().Index;
  154. }
  155. }
  156. }
  157. }
  158. _blockInfo[block.Index] = new BlockInfo(hasCall, intFixedRegisters, vecFixedRegisters);
  159. }
  160. int sequence = 0;
  161. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  162. {
  163. BasicBlock block = cfg.PostOrderBlocks[index];
  164. ref BlockInfo blkInfo = ref _blockInfo[block.Index];
  165. int intLocalFreeRegisters = intFreeRegisters & ~blkInfo.IntFixedRegisters;
  166. int vecLocalFreeRegisters = vecFreeRegisters & ~blkInfo.VecFixedRegisters;
  167. int intCallerSavedRegisters = blkInfo.HasCall ? regMasks.IntCallerSavedRegisters : 0;
  168. int vecCallerSavedRegisters = blkInfo.HasCall ? regMasks.VecCallerSavedRegisters : 0;
  169. int intSpillTempRegisters = SelectSpillTemps(
  170. intCallerSavedRegisters & ~blkInfo.IntFixedRegisters,
  171. intLocalFreeRegisters);
  172. int vecSpillTempRegisters = SelectSpillTemps(
  173. vecCallerSavedRegisters & ~blkInfo.VecFixedRegisters,
  174. vecLocalFreeRegisters);
  175. intLocalFreeRegisters &= ~(intSpillTempRegisters | intCallerSavedRegisters);
  176. vecLocalFreeRegisters &= ~(vecSpillTempRegisters | vecCallerSavedRegisters);
  177. for (Operation node = block.Operations.First; node != default; node = node.ListNext)
  178. {
  179. int intLocalUse = 0;
  180. int vecLocalUse = 0;
  181. Operand AllocateRegister(Operand local)
  182. {
  183. ref LocalInfo info = ref GetLocalInfo(local);
  184. info.UsesAllocated++;
  185. Debug.Assert(info.UsesAllocated <= info.Uses);
  186. if (info.Register != default)
  187. {
  188. if (info.UsesAllocated == info.Uses)
  189. {
  190. Register reg = info.Register.GetRegister();
  191. if (local.Type.IsInteger())
  192. {
  193. intLocalFreeRegisters |= 1 << reg.Index;
  194. }
  195. else
  196. {
  197. vecLocalFreeRegisters |= 1 << reg.Index;
  198. }
  199. }
  200. return info.Register;
  201. }
  202. else
  203. {
  204. Operand temp = info.Temp;
  205. if (temp == default || info.Sequence != sequence)
  206. {
  207. temp = local.Type.IsInteger()
  208. ? GetSpillTemp(local, intSpillTempRegisters, ref intLocalUse)
  209. : GetSpillTemp(local, vecSpillTempRegisters, ref vecLocalUse);
  210. info.Sequence = sequence;
  211. info.Temp = temp;
  212. }
  213. Operation fillOp = Operation(Instruction.Fill, temp, info.SpillOffset);
  214. block.Operations.AddBefore(node, fillOp);
  215. return temp;
  216. }
  217. }
  218. bool folded = false;
  219. // If operation is a copy of a local and that local is living on the stack, we turn the copy into
  220. // a fill, instead of inserting a fill before it.
  221. if (node.Instruction == Instruction.Copy)
  222. {
  223. Operand source = node.GetSource(0);
  224. if (source.Kind == OperandKind.LocalVariable)
  225. {
  226. ref LocalInfo info = ref GetLocalInfo(source);
  227. if (info.Register == default)
  228. {
  229. Operation fillOp = Operation(Instruction.Fill, node.Destination, info.SpillOffset);
  230. block.Operations.AddBefore(node, fillOp);
  231. block.Operations.Remove(node);
  232. node = fillOp;
  233. folded = true;
  234. }
  235. }
  236. }
  237. if (!folded)
  238. {
  239. foreach (ref Operand source in node.SourcesUnsafe)
  240. {
  241. if (source.Kind == OperandKind.LocalVariable)
  242. {
  243. source = AllocateRegister(source);
  244. }
  245. else if (source.Kind == OperandKind.Memory)
  246. {
  247. MemoryOperand memOp = source.GetMemory();
  248. if (memOp.BaseAddress != default)
  249. {
  250. memOp.BaseAddress = AllocateRegister(memOp.BaseAddress);
  251. }
  252. if (memOp.Index != default)
  253. {
  254. memOp.Index = AllocateRegister(memOp.Index);
  255. }
  256. }
  257. }
  258. }
  259. int intLocalAsg = 0;
  260. int vecLocalAsg = 0;
  261. foreach (ref Operand dest in node.DestinationsUnsafe)
  262. {
  263. if (dest.Kind != OperandKind.LocalVariable)
  264. {
  265. continue;
  266. }
  267. ref LocalInfo info = ref GetLocalInfo(dest);
  268. if (info.UsesAllocated == 0)
  269. {
  270. int mask = dest.Type.IsInteger()
  271. ? intLocalFreeRegisters
  272. : vecLocalFreeRegisters;
  273. if (info.IsBlockLocal && mask != 0)
  274. {
  275. int selectedReg = BitOperations.TrailingZeroCount(mask);
  276. info.Register = Register(selectedReg, info.Type.ToRegisterType(), info.Type);
  277. if (dest.Type.IsInteger())
  278. {
  279. intLocalFreeRegisters &= ~(1 << selectedReg);
  280. intUsedRegisters |= 1 << selectedReg;
  281. }
  282. else
  283. {
  284. vecLocalFreeRegisters &= ~(1 << selectedReg);
  285. vecUsedRegisters |= 1 << selectedReg;
  286. }
  287. }
  288. else
  289. {
  290. info.Register = default;
  291. info.SpillOffset = Const(stackAlloc.Allocate(dest.Type.GetSizeInBytes()));
  292. }
  293. }
  294. info.UsesAllocated++;
  295. Debug.Assert(info.UsesAllocated <= info.Uses);
  296. if (info.Register != default)
  297. {
  298. dest = info.Register;
  299. }
  300. else
  301. {
  302. Operand temp = info.Temp;
  303. if (temp == default || info.Sequence != sequence)
  304. {
  305. temp = dest.Type.IsInteger()
  306. ? GetSpillTemp(dest, intSpillTempRegisters, ref intLocalAsg)
  307. : GetSpillTemp(dest, vecSpillTempRegisters, ref vecLocalAsg);
  308. info.Sequence = sequence;
  309. info.Temp = temp;
  310. }
  311. dest = temp;
  312. Operation spillOp = Operation(Instruction.Spill, default, info.SpillOffset, temp);
  313. block.Operations.AddAfter(node, spillOp);
  314. node = spillOp;
  315. }
  316. }
  317. sequence++;
  318. intUsedRegisters |= intLocalAsg | intLocalUse;
  319. vecUsedRegisters |= vecLocalAsg | vecLocalUse;
  320. }
  321. }
  322. return new AllocationResult(intUsedRegisters, vecUsedRegisters, stackAlloc.TotalSize);
  323. }
  324. private static int SelectSpillTemps(int mask0, int mask1)
  325. {
  326. int selection = 0;
  327. int count = 0;
  328. while (count < MaxIROperands && mask0 != 0)
  329. {
  330. int mask = mask0 & -mask0;
  331. selection |= mask;
  332. mask0 &= ~mask;
  333. count++;
  334. }
  335. while (count < MaxIROperands && mask1 != 0)
  336. {
  337. int mask = mask1 & -mask1;
  338. selection |= mask;
  339. mask1 &= ~mask;
  340. count++;
  341. }
  342. Debug.Assert(count == MaxIROperands, "No enough registers for spill temps.");
  343. return selection;
  344. }
  345. private static Operand GetSpillTemp(Operand local, int freeMask, ref int useMask)
  346. {
  347. int selectedReg = BitOperations.TrailingZeroCount(freeMask & ~useMask);
  348. useMask |= 1 << selectedReg;
  349. return Register(selectedReg, local.Type.ToRegisterType(), local.Type);
  350. }
  351. private static int UsesCount(Operand local)
  352. {
  353. return local.AssignmentsCount + local.UsesCount;
  354. }
  355. }
  356. }