ILEmitterCtx.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. using ChocolArm64.Decoders;
  2. using ChocolArm64.Instructions;
  3. using ChocolArm64.State;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. namespace ChocolArm64.Translation
  9. {
  10. class ILEmitterCtx
  11. {
  12. private TranslatorCache _cache;
  13. private TranslatorQueue _queue;
  14. private Dictionary<long, ILLabel> _labels;
  15. private long _subPosition;
  16. private int _opcIndex;
  17. private Block _currBlock;
  18. public Block CurrBlock => _currBlock;
  19. public OpCode64 CurrOp => _currBlock?.OpCodes[_opcIndex];
  20. public TranslationTier Tier { get; }
  21. public Aarch32Mode Mode { get; } = Aarch32Mode.User; //TODO
  22. private Dictionary<Block, ILBlock> _visitedBlocks;
  23. private Queue<Block> _branchTargets;
  24. private List<ILBlock> _ilBlocks;
  25. private ILBlock _ilBlock;
  26. private OpCode64 _optOpLastCompare;
  27. private OpCode64 _optOpLastFlagSet;
  28. //This is the index of the temporary register, used to store temporary
  29. //values needed by some functions, since IL doesn't have a swap instruction.
  30. //You can use any value here as long it doesn't conflict with the indices
  31. //for the other registers. Any value >= 64 or < 0 will do.
  32. private const int IntTmpIndex = -1;
  33. private const int RorTmpIndex = -2;
  34. private const int CmpOptTmp1Index = -3;
  35. private const int CmpOptTmp2Index = -4;
  36. private const int VecTmp1Index = -5;
  37. private const int VecTmp2Index = -6;
  38. public ILEmitterCtx(TranslatorCache cache, TranslatorQueue queue, TranslationTier tier, Block graph)
  39. {
  40. _cache = cache ?? throw new ArgumentNullException(nameof(cache));
  41. _queue = queue ?? throw new ArgumentNullException(nameof(queue));
  42. _currBlock = graph ?? throw new ArgumentNullException(nameof(graph));
  43. Tier = tier;
  44. _labels = new Dictionary<long, ILLabel>();
  45. _visitedBlocks = new Dictionary<Block, ILBlock>();
  46. _visitedBlocks.Add(graph, new ILBlock());
  47. _branchTargets = new Queue<Block>();
  48. _ilBlocks = new List<ILBlock>();
  49. _subPosition = graph.Position;
  50. ResetBlockState();
  51. AdvanceOpCode();
  52. }
  53. public ILBlock[] GetILBlocks()
  54. {
  55. EmitAllOpCodes();
  56. return _ilBlocks.ToArray();
  57. }
  58. private void EmitAllOpCodes()
  59. {
  60. do
  61. {
  62. EmitOpCode();
  63. }
  64. while (AdvanceOpCode());
  65. }
  66. private void EmitOpCode()
  67. {
  68. if (_currBlock == null)
  69. {
  70. return;
  71. }
  72. if (_opcIndex == 0)
  73. {
  74. MarkLabel(GetLabel(_currBlock.Position));
  75. EmitSynchronization();
  76. }
  77. //On AARCH32 mode, (almost) all instruction can be conditionally
  78. //executed, and the required condition is encoded on the opcode.
  79. //We handle that here, skipping the instruction if the condition
  80. //is not met. We can just ignore it when the condition is "Always",
  81. //because in this case the instruction is always going to be executed.
  82. //Condition "Never" is also ignored because this is a special encoding
  83. //used by some unconditional instructions.
  84. ILLabel lblSkip = null;
  85. if (CurrOp is OpCode32 op && op.Cond < Condition.Al)
  86. {
  87. lblSkip = new ILLabel();
  88. EmitCondBranch(lblSkip, GetInverseCond(op.Cond));
  89. }
  90. CurrOp.Emitter(this);
  91. if (lblSkip != null)
  92. {
  93. MarkLabel(lblSkip);
  94. //If this is the last op on the block, and there's no "next" block
  95. //after this one, then we have to return right now, with the address
  96. //of the next instruction to be executed (in the case that the condition
  97. //is false, and the branch was not taken, as all basic blocks should end with
  98. //some kind of branch).
  99. if (CurrOp == CurrBlock.GetLastOp() && CurrBlock.Next == null)
  100. {
  101. EmitStoreState();
  102. EmitLdc_I8(CurrOp.Position + CurrOp.OpCodeSizeInBytes);
  103. Emit(OpCodes.Ret);
  104. }
  105. }
  106. _ilBlock.Add(new ILBarrier());
  107. }
  108. private Condition GetInverseCond(Condition cond)
  109. {
  110. //Bit 0 of all conditions is basically a negation bit, so
  111. //inverting this bit has the effect of inverting the condition.
  112. return (Condition)((int)cond ^ 1);
  113. }
  114. private void EmitSynchronization()
  115. {
  116. EmitLdarg(TranslatedSub.StateArgIdx);
  117. EmitLdc_I4(_currBlock.OpCodes.Count);
  118. EmitPrivateCall(typeof(CpuThreadState), nameof(CpuThreadState.Synchronize));
  119. EmitLdc_I4(0);
  120. ILLabel lblContinue = new ILLabel();
  121. Emit(OpCodes.Bne_Un_S, lblContinue);
  122. EmitLdc_I8(0);
  123. Emit(OpCodes.Ret);
  124. MarkLabel(lblContinue);
  125. }
  126. private bool AdvanceOpCode()
  127. {
  128. if (_currBlock == null)
  129. {
  130. return false;
  131. }
  132. while (++_opcIndex >= _currBlock.OpCodes.Count)
  133. {
  134. if (!AdvanceBlock())
  135. {
  136. return false;
  137. }
  138. ResetBlockState();
  139. }
  140. return true;
  141. }
  142. private bool AdvanceBlock()
  143. {
  144. if (_currBlock.Branch != null)
  145. {
  146. if (_visitedBlocks.TryAdd(_currBlock.Branch, _ilBlock.Branch))
  147. {
  148. _branchTargets.Enqueue(_currBlock.Branch);
  149. }
  150. }
  151. if (_currBlock.Next != null)
  152. {
  153. if (_visitedBlocks.TryAdd(_currBlock.Next, _ilBlock.Next))
  154. {
  155. _currBlock = _currBlock.Next;
  156. return true;
  157. }
  158. else
  159. {
  160. Emit(OpCodes.Br, GetLabel(_currBlock.Next.Position));
  161. }
  162. }
  163. return _branchTargets.TryDequeue(out _currBlock);
  164. }
  165. private void ResetBlockState()
  166. {
  167. _ilBlock = _visitedBlocks[_currBlock];
  168. _ilBlocks.Add(_ilBlock);
  169. _ilBlock.Next = GetOrCreateILBlock(_currBlock.Next);
  170. _ilBlock.Branch = GetOrCreateILBlock(_currBlock.Branch);
  171. _opcIndex = -1;
  172. _optOpLastFlagSet = null;
  173. _optOpLastCompare = null;
  174. }
  175. private ILBlock GetOrCreateILBlock(Block block)
  176. {
  177. if (block == null)
  178. {
  179. return null;
  180. }
  181. if (_visitedBlocks.TryGetValue(block, out ILBlock ilBlock))
  182. {
  183. return ilBlock;
  184. }
  185. return new ILBlock();
  186. }
  187. public void TranslateAhead(long position, ExecutionMode mode = ExecutionMode.Aarch64)
  188. {
  189. if (_cache.TryGetSubroutine(position, out TranslatedSub sub) && sub.Tier != TranslationTier.Tier0)
  190. {
  191. return;
  192. }
  193. _queue.Enqueue(new TranslatorQueueItem(position, mode, TranslationTier.Tier1));
  194. }
  195. public bool TryOptEmitSubroutineCall()
  196. {
  197. if (_currBlock.Next == null)
  198. {
  199. return false;
  200. }
  201. if (CurrOp.Emitter != InstEmit.Bl)
  202. {
  203. return false;
  204. }
  205. if (!_cache.TryGetSubroutine(((OpCodeBImmAl64)CurrOp).Imm, out TranslatedSub subroutine))
  206. {
  207. return false;
  208. }
  209. for (int index = 0; index < TranslatedSub.FixedArgTypes.Length; index++)
  210. {
  211. EmitLdarg(index);
  212. }
  213. EmitCall(subroutine.Method);
  214. return true;
  215. }
  216. public void TryOptMarkCondWithoutCmp()
  217. {
  218. _optOpLastCompare = CurrOp;
  219. InstEmitAluHelper.EmitAluLoadOpers(this);
  220. Stloc(CmpOptTmp2Index, IoType.Int);
  221. Stloc(CmpOptTmp1Index, IoType.Int);
  222. }
  223. private Dictionary<Condition, OpCode> _branchOps = new Dictionary<Condition, OpCode>()
  224. {
  225. { Condition.Eq, OpCodes.Beq },
  226. { Condition.Ne, OpCodes.Bne_Un },
  227. { Condition.GeUn, OpCodes.Bge_Un },
  228. { Condition.LtUn, OpCodes.Blt_Un },
  229. { Condition.GtUn, OpCodes.Bgt_Un },
  230. { Condition.LeUn, OpCodes.Ble_Un },
  231. { Condition.Ge, OpCodes.Bge },
  232. { Condition.Lt, OpCodes.Blt },
  233. { Condition.Gt, OpCodes.Bgt },
  234. { Condition.Le, OpCodes.Ble }
  235. };
  236. public void EmitCondBranch(ILLabel target, Condition cond)
  237. {
  238. OpCode ilOp;
  239. int intCond = (int)cond;
  240. if (_optOpLastCompare != null &&
  241. _optOpLastCompare == _optOpLastFlagSet && _branchOps.ContainsKey(cond))
  242. {
  243. Ldloc(CmpOptTmp1Index, IoType.Int, _optOpLastCompare.RegisterSize);
  244. Ldloc(CmpOptTmp2Index, IoType.Int, _optOpLastCompare.RegisterSize);
  245. ilOp = _branchOps[cond];
  246. }
  247. else if (intCond < 14)
  248. {
  249. int condTrue = intCond >> 1;
  250. switch (condTrue)
  251. {
  252. case 0: EmitLdflg((int)PState.ZBit); break;
  253. case 1: EmitLdflg((int)PState.CBit); break;
  254. case 2: EmitLdflg((int)PState.NBit); break;
  255. case 3: EmitLdflg((int)PState.VBit); break;
  256. case 4:
  257. EmitLdflg((int)PState.CBit);
  258. EmitLdflg((int)PState.ZBit);
  259. Emit(OpCodes.Not);
  260. Emit(OpCodes.And);
  261. break;
  262. case 5:
  263. case 6:
  264. EmitLdflg((int)PState.NBit);
  265. EmitLdflg((int)PState.VBit);
  266. Emit(OpCodes.Ceq);
  267. if (condTrue == 6)
  268. {
  269. EmitLdflg((int)PState.ZBit);
  270. Emit(OpCodes.Not);
  271. Emit(OpCodes.And);
  272. }
  273. break;
  274. }
  275. ilOp = (intCond & 1) != 0
  276. ? OpCodes.Brfalse
  277. : OpCodes.Brtrue;
  278. }
  279. else
  280. {
  281. ilOp = OpCodes.Br;
  282. }
  283. Emit(ilOp, target);
  284. }
  285. public void EmitCast(IntType intType)
  286. {
  287. switch (intType)
  288. {
  289. case IntType.UInt8: Emit(OpCodes.Conv_U1); break;
  290. case IntType.UInt16: Emit(OpCodes.Conv_U2); break;
  291. case IntType.UInt32: Emit(OpCodes.Conv_U4); break;
  292. case IntType.UInt64: Emit(OpCodes.Conv_U8); break;
  293. case IntType.Int8: Emit(OpCodes.Conv_I1); break;
  294. case IntType.Int16: Emit(OpCodes.Conv_I2); break;
  295. case IntType.Int32: Emit(OpCodes.Conv_I4); break;
  296. case IntType.Int64: Emit(OpCodes.Conv_I8); break;
  297. }
  298. bool sz64 = CurrOp.RegisterSize != RegisterSize.Int32;
  299. if (sz64 == (intType == IntType.UInt64 ||
  300. intType == IntType.Int64))
  301. {
  302. return;
  303. }
  304. if (sz64)
  305. {
  306. Emit(intType >= IntType.Int8
  307. ? OpCodes.Conv_I8
  308. : OpCodes.Conv_U8);
  309. }
  310. else
  311. {
  312. Emit(OpCodes.Conv_U4);
  313. }
  314. }
  315. public void EmitLsl(int amount) => EmitILShift(amount, OpCodes.Shl);
  316. public void EmitLsr(int amount) => EmitILShift(amount, OpCodes.Shr_Un);
  317. public void EmitAsr(int amount) => EmitILShift(amount, OpCodes.Shr);
  318. private void EmitILShift(int amount, OpCode ilOp)
  319. {
  320. if (amount > 0)
  321. {
  322. EmitLdc_I4(amount);
  323. Emit(ilOp);
  324. }
  325. }
  326. public void EmitRor(int amount)
  327. {
  328. if (amount > 0)
  329. {
  330. Stloc(RorTmpIndex, IoType.Int);
  331. Ldloc(RorTmpIndex, IoType.Int);
  332. EmitLdc_I4(amount);
  333. Emit(OpCodes.Shr_Un);
  334. Ldloc(RorTmpIndex, IoType.Int);
  335. EmitLdc_I4(CurrOp.GetBitsCount() - amount);
  336. Emit(OpCodes.Shl);
  337. Emit(OpCodes.Or);
  338. }
  339. }
  340. public ILLabel GetLabel(long position)
  341. {
  342. if (!_labels.TryGetValue(position, out ILLabel output))
  343. {
  344. output = new ILLabel();
  345. _labels.Add(position, output);
  346. }
  347. return output;
  348. }
  349. public void MarkLabel(ILLabel label)
  350. {
  351. _ilBlock.Add(label);
  352. }
  353. public void Emit(OpCode ilOp)
  354. {
  355. _ilBlock.Add(new ILOpCode(ilOp));
  356. }
  357. public void Emit(OpCode ilOp, ILLabel label)
  358. {
  359. _ilBlock.Add(new ILOpCodeBranch(ilOp, label));
  360. }
  361. public void EmitFieldLoad(FieldInfo info)
  362. {
  363. _ilBlock.Add(new ILOpCodeLoadField(info));
  364. }
  365. public void EmitPrint(string text)
  366. {
  367. _ilBlock.Add(new ILOpCodeLog(text));
  368. }
  369. public void EmitLdarg(int index)
  370. {
  371. _ilBlock.Add(new ILOpCodeLoad(index, IoType.Arg));
  372. }
  373. public void EmitLdintzr(int index)
  374. {
  375. if (index != RegisterAlias.Zr)
  376. {
  377. EmitLdint(index);
  378. }
  379. else
  380. {
  381. EmitLdc_I(0);
  382. }
  383. }
  384. public void EmitStintzr(int index)
  385. {
  386. if (index != RegisterAlias.Zr)
  387. {
  388. EmitStint(index);
  389. }
  390. else
  391. {
  392. Emit(OpCodes.Pop);
  393. }
  394. }
  395. public void EmitLoadState()
  396. {
  397. if (_ilBlock.Next == null)
  398. {
  399. throw new InvalidOperationException("Can't load state for next block, because there's no next block.");
  400. }
  401. _ilBlock.Add(new ILOpCodeLoadState(_ilBlock.Next));
  402. }
  403. public void EmitStoreState()
  404. {
  405. _ilBlock.Add(new ILOpCodeStoreState(_ilBlock));
  406. }
  407. public void EmitLdtmp() => EmitLdint(IntTmpIndex);
  408. public void EmitSttmp() => EmitStint(IntTmpIndex);
  409. public void EmitLdvectmp() => EmitLdvec(VecTmp1Index);
  410. public void EmitStvectmp() => EmitStvec(VecTmp1Index);
  411. public void EmitLdvectmp2() => EmitLdvec(VecTmp2Index);
  412. public void EmitStvectmp2() => EmitStvec(VecTmp2Index);
  413. public void EmitLdint(int index) => Ldloc(index, IoType.Int);
  414. public void EmitStint(int index) => Stloc(index, IoType.Int);
  415. public void EmitLdvec(int index) => Ldloc(index, IoType.Vector);
  416. public void EmitStvec(int index) => Stloc(index, IoType.Vector);
  417. public void EmitLdflg(int index) => Ldloc(index, IoType.Flag);
  418. public void EmitStflg(int index)
  419. {
  420. //Set this only if any of the NZCV flag bits were modified.
  421. //This is used to ensure that, when emiting a direct IL branch
  422. //instruction for compare + branch sequences, we're not expecting
  423. //to use comparison values from an old instruction, when in fact
  424. //the flags were already overwritten by another instruction further along.
  425. if (index >= (int)PState.VBit)
  426. {
  427. _optOpLastFlagSet = CurrOp;
  428. }
  429. Stloc(index, IoType.Flag);
  430. }
  431. private void Ldloc(int index, IoType ioType)
  432. {
  433. _ilBlock.Add(new ILOpCodeLoad(index, ioType, CurrOp.RegisterSize));
  434. }
  435. private void Ldloc(int index, IoType ioType, RegisterSize registerSize)
  436. {
  437. _ilBlock.Add(new ILOpCodeLoad(index, ioType, registerSize));
  438. }
  439. private void Stloc(int index, IoType ioType)
  440. {
  441. _ilBlock.Add(new ILOpCodeStore(index, ioType, CurrOp.RegisterSize));
  442. }
  443. public void EmitCallPropGet(Type objType, string propName)
  444. {
  445. if (objType == null)
  446. {
  447. throw new ArgumentNullException(nameof(objType));
  448. }
  449. if (propName == null)
  450. {
  451. throw new ArgumentNullException(nameof(propName));
  452. }
  453. EmitCall(objType.GetMethod($"get_{propName}"));
  454. }
  455. public void EmitCallPropSet(Type objType, string propName)
  456. {
  457. if (objType == null)
  458. {
  459. throw new ArgumentNullException(nameof(objType));
  460. }
  461. if (propName == null)
  462. {
  463. throw new ArgumentNullException(nameof(propName));
  464. }
  465. EmitCall(objType.GetMethod($"set_{propName}"));
  466. }
  467. public void EmitCall(Type objType, string mthdName)
  468. {
  469. if (objType == null)
  470. {
  471. throw new ArgumentNullException(nameof(objType));
  472. }
  473. if (mthdName == null)
  474. {
  475. throw new ArgumentNullException(nameof(mthdName));
  476. }
  477. EmitCall(objType.GetMethod(mthdName));
  478. }
  479. public void EmitPrivateCall(Type objType, string mthdName)
  480. {
  481. if (objType == null)
  482. {
  483. throw new ArgumentNullException(nameof(objType));
  484. }
  485. if (mthdName == null)
  486. {
  487. throw new ArgumentNullException(nameof(mthdName));
  488. }
  489. EmitCall(objType.GetMethod(mthdName, BindingFlags.Instance | BindingFlags.NonPublic));
  490. }
  491. public void EmitCall(MethodInfo mthdInfo, bool isVirtual = false)
  492. {
  493. _ilBlock.Add(new ILOpCodeCall(mthdInfo ?? throw new ArgumentNullException(nameof(mthdInfo)), isVirtual));
  494. }
  495. public void EmitLdc_I(long value)
  496. {
  497. if (CurrOp.RegisterSize == RegisterSize.Int32)
  498. {
  499. EmitLdc_I4((int)value);
  500. }
  501. else
  502. {
  503. EmitLdc_I8(value);
  504. }
  505. }
  506. public void EmitLdc_I4(int value)
  507. {
  508. _ilBlock.Add(new ILOpCodeConst(value));
  509. }
  510. public void EmitLdc_I8(long value)
  511. {
  512. _ilBlock.Add(new ILOpCodeConst(value));
  513. }
  514. public void EmitLdc_R4(float value)
  515. {
  516. _ilBlock.Add(new ILOpCodeConst(value));
  517. }
  518. public void EmitLdc_R8(double value)
  519. {
  520. _ilBlock.Add(new ILOpCodeConst(value));
  521. }
  522. public void EmitZnFlagCheck()
  523. {
  524. EmitZnCheck(OpCodes.Ceq, (int)PState.ZBit);
  525. EmitZnCheck(OpCodes.Clt, (int)PState.NBit);
  526. }
  527. private void EmitZnCheck(OpCode ilCmpOp, int flag)
  528. {
  529. Emit(OpCodes.Dup);
  530. Emit(OpCodes.Ldc_I4_0);
  531. if (CurrOp.RegisterSize != RegisterSize.Int32)
  532. {
  533. Emit(OpCodes.Conv_I8);
  534. }
  535. Emit(ilCmpOp);
  536. EmitStflg(flag);
  537. }
  538. }
  539. }