Operand.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. using ARMeilleure.CodeGen.Linking;
  2. using ARMeilleure.Common;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Runtime.CompilerServices;
  7. namespace ARMeilleure.IntermediateRepresentation
  8. {
  9. unsafe struct Operand : IEquatable<Operand>
  10. {
  11. internal struct Data
  12. {
  13. public byte Kind;
  14. public byte Type;
  15. public byte SymbolType;
  16. public byte Padding; // Unused space.
  17. public ushort AssignmentsCount;
  18. public ushort AssignmentsCapacity;
  19. public uint UsesCount;
  20. public uint UsesCapacity;
  21. public Operation* Assignments;
  22. public Operation* Uses;
  23. public ulong Value;
  24. public ulong SymbolValue;
  25. }
  26. private Data* _data;
  27. public OperandKind Kind
  28. {
  29. get => (OperandKind)_data->Kind;
  30. private set => _data->Kind = (byte)value;
  31. }
  32. public OperandType Type
  33. {
  34. get => (OperandType)_data->Type;
  35. private set => _data->Type = (byte)value;
  36. }
  37. public ulong Value
  38. {
  39. get => _data->Value;
  40. private set => _data->Value = value;
  41. }
  42. public Symbol Symbol
  43. {
  44. get
  45. {
  46. Debug.Assert(Kind != OperandKind.Memory);
  47. return new Symbol((SymbolType)_data->SymbolType, _data->SymbolValue);
  48. }
  49. private set
  50. {
  51. Debug.Assert(Kind != OperandKind.Memory);
  52. if (value.Type == SymbolType.None)
  53. {
  54. _data->SymbolType = (byte)SymbolType.None;
  55. }
  56. else
  57. {
  58. _data->SymbolType = (byte)value.Type;
  59. _data->SymbolValue = value.Value;
  60. }
  61. }
  62. }
  63. public ReadOnlySpan<Operation> Assignments
  64. {
  65. get
  66. {
  67. Debug.Assert(Kind != OperandKind.Memory);
  68. return new ReadOnlySpan<Operation>(_data->Assignments, _data->AssignmentsCount);
  69. }
  70. }
  71. public ReadOnlySpan<Operation> Uses
  72. {
  73. get
  74. {
  75. Debug.Assert(Kind != OperandKind.Memory);
  76. return new ReadOnlySpan<Operation>(_data->Uses, (int)_data->UsesCount);
  77. }
  78. }
  79. public int UsesCount => (int)_data->UsesCount;
  80. public int AssignmentsCount => _data->AssignmentsCount;
  81. public bool Relocatable => Symbol.Type != SymbolType.None;
  82. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  83. public Register GetRegister()
  84. {
  85. Debug.Assert(Kind == OperandKind.Register);
  86. return new Register((int)Value & 0xffffff, (RegisterType)(Value >> 24));
  87. }
  88. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  89. public MemoryOperand GetMemory()
  90. {
  91. Debug.Assert(Kind == OperandKind.Memory);
  92. return new MemoryOperand(this);
  93. }
  94. public int GetLocalNumber()
  95. {
  96. Debug.Assert(Kind == OperandKind.LocalVariable);
  97. return (int)Value;
  98. }
  99. public byte AsByte()
  100. {
  101. return (byte)Value;
  102. }
  103. public short AsInt16()
  104. {
  105. return (short)Value;
  106. }
  107. public int AsInt32()
  108. {
  109. return (int)Value;
  110. }
  111. public long AsInt64()
  112. {
  113. return (long)Value;
  114. }
  115. public float AsFloat()
  116. {
  117. return BitConverter.Int32BitsToSingle((int)Value);
  118. }
  119. public double AsDouble()
  120. {
  121. return BitConverter.Int64BitsToDouble((long)Value);
  122. }
  123. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  124. internal ref ulong GetValueUnsafe()
  125. {
  126. return ref _data->Value;
  127. }
  128. internal void NumberLocal(int number)
  129. {
  130. if (Kind != OperandKind.LocalVariable)
  131. {
  132. throw new InvalidOperationException("The operand is not a local variable.");
  133. }
  134. Value = (ulong)number;
  135. }
  136. public void AddAssignment(Operation operation)
  137. {
  138. if (Kind == OperandKind.LocalVariable)
  139. {
  140. Add(operation, ref _data->Assignments, ref _data->AssignmentsCount, ref _data->AssignmentsCapacity);
  141. }
  142. else if (Kind == OperandKind.Memory)
  143. {
  144. MemoryOperand memOp = GetMemory();
  145. Operand addr = memOp.BaseAddress;
  146. Operand index = memOp.Index;
  147. if (addr != default)
  148. {
  149. Add(operation, ref addr._data->Assignments, ref addr._data->AssignmentsCount, ref addr._data->AssignmentsCapacity);
  150. }
  151. if (index != default)
  152. {
  153. Add(operation, ref index._data->Assignments, ref index._data->AssignmentsCount, ref index._data->AssignmentsCapacity);
  154. }
  155. }
  156. }
  157. public void RemoveAssignment(Operation operation)
  158. {
  159. if (Kind == OperandKind.LocalVariable)
  160. {
  161. Remove(operation, ref _data->Assignments, ref _data->AssignmentsCount);
  162. }
  163. else if (Kind == OperandKind.Memory)
  164. {
  165. MemoryOperand memOp = GetMemory();
  166. Operand addr = memOp.BaseAddress;
  167. Operand index = memOp.Index;
  168. if (addr != default)
  169. {
  170. Remove(operation, ref addr._data->Assignments, ref addr._data->AssignmentsCount);
  171. }
  172. if (index != default)
  173. {
  174. Remove(operation, ref index._data->Assignments, ref index._data->AssignmentsCount);
  175. }
  176. }
  177. }
  178. public void AddUse(Operation operation)
  179. {
  180. if (Kind == OperandKind.LocalVariable)
  181. {
  182. Add(operation, ref _data->Uses, ref _data->UsesCount, ref _data->UsesCapacity);
  183. }
  184. else if (Kind == OperandKind.Memory)
  185. {
  186. MemoryOperand memOp = GetMemory();
  187. Operand addr = memOp.BaseAddress;
  188. Operand index = memOp.Index;
  189. if (addr != default)
  190. {
  191. Add(operation, ref addr._data->Uses, ref addr._data->UsesCount, ref addr._data->UsesCapacity);
  192. }
  193. if (index != default)
  194. {
  195. Add(operation, ref index._data->Uses, ref index._data->UsesCount, ref index._data->UsesCapacity);
  196. }
  197. }
  198. }
  199. public void RemoveUse(Operation operation)
  200. {
  201. if (Kind == OperandKind.LocalVariable)
  202. {
  203. Remove(operation, ref _data->Uses, ref _data->UsesCount);
  204. }
  205. else if (Kind == OperandKind.Memory)
  206. {
  207. MemoryOperand memOp = GetMemory();
  208. Operand addr = memOp.BaseAddress;
  209. Operand index = memOp.Index;
  210. if (addr != default)
  211. {
  212. Remove(operation, ref addr._data->Uses, ref addr._data->UsesCount);
  213. }
  214. if (index != default)
  215. {
  216. Remove(operation, ref index._data->Uses, ref index._data->UsesCount);
  217. }
  218. }
  219. }
  220. private static void New<T>(ref T* data, ref ushort count, ref ushort capacity, ushort initialCapacity) where T : unmanaged
  221. {
  222. count = 0;
  223. capacity = initialCapacity;
  224. data = Allocators.References.Allocate<T>(initialCapacity);
  225. }
  226. private static void New<T>(ref T* data, ref uint count, ref uint capacity, uint initialCapacity) where T : unmanaged
  227. {
  228. count = 0;
  229. capacity = initialCapacity;
  230. data = Allocators.References.Allocate<T>(initialCapacity);
  231. }
  232. private static void Add<T>(T item, ref T* data, ref ushort count, ref ushort capacity) where T : unmanaged
  233. {
  234. if (count < capacity)
  235. {
  236. data[(uint)count++] = item;
  237. return;
  238. }
  239. // Could not add item in the fast path, fallback onto the slow path.
  240. ExpandAdd(item, ref data, ref count, ref capacity);
  241. static void ExpandAdd(T item, ref T* data, ref ushort count, ref ushort capacity)
  242. {
  243. ushort newCount = checked((ushort)(count + 1));
  244. ushort newCapacity = (ushort)Math.Min(capacity * 2, ushort.MaxValue);
  245. var oldSpan = new Span<T>(data, count);
  246. capacity = newCapacity;
  247. data = Allocators.References.Allocate<T>(capacity);
  248. oldSpan.CopyTo(new Span<T>(data, count));
  249. data[count] = item;
  250. count = newCount;
  251. }
  252. }
  253. private static void Add<T>(T item, ref T* data, ref uint count, ref uint capacity) where T : unmanaged
  254. {
  255. if (count < capacity)
  256. {
  257. data[count++] = item;
  258. return;
  259. }
  260. // Could not add item in the fast path, fallback onto the slow path.
  261. ExpandAdd(item, ref data, ref count, ref capacity);
  262. static void ExpandAdd(T item, ref T* data, ref uint count, ref uint capacity)
  263. {
  264. uint newCount = checked(count + 1);
  265. uint newCapacity = (uint)Math.Min(capacity * 2, int.MaxValue);
  266. if (newCapacity <= capacity)
  267. {
  268. throw new OverflowException();
  269. }
  270. var oldSpan = new Span<T>(data, (int)count);
  271. capacity = newCapacity;
  272. data = Allocators.References.Allocate<T>(capacity);
  273. oldSpan.CopyTo(new Span<T>(data, (int)count));
  274. data[count] = item;
  275. count = newCount;
  276. }
  277. }
  278. private static void Remove<T>(in T item, ref T* data, ref ushort count) where T : unmanaged
  279. {
  280. var span = new Span<T>(data, count);
  281. for (int i = 0; i < span.Length; i++)
  282. {
  283. if (EqualityComparer<T>.Default.Equals(span[i], item))
  284. {
  285. if (i + 1 < count)
  286. {
  287. span.Slice(i + 1).CopyTo(span.Slice(i));
  288. }
  289. count--;
  290. return;
  291. }
  292. }
  293. }
  294. private static void Remove<T>(in T item, ref T* data, ref uint count) where T : unmanaged
  295. {
  296. var span = new Span<T>(data, (int)count);
  297. for (int i = 0; i < span.Length; i++)
  298. {
  299. if (EqualityComparer<T>.Default.Equals(span[i], item))
  300. {
  301. if (i + 1 < count)
  302. {
  303. span.Slice(i + 1).CopyTo(span.Slice(i));
  304. }
  305. count--;
  306. return;
  307. }
  308. }
  309. }
  310. public override int GetHashCode()
  311. {
  312. return ((ulong)_data).GetHashCode();
  313. }
  314. public bool Equals(Operand operand)
  315. {
  316. return operand._data == _data;
  317. }
  318. public override bool Equals(object obj)
  319. {
  320. return obj is Operand operand && Equals(operand);
  321. }
  322. public static bool operator ==(Operand a, Operand b)
  323. {
  324. return a.Equals(b);
  325. }
  326. public static bool operator !=(Operand a, Operand b)
  327. {
  328. return !a.Equals(b);
  329. }
  330. public static class Factory
  331. {
  332. private const int InternTableSize = 256;
  333. private const int InternTableProbeLength = 8;
  334. [ThreadStatic]
  335. private static Data* _internTable;
  336. private static Data* InternTable
  337. {
  338. get
  339. {
  340. if (_internTable == null)
  341. {
  342. _internTable = (Data*)NativeAllocator.Instance.Allocate((uint)sizeof(Data) * InternTableSize);
  343. // Make sure the table is zeroed.
  344. new Span<Data>(_internTable, InternTableSize).Clear();
  345. }
  346. return _internTable;
  347. }
  348. }
  349. private static Operand Make(OperandKind kind, OperandType type, ulong value, Symbol symbol = default)
  350. {
  351. Debug.Assert(kind != OperandKind.None);
  352. Data* data = null;
  353. // If constant or register, then try to look up in the intern table before allocating.
  354. if (kind == OperandKind.Constant || kind == OperandKind.Register)
  355. {
  356. uint hash = (uint)HashCode.Combine(kind, type, value);
  357. // Look in the next InternTableProbeLength slots for a match.
  358. for (uint i = 0; i < InternTableProbeLength; i++)
  359. {
  360. Operand interned = new();
  361. interned._data = &InternTable[(hash + i) % InternTableSize];
  362. // If slot matches the allocation request then return that slot.
  363. if (interned.Kind == kind && interned.Type == type && interned.Value == value && interned.Symbol == symbol)
  364. {
  365. return interned;
  366. }
  367. // Otherwise if the slot is not occupied, we store in that slot.
  368. else if (interned.Kind == OperandKind.None)
  369. {
  370. data = interned._data;
  371. break;
  372. }
  373. }
  374. }
  375. // If we could not get a slot from the intern table, we allocate somewhere else and store there.
  376. if (data == null)
  377. {
  378. data = Allocators.Operands.Allocate<Data>();
  379. }
  380. *data = default;
  381. Operand result = new();
  382. result._data = data;
  383. result.Value = value;
  384. result.Kind = kind;
  385. result.Type = type;
  386. if (kind != OperandKind.Memory)
  387. {
  388. result.Symbol = symbol;
  389. }
  390. // If local variable, then the use and def list is initialized with default sizes.
  391. if (kind == OperandKind.LocalVariable)
  392. {
  393. New(ref result._data->Assignments, ref result._data->AssignmentsCount, ref result._data->AssignmentsCapacity, 1);
  394. New(ref result._data->Uses, ref result._data->UsesCount, ref result._data->UsesCapacity, 4);
  395. }
  396. return result;
  397. }
  398. public static Operand Const(OperandType type, long value)
  399. {
  400. Debug.Assert(type is OperandType.I32 or OperandType.I64);
  401. return type == OperandType.I32 ? Const((int)value) : Const(value);
  402. }
  403. public static Operand Const(bool value)
  404. {
  405. return Const(value ? 1 : 0);
  406. }
  407. public static Operand Const(int value)
  408. {
  409. return Const((uint)value);
  410. }
  411. public static Operand Const(uint value)
  412. {
  413. return Make(OperandKind.Constant, OperandType.I32, value);
  414. }
  415. public static Operand Const(long value)
  416. {
  417. return Const(value, symbol: default);
  418. }
  419. public static Operand Const<T>(ref T reference, Symbol symbol = default)
  420. {
  421. return Const((long)Unsafe.AsPointer(ref reference), symbol);
  422. }
  423. public static Operand Const(long value, Symbol symbol)
  424. {
  425. return Make(OperandKind.Constant, OperandType.I64, (ulong)value, symbol);
  426. }
  427. public static Operand Const(ulong value)
  428. {
  429. return Make(OperandKind.Constant, OperandType.I64, value);
  430. }
  431. public static Operand ConstF(float value)
  432. {
  433. return Make(OperandKind.Constant, OperandType.FP32, (ulong)BitConverter.SingleToInt32Bits(value));
  434. }
  435. public static Operand ConstF(double value)
  436. {
  437. return Make(OperandKind.Constant, OperandType.FP64, (ulong)BitConverter.DoubleToInt64Bits(value));
  438. }
  439. public static Operand Label()
  440. {
  441. return Make(OperandKind.Label, OperandType.None, 0);
  442. }
  443. public static Operand Local(OperandType type)
  444. {
  445. return Make(OperandKind.LocalVariable, type, 0);
  446. }
  447. public static Operand Register(int index, RegisterType regType, OperandType type)
  448. {
  449. return Make(OperandKind.Register, type, (ulong)((int)regType << 24 | index));
  450. }
  451. public static Operand Undef()
  452. {
  453. return Make(OperandKind.Undefined, OperandType.None, 0);
  454. }
  455. public static Operand MemoryOp(
  456. OperandType type,
  457. Operand baseAddress,
  458. Operand index = default,
  459. Multiplier scale = Multiplier.x1,
  460. int displacement = 0)
  461. {
  462. Operand result = Make(OperandKind.Memory, type, 0);
  463. MemoryOperand memory = result.GetMemory();
  464. memory.BaseAddress = baseAddress;
  465. memory.Index = index;
  466. memory.Scale = scale;
  467. memory.Displacement = displacement;
  468. return result;
  469. }
  470. }
  471. }
  472. }